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       return CK_FixedPointToBoolean;
5898     case Type::STK_Integral:
5899     case Type::STK_Floating:
5900     case Type::STK_IntegralComplex:
5901     case Type::STK_FloatingComplex:
5902       Diag(Src.get()->getExprLoc(),
5903            diag::err_unimplemented_conversion_with_fixed_point_type)
5904           << DestTy;
5905       return CK_IntegralCast;
5906     case Type::STK_CPointer:
5907     case Type::STK_ObjCObjectPointer:
5908     case Type::STK_BlockPointer:
5909     case Type::STK_MemberPointer:
5910       llvm_unreachable("illegal cast to pointer type");
5911     }
5912     llvm_unreachable("Should have returned before this");
5913 
5914   case Type::STK_Bool: // casting from bool is like casting from an integer
5915   case Type::STK_Integral:
5916     switch (DestTy->getScalarTypeKind()) {
5917     case Type::STK_CPointer:
5918     case Type::STK_ObjCObjectPointer:
5919     case Type::STK_BlockPointer:
5920       if (Src.get()->isNullPointerConstant(Context,
5921                                            Expr::NPC_ValueDependentIsNull))
5922         return CK_NullToPointer;
5923       return CK_IntegralToPointer;
5924     case Type::STK_Bool:
5925       return CK_IntegralToBoolean;
5926     case Type::STK_Integral:
5927       return CK_IntegralCast;
5928     case Type::STK_Floating:
5929       return CK_IntegralToFloating;
5930     case Type::STK_IntegralComplex:
5931       Src = ImpCastExprToType(Src.get(),
5932                       DestTy->castAs<ComplexType>()->getElementType(),
5933                       CK_IntegralCast);
5934       return CK_IntegralRealToComplex;
5935     case Type::STK_FloatingComplex:
5936       Src = ImpCastExprToType(Src.get(),
5937                       DestTy->castAs<ComplexType>()->getElementType(),
5938                       CK_IntegralToFloating);
5939       return CK_FloatingRealToComplex;
5940     case Type::STK_MemberPointer:
5941       llvm_unreachable("member pointer type in C");
5942     case Type::STK_FixedPoint:
5943       Diag(Src.get()->getExprLoc(),
5944            diag::err_unimplemented_conversion_with_fixed_point_type)
5945           << SrcTy;
5946       return CK_IntegralCast;
5947     }
5948     llvm_unreachable("Should have returned before this");
5949 
5950   case Type::STK_Floating:
5951     switch (DestTy->getScalarTypeKind()) {
5952     case Type::STK_Floating:
5953       return CK_FloatingCast;
5954     case Type::STK_Bool:
5955       return CK_FloatingToBoolean;
5956     case Type::STK_Integral:
5957       return CK_FloatingToIntegral;
5958     case Type::STK_FloatingComplex:
5959       Src = ImpCastExprToType(Src.get(),
5960                               DestTy->castAs<ComplexType>()->getElementType(),
5961                               CK_FloatingCast);
5962       return CK_FloatingRealToComplex;
5963     case Type::STK_IntegralComplex:
5964       Src = ImpCastExprToType(Src.get(),
5965                               DestTy->castAs<ComplexType>()->getElementType(),
5966                               CK_FloatingToIntegral);
5967       return CK_IntegralRealToComplex;
5968     case Type::STK_CPointer:
5969     case Type::STK_ObjCObjectPointer:
5970     case Type::STK_BlockPointer:
5971       llvm_unreachable("valid float->pointer cast?");
5972     case Type::STK_MemberPointer:
5973       llvm_unreachable("member pointer type in C");
5974     case Type::STK_FixedPoint:
5975       Diag(Src.get()->getExprLoc(),
5976            diag::err_unimplemented_conversion_with_fixed_point_type)
5977           << SrcTy;
5978       return CK_IntegralCast;
5979     }
5980     llvm_unreachable("Should have returned before this");
5981 
5982   case Type::STK_FloatingComplex:
5983     switch (DestTy->getScalarTypeKind()) {
5984     case Type::STK_FloatingComplex:
5985       return CK_FloatingComplexCast;
5986     case Type::STK_IntegralComplex:
5987       return CK_FloatingComplexToIntegralComplex;
5988     case Type::STK_Floating: {
5989       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5990       if (Context.hasSameType(ET, DestTy))
5991         return CK_FloatingComplexToReal;
5992       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5993       return CK_FloatingCast;
5994     }
5995     case Type::STK_Bool:
5996       return CK_FloatingComplexToBoolean;
5997     case Type::STK_Integral:
5998       Src = ImpCastExprToType(Src.get(),
5999                               SrcTy->castAs<ComplexType>()->getElementType(),
6000                               CK_FloatingComplexToReal);
6001       return CK_FloatingToIntegral;
6002     case Type::STK_CPointer:
6003     case Type::STK_ObjCObjectPointer:
6004     case Type::STK_BlockPointer:
6005       llvm_unreachable("valid complex float->pointer cast?");
6006     case Type::STK_MemberPointer:
6007       llvm_unreachable("member pointer type in C");
6008     case Type::STK_FixedPoint:
6009       Diag(Src.get()->getExprLoc(),
6010            diag::err_unimplemented_conversion_with_fixed_point_type)
6011           << SrcTy;
6012       return CK_IntegralCast;
6013     }
6014     llvm_unreachable("Should have returned before this");
6015 
6016   case Type::STK_IntegralComplex:
6017     switch (DestTy->getScalarTypeKind()) {
6018     case Type::STK_FloatingComplex:
6019       return CK_IntegralComplexToFloatingComplex;
6020     case Type::STK_IntegralComplex:
6021       return CK_IntegralComplexCast;
6022     case Type::STK_Integral: {
6023       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6024       if (Context.hasSameType(ET, DestTy))
6025         return CK_IntegralComplexToReal;
6026       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6027       return CK_IntegralCast;
6028     }
6029     case Type::STK_Bool:
6030       return CK_IntegralComplexToBoolean;
6031     case Type::STK_Floating:
6032       Src = ImpCastExprToType(Src.get(),
6033                               SrcTy->castAs<ComplexType>()->getElementType(),
6034                               CK_IntegralComplexToReal);
6035       return CK_IntegralToFloating;
6036     case Type::STK_CPointer:
6037     case Type::STK_ObjCObjectPointer:
6038     case Type::STK_BlockPointer:
6039       llvm_unreachable("valid complex int->pointer cast?");
6040     case Type::STK_MemberPointer:
6041       llvm_unreachable("member pointer type in C");
6042     case Type::STK_FixedPoint:
6043       Diag(Src.get()->getExprLoc(),
6044            diag::err_unimplemented_conversion_with_fixed_point_type)
6045           << SrcTy;
6046       return CK_IntegralCast;
6047     }
6048     llvm_unreachable("Should have returned before this");
6049   }
6050 
6051   llvm_unreachable("Unhandled scalar cast");
6052 }
6053 
6054 static bool breakDownVectorType(QualType type, uint64_t &len,
6055                                 QualType &eltType) {
6056   // Vectors are simple.
6057   if (const VectorType *vecType = type->getAs<VectorType>()) {
6058     len = vecType->getNumElements();
6059     eltType = vecType->getElementType();
6060     assert(eltType->isScalarType());
6061     return true;
6062   }
6063 
6064   // We allow lax conversion to and from non-vector types, but only if
6065   // they're real types (i.e. non-complex, non-pointer scalar types).
6066   if (!type->isRealType()) return false;
6067 
6068   len = 1;
6069   eltType = type;
6070   return true;
6071 }
6072 
6073 /// Are the two types lax-compatible vector types?  That is, given
6074 /// that one of them is a vector, do they have equal storage sizes,
6075 /// where the storage size is the number of elements times the element
6076 /// size?
6077 ///
6078 /// This will also return false if either of the types is neither a
6079 /// vector nor a real type.
6080 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6081   assert(destTy->isVectorType() || srcTy->isVectorType());
6082 
6083   // Disallow lax conversions between scalars and ExtVectors (these
6084   // conversions are allowed for other vector types because common headers
6085   // depend on them).  Most scalar OP ExtVector cases are handled by the
6086   // splat path anyway, which does what we want (convert, not bitcast).
6087   // What this rules out for ExtVectors is crazy things like char4*float.
6088   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6089   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6090 
6091   uint64_t srcLen, destLen;
6092   QualType srcEltTy, destEltTy;
6093   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6094   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6095 
6096   // ASTContext::getTypeSize will return the size rounded up to a
6097   // power of 2, so instead of using that, we need to use the raw
6098   // element size multiplied by the element count.
6099   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6100   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6101 
6102   return (srcLen * srcEltSize == destLen * destEltSize);
6103 }
6104 
6105 /// Is this a legal conversion between two types, one of which is
6106 /// known to be a vector type?
6107 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6108   assert(destTy->isVectorType() || srcTy->isVectorType());
6109 
6110   if (!Context.getLangOpts().LaxVectorConversions)
6111     return false;
6112   return areLaxCompatibleVectorTypes(srcTy, destTy);
6113 }
6114 
6115 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6116                            CastKind &Kind) {
6117   assert(VectorTy->isVectorType() && "Not a vector type!");
6118 
6119   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6120     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6121       return Diag(R.getBegin(),
6122                   Ty->isVectorType() ?
6123                   diag::err_invalid_conversion_between_vectors :
6124                   diag::err_invalid_conversion_between_vector_and_integer)
6125         << VectorTy << Ty << R;
6126   } else
6127     return Diag(R.getBegin(),
6128                 diag::err_invalid_conversion_between_vector_and_scalar)
6129       << VectorTy << Ty << R;
6130 
6131   Kind = CK_BitCast;
6132   return false;
6133 }
6134 
6135 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6136   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6137 
6138   if (DestElemTy == SplattedExpr->getType())
6139     return SplattedExpr;
6140 
6141   assert(DestElemTy->isFloatingType() ||
6142          DestElemTy->isIntegralOrEnumerationType());
6143 
6144   CastKind CK;
6145   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6146     // OpenCL requires that we convert `true` boolean expressions to -1, but
6147     // only when splatting vectors.
6148     if (DestElemTy->isFloatingType()) {
6149       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6150       // in two steps: boolean to signed integral, then to floating.
6151       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6152                                                  CK_BooleanToSignedIntegral);
6153       SplattedExpr = CastExprRes.get();
6154       CK = CK_IntegralToFloating;
6155     } else {
6156       CK = CK_BooleanToSignedIntegral;
6157     }
6158   } else {
6159     ExprResult CastExprRes = SplattedExpr;
6160     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6161     if (CastExprRes.isInvalid())
6162       return ExprError();
6163     SplattedExpr = CastExprRes.get();
6164   }
6165   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6166 }
6167 
6168 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6169                                     Expr *CastExpr, CastKind &Kind) {
6170   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6171 
6172   QualType SrcTy = CastExpr->getType();
6173 
6174   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6175   // an ExtVectorType.
6176   // In OpenCL, casts between vectors of different types are not allowed.
6177   // (See OpenCL 6.2).
6178   if (SrcTy->isVectorType()) {
6179     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6180         (getLangOpts().OpenCL &&
6181          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6182       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6183         << DestTy << SrcTy << R;
6184       return ExprError();
6185     }
6186     Kind = CK_BitCast;
6187     return CastExpr;
6188   }
6189 
6190   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6191   // conversion will take place first from scalar to elt type, and then
6192   // splat from elt type to vector.
6193   if (SrcTy->isPointerType())
6194     return Diag(R.getBegin(),
6195                 diag::err_invalid_conversion_between_vector_and_scalar)
6196       << DestTy << SrcTy << R;
6197 
6198   Kind = CK_VectorSplat;
6199   return prepareVectorSplat(DestTy, CastExpr);
6200 }
6201 
6202 ExprResult
6203 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6204                     Declarator &D, ParsedType &Ty,
6205                     SourceLocation RParenLoc, Expr *CastExpr) {
6206   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6207          "ActOnCastExpr(): missing type or expr");
6208 
6209   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6210   if (D.isInvalidType())
6211     return ExprError();
6212 
6213   if (getLangOpts().CPlusPlus) {
6214     // Check that there are no default arguments (C++ only).
6215     CheckExtraCXXDefaultArguments(D);
6216   } else {
6217     // Make sure any TypoExprs have been dealt with.
6218     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6219     if (!Res.isUsable())
6220       return ExprError();
6221     CastExpr = Res.get();
6222   }
6223 
6224   checkUnusedDeclAttributes(D);
6225 
6226   QualType castType = castTInfo->getType();
6227   Ty = CreateParsedType(castType, castTInfo);
6228 
6229   bool isVectorLiteral = false;
6230 
6231   // Check for an altivec or OpenCL literal,
6232   // i.e. all the elements are integer constants.
6233   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6234   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6235   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6236        && castType->isVectorType() && (PE || PLE)) {
6237     if (PLE && PLE->getNumExprs() == 0) {
6238       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6239       return ExprError();
6240     }
6241     if (PE || PLE->getNumExprs() == 1) {
6242       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6243       if (!E->getType()->isVectorType())
6244         isVectorLiteral = true;
6245     }
6246     else
6247       isVectorLiteral = true;
6248   }
6249 
6250   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6251   // then handle it as such.
6252   if (isVectorLiteral)
6253     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6254 
6255   // If the Expr being casted is a ParenListExpr, handle it specially.
6256   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6257   // sequence of BinOp comma operators.
6258   if (isa<ParenListExpr>(CastExpr)) {
6259     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6260     if (Result.isInvalid()) return ExprError();
6261     CastExpr = Result.get();
6262   }
6263 
6264   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6265       !getSourceManager().isInSystemMacro(LParenLoc))
6266     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6267 
6268   CheckTollFreeBridgeCast(castType, CastExpr);
6269 
6270   CheckObjCBridgeRelatedCast(castType, CastExpr);
6271 
6272   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6273 
6274   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6275 }
6276 
6277 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6278                                     SourceLocation RParenLoc, Expr *E,
6279                                     TypeSourceInfo *TInfo) {
6280   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6281          "Expected paren or paren list expression");
6282 
6283   Expr **exprs;
6284   unsigned numExprs;
6285   Expr *subExpr;
6286   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6287   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6288     LiteralLParenLoc = PE->getLParenLoc();
6289     LiteralRParenLoc = PE->getRParenLoc();
6290     exprs = PE->getExprs();
6291     numExprs = PE->getNumExprs();
6292   } else { // isa<ParenExpr> by assertion at function entrance
6293     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6294     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6295     subExpr = cast<ParenExpr>(E)->getSubExpr();
6296     exprs = &subExpr;
6297     numExprs = 1;
6298   }
6299 
6300   QualType Ty = TInfo->getType();
6301   assert(Ty->isVectorType() && "Expected vector type");
6302 
6303   SmallVector<Expr *, 8> initExprs;
6304   const VectorType *VTy = Ty->getAs<VectorType>();
6305   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6306 
6307   // '(...)' form of vector initialization in AltiVec: the number of
6308   // initializers must be one or must match the size of the vector.
6309   // If a single value is specified in the initializer then it will be
6310   // replicated to all the components of the vector
6311   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6312     // The number of initializers must be one or must match the size of the
6313     // vector. If a single value is specified in the initializer then it will
6314     // be replicated to all the components of the vector
6315     if (numExprs == 1) {
6316       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6317       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6318       if (Literal.isInvalid())
6319         return ExprError();
6320       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6321                                   PrepareScalarCast(Literal, ElemTy));
6322       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6323     }
6324     else if (numExprs < numElems) {
6325       Diag(E->getExprLoc(),
6326            diag::err_incorrect_number_of_vector_initializers);
6327       return ExprError();
6328     }
6329     else
6330       initExprs.append(exprs, exprs + numExprs);
6331   }
6332   else {
6333     // For OpenCL, when the number of initializers is a single value,
6334     // it will be replicated to all components of the vector.
6335     if (getLangOpts().OpenCL &&
6336         VTy->getVectorKind() == VectorType::GenericVector &&
6337         numExprs == 1) {
6338         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6339         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6340         if (Literal.isInvalid())
6341           return ExprError();
6342         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6343                                     PrepareScalarCast(Literal, ElemTy));
6344         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6345     }
6346 
6347     initExprs.append(exprs, exprs + numExprs);
6348   }
6349   // FIXME: This means that pretty-printing the final AST will produce curly
6350   // braces instead of the original commas.
6351   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6352                                                    initExprs, LiteralRParenLoc);
6353   initE->setType(Ty);
6354   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6355 }
6356 
6357 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6358 /// the ParenListExpr into a sequence of comma binary operators.
6359 ExprResult
6360 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6361   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6362   if (!E)
6363     return OrigExpr;
6364 
6365   ExprResult Result(E->getExpr(0));
6366 
6367   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6368     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6369                         E->getExpr(i));
6370 
6371   if (Result.isInvalid()) return ExprError();
6372 
6373   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6374 }
6375 
6376 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6377                                     SourceLocation R,
6378                                     MultiExprArg Val) {
6379   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6380   return expr;
6381 }
6382 
6383 /// Emit a specialized diagnostic when one expression is a null pointer
6384 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6385 /// emitted.
6386 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6387                                       SourceLocation QuestionLoc) {
6388   Expr *NullExpr = LHSExpr;
6389   Expr *NonPointerExpr = RHSExpr;
6390   Expr::NullPointerConstantKind NullKind =
6391       NullExpr->isNullPointerConstant(Context,
6392                                       Expr::NPC_ValueDependentIsNotNull);
6393 
6394   if (NullKind == Expr::NPCK_NotNull) {
6395     NullExpr = RHSExpr;
6396     NonPointerExpr = LHSExpr;
6397     NullKind =
6398         NullExpr->isNullPointerConstant(Context,
6399                                         Expr::NPC_ValueDependentIsNotNull);
6400   }
6401 
6402   if (NullKind == Expr::NPCK_NotNull)
6403     return false;
6404 
6405   if (NullKind == Expr::NPCK_ZeroExpression)
6406     return false;
6407 
6408   if (NullKind == Expr::NPCK_ZeroLiteral) {
6409     // In this case, check to make sure that we got here from a "NULL"
6410     // string in the source code.
6411     NullExpr = NullExpr->IgnoreParenImpCasts();
6412     SourceLocation loc = NullExpr->getExprLoc();
6413     if (!findMacroSpelling(loc, "NULL"))
6414       return false;
6415   }
6416 
6417   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6418   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6419       << NonPointerExpr->getType() << DiagType
6420       << NonPointerExpr->getSourceRange();
6421   return true;
6422 }
6423 
6424 /// Return false if the condition expression is valid, true otherwise.
6425 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6426   QualType CondTy = Cond->getType();
6427 
6428   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6429   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6430     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6431       << CondTy << Cond->getSourceRange();
6432     return true;
6433   }
6434 
6435   // C99 6.5.15p2
6436   if (CondTy->isScalarType()) return false;
6437 
6438   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6439     << CondTy << Cond->getSourceRange();
6440   return true;
6441 }
6442 
6443 /// Handle when one or both operands are void type.
6444 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6445                                          ExprResult &RHS) {
6446     Expr *LHSExpr = LHS.get();
6447     Expr *RHSExpr = RHS.get();
6448 
6449     if (!LHSExpr->getType()->isVoidType())
6450       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6451           << RHSExpr->getSourceRange();
6452     if (!RHSExpr->getType()->isVoidType())
6453       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6454           << LHSExpr->getSourceRange();
6455     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6456     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6457     return S.Context.VoidTy;
6458 }
6459 
6460 /// Return false if the NullExpr can be promoted to PointerTy,
6461 /// true otherwise.
6462 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6463                                         QualType PointerTy) {
6464   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6465       !NullExpr.get()->isNullPointerConstant(S.Context,
6466                                             Expr::NPC_ValueDependentIsNull))
6467     return true;
6468 
6469   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6470   return false;
6471 }
6472 
6473 /// Checks compatibility between two pointers and return the resulting
6474 /// type.
6475 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6476                                                      ExprResult &RHS,
6477                                                      SourceLocation Loc) {
6478   QualType LHSTy = LHS.get()->getType();
6479   QualType RHSTy = RHS.get()->getType();
6480 
6481   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6482     // Two identical pointers types are always compatible.
6483     return LHSTy;
6484   }
6485 
6486   QualType lhptee, rhptee;
6487 
6488   // Get the pointee types.
6489   bool IsBlockPointer = false;
6490   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6491     lhptee = LHSBTy->getPointeeType();
6492     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6493     IsBlockPointer = true;
6494   } else {
6495     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6496     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6497   }
6498 
6499   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6500   // differently qualified versions of compatible types, the result type is
6501   // a pointer to an appropriately qualified version of the composite
6502   // type.
6503 
6504   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6505   // clause doesn't make sense for our extensions. E.g. address space 2 should
6506   // be incompatible with address space 3: they may live on different devices or
6507   // anything.
6508   Qualifiers lhQual = lhptee.getQualifiers();
6509   Qualifiers rhQual = rhptee.getQualifiers();
6510 
6511   LangAS ResultAddrSpace = LangAS::Default;
6512   LangAS LAddrSpace = lhQual.getAddressSpace();
6513   LangAS RAddrSpace = rhQual.getAddressSpace();
6514 
6515   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6516   // spaces is disallowed.
6517   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6518     ResultAddrSpace = LAddrSpace;
6519   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6520     ResultAddrSpace = RAddrSpace;
6521   else {
6522     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6523         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6524         << RHS.get()->getSourceRange();
6525     return QualType();
6526   }
6527 
6528   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6529   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6530   lhQual.removeCVRQualifiers();
6531   rhQual.removeCVRQualifiers();
6532 
6533   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6534   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6535   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6536   // qual types are compatible iff
6537   //  * corresponded types are compatible
6538   //  * CVR qualifiers are equal
6539   //  * address spaces are equal
6540   // Thus for conditional operator we merge CVR and address space unqualified
6541   // pointees and if there is a composite type we return a pointer to it with
6542   // merged qualifiers.
6543   LHSCastKind =
6544       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6545   RHSCastKind =
6546       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6547   lhQual.removeAddressSpace();
6548   rhQual.removeAddressSpace();
6549 
6550   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6551   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6552 
6553   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6554 
6555   if (CompositeTy.isNull()) {
6556     // In this situation, we assume void* type. No especially good
6557     // reason, but this is what gcc does, and we do have to pick
6558     // to get a consistent AST.
6559     QualType incompatTy;
6560     incompatTy = S.Context.getPointerType(
6561         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6562     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6563     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6564 
6565     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6566     // for casts between types with incompatible address space qualifiers.
6567     // For the following code the compiler produces casts between global and
6568     // local address spaces of the corresponded innermost pointees:
6569     // local int *global *a;
6570     // global int *global *b;
6571     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6572     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6573         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6574         << RHS.get()->getSourceRange();
6575 
6576     return incompatTy;
6577   }
6578 
6579   // The pointer types are compatible.
6580   // In case of OpenCL ResultTy should have the address space qualifier
6581   // which is a superset of address spaces of both the 2nd and the 3rd
6582   // operands of the conditional operator.
6583   QualType ResultTy = [&, ResultAddrSpace]() {
6584     if (S.getLangOpts().OpenCL) {
6585       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6586       CompositeQuals.setAddressSpace(ResultAddrSpace);
6587       return S.Context
6588           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6589           .withCVRQualifiers(MergedCVRQual);
6590     }
6591     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6592   }();
6593   if (IsBlockPointer)
6594     ResultTy = S.Context.getBlockPointerType(ResultTy);
6595   else
6596     ResultTy = S.Context.getPointerType(ResultTy);
6597 
6598   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6599   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6600   return ResultTy;
6601 }
6602 
6603 /// Return the resulting type when the operands are both block pointers.
6604 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6605                                                           ExprResult &LHS,
6606                                                           ExprResult &RHS,
6607                                                           SourceLocation Loc) {
6608   QualType LHSTy = LHS.get()->getType();
6609   QualType RHSTy = RHS.get()->getType();
6610 
6611   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6612     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6613       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6614       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6615       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6616       return destType;
6617     }
6618     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6619       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6620       << RHS.get()->getSourceRange();
6621     return QualType();
6622   }
6623 
6624   // We have 2 block pointer types.
6625   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6626 }
6627 
6628 /// Return the resulting type when the operands are both pointers.
6629 static QualType
6630 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6631                                             ExprResult &RHS,
6632                                             SourceLocation Loc) {
6633   // get the pointer types
6634   QualType LHSTy = LHS.get()->getType();
6635   QualType RHSTy = RHS.get()->getType();
6636 
6637   // get the "pointed to" types
6638   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6639   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6640 
6641   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6642   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6643     // Figure out necessary qualifiers (C99 6.5.15p6)
6644     QualType destPointee
6645       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6646     QualType destType = S.Context.getPointerType(destPointee);
6647     // Add qualifiers if necessary.
6648     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6649     // Promote to void*.
6650     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6651     return destType;
6652   }
6653   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6654     QualType destPointee
6655       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6656     QualType destType = S.Context.getPointerType(destPointee);
6657     // Add qualifiers if necessary.
6658     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6659     // Promote to void*.
6660     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6661     return destType;
6662   }
6663 
6664   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6665 }
6666 
6667 /// Return false if the first expression is not an integer and the second
6668 /// expression is not a pointer, true otherwise.
6669 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6670                                         Expr* PointerExpr, SourceLocation Loc,
6671                                         bool IsIntFirstExpr) {
6672   if (!PointerExpr->getType()->isPointerType() ||
6673       !Int.get()->getType()->isIntegerType())
6674     return false;
6675 
6676   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6677   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6678 
6679   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6680     << Expr1->getType() << Expr2->getType()
6681     << Expr1->getSourceRange() << Expr2->getSourceRange();
6682   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6683                             CK_IntegralToPointer);
6684   return true;
6685 }
6686 
6687 /// Simple conversion between integer and floating point types.
6688 ///
6689 /// Used when handling the OpenCL conditional operator where the
6690 /// condition is a vector while the other operands are scalar.
6691 ///
6692 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6693 /// types are either integer or floating type. Between the two
6694 /// operands, the type with the higher rank is defined as the "result
6695 /// type". The other operand needs to be promoted to the same type. No
6696 /// other type promotion is allowed. We cannot use
6697 /// UsualArithmeticConversions() for this purpose, since it always
6698 /// promotes promotable types.
6699 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6700                                             ExprResult &RHS,
6701                                             SourceLocation QuestionLoc) {
6702   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6703   if (LHS.isInvalid())
6704     return QualType();
6705   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6706   if (RHS.isInvalid())
6707     return QualType();
6708 
6709   // For conversion purposes, we ignore any qualifiers.
6710   // For example, "const float" and "float" are equivalent.
6711   QualType LHSType =
6712     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6713   QualType RHSType =
6714     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6715 
6716   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6717     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6718       << LHSType << LHS.get()->getSourceRange();
6719     return QualType();
6720   }
6721 
6722   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6723     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6724       << RHSType << RHS.get()->getSourceRange();
6725     return QualType();
6726   }
6727 
6728   // If both types are identical, no conversion is needed.
6729   if (LHSType == RHSType)
6730     return LHSType;
6731 
6732   // Now handle "real" floating types (i.e. float, double, long double).
6733   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6734     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6735                                  /*IsCompAssign = */ false);
6736 
6737   // Finally, we have two differing integer types.
6738   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6739   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6740 }
6741 
6742 /// Convert scalar operands to a vector that matches the
6743 ///        condition in length.
6744 ///
6745 /// Used when handling the OpenCL conditional operator where the
6746 /// condition is a vector while the other operands are scalar.
6747 ///
6748 /// We first compute the "result type" for the scalar operands
6749 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6750 /// into a vector of that type where the length matches the condition
6751 /// vector type. s6.11.6 requires that the element types of the result
6752 /// and the condition must have the same number of bits.
6753 static QualType
6754 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6755                               QualType CondTy, SourceLocation QuestionLoc) {
6756   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6757   if (ResTy.isNull()) return QualType();
6758 
6759   const VectorType *CV = CondTy->getAs<VectorType>();
6760   assert(CV);
6761 
6762   // Determine the vector result type
6763   unsigned NumElements = CV->getNumElements();
6764   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6765 
6766   // Ensure that all types have the same number of bits
6767   if (S.Context.getTypeSize(CV->getElementType())
6768       != S.Context.getTypeSize(ResTy)) {
6769     // Since VectorTy is created internally, it does not pretty print
6770     // with an OpenCL name. Instead, we just print a description.
6771     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6772     SmallString<64> Str;
6773     llvm::raw_svector_ostream OS(Str);
6774     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6775     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6776       << CondTy << OS.str();
6777     return QualType();
6778   }
6779 
6780   // Convert operands to the vector result type
6781   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6782   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6783 
6784   return VectorTy;
6785 }
6786 
6787 /// Return false if this is a valid OpenCL condition vector
6788 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6789                                        SourceLocation QuestionLoc) {
6790   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6791   // integral type.
6792   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6793   assert(CondTy);
6794   QualType EleTy = CondTy->getElementType();
6795   if (EleTy->isIntegerType()) return false;
6796 
6797   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6798     << Cond->getType() << Cond->getSourceRange();
6799   return true;
6800 }
6801 
6802 /// Return false if the vector condition type and the vector
6803 ///        result type are compatible.
6804 ///
6805 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6806 /// number of elements, and their element types have the same number
6807 /// of bits.
6808 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6809                               SourceLocation QuestionLoc) {
6810   const VectorType *CV = CondTy->getAs<VectorType>();
6811   const VectorType *RV = VecResTy->getAs<VectorType>();
6812   assert(CV && RV);
6813 
6814   if (CV->getNumElements() != RV->getNumElements()) {
6815     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6816       << CondTy << VecResTy;
6817     return true;
6818   }
6819 
6820   QualType CVE = CV->getElementType();
6821   QualType RVE = RV->getElementType();
6822 
6823   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6824     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6825       << CondTy << VecResTy;
6826     return true;
6827   }
6828 
6829   return false;
6830 }
6831 
6832 /// Return the resulting type for the conditional operator in
6833 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6834 ///        s6.3.i) when the condition is a vector type.
6835 static QualType
6836 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6837                              ExprResult &LHS, ExprResult &RHS,
6838                              SourceLocation QuestionLoc) {
6839   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6840   if (Cond.isInvalid())
6841     return QualType();
6842   QualType CondTy = Cond.get()->getType();
6843 
6844   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6845     return QualType();
6846 
6847   // If either operand is a vector then find the vector type of the
6848   // result as specified in OpenCL v1.1 s6.3.i.
6849   if (LHS.get()->getType()->isVectorType() ||
6850       RHS.get()->getType()->isVectorType()) {
6851     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6852                                               /*isCompAssign*/false,
6853                                               /*AllowBothBool*/true,
6854                                               /*AllowBoolConversions*/false);
6855     if (VecResTy.isNull()) return QualType();
6856     // The result type must match the condition type as specified in
6857     // OpenCL v1.1 s6.11.6.
6858     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6859       return QualType();
6860     return VecResTy;
6861   }
6862 
6863   // Both operands are scalar.
6864   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6865 }
6866 
6867 /// Return true if the Expr is block type
6868 static bool checkBlockType(Sema &S, const Expr *E) {
6869   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6870     QualType Ty = CE->getCallee()->getType();
6871     if (Ty->isBlockPointerType()) {
6872       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6873       return true;
6874     }
6875   }
6876   return false;
6877 }
6878 
6879 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6880 /// In that case, LHS = cond.
6881 /// C99 6.5.15
6882 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6883                                         ExprResult &RHS, ExprValueKind &VK,
6884                                         ExprObjectKind &OK,
6885                                         SourceLocation QuestionLoc) {
6886 
6887   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6888   if (!LHSResult.isUsable()) return QualType();
6889   LHS = LHSResult;
6890 
6891   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6892   if (!RHSResult.isUsable()) return QualType();
6893   RHS = RHSResult;
6894 
6895   // C++ is sufficiently different to merit its own checker.
6896   if (getLangOpts().CPlusPlus)
6897     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6898 
6899   VK = VK_RValue;
6900   OK = OK_Ordinary;
6901 
6902   // The OpenCL operator with a vector condition is sufficiently
6903   // different to merit its own checker.
6904   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6905     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6906 
6907   // First, check the condition.
6908   Cond = UsualUnaryConversions(Cond.get());
6909   if (Cond.isInvalid())
6910     return QualType();
6911   if (checkCondition(*this, Cond.get(), QuestionLoc))
6912     return QualType();
6913 
6914   // Now check the two expressions.
6915   if (LHS.get()->getType()->isVectorType() ||
6916       RHS.get()->getType()->isVectorType())
6917     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6918                                /*AllowBothBool*/true,
6919                                /*AllowBoolConversions*/false);
6920 
6921   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6922   if (LHS.isInvalid() || RHS.isInvalid())
6923     return QualType();
6924 
6925   QualType LHSTy = LHS.get()->getType();
6926   QualType RHSTy = RHS.get()->getType();
6927 
6928   // Diagnose attempts to convert between __float128 and long double where
6929   // such conversions currently can't be handled.
6930   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6931     Diag(QuestionLoc,
6932          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6933       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6934     return QualType();
6935   }
6936 
6937   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6938   // selection operator (?:).
6939   if (getLangOpts().OpenCL &&
6940       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6941     return QualType();
6942   }
6943 
6944   // If both operands have arithmetic type, do the usual arithmetic conversions
6945   // to find a common type: C99 6.5.15p3,5.
6946   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6947     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6948     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6949 
6950     return ResTy;
6951   }
6952 
6953   // If both operands are the same structure or union type, the result is that
6954   // type.
6955   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6956     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6957       if (LHSRT->getDecl() == RHSRT->getDecl())
6958         // "If both the operands have structure or union type, the result has
6959         // that type."  This implies that CV qualifiers are dropped.
6960         return LHSTy.getUnqualifiedType();
6961     // FIXME: Type of conditional expression must be complete in C mode.
6962   }
6963 
6964   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6965   // The following || allows only one side to be void (a GCC-ism).
6966   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6967     return checkConditionalVoidType(*this, LHS, RHS);
6968   }
6969 
6970   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6971   // the type of the other operand."
6972   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6973   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6974 
6975   // All objective-c pointer type analysis is done here.
6976   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6977                                                         QuestionLoc);
6978   if (LHS.isInvalid() || RHS.isInvalid())
6979     return QualType();
6980   if (!compositeType.isNull())
6981     return compositeType;
6982 
6983 
6984   // Handle block pointer types.
6985   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6986     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6987                                                      QuestionLoc);
6988 
6989   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6990   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6991     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6992                                                        QuestionLoc);
6993 
6994   // GCC compatibility: soften pointer/integer mismatch.  Note that
6995   // null pointers have been filtered out by this point.
6996   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6997       /*isIntFirstExpr=*/true))
6998     return RHSTy;
6999   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7000       /*isIntFirstExpr=*/false))
7001     return LHSTy;
7002 
7003   // Emit a better diagnostic if one of the expressions is a null pointer
7004   // constant and the other is not a pointer type. In this case, the user most
7005   // likely forgot to take the address of the other expression.
7006   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7007     return QualType();
7008 
7009   // Otherwise, the operands are not compatible.
7010   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7011     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7012     << RHS.get()->getSourceRange();
7013   return QualType();
7014 }
7015 
7016 /// FindCompositeObjCPointerType - Helper method to find composite type of
7017 /// two objective-c pointer types of the two input expressions.
7018 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7019                                             SourceLocation QuestionLoc) {
7020   QualType LHSTy = LHS.get()->getType();
7021   QualType RHSTy = RHS.get()->getType();
7022 
7023   // Handle things like Class and struct objc_class*.  Here we case the result
7024   // to the pseudo-builtin, because that will be implicitly cast back to the
7025   // redefinition type if an attempt is made to access its fields.
7026   if (LHSTy->isObjCClassType() &&
7027       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7028     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7029     return LHSTy;
7030   }
7031   if (RHSTy->isObjCClassType() &&
7032       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7033     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7034     return RHSTy;
7035   }
7036   // And the same for struct objc_object* / id
7037   if (LHSTy->isObjCIdType() &&
7038       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7039     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7040     return LHSTy;
7041   }
7042   if (RHSTy->isObjCIdType() &&
7043       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7044     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7045     return RHSTy;
7046   }
7047   // And the same for struct objc_selector* / SEL
7048   if (Context.isObjCSelType(LHSTy) &&
7049       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7050     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7051     return LHSTy;
7052   }
7053   if (Context.isObjCSelType(RHSTy) &&
7054       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7055     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7056     return RHSTy;
7057   }
7058   // Check constraints for Objective-C object pointers types.
7059   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7060 
7061     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7062       // Two identical object pointer types are always compatible.
7063       return LHSTy;
7064     }
7065     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7066     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7067     QualType compositeType = LHSTy;
7068 
7069     // If both operands are interfaces and either operand can be
7070     // assigned to the other, use that type as the composite
7071     // type. This allows
7072     //   xxx ? (A*) a : (B*) b
7073     // where B is a subclass of A.
7074     //
7075     // Additionally, as for assignment, if either type is 'id'
7076     // allow silent coercion. Finally, if the types are
7077     // incompatible then make sure to use 'id' as the composite
7078     // type so the result is acceptable for sending messages to.
7079 
7080     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7081     // It could return the composite type.
7082     if (!(compositeType =
7083           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7084       // Nothing more to do.
7085     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7086       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7087     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7088       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7089     } else if ((LHSTy->isObjCQualifiedIdType() ||
7090                 RHSTy->isObjCQualifiedIdType()) &&
7091                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7092       // Need to handle "id<xx>" explicitly.
7093       // GCC allows qualified id and any Objective-C type to devolve to
7094       // id. Currently localizing to here until clear this should be
7095       // part of ObjCQualifiedIdTypesAreCompatible.
7096       compositeType = Context.getObjCIdType();
7097     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7098       compositeType = Context.getObjCIdType();
7099     } else {
7100       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7101       << LHSTy << RHSTy
7102       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7103       QualType incompatTy = Context.getObjCIdType();
7104       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7105       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7106       return incompatTy;
7107     }
7108     // The object pointer types are compatible.
7109     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7110     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7111     return compositeType;
7112   }
7113   // Check Objective-C object pointer types and 'void *'
7114   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7115     if (getLangOpts().ObjCAutoRefCount) {
7116       // ARC forbids the implicit conversion of object pointers to 'void *',
7117       // so these types are not compatible.
7118       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7119           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7120       LHS = RHS = true;
7121       return QualType();
7122     }
7123     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7124     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7125     QualType destPointee
7126     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7127     QualType destType = Context.getPointerType(destPointee);
7128     // Add qualifiers if necessary.
7129     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7130     // Promote to void*.
7131     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7132     return destType;
7133   }
7134   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7135     if (getLangOpts().ObjCAutoRefCount) {
7136       // ARC forbids the implicit conversion of object pointers to 'void *',
7137       // so these types are not compatible.
7138       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7139           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7140       LHS = RHS = true;
7141       return QualType();
7142     }
7143     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7144     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7145     QualType destPointee
7146     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7147     QualType destType = Context.getPointerType(destPointee);
7148     // Add qualifiers if necessary.
7149     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7150     // Promote to void*.
7151     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7152     return destType;
7153   }
7154   return QualType();
7155 }
7156 
7157 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7158 /// ParenRange in parentheses.
7159 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7160                                const PartialDiagnostic &Note,
7161                                SourceRange ParenRange) {
7162   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7163   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7164       EndLoc.isValid()) {
7165     Self.Diag(Loc, Note)
7166       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7167       << FixItHint::CreateInsertion(EndLoc, ")");
7168   } else {
7169     // We can't display the parentheses, so just show the bare note.
7170     Self.Diag(Loc, Note) << ParenRange;
7171   }
7172 }
7173 
7174 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7175   return BinaryOperator::isAdditiveOp(Opc) ||
7176          BinaryOperator::isMultiplicativeOp(Opc) ||
7177          BinaryOperator::isShiftOp(Opc);
7178 }
7179 
7180 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7181 /// expression, either using a built-in or overloaded operator,
7182 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7183 /// expression.
7184 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7185                                    Expr **RHSExprs) {
7186   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7187   E = E->IgnoreImpCasts();
7188   E = E->IgnoreConversionOperator();
7189   E = E->IgnoreImpCasts();
7190   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7191     E = MTE->GetTemporaryExpr();
7192     E = E->IgnoreImpCasts();
7193   }
7194 
7195   // Built-in binary operator.
7196   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7197     if (IsArithmeticOp(OP->getOpcode())) {
7198       *Opcode = OP->getOpcode();
7199       *RHSExprs = OP->getRHS();
7200       return true;
7201     }
7202   }
7203 
7204   // Overloaded operator.
7205   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7206     if (Call->getNumArgs() != 2)
7207       return false;
7208 
7209     // Make sure this is really a binary operator that is safe to pass into
7210     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7211     OverloadedOperatorKind OO = Call->getOperator();
7212     if (OO < OO_Plus || OO > OO_Arrow ||
7213         OO == OO_PlusPlus || OO == OO_MinusMinus)
7214       return false;
7215 
7216     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7217     if (IsArithmeticOp(OpKind)) {
7218       *Opcode = OpKind;
7219       *RHSExprs = Call->getArg(1);
7220       return true;
7221     }
7222   }
7223 
7224   return false;
7225 }
7226 
7227 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7228 /// or is a logical expression such as (x==y) which has int type, but is
7229 /// commonly interpreted as boolean.
7230 static bool ExprLooksBoolean(Expr *E) {
7231   E = E->IgnoreParenImpCasts();
7232 
7233   if (E->getType()->isBooleanType())
7234     return true;
7235   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7236     return OP->isComparisonOp() || OP->isLogicalOp();
7237   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7238     return OP->getOpcode() == UO_LNot;
7239   if (E->getType()->isPointerType())
7240     return true;
7241   // FIXME: What about overloaded operator calls returning "unspecified boolean
7242   // type"s (commonly pointer-to-members)?
7243 
7244   return false;
7245 }
7246 
7247 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7248 /// and binary operator are mixed in a way that suggests the programmer assumed
7249 /// the conditional operator has higher precedence, for example:
7250 /// "int x = a + someBinaryCondition ? 1 : 2".
7251 static void DiagnoseConditionalPrecedence(Sema &Self,
7252                                           SourceLocation OpLoc,
7253                                           Expr *Condition,
7254                                           Expr *LHSExpr,
7255                                           Expr *RHSExpr) {
7256   BinaryOperatorKind CondOpcode;
7257   Expr *CondRHS;
7258 
7259   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7260     return;
7261   if (!ExprLooksBoolean(CondRHS))
7262     return;
7263 
7264   // The condition is an arithmetic binary expression, with a right-
7265   // hand side that looks boolean, so warn.
7266 
7267   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7268       << Condition->getSourceRange()
7269       << BinaryOperator::getOpcodeStr(CondOpcode);
7270 
7271   SuggestParentheses(
7272       Self, OpLoc,
7273       Self.PDiag(diag::note_precedence_silence)
7274           << BinaryOperator::getOpcodeStr(CondOpcode),
7275       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7276 
7277   SuggestParentheses(Self, OpLoc,
7278                      Self.PDiag(diag::note_precedence_conditional_first),
7279                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7280 }
7281 
7282 /// Compute the nullability of a conditional expression.
7283 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7284                                               QualType LHSTy, QualType RHSTy,
7285                                               ASTContext &Ctx) {
7286   if (!ResTy->isAnyPointerType())
7287     return ResTy;
7288 
7289   auto GetNullability = [&Ctx](QualType Ty) {
7290     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7291     if (Kind)
7292       return *Kind;
7293     return NullabilityKind::Unspecified;
7294   };
7295 
7296   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7297   NullabilityKind MergedKind;
7298 
7299   // Compute nullability of a binary conditional expression.
7300   if (IsBin) {
7301     if (LHSKind == NullabilityKind::NonNull)
7302       MergedKind = NullabilityKind::NonNull;
7303     else
7304       MergedKind = RHSKind;
7305   // Compute nullability of a normal conditional expression.
7306   } else {
7307     if (LHSKind == NullabilityKind::Nullable ||
7308         RHSKind == NullabilityKind::Nullable)
7309       MergedKind = NullabilityKind::Nullable;
7310     else if (LHSKind == NullabilityKind::NonNull)
7311       MergedKind = RHSKind;
7312     else if (RHSKind == NullabilityKind::NonNull)
7313       MergedKind = LHSKind;
7314     else
7315       MergedKind = NullabilityKind::Unspecified;
7316   }
7317 
7318   // Return if ResTy already has the correct nullability.
7319   if (GetNullability(ResTy) == MergedKind)
7320     return ResTy;
7321 
7322   // Strip all nullability from ResTy.
7323   while (ResTy->getNullability(Ctx))
7324     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7325 
7326   // Create a new AttributedType with the new nullability kind.
7327   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7328   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7329 }
7330 
7331 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7332 /// in the case of a the GNU conditional expr extension.
7333 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7334                                     SourceLocation ColonLoc,
7335                                     Expr *CondExpr, Expr *LHSExpr,
7336                                     Expr *RHSExpr) {
7337   if (!getLangOpts().CPlusPlus) {
7338     // C cannot handle TypoExpr nodes in the condition because it
7339     // doesn't handle dependent types properly, so make sure any TypoExprs have
7340     // been dealt with before checking the operands.
7341     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7342     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7343     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7344 
7345     if (!CondResult.isUsable())
7346       return ExprError();
7347 
7348     if (LHSExpr) {
7349       if (!LHSResult.isUsable())
7350         return ExprError();
7351     }
7352 
7353     if (!RHSResult.isUsable())
7354       return ExprError();
7355 
7356     CondExpr = CondResult.get();
7357     LHSExpr = LHSResult.get();
7358     RHSExpr = RHSResult.get();
7359   }
7360 
7361   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7362   // was the condition.
7363   OpaqueValueExpr *opaqueValue = nullptr;
7364   Expr *commonExpr = nullptr;
7365   if (!LHSExpr) {
7366     commonExpr = CondExpr;
7367     // Lower out placeholder types first.  This is important so that we don't
7368     // try to capture a placeholder. This happens in few cases in C++; such
7369     // as Objective-C++'s dictionary subscripting syntax.
7370     if (commonExpr->hasPlaceholderType()) {
7371       ExprResult result = CheckPlaceholderExpr(commonExpr);
7372       if (!result.isUsable()) return ExprError();
7373       commonExpr = result.get();
7374     }
7375     // We usually want to apply unary conversions *before* saving, except
7376     // in the special case of a C++ l-value conditional.
7377     if (!(getLangOpts().CPlusPlus
7378           && !commonExpr->isTypeDependent()
7379           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7380           && commonExpr->isGLValue()
7381           && commonExpr->isOrdinaryOrBitFieldObject()
7382           && RHSExpr->isOrdinaryOrBitFieldObject()
7383           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7384       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7385       if (commonRes.isInvalid())
7386         return ExprError();
7387       commonExpr = commonRes.get();
7388     }
7389 
7390     // If the common expression is a class or array prvalue, materialize it
7391     // so that we can safely refer to it multiple times.
7392     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7393                                    commonExpr->getType()->isArrayType())) {
7394       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7395       if (MatExpr.isInvalid())
7396         return ExprError();
7397       commonExpr = MatExpr.get();
7398     }
7399 
7400     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7401                                                 commonExpr->getType(),
7402                                                 commonExpr->getValueKind(),
7403                                                 commonExpr->getObjectKind(),
7404                                                 commonExpr);
7405     LHSExpr = CondExpr = opaqueValue;
7406   }
7407 
7408   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7409   ExprValueKind VK = VK_RValue;
7410   ExprObjectKind OK = OK_Ordinary;
7411   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7412   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7413                                              VK, OK, QuestionLoc);
7414   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7415       RHS.isInvalid())
7416     return ExprError();
7417 
7418   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7419                                 RHS.get());
7420 
7421   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7422 
7423   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7424                                          Context);
7425 
7426   if (!commonExpr)
7427     return new (Context)
7428         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7429                             RHS.get(), result, VK, OK);
7430 
7431   return new (Context) BinaryConditionalOperator(
7432       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7433       ColonLoc, result, VK, OK);
7434 }
7435 
7436 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7437 // being closely modeled after the C99 spec:-). The odd characteristic of this
7438 // routine is it effectively iqnores the qualifiers on the top level pointee.
7439 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7440 // FIXME: add a couple examples in this comment.
7441 static Sema::AssignConvertType
7442 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7443   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7444   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7445 
7446   // get the "pointed to" type (ignoring qualifiers at the top level)
7447   const Type *lhptee, *rhptee;
7448   Qualifiers lhq, rhq;
7449   std::tie(lhptee, lhq) =
7450       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7451   std::tie(rhptee, rhq) =
7452       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7453 
7454   Sema::AssignConvertType ConvTy = Sema::Compatible;
7455 
7456   // C99 6.5.16.1p1: This following citation is common to constraints
7457   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7458   // qualifiers of the type *pointed to* by the right;
7459 
7460   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7461   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7462       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7463     // Ignore lifetime for further calculation.
7464     lhq.removeObjCLifetime();
7465     rhq.removeObjCLifetime();
7466   }
7467 
7468   if (!lhq.compatiblyIncludes(rhq)) {
7469     // Treat address-space mismatches as fatal.  TODO: address subspaces
7470     if (!lhq.isAddressSpaceSupersetOf(rhq))
7471       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7472 
7473     // It's okay to add or remove GC or lifetime qualifiers when converting to
7474     // and from void*.
7475     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7476                         .compatiblyIncludes(
7477                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7478              && (lhptee->isVoidType() || rhptee->isVoidType()))
7479       ; // keep old
7480 
7481     // Treat lifetime mismatches as fatal.
7482     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7483       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7484 
7485     // For GCC/MS compatibility, other qualifier mismatches are treated
7486     // as still compatible in C.
7487     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7488   }
7489 
7490   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7491   // incomplete type and the other is a pointer to a qualified or unqualified
7492   // version of void...
7493   if (lhptee->isVoidType()) {
7494     if (rhptee->isIncompleteOrObjectType())
7495       return ConvTy;
7496 
7497     // As an extension, we allow cast to/from void* to function pointer.
7498     assert(rhptee->isFunctionType());
7499     return Sema::FunctionVoidPointer;
7500   }
7501 
7502   if (rhptee->isVoidType()) {
7503     if (lhptee->isIncompleteOrObjectType())
7504       return ConvTy;
7505 
7506     // As an extension, we allow cast to/from void* to function pointer.
7507     assert(lhptee->isFunctionType());
7508     return Sema::FunctionVoidPointer;
7509   }
7510 
7511   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7512   // unqualified versions of compatible types, ...
7513   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7514   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7515     // Check if the pointee types are compatible ignoring the sign.
7516     // We explicitly check for char so that we catch "char" vs
7517     // "unsigned char" on systems where "char" is unsigned.
7518     if (lhptee->isCharType())
7519       ltrans = S.Context.UnsignedCharTy;
7520     else if (lhptee->hasSignedIntegerRepresentation())
7521       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7522 
7523     if (rhptee->isCharType())
7524       rtrans = S.Context.UnsignedCharTy;
7525     else if (rhptee->hasSignedIntegerRepresentation())
7526       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7527 
7528     if (ltrans == rtrans) {
7529       // Types are compatible ignoring the sign. Qualifier incompatibility
7530       // takes priority over sign incompatibility because the sign
7531       // warning can be disabled.
7532       if (ConvTy != Sema::Compatible)
7533         return ConvTy;
7534 
7535       return Sema::IncompatiblePointerSign;
7536     }
7537 
7538     // If we are a multi-level pointer, it's possible that our issue is simply
7539     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7540     // the eventual target type is the same and the pointers have the same
7541     // level of indirection, this must be the issue.
7542     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7543       do {
7544         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7545         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7546       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7547 
7548       if (lhptee == rhptee)
7549         return Sema::IncompatibleNestedPointerQualifiers;
7550     }
7551 
7552     // General pointer incompatibility takes priority over qualifiers.
7553     return Sema::IncompatiblePointer;
7554   }
7555   if (!S.getLangOpts().CPlusPlus &&
7556       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7557     return Sema::IncompatiblePointer;
7558   return ConvTy;
7559 }
7560 
7561 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7562 /// block pointer types are compatible or whether a block and normal pointer
7563 /// are compatible. It is more restrict than comparing two function pointer
7564 // types.
7565 static Sema::AssignConvertType
7566 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7567                                     QualType RHSType) {
7568   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7569   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7570 
7571   QualType lhptee, rhptee;
7572 
7573   // get the "pointed to" type (ignoring qualifiers at the top level)
7574   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7575   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7576 
7577   // In C++, the types have to match exactly.
7578   if (S.getLangOpts().CPlusPlus)
7579     return Sema::IncompatibleBlockPointer;
7580 
7581   Sema::AssignConvertType ConvTy = Sema::Compatible;
7582 
7583   // For blocks we enforce that qualifiers are identical.
7584   Qualifiers LQuals = lhptee.getLocalQualifiers();
7585   Qualifiers RQuals = rhptee.getLocalQualifiers();
7586   if (S.getLangOpts().OpenCL) {
7587     LQuals.removeAddressSpace();
7588     RQuals.removeAddressSpace();
7589   }
7590   if (LQuals != RQuals)
7591     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7592 
7593   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7594   // assignment.
7595   // The current behavior is similar to C++ lambdas. A block might be
7596   // assigned to a variable iff its return type and parameters are compatible
7597   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7598   // an assignment. Presumably it should behave in way that a function pointer
7599   // assignment does in C, so for each parameter and return type:
7600   //  * CVR and address space of LHS should be a superset of CVR and address
7601   //  space of RHS.
7602   //  * unqualified types should be compatible.
7603   if (S.getLangOpts().OpenCL) {
7604     if (!S.Context.typesAreBlockPointerCompatible(
7605             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7606             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7607       return Sema::IncompatibleBlockPointer;
7608   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7609     return Sema::IncompatibleBlockPointer;
7610 
7611   return ConvTy;
7612 }
7613 
7614 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7615 /// for assignment compatibility.
7616 static Sema::AssignConvertType
7617 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7618                                    QualType RHSType) {
7619   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7620   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7621 
7622   if (LHSType->isObjCBuiltinType()) {
7623     // Class is not compatible with ObjC object pointers.
7624     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7625         !RHSType->isObjCQualifiedClassType())
7626       return Sema::IncompatiblePointer;
7627     return Sema::Compatible;
7628   }
7629   if (RHSType->isObjCBuiltinType()) {
7630     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7631         !LHSType->isObjCQualifiedClassType())
7632       return Sema::IncompatiblePointer;
7633     return Sema::Compatible;
7634   }
7635   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7636   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7637 
7638   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7639       // make an exception for id<P>
7640       !LHSType->isObjCQualifiedIdType())
7641     return Sema::CompatiblePointerDiscardsQualifiers;
7642 
7643   if (S.Context.typesAreCompatible(LHSType, RHSType))
7644     return Sema::Compatible;
7645   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7646     return Sema::IncompatibleObjCQualifiedId;
7647   return Sema::IncompatiblePointer;
7648 }
7649 
7650 Sema::AssignConvertType
7651 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7652                                  QualType LHSType, QualType RHSType) {
7653   // Fake up an opaque expression.  We don't actually care about what
7654   // cast operations are required, so if CheckAssignmentConstraints
7655   // adds casts to this they'll be wasted, but fortunately that doesn't
7656   // usually happen on valid code.
7657   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7658   ExprResult RHSPtr = &RHSExpr;
7659   CastKind K;
7660 
7661   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7662 }
7663 
7664 /// This helper function returns true if QT is a vector type that has element
7665 /// type ElementType.
7666 static bool isVector(QualType QT, QualType ElementType) {
7667   if (const VectorType *VT = QT->getAs<VectorType>())
7668     return VT->getElementType() == ElementType;
7669   return false;
7670 }
7671 
7672 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7673 /// has code to accommodate several GCC extensions when type checking
7674 /// pointers. Here are some objectionable examples that GCC considers warnings:
7675 ///
7676 ///  int a, *pint;
7677 ///  short *pshort;
7678 ///  struct foo *pfoo;
7679 ///
7680 ///  pint = pshort; // warning: assignment from incompatible pointer type
7681 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7682 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7683 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7684 ///
7685 /// As a result, the code for dealing with pointers is more complex than the
7686 /// C99 spec dictates.
7687 ///
7688 /// Sets 'Kind' for any result kind except Incompatible.
7689 Sema::AssignConvertType
7690 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7691                                  CastKind &Kind, bool ConvertRHS) {
7692   QualType RHSType = RHS.get()->getType();
7693   QualType OrigLHSType = LHSType;
7694 
7695   // Get canonical types.  We're not formatting these types, just comparing
7696   // them.
7697   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7698   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7699 
7700   // Common case: no conversion required.
7701   if (LHSType == RHSType) {
7702     Kind = CK_NoOp;
7703     return Compatible;
7704   }
7705 
7706   // If we have an atomic type, try a non-atomic assignment, then just add an
7707   // atomic qualification step.
7708   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7709     Sema::AssignConvertType result =
7710       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7711     if (result != Compatible)
7712       return result;
7713     if (Kind != CK_NoOp && ConvertRHS)
7714       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7715     Kind = CK_NonAtomicToAtomic;
7716     return Compatible;
7717   }
7718 
7719   // If the left-hand side is a reference type, then we are in a
7720   // (rare!) case where we've allowed the use of references in C,
7721   // e.g., as a parameter type in a built-in function. In this case,
7722   // just make sure that the type referenced is compatible with the
7723   // right-hand side type. The caller is responsible for adjusting
7724   // LHSType so that the resulting expression does not have reference
7725   // type.
7726   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7727     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7728       Kind = CK_LValueBitCast;
7729       return Compatible;
7730     }
7731     return Incompatible;
7732   }
7733 
7734   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7735   // to the same ExtVector type.
7736   if (LHSType->isExtVectorType()) {
7737     if (RHSType->isExtVectorType())
7738       return Incompatible;
7739     if (RHSType->isArithmeticType()) {
7740       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7741       if (ConvertRHS)
7742         RHS = prepareVectorSplat(LHSType, RHS.get());
7743       Kind = CK_VectorSplat;
7744       return Compatible;
7745     }
7746   }
7747 
7748   // Conversions to or from vector type.
7749   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7750     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7751       // Allow assignments of an AltiVec vector type to an equivalent GCC
7752       // vector type and vice versa
7753       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7754         Kind = CK_BitCast;
7755         return Compatible;
7756       }
7757 
7758       // If we are allowing lax vector conversions, and LHS and RHS are both
7759       // vectors, the total size only needs to be the same. This is a bitcast;
7760       // no bits are changed but the result type is different.
7761       if (isLaxVectorConversion(RHSType, LHSType)) {
7762         Kind = CK_BitCast;
7763         return IncompatibleVectors;
7764       }
7765     }
7766 
7767     // When the RHS comes from another lax conversion (e.g. binops between
7768     // scalars and vectors) the result is canonicalized as a vector. When the
7769     // LHS is also a vector, the lax is allowed by the condition above. Handle
7770     // the case where LHS is a scalar.
7771     if (LHSType->isScalarType()) {
7772       const VectorType *VecType = RHSType->getAs<VectorType>();
7773       if (VecType && VecType->getNumElements() == 1 &&
7774           isLaxVectorConversion(RHSType, LHSType)) {
7775         ExprResult *VecExpr = &RHS;
7776         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7777         Kind = CK_BitCast;
7778         return Compatible;
7779       }
7780     }
7781 
7782     return Incompatible;
7783   }
7784 
7785   // Diagnose attempts to convert between __float128 and long double where
7786   // such conversions currently can't be handled.
7787   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7788     return Incompatible;
7789 
7790   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7791   // discards the imaginary part.
7792   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7793       !LHSType->getAs<ComplexType>())
7794     return Incompatible;
7795 
7796   // Arithmetic conversions.
7797   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7798       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7799     if (ConvertRHS)
7800       Kind = PrepareScalarCast(RHS, LHSType);
7801     return Compatible;
7802   }
7803 
7804   // Conversions to normal pointers.
7805   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7806     // U* -> T*
7807     if (isa<PointerType>(RHSType)) {
7808       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7809       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7810       if (AddrSpaceL != AddrSpaceR)
7811         Kind = CK_AddressSpaceConversion;
7812       else if (Context.hasCvrSimilarType(RHSType, LHSType))
7813         Kind = CK_NoOp;
7814       else
7815         Kind = CK_BitCast;
7816       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7817     }
7818 
7819     // int -> T*
7820     if (RHSType->isIntegerType()) {
7821       Kind = CK_IntegralToPointer; // FIXME: null?
7822       return IntToPointer;
7823     }
7824 
7825     // C pointers are not compatible with ObjC object pointers,
7826     // with two exceptions:
7827     if (isa<ObjCObjectPointerType>(RHSType)) {
7828       //  - conversions to void*
7829       if (LHSPointer->getPointeeType()->isVoidType()) {
7830         Kind = CK_BitCast;
7831         return Compatible;
7832       }
7833 
7834       //  - conversions from 'Class' to the redefinition type
7835       if (RHSType->isObjCClassType() &&
7836           Context.hasSameType(LHSType,
7837                               Context.getObjCClassRedefinitionType())) {
7838         Kind = CK_BitCast;
7839         return Compatible;
7840       }
7841 
7842       Kind = CK_BitCast;
7843       return IncompatiblePointer;
7844     }
7845 
7846     // U^ -> void*
7847     if (RHSType->getAs<BlockPointerType>()) {
7848       if (LHSPointer->getPointeeType()->isVoidType()) {
7849         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7850         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7851                                 ->getPointeeType()
7852                                 .getAddressSpace();
7853         Kind =
7854             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7855         return Compatible;
7856       }
7857     }
7858 
7859     return Incompatible;
7860   }
7861 
7862   // Conversions to block pointers.
7863   if (isa<BlockPointerType>(LHSType)) {
7864     // U^ -> T^
7865     if (RHSType->isBlockPointerType()) {
7866       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7867                               ->getPointeeType()
7868                               .getAddressSpace();
7869       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7870                               ->getPointeeType()
7871                               .getAddressSpace();
7872       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7873       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7874     }
7875 
7876     // int or null -> T^
7877     if (RHSType->isIntegerType()) {
7878       Kind = CK_IntegralToPointer; // FIXME: null
7879       return IntToBlockPointer;
7880     }
7881 
7882     // id -> T^
7883     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7884       Kind = CK_AnyPointerToBlockPointerCast;
7885       return Compatible;
7886     }
7887 
7888     // void* -> T^
7889     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7890       if (RHSPT->getPointeeType()->isVoidType()) {
7891         Kind = CK_AnyPointerToBlockPointerCast;
7892         return Compatible;
7893       }
7894 
7895     return Incompatible;
7896   }
7897 
7898   // Conversions to Objective-C pointers.
7899   if (isa<ObjCObjectPointerType>(LHSType)) {
7900     // A* -> B*
7901     if (RHSType->isObjCObjectPointerType()) {
7902       Kind = CK_BitCast;
7903       Sema::AssignConvertType result =
7904         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7905       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7906           result == Compatible &&
7907           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7908         result = IncompatibleObjCWeakRef;
7909       return result;
7910     }
7911 
7912     // int or null -> A*
7913     if (RHSType->isIntegerType()) {
7914       Kind = CK_IntegralToPointer; // FIXME: null
7915       return IntToPointer;
7916     }
7917 
7918     // In general, C pointers are not compatible with ObjC object pointers,
7919     // with two exceptions:
7920     if (isa<PointerType>(RHSType)) {
7921       Kind = CK_CPointerToObjCPointerCast;
7922 
7923       //  - conversions from 'void*'
7924       if (RHSType->isVoidPointerType()) {
7925         return Compatible;
7926       }
7927 
7928       //  - conversions to 'Class' from its redefinition type
7929       if (LHSType->isObjCClassType() &&
7930           Context.hasSameType(RHSType,
7931                               Context.getObjCClassRedefinitionType())) {
7932         return Compatible;
7933       }
7934 
7935       return IncompatiblePointer;
7936     }
7937 
7938     // Only under strict condition T^ is compatible with an Objective-C pointer.
7939     if (RHSType->isBlockPointerType() &&
7940         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7941       if (ConvertRHS)
7942         maybeExtendBlockObject(RHS);
7943       Kind = CK_BlockPointerToObjCPointerCast;
7944       return Compatible;
7945     }
7946 
7947     return Incompatible;
7948   }
7949 
7950   // Conversions from pointers that are not covered by the above.
7951   if (isa<PointerType>(RHSType)) {
7952     // T* -> _Bool
7953     if (LHSType == Context.BoolTy) {
7954       Kind = CK_PointerToBoolean;
7955       return Compatible;
7956     }
7957 
7958     // T* -> int
7959     if (LHSType->isIntegerType()) {
7960       Kind = CK_PointerToIntegral;
7961       return PointerToInt;
7962     }
7963 
7964     return Incompatible;
7965   }
7966 
7967   // Conversions from Objective-C pointers that are not covered by the above.
7968   if (isa<ObjCObjectPointerType>(RHSType)) {
7969     // T* -> _Bool
7970     if (LHSType == Context.BoolTy) {
7971       Kind = CK_PointerToBoolean;
7972       return Compatible;
7973     }
7974 
7975     // T* -> int
7976     if (LHSType->isIntegerType()) {
7977       Kind = CK_PointerToIntegral;
7978       return PointerToInt;
7979     }
7980 
7981     return Incompatible;
7982   }
7983 
7984   // struct A -> struct B
7985   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7986     if (Context.typesAreCompatible(LHSType, RHSType)) {
7987       Kind = CK_NoOp;
7988       return Compatible;
7989     }
7990   }
7991 
7992   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7993     Kind = CK_IntToOCLSampler;
7994     return Compatible;
7995   }
7996 
7997   return Incompatible;
7998 }
7999 
8000 /// Constructs a transparent union from an expression that is
8001 /// used to initialize the transparent union.
8002 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8003                                       ExprResult &EResult, QualType UnionType,
8004                                       FieldDecl *Field) {
8005   // Build an initializer list that designates the appropriate member
8006   // of the transparent union.
8007   Expr *E = EResult.get();
8008   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8009                                                    E, SourceLocation());
8010   Initializer->setType(UnionType);
8011   Initializer->setInitializedFieldInUnion(Field);
8012 
8013   // Build a compound literal constructing a value of the transparent
8014   // union type from this initializer list.
8015   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8016   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8017                                         VK_RValue, Initializer, false);
8018 }
8019 
8020 Sema::AssignConvertType
8021 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8022                                                ExprResult &RHS) {
8023   QualType RHSType = RHS.get()->getType();
8024 
8025   // If the ArgType is a Union type, we want to handle a potential
8026   // transparent_union GCC extension.
8027   const RecordType *UT = ArgType->getAsUnionType();
8028   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8029     return Incompatible;
8030 
8031   // The field to initialize within the transparent union.
8032   RecordDecl *UD = UT->getDecl();
8033   FieldDecl *InitField = nullptr;
8034   // It's compatible if the expression matches any of the fields.
8035   for (auto *it : UD->fields()) {
8036     if (it->getType()->isPointerType()) {
8037       // If the transparent union contains a pointer type, we allow:
8038       // 1) void pointer
8039       // 2) null pointer constant
8040       if (RHSType->isPointerType())
8041         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8042           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8043           InitField = it;
8044           break;
8045         }
8046 
8047       if (RHS.get()->isNullPointerConstant(Context,
8048                                            Expr::NPC_ValueDependentIsNull)) {
8049         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8050                                 CK_NullToPointer);
8051         InitField = it;
8052         break;
8053       }
8054     }
8055 
8056     CastKind Kind;
8057     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8058           == Compatible) {
8059       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8060       InitField = it;
8061       break;
8062     }
8063   }
8064 
8065   if (!InitField)
8066     return Incompatible;
8067 
8068   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8069   return Compatible;
8070 }
8071 
8072 Sema::AssignConvertType
8073 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8074                                        bool Diagnose,
8075                                        bool DiagnoseCFAudited,
8076                                        bool ConvertRHS) {
8077   // We need to be able to tell the caller whether we diagnosed a problem, if
8078   // they ask us to issue diagnostics.
8079   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8080 
8081   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8082   // we can't avoid *all* modifications at the moment, so we need some somewhere
8083   // to put the updated value.
8084   ExprResult LocalRHS = CallerRHS;
8085   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8086 
8087   if (getLangOpts().CPlusPlus) {
8088     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8089       // C++ 5.17p3: If the left operand is not of class type, the
8090       // expression is implicitly converted (C++ 4) to the
8091       // cv-unqualified type of the left operand.
8092       QualType RHSType = RHS.get()->getType();
8093       if (Diagnose) {
8094         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8095                                         AA_Assigning);
8096       } else {
8097         ImplicitConversionSequence ICS =
8098             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8099                                   /*SuppressUserConversions=*/false,
8100                                   /*AllowExplicit=*/false,
8101                                   /*InOverloadResolution=*/false,
8102                                   /*CStyle=*/false,
8103                                   /*AllowObjCWritebackConversion=*/false);
8104         if (ICS.isFailure())
8105           return Incompatible;
8106         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8107                                         ICS, AA_Assigning);
8108       }
8109       if (RHS.isInvalid())
8110         return Incompatible;
8111       Sema::AssignConvertType result = Compatible;
8112       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8113           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8114         result = IncompatibleObjCWeakRef;
8115       return result;
8116     }
8117 
8118     // FIXME: Currently, we fall through and treat C++ classes like C
8119     // structures.
8120     // FIXME: We also fall through for atomics; not sure what should
8121     // happen there, though.
8122   } else if (RHS.get()->getType() == Context.OverloadTy) {
8123     // As a set of extensions to C, we support overloading on functions. These
8124     // functions need to be resolved here.
8125     DeclAccessPair DAP;
8126     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8127             RHS.get(), LHSType, /*Complain=*/false, DAP))
8128       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8129     else
8130       return Incompatible;
8131   }
8132 
8133   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8134   // a null pointer constant.
8135   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8136        LHSType->isBlockPointerType()) &&
8137       RHS.get()->isNullPointerConstant(Context,
8138                                        Expr::NPC_ValueDependentIsNull)) {
8139     if (Diagnose || ConvertRHS) {
8140       CastKind Kind;
8141       CXXCastPath Path;
8142       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8143                              /*IgnoreBaseAccess=*/false, Diagnose);
8144       if (ConvertRHS)
8145         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8146     }
8147     return Compatible;
8148   }
8149 
8150   // OpenCL queue_t type assignment.
8151   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8152                                  Context, Expr::NPC_ValueDependentIsNull)) {
8153     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8154     return Compatible;
8155   }
8156 
8157   // This check seems unnatural, however it is necessary to ensure the proper
8158   // conversion of functions/arrays. If the conversion were done for all
8159   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8160   // expressions that suppress this implicit conversion (&, sizeof).
8161   //
8162   // Suppress this for references: C++ 8.5.3p5.
8163   if (!LHSType->isReferenceType()) {
8164     // FIXME: We potentially allocate here even if ConvertRHS is false.
8165     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8166     if (RHS.isInvalid())
8167       return Incompatible;
8168   }
8169   CastKind Kind;
8170   Sema::AssignConvertType result =
8171     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8172 
8173   // C99 6.5.16.1p2: The value of the right operand is converted to the
8174   // type of the assignment expression.
8175   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8176   // so that we can use references in built-in functions even in C.
8177   // The getNonReferenceType() call makes sure that the resulting expression
8178   // does not have reference type.
8179   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8180     QualType Ty = LHSType.getNonLValueExprType(Context);
8181     Expr *E = RHS.get();
8182 
8183     // Check for various Objective-C errors. If we are not reporting
8184     // diagnostics and just checking for errors, e.g., during overload
8185     // resolution, return Incompatible to indicate the failure.
8186     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8187         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8188                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8189       if (!Diagnose)
8190         return Incompatible;
8191     }
8192     if (getLangOpts().ObjC1 &&
8193         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8194                                            E->getType(), E, Diagnose) ||
8195          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8196       if (!Diagnose)
8197         return Incompatible;
8198       // Replace the expression with a corrected version and continue so we
8199       // can find further errors.
8200       RHS = E;
8201       return Compatible;
8202     }
8203 
8204     if (ConvertRHS)
8205       RHS = ImpCastExprToType(E, Ty, Kind);
8206   }
8207   return result;
8208 }
8209 
8210 namespace {
8211 /// The original operand to an operator, prior to the application of the usual
8212 /// arithmetic conversions and converting the arguments of a builtin operator
8213 /// candidate.
8214 struct OriginalOperand {
8215   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8216     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8217       Op = MTE->GetTemporaryExpr();
8218     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8219       Op = BTE->getSubExpr();
8220     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8221       Orig = ICE->getSubExprAsWritten();
8222       Conversion = ICE->getConversionFunction();
8223     }
8224   }
8225 
8226   QualType getType() const { return Orig->getType(); }
8227 
8228   Expr *Orig;
8229   NamedDecl *Conversion;
8230 };
8231 }
8232 
8233 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8234                                ExprResult &RHS) {
8235   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8236 
8237   Diag(Loc, diag::err_typecheck_invalid_operands)
8238     << OrigLHS.getType() << OrigRHS.getType()
8239     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8240 
8241   // If a user-defined conversion was applied to either of the operands prior
8242   // to applying the built-in operator rules, tell the user about it.
8243   if (OrigLHS.Conversion) {
8244     Diag(OrigLHS.Conversion->getLocation(),
8245          diag::note_typecheck_invalid_operands_converted)
8246       << 0 << LHS.get()->getType();
8247   }
8248   if (OrigRHS.Conversion) {
8249     Diag(OrigRHS.Conversion->getLocation(),
8250          diag::note_typecheck_invalid_operands_converted)
8251       << 1 << RHS.get()->getType();
8252   }
8253 
8254   return QualType();
8255 }
8256 
8257 // Diagnose cases where a scalar was implicitly converted to a vector and
8258 // diagnose the underlying types. Otherwise, diagnose the error
8259 // as invalid vector logical operands for non-C++ cases.
8260 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8261                                             ExprResult &RHS) {
8262   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8263   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8264 
8265   bool LHSNatVec = LHSType->isVectorType();
8266   bool RHSNatVec = RHSType->isVectorType();
8267 
8268   if (!(LHSNatVec && RHSNatVec)) {
8269     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8270     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8271     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8272         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8273         << Vector->getSourceRange();
8274     return QualType();
8275   }
8276 
8277   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8278       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8279       << RHS.get()->getSourceRange();
8280 
8281   return QualType();
8282 }
8283 
8284 /// Try to convert a value of non-vector type to a vector type by converting
8285 /// the type to the element type of the vector and then performing a splat.
8286 /// If the language is OpenCL, we only use conversions that promote scalar
8287 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8288 /// for float->int.
8289 ///
8290 /// OpenCL V2.0 6.2.6.p2:
8291 /// An error shall occur if any scalar operand type has greater rank
8292 /// than the type of the vector element.
8293 ///
8294 /// \param scalar - if non-null, actually perform the conversions
8295 /// \return true if the operation fails (but without diagnosing the failure)
8296 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8297                                      QualType scalarTy,
8298                                      QualType vectorEltTy,
8299                                      QualType vectorTy,
8300                                      unsigned &DiagID) {
8301   // The conversion to apply to the scalar before splatting it,
8302   // if necessary.
8303   CastKind scalarCast = CK_NoOp;
8304 
8305   if (vectorEltTy->isIntegralType(S.Context)) {
8306     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8307         (scalarTy->isIntegerType() &&
8308          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8309       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8310       return true;
8311     }
8312     if (!scalarTy->isIntegralType(S.Context))
8313       return true;
8314     scalarCast = CK_IntegralCast;
8315   } else if (vectorEltTy->isRealFloatingType()) {
8316     if (scalarTy->isRealFloatingType()) {
8317       if (S.getLangOpts().OpenCL &&
8318           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8319         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8320         return true;
8321       }
8322       scalarCast = CK_FloatingCast;
8323     }
8324     else if (scalarTy->isIntegralType(S.Context))
8325       scalarCast = CK_IntegralToFloating;
8326     else
8327       return true;
8328   } else {
8329     return true;
8330   }
8331 
8332   // Adjust scalar if desired.
8333   if (scalar) {
8334     if (scalarCast != CK_NoOp)
8335       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8336     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8337   }
8338   return false;
8339 }
8340 
8341 /// Convert vector E to a vector with the same number of elements but different
8342 /// element type.
8343 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8344   const auto *VecTy = E->getType()->getAs<VectorType>();
8345   assert(VecTy && "Expression E must be a vector");
8346   QualType NewVecTy = S.Context.getVectorType(ElementType,
8347                                               VecTy->getNumElements(),
8348                                               VecTy->getVectorKind());
8349 
8350   // Look through the implicit cast. Return the subexpression if its type is
8351   // NewVecTy.
8352   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8353     if (ICE->getSubExpr()->getType() == NewVecTy)
8354       return ICE->getSubExpr();
8355 
8356   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8357   return S.ImpCastExprToType(E, NewVecTy, Cast);
8358 }
8359 
8360 /// Test if a (constant) integer Int can be casted to another integer type
8361 /// IntTy without losing precision.
8362 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8363                                       QualType OtherIntTy) {
8364   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8365 
8366   // Reject cases where the value of the Int is unknown as that would
8367   // possibly cause truncation, but accept cases where the scalar can be
8368   // demoted without loss of precision.
8369   llvm::APSInt Result;
8370   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8371   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8372   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8373   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8374 
8375   if (CstInt) {
8376     // If the scalar is constant and is of a higher order and has more active
8377     // bits that the vector element type, reject it.
8378     unsigned NumBits = IntSigned
8379                            ? (Result.isNegative() ? Result.getMinSignedBits()
8380                                                   : Result.getActiveBits())
8381                            : Result.getActiveBits();
8382     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8383       return true;
8384 
8385     // If the signedness of the scalar type and the vector element type
8386     // differs and the number of bits is greater than that of the vector
8387     // element reject it.
8388     return (IntSigned != OtherIntSigned &&
8389             NumBits > S.Context.getIntWidth(OtherIntTy));
8390   }
8391 
8392   // Reject cases where the value of the scalar is not constant and it's
8393   // order is greater than that of the vector element type.
8394   return (Order < 0);
8395 }
8396 
8397 /// Test if a (constant) integer Int can be casted to floating point type
8398 /// FloatTy without losing precision.
8399 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8400                                      QualType FloatTy) {
8401   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8402 
8403   // Determine if the integer constant can be expressed as a floating point
8404   // number of the appropriate type.
8405   llvm::APSInt Result;
8406   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8407   uint64_t Bits = 0;
8408   if (CstInt) {
8409     // Reject constants that would be truncated if they were converted to
8410     // the floating point type. Test by simple to/from conversion.
8411     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8412     //        could be avoided if there was a convertFromAPInt method
8413     //        which could signal back if implicit truncation occurred.
8414     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8415     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8416                            llvm::APFloat::rmTowardZero);
8417     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8418                              !IntTy->hasSignedIntegerRepresentation());
8419     bool Ignored = false;
8420     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8421                            &Ignored);
8422     if (Result != ConvertBack)
8423       return true;
8424   } else {
8425     // Reject types that cannot be fully encoded into the mantissa of
8426     // the float.
8427     Bits = S.Context.getTypeSize(IntTy);
8428     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8429         S.Context.getFloatTypeSemantics(FloatTy));
8430     if (Bits > FloatPrec)
8431       return true;
8432   }
8433 
8434   return false;
8435 }
8436 
8437 /// Attempt to convert and splat Scalar into a vector whose types matches
8438 /// Vector following GCC conversion rules. The rule is that implicit
8439 /// conversion can occur when Scalar can be casted to match Vector's element
8440 /// type without causing truncation of Scalar.
8441 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8442                                         ExprResult *Vector) {
8443   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8444   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8445   const VectorType *VT = VectorTy->getAs<VectorType>();
8446 
8447   assert(!isa<ExtVectorType>(VT) &&
8448          "ExtVectorTypes should not be handled here!");
8449 
8450   QualType VectorEltTy = VT->getElementType();
8451 
8452   // Reject cases where the vector element type or the scalar element type are
8453   // not integral or floating point types.
8454   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8455     return true;
8456 
8457   // The conversion to apply to the scalar before splatting it,
8458   // if necessary.
8459   CastKind ScalarCast = CK_NoOp;
8460 
8461   // Accept cases where the vector elements are integers and the scalar is
8462   // an integer.
8463   // FIXME: Notionally if the scalar was a floating point value with a precise
8464   //        integral representation, we could cast it to an appropriate integer
8465   //        type and then perform the rest of the checks here. GCC will perform
8466   //        this conversion in some cases as determined by the input language.
8467   //        We should accept it on a language independent basis.
8468   if (VectorEltTy->isIntegralType(S.Context) &&
8469       ScalarTy->isIntegralType(S.Context) &&
8470       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8471 
8472     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8473       return true;
8474 
8475     ScalarCast = CK_IntegralCast;
8476   } else if (VectorEltTy->isRealFloatingType()) {
8477     if (ScalarTy->isRealFloatingType()) {
8478 
8479       // Reject cases where the scalar type is not a constant and has a higher
8480       // Order than the vector element type.
8481       llvm::APFloat Result(0.0);
8482       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8483       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8484       if (!CstScalar && Order < 0)
8485         return true;
8486 
8487       // If the scalar cannot be safely casted to the vector element type,
8488       // reject it.
8489       if (CstScalar) {
8490         bool Truncated = false;
8491         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8492                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8493         if (Truncated)
8494           return true;
8495       }
8496 
8497       ScalarCast = CK_FloatingCast;
8498     } else if (ScalarTy->isIntegralType(S.Context)) {
8499       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8500         return true;
8501 
8502       ScalarCast = CK_IntegralToFloating;
8503     } else
8504       return true;
8505   }
8506 
8507   // Adjust scalar if desired.
8508   if (Scalar) {
8509     if (ScalarCast != CK_NoOp)
8510       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8511     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8512   }
8513   return false;
8514 }
8515 
8516 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8517                                    SourceLocation Loc, bool IsCompAssign,
8518                                    bool AllowBothBool,
8519                                    bool AllowBoolConversions) {
8520   if (!IsCompAssign) {
8521     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8522     if (LHS.isInvalid())
8523       return QualType();
8524   }
8525   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8526   if (RHS.isInvalid())
8527     return QualType();
8528 
8529   // For conversion purposes, we ignore any qualifiers.
8530   // For example, "const float" and "float" are equivalent.
8531   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8532   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8533 
8534   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8535   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8536   assert(LHSVecType || RHSVecType);
8537 
8538   // AltiVec-style "vector bool op vector bool" combinations are allowed
8539   // for some operators but not others.
8540   if (!AllowBothBool &&
8541       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8542       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8543     return InvalidOperands(Loc, LHS, RHS);
8544 
8545   // If the vector types are identical, return.
8546   if (Context.hasSameType(LHSType, RHSType))
8547     return LHSType;
8548 
8549   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8550   if (LHSVecType && RHSVecType &&
8551       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8552     if (isa<ExtVectorType>(LHSVecType)) {
8553       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8554       return LHSType;
8555     }
8556 
8557     if (!IsCompAssign)
8558       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8559     return RHSType;
8560   }
8561 
8562   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8563   // can be mixed, with the result being the non-bool type.  The non-bool
8564   // operand must have integer element type.
8565   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8566       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8567       (Context.getTypeSize(LHSVecType->getElementType()) ==
8568        Context.getTypeSize(RHSVecType->getElementType()))) {
8569     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8570         LHSVecType->getElementType()->isIntegerType() &&
8571         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8572       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8573       return LHSType;
8574     }
8575     if (!IsCompAssign &&
8576         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8577         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8578         RHSVecType->getElementType()->isIntegerType()) {
8579       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8580       return RHSType;
8581     }
8582   }
8583 
8584   // If there's a vector type and a scalar, try to convert the scalar to
8585   // the vector element type and splat.
8586   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8587   if (!RHSVecType) {
8588     if (isa<ExtVectorType>(LHSVecType)) {
8589       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8590                                     LHSVecType->getElementType(), LHSType,
8591                                     DiagID))
8592         return LHSType;
8593     } else {
8594       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8595         return LHSType;
8596     }
8597   }
8598   if (!LHSVecType) {
8599     if (isa<ExtVectorType>(RHSVecType)) {
8600       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8601                                     LHSType, RHSVecType->getElementType(),
8602                                     RHSType, DiagID))
8603         return RHSType;
8604     } else {
8605       if (LHS.get()->getValueKind() == VK_LValue ||
8606           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8607         return RHSType;
8608     }
8609   }
8610 
8611   // FIXME: The code below also handles conversion between vectors and
8612   // non-scalars, we should break this down into fine grained specific checks
8613   // and emit proper diagnostics.
8614   QualType VecType = LHSVecType ? LHSType : RHSType;
8615   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8616   QualType OtherType = LHSVecType ? RHSType : LHSType;
8617   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8618   if (isLaxVectorConversion(OtherType, VecType)) {
8619     // If we're allowing lax vector conversions, only the total (data) size
8620     // needs to be the same. For non compound assignment, if one of the types is
8621     // scalar, the result is always the vector type.
8622     if (!IsCompAssign) {
8623       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8624       return VecType;
8625     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8626     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8627     // type. Note that this is already done by non-compound assignments in
8628     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8629     // <1 x T> -> T. The result is also a vector type.
8630     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8631                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8632       ExprResult *RHSExpr = &RHS;
8633       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8634       return VecType;
8635     }
8636   }
8637 
8638   // Okay, the expression is invalid.
8639 
8640   // If there's a non-vector, non-real operand, diagnose that.
8641   if ((!RHSVecType && !RHSType->isRealType()) ||
8642       (!LHSVecType && !LHSType->isRealType())) {
8643     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8644       << LHSType << RHSType
8645       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8646     return QualType();
8647   }
8648 
8649   // OpenCL V1.1 6.2.6.p1:
8650   // If the operands are of more than one vector type, then an error shall
8651   // occur. Implicit conversions between vector types are not permitted, per
8652   // section 6.2.1.
8653   if (getLangOpts().OpenCL &&
8654       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8655       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8656     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8657                                                            << RHSType;
8658     return QualType();
8659   }
8660 
8661 
8662   // If there is a vector type that is not a ExtVector and a scalar, we reach
8663   // this point if scalar could not be converted to the vector's element type
8664   // without truncation.
8665   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8666       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8667     QualType Scalar = LHSVecType ? RHSType : LHSType;
8668     QualType Vector = LHSVecType ? LHSType : RHSType;
8669     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8670     Diag(Loc,
8671          diag::err_typecheck_vector_not_convertable_implict_truncation)
8672         << ScalarOrVector << Scalar << Vector;
8673 
8674     return QualType();
8675   }
8676 
8677   // Otherwise, use the generic diagnostic.
8678   Diag(Loc, DiagID)
8679     << LHSType << RHSType
8680     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8681   return QualType();
8682 }
8683 
8684 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8685 // expression.  These are mainly cases where the null pointer is used as an
8686 // integer instead of a pointer.
8687 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8688                                 SourceLocation Loc, bool IsCompare) {
8689   // The canonical way to check for a GNU null is with isNullPointerConstant,
8690   // but we use a bit of a hack here for speed; this is a relatively
8691   // hot path, and isNullPointerConstant is slow.
8692   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8693   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8694 
8695   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8696 
8697   // Avoid analyzing cases where the result will either be invalid (and
8698   // diagnosed as such) or entirely valid and not something to warn about.
8699   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8700       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8701     return;
8702 
8703   // Comparison operations would not make sense with a null pointer no matter
8704   // what the other expression is.
8705   if (!IsCompare) {
8706     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8707         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8708         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8709     return;
8710   }
8711 
8712   // The rest of the operations only make sense with a null pointer
8713   // if the other expression is a pointer.
8714   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8715       NonNullType->canDecayToPointerType())
8716     return;
8717 
8718   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8719       << LHSNull /* LHS is NULL */ << NonNullType
8720       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8721 }
8722 
8723 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8724                                                ExprResult &RHS,
8725                                                SourceLocation Loc, bool IsDiv) {
8726   // Check for division/remainder by zero.
8727   llvm::APSInt RHSValue;
8728   if (!RHS.get()->isValueDependent() &&
8729       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8730     S.DiagRuntimeBehavior(Loc, RHS.get(),
8731                           S.PDiag(diag::warn_remainder_division_by_zero)
8732                             << IsDiv << RHS.get()->getSourceRange());
8733 }
8734 
8735 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8736                                            SourceLocation Loc,
8737                                            bool IsCompAssign, bool IsDiv) {
8738   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8739 
8740   if (LHS.get()->getType()->isVectorType() ||
8741       RHS.get()->getType()->isVectorType())
8742     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8743                                /*AllowBothBool*/getLangOpts().AltiVec,
8744                                /*AllowBoolConversions*/false);
8745 
8746   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8747   if (LHS.isInvalid() || RHS.isInvalid())
8748     return QualType();
8749 
8750 
8751   if (compType.isNull() || !compType->isArithmeticType())
8752     return InvalidOperands(Loc, LHS, RHS);
8753   if (IsDiv)
8754     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8755   return compType;
8756 }
8757 
8758 QualType Sema::CheckRemainderOperands(
8759   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8760   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8761 
8762   if (LHS.get()->getType()->isVectorType() ||
8763       RHS.get()->getType()->isVectorType()) {
8764     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8765         RHS.get()->getType()->hasIntegerRepresentation())
8766       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8767                                  /*AllowBothBool*/getLangOpts().AltiVec,
8768                                  /*AllowBoolConversions*/false);
8769     return InvalidOperands(Loc, LHS, RHS);
8770   }
8771 
8772   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8773   if (LHS.isInvalid() || RHS.isInvalid())
8774     return QualType();
8775 
8776   if (compType.isNull() || !compType->isIntegerType())
8777     return InvalidOperands(Loc, LHS, RHS);
8778   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8779   return compType;
8780 }
8781 
8782 /// Diagnose invalid arithmetic on two void pointers.
8783 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8784                                                 Expr *LHSExpr, Expr *RHSExpr) {
8785   S.Diag(Loc, S.getLangOpts().CPlusPlus
8786                 ? diag::err_typecheck_pointer_arith_void_type
8787                 : diag::ext_gnu_void_ptr)
8788     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8789                             << RHSExpr->getSourceRange();
8790 }
8791 
8792 /// Diagnose invalid arithmetic on a void pointer.
8793 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8794                                             Expr *Pointer) {
8795   S.Diag(Loc, S.getLangOpts().CPlusPlus
8796                 ? diag::err_typecheck_pointer_arith_void_type
8797                 : diag::ext_gnu_void_ptr)
8798     << 0 /* one pointer */ << Pointer->getSourceRange();
8799 }
8800 
8801 /// Diagnose invalid arithmetic on a null pointer.
8802 ///
8803 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8804 /// idiom, which we recognize as a GNU extension.
8805 ///
8806 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8807                                             Expr *Pointer, bool IsGNUIdiom) {
8808   if (IsGNUIdiom)
8809     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8810       << Pointer->getSourceRange();
8811   else
8812     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8813       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8814 }
8815 
8816 /// Diagnose invalid arithmetic on two function pointers.
8817 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8818                                                     Expr *LHS, Expr *RHS) {
8819   assert(LHS->getType()->isAnyPointerType());
8820   assert(RHS->getType()->isAnyPointerType());
8821   S.Diag(Loc, S.getLangOpts().CPlusPlus
8822                 ? diag::err_typecheck_pointer_arith_function_type
8823                 : diag::ext_gnu_ptr_func_arith)
8824     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8825     // We only show the second type if it differs from the first.
8826     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8827                                                    RHS->getType())
8828     << RHS->getType()->getPointeeType()
8829     << LHS->getSourceRange() << RHS->getSourceRange();
8830 }
8831 
8832 /// Diagnose invalid arithmetic on a function pointer.
8833 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8834                                                 Expr *Pointer) {
8835   assert(Pointer->getType()->isAnyPointerType());
8836   S.Diag(Loc, S.getLangOpts().CPlusPlus
8837                 ? diag::err_typecheck_pointer_arith_function_type
8838                 : diag::ext_gnu_ptr_func_arith)
8839     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8840     << 0 /* one pointer, so only one type */
8841     << Pointer->getSourceRange();
8842 }
8843 
8844 /// Emit error if Operand is incomplete pointer type
8845 ///
8846 /// \returns True if pointer has incomplete type
8847 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8848                                                  Expr *Operand) {
8849   QualType ResType = Operand->getType();
8850   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8851     ResType = ResAtomicType->getValueType();
8852 
8853   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8854   QualType PointeeTy = ResType->getPointeeType();
8855   return S.RequireCompleteType(Loc, PointeeTy,
8856                                diag::err_typecheck_arithmetic_incomplete_type,
8857                                PointeeTy, Operand->getSourceRange());
8858 }
8859 
8860 /// Check the validity of an arithmetic pointer operand.
8861 ///
8862 /// If the operand has pointer type, this code will check for pointer types
8863 /// which are invalid in arithmetic operations. These will be diagnosed
8864 /// appropriately, including whether or not the use is supported as an
8865 /// extension.
8866 ///
8867 /// \returns True when the operand is valid to use (even if as an extension).
8868 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8869                                             Expr *Operand) {
8870   QualType ResType = Operand->getType();
8871   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8872     ResType = ResAtomicType->getValueType();
8873 
8874   if (!ResType->isAnyPointerType()) return true;
8875 
8876   QualType PointeeTy = ResType->getPointeeType();
8877   if (PointeeTy->isVoidType()) {
8878     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8879     return !S.getLangOpts().CPlusPlus;
8880   }
8881   if (PointeeTy->isFunctionType()) {
8882     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8883     return !S.getLangOpts().CPlusPlus;
8884   }
8885 
8886   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8887 
8888   return true;
8889 }
8890 
8891 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8892 /// operands.
8893 ///
8894 /// This routine will diagnose any invalid arithmetic on pointer operands much
8895 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8896 /// for emitting a single diagnostic even for operations where both LHS and RHS
8897 /// are (potentially problematic) pointers.
8898 ///
8899 /// \returns True when the operand is valid to use (even if as an extension).
8900 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8901                                                 Expr *LHSExpr, Expr *RHSExpr) {
8902   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8903   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8904   if (!isLHSPointer && !isRHSPointer) return true;
8905 
8906   QualType LHSPointeeTy, RHSPointeeTy;
8907   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8908   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8909 
8910   // if both are pointers check if operation is valid wrt address spaces
8911   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8912     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8913     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8914     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8915       S.Diag(Loc,
8916              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8917           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8918           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8919       return false;
8920     }
8921   }
8922 
8923   // Check for arithmetic on pointers to incomplete types.
8924   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8925   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8926   if (isLHSVoidPtr || isRHSVoidPtr) {
8927     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8928     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8929     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8930 
8931     return !S.getLangOpts().CPlusPlus;
8932   }
8933 
8934   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8935   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8936   if (isLHSFuncPtr || isRHSFuncPtr) {
8937     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8938     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8939                                                                 RHSExpr);
8940     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8941 
8942     return !S.getLangOpts().CPlusPlus;
8943   }
8944 
8945   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8946     return false;
8947   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8948     return false;
8949 
8950   return true;
8951 }
8952 
8953 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8954 /// literal.
8955 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8956                                   Expr *LHSExpr, Expr *RHSExpr) {
8957   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8958   Expr* IndexExpr = RHSExpr;
8959   if (!StrExpr) {
8960     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8961     IndexExpr = LHSExpr;
8962   }
8963 
8964   bool IsStringPlusInt = StrExpr &&
8965       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8966   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8967     return;
8968 
8969   llvm::APSInt index;
8970   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8971     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8972     if (index.isNonNegative() &&
8973         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8974                               index.isUnsigned()))
8975       return;
8976   }
8977 
8978   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
8979   Self.Diag(OpLoc, diag::warn_string_plus_int)
8980       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8981 
8982   // Only print a fixit for "str" + int, not for int + "str".
8983   if (IndexExpr == RHSExpr) {
8984     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
8985     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8986         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
8987         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8988         << FixItHint::CreateInsertion(EndLoc, "]");
8989   } else
8990     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8991 }
8992 
8993 /// Emit a warning when adding a char literal to a string.
8994 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8995                                    Expr *LHSExpr, Expr *RHSExpr) {
8996   const Expr *StringRefExpr = LHSExpr;
8997   const CharacterLiteral *CharExpr =
8998       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8999 
9000   if (!CharExpr) {
9001     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9002     StringRefExpr = RHSExpr;
9003   }
9004 
9005   if (!CharExpr || !StringRefExpr)
9006     return;
9007 
9008   const QualType StringType = StringRefExpr->getType();
9009 
9010   // Return if not a PointerType.
9011   if (!StringType->isAnyPointerType())
9012     return;
9013 
9014   // Return if not a CharacterType.
9015   if (!StringType->getPointeeType()->isAnyCharacterType())
9016     return;
9017 
9018   ASTContext &Ctx = Self.getASTContext();
9019   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9020 
9021   const QualType CharType = CharExpr->getType();
9022   if (!CharType->isAnyCharacterType() &&
9023       CharType->isIntegerType() &&
9024       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9025     Self.Diag(OpLoc, diag::warn_string_plus_char)
9026         << DiagRange << Ctx.CharTy;
9027   } else {
9028     Self.Diag(OpLoc, diag::warn_string_plus_char)
9029         << DiagRange << CharExpr->getType();
9030   }
9031 
9032   // Only print a fixit for str + char, not for char + str.
9033   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9034     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9035     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9036         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9037         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9038         << FixItHint::CreateInsertion(EndLoc, "]");
9039   } else {
9040     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9041   }
9042 }
9043 
9044 /// Emit error when two pointers are incompatible.
9045 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9046                                            Expr *LHSExpr, Expr *RHSExpr) {
9047   assert(LHSExpr->getType()->isAnyPointerType());
9048   assert(RHSExpr->getType()->isAnyPointerType());
9049   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9050     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9051     << RHSExpr->getSourceRange();
9052 }
9053 
9054 // C99 6.5.6
9055 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9056                                      SourceLocation Loc, BinaryOperatorKind Opc,
9057                                      QualType* CompLHSTy) {
9058   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9059 
9060   if (LHS.get()->getType()->isVectorType() ||
9061       RHS.get()->getType()->isVectorType()) {
9062     QualType compType = CheckVectorOperands(
9063         LHS, RHS, Loc, CompLHSTy,
9064         /*AllowBothBool*/getLangOpts().AltiVec,
9065         /*AllowBoolConversions*/getLangOpts().ZVector);
9066     if (CompLHSTy) *CompLHSTy = compType;
9067     return compType;
9068   }
9069 
9070   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9071   if (LHS.isInvalid() || RHS.isInvalid())
9072     return QualType();
9073 
9074   // Diagnose "string literal" '+' int and string '+' "char literal".
9075   if (Opc == BO_Add) {
9076     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9077     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9078   }
9079 
9080   // handle the common case first (both operands are arithmetic).
9081   if (!compType.isNull() && compType->isArithmeticType()) {
9082     if (CompLHSTy) *CompLHSTy = compType;
9083     return compType;
9084   }
9085 
9086   // Type-checking.  Ultimately the pointer's going to be in PExp;
9087   // note that we bias towards the LHS being the pointer.
9088   Expr *PExp = LHS.get(), *IExp = RHS.get();
9089 
9090   bool isObjCPointer;
9091   if (PExp->getType()->isPointerType()) {
9092     isObjCPointer = false;
9093   } else if (PExp->getType()->isObjCObjectPointerType()) {
9094     isObjCPointer = true;
9095   } else {
9096     std::swap(PExp, IExp);
9097     if (PExp->getType()->isPointerType()) {
9098       isObjCPointer = false;
9099     } else if (PExp->getType()->isObjCObjectPointerType()) {
9100       isObjCPointer = true;
9101     } else {
9102       return InvalidOperands(Loc, LHS, RHS);
9103     }
9104   }
9105   assert(PExp->getType()->isAnyPointerType());
9106 
9107   if (!IExp->getType()->isIntegerType())
9108     return InvalidOperands(Loc, LHS, RHS);
9109 
9110   // Adding to a null pointer results in undefined behavior.
9111   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9112           Context, Expr::NPC_ValueDependentIsNotNull)) {
9113     // In C++ adding zero to a null pointer is defined.
9114     llvm::APSInt KnownVal;
9115     if (!getLangOpts().CPlusPlus ||
9116         (!IExp->isValueDependent() &&
9117          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9118       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9119       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9120           Context, BO_Add, PExp, IExp);
9121       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9122     }
9123   }
9124 
9125   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9126     return QualType();
9127 
9128   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9129     return QualType();
9130 
9131   // Check array bounds for pointer arithemtic
9132   CheckArrayAccess(PExp, IExp);
9133 
9134   if (CompLHSTy) {
9135     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9136     if (LHSTy.isNull()) {
9137       LHSTy = LHS.get()->getType();
9138       if (LHSTy->isPromotableIntegerType())
9139         LHSTy = Context.getPromotedIntegerType(LHSTy);
9140     }
9141     *CompLHSTy = LHSTy;
9142   }
9143 
9144   return PExp->getType();
9145 }
9146 
9147 // C99 6.5.6
9148 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9149                                         SourceLocation Loc,
9150                                         QualType* CompLHSTy) {
9151   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9152 
9153   if (LHS.get()->getType()->isVectorType() ||
9154       RHS.get()->getType()->isVectorType()) {
9155     QualType compType = CheckVectorOperands(
9156         LHS, RHS, Loc, CompLHSTy,
9157         /*AllowBothBool*/getLangOpts().AltiVec,
9158         /*AllowBoolConversions*/getLangOpts().ZVector);
9159     if (CompLHSTy) *CompLHSTy = compType;
9160     return compType;
9161   }
9162 
9163   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9164   if (LHS.isInvalid() || RHS.isInvalid())
9165     return QualType();
9166 
9167   // Enforce type constraints: C99 6.5.6p3.
9168 
9169   // Handle the common case first (both operands are arithmetic).
9170   if (!compType.isNull() && compType->isArithmeticType()) {
9171     if (CompLHSTy) *CompLHSTy = compType;
9172     return compType;
9173   }
9174 
9175   // Either ptr - int   or   ptr - ptr.
9176   if (LHS.get()->getType()->isAnyPointerType()) {
9177     QualType lpointee = LHS.get()->getType()->getPointeeType();
9178 
9179     // Diagnose bad cases where we step over interface counts.
9180     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9181         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9182       return QualType();
9183 
9184     // The result type of a pointer-int computation is the pointer type.
9185     if (RHS.get()->getType()->isIntegerType()) {
9186       // Subtracting from a null pointer should produce a warning.
9187       // The last argument to the diagnose call says this doesn't match the
9188       // GNU int-to-pointer idiom.
9189       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9190                                            Expr::NPC_ValueDependentIsNotNull)) {
9191         // In C++ adding zero to a null pointer is defined.
9192         llvm::APSInt KnownVal;
9193         if (!getLangOpts().CPlusPlus ||
9194             (!RHS.get()->isValueDependent() &&
9195              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9196           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9197         }
9198       }
9199 
9200       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9201         return QualType();
9202 
9203       // Check array bounds for pointer arithemtic
9204       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9205                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9206 
9207       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9208       return LHS.get()->getType();
9209     }
9210 
9211     // Handle pointer-pointer subtractions.
9212     if (const PointerType *RHSPTy
9213           = RHS.get()->getType()->getAs<PointerType>()) {
9214       QualType rpointee = RHSPTy->getPointeeType();
9215 
9216       if (getLangOpts().CPlusPlus) {
9217         // Pointee types must be the same: C++ [expr.add]
9218         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9219           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9220         }
9221       } else {
9222         // Pointee types must be compatible C99 6.5.6p3
9223         if (!Context.typesAreCompatible(
9224                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9225                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9226           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9227           return QualType();
9228         }
9229       }
9230 
9231       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9232                                                LHS.get(), RHS.get()))
9233         return QualType();
9234 
9235       // FIXME: Add warnings for nullptr - ptr.
9236 
9237       // The pointee type may have zero size.  As an extension, a structure or
9238       // union may have zero size or an array may have zero length.  In this
9239       // case subtraction does not make sense.
9240       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9241         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9242         if (ElementSize.isZero()) {
9243           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9244             << rpointee.getUnqualifiedType()
9245             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9246         }
9247       }
9248 
9249       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9250       return Context.getPointerDiffType();
9251     }
9252   }
9253 
9254   return InvalidOperands(Loc, LHS, RHS);
9255 }
9256 
9257 static bool isScopedEnumerationType(QualType T) {
9258   if (const EnumType *ET = T->getAs<EnumType>())
9259     return ET->getDecl()->isScoped();
9260   return false;
9261 }
9262 
9263 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9264                                    SourceLocation Loc, BinaryOperatorKind Opc,
9265                                    QualType LHSType) {
9266   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9267   // so skip remaining warnings as we don't want to modify values within Sema.
9268   if (S.getLangOpts().OpenCL)
9269     return;
9270 
9271   llvm::APSInt Right;
9272   // Check right/shifter operand
9273   if (RHS.get()->isValueDependent() ||
9274       !RHS.get()->EvaluateAsInt(Right, S.Context))
9275     return;
9276 
9277   if (Right.isNegative()) {
9278     S.DiagRuntimeBehavior(Loc, RHS.get(),
9279                           S.PDiag(diag::warn_shift_negative)
9280                             << RHS.get()->getSourceRange());
9281     return;
9282   }
9283   llvm::APInt LeftBits(Right.getBitWidth(),
9284                        S.Context.getTypeSize(LHS.get()->getType()));
9285   if (Right.uge(LeftBits)) {
9286     S.DiagRuntimeBehavior(Loc, RHS.get(),
9287                           S.PDiag(diag::warn_shift_gt_typewidth)
9288                             << RHS.get()->getSourceRange());
9289     return;
9290   }
9291   if (Opc != BO_Shl)
9292     return;
9293 
9294   // When left shifting an ICE which is signed, we can check for overflow which
9295   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9296   // integers have defined behavior modulo one more than the maximum value
9297   // representable in the result type, so never warn for those.
9298   llvm::APSInt Left;
9299   if (LHS.get()->isValueDependent() ||
9300       LHSType->hasUnsignedIntegerRepresentation() ||
9301       !LHS.get()->EvaluateAsInt(Left, S.Context))
9302     return;
9303 
9304   // If LHS does not have a signed type and non-negative value
9305   // then, the behavior is undefined. Warn about it.
9306   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9307     S.DiagRuntimeBehavior(Loc, LHS.get(),
9308                           S.PDiag(diag::warn_shift_lhs_negative)
9309                             << LHS.get()->getSourceRange());
9310     return;
9311   }
9312 
9313   llvm::APInt ResultBits =
9314       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9315   if (LeftBits.uge(ResultBits))
9316     return;
9317   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9318   Result = Result.shl(Right);
9319 
9320   // Print the bit representation of the signed integer as an unsigned
9321   // hexadecimal number.
9322   SmallString<40> HexResult;
9323   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9324 
9325   // If we are only missing a sign bit, this is less likely to result in actual
9326   // bugs -- if the result is cast back to an unsigned type, it will have the
9327   // expected value. Thus we place this behind a different warning that can be
9328   // turned off separately if needed.
9329   if (LeftBits == ResultBits - 1) {
9330     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9331         << HexResult << LHSType
9332         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9333     return;
9334   }
9335 
9336   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9337     << HexResult.str() << Result.getMinSignedBits() << LHSType
9338     << Left.getBitWidth() << LHS.get()->getSourceRange()
9339     << RHS.get()->getSourceRange();
9340 }
9341 
9342 /// Return the resulting type when a vector is shifted
9343 ///        by a scalar or vector shift amount.
9344 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9345                                  SourceLocation Loc, bool IsCompAssign) {
9346   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9347   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9348       !LHS.get()->getType()->isVectorType()) {
9349     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9350       << RHS.get()->getType() << LHS.get()->getType()
9351       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9352     return QualType();
9353   }
9354 
9355   if (!IsCompAssign) {
9356     LHS = S.UsualUnaryConversions(LHS.get());
9357     if (LHS.isInvalid()) return QualType();
9358   }
9359 
9360   RHS = S.UsualUnaryConversions(RHS.get());
9361   if (RHS.isInvalid()) return QualType();
9362 
9363   QualType LHSType = LHS.get()->getType();
9364   // Note that LHS might be a scalar because the routine calls not only in
9365   // OpenCL case.
9366   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9367   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9368 
9369   // Note that RHS might not be a vector.
9370   QualType RHSType = RHS.get()->getType();
9371   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9372   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9373 
9374   // The operands need to be integers.
9375   if (!LHSEleType->isIntegerType()) {
9376     S.Diag(Loc, diag::err_typecheck_expect_int)
9377       << LHS.get()->getType() << LHS.get()->getSourceRange();
9378     return QualType();
9379   }
9380 
9381   if (!RHSEleType->isIntegerType()) {
9382     S.Diag(Loc, diag::err_typecheck_expect_int)
9383       << RHS.get()->getType() << RHS.get()->getSourceRange();
9384     return QualType();
9385   }
9386 
9387   if (!LHSVecTy) {
9388     assert(RHSVecTy);
9389     if (IsCompAssign)
9390       return RHSType;
9391     if (LHSEleType != RHSEleType) {
9392       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9393       LHSEleType = RHSEleType;
9394     }
9395     QualType VecTy =
9396         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9397     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9398     LHSType = VecTy;
9399   } else if (RHSVecTy) {
9400     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9401     // are applied component-wise. So if RHS is a vector, then ensure
9402     // that the number of elements is the same as LHS...
9403     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9404       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9405         << LHS.get()->getType() << RHS.get()->getType()
9406         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9407       return QualType();
9408     }
9409     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9410       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9411       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9412       if (LHSBT != RHSBT &&
9413           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9414         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9415             << LHS.get()->getType() << RHS.get()->getType()
9416             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9417       }
9418     }
9419   } else {
9420     // ...else expand RHS to match the number of elements in LHS.
9421     QualType VecTy =
9422       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9423     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9424   }
9425 
9426   return LHSType;
9427 }
9428 
9429 // C99 6.5.7
9430 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9431                                   SourceLocation Loc, BinaryOperatorKind Opc,
9432                                   bool IsCompAssign) {
9433   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9434 
9435   // Vector shifts promote their scalar inputs to vector type.
9436   if (LHS.get()->getType()->isVectorType() ||
9437       RHS.get()->getType()->isVectorType()) {
9438     if (LangOpts.ZVector) {
9439       // The shift operators for the z vector extensions work basically
9440       // like general shifts, except that neither the LHS nor the RHS is
9441       // allowed to be a "vector bool".
9442       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9443         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9444           return InvalidOperands(Loc, LHS, RHS);
9445       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9446         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9447           return InvalidOperands(Loc, LHS, RHS);
9448     }
9449     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9450   }
9451 
9452   // Shifts don't perform usual arithmetic conversions, they just do integer
9453   // promotions on each operand. C99 6.5.7p3
9454 
9455   // For the LHS, do usual unary conversions, but then reset them away
9456   // if this is a compound assignment.
9457   ExprResult OldLHS = LHS;
9458   LHS = UsualUnaryConversions(LHS.get());
9459   if (LHS.isInvalid())
9460     return QualType();
9461   QualType LHSType = LHS.get()->getType();
9462   if (IsCompAssign) LHS = OldLHS;
9463 
9464   // The RHS is simpler.
9465   RHS = UsualUnaryConversions(RHS.get());
9466   if (RHS.isInvalid())
9467     return QualType();
9468   QualType RHSType = RHS.get()->getType();
9469 
9470   // C99 6.5.7p2: Each of the operands shall have integer type.
9471   if (!LHSType->hasIntegerRepresentation() ||
9472       !RHSType->hasIntegerRepresentation())
9473     return InvalidOperands(Loc, LHS, RHS);
9474 
9475   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9476   // hasIntegerRepresentation() above instead of this.
9477   if (isScopedEnumerationType(LHSType) ||
9478       isScopedEnumerationType(RHSType)) {
9479     return InvalidOperands(Loc, LHS, RHS);
9480   }
9481   // Sanity-check shift operands
9482   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9483 
9484   // "The type of the result is that of the promoted left operand."
9485   return LHSType;
9486 }
9487 
9488 /// If two different enums are compared, raise a warning.
9489 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9490                                 Expr *RHS) {
9491   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9492   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9493 
9494   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9495   if (!LHSEnumType)
9496     return;
9497   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9498   if (!RHSEnumType)
9499     return;
9500 
9501   // Ignore anonymous enums.
9502   if (!LHSEnumType->getDecl()->getIdentifier() &&
9503       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9504     return;
9505   if (!RHSEnumType->getDecl()->getIdentifier() &&
9506       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9507     return;
9508 
9509   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9510     return;
9511 
9512   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9513       << LHSStrippedType << RHSStrippedType
9514       << LHS->getSourceRange() << RHS->getSourceRange();
9515 }
9516 
9517 /// Diagnose bad pointer comparisons.
9518 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9519                                               ExprResult &LHS, ExprResult &RHS,
9520                                               bool IsError) {
9521   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9522                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9523     << LHS.get()->getType() << RHS.get()->getType()
9524     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9525 }
9526 
9527 /// Returns false if the pointers are converted to a composite type,
9528 /// true otherwise.
9529 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9530                                            ExprResult &LHS, ExprResult &RHS) {
9531   // C++ [expr.rel]p2:
9532   //   [...] Pointer conversions (4.10) and qualification
9533   //   conversions (4.4) are performed on pointer operands (or on
9534   //   a pointer operand and a null pointer constant) to bring
9535   //   them to their composite pointer type. [...]
9536   //
9537   // C++ [expr.eq]p1 uses the same notion for (in)equality
9538   // comparisons of pointers.
9539 
9540   QualType LHSType = LHS.get()->getType();
9541   QualType RHSType = RHS.get()->getType();
9542   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9543          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9544 
9545   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9546   if (T.isNull()) {
9547     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9548         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9549       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9550     else
9551       S.InvalidOperands(Loc, LHS, RHS);
9552     return true;
9553   }
9554 
9555   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9556   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9557   return false;
9558 }
9559 
9560 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9561                                                     ExprResult &LHS,
9562                                                     ExprResult &RHS,
9563                                                     bool IsError) {
9564   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9565                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9566     << LHS.get()->getType() << RHS.get()->getType()
9567     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9568 }
9569 
9570 static bool isObjCObjectLiteral(ExprResult &E) {
9571   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9572   case Stmt::ObjCArrayLiteralClass:
9573   case Stmt::ObjCDictionaryLiteralClass:
9574   case Stmt::ObjCStringLiteralClass:
9575   case Stmt::ObjCBoxedExprClass:
9576     return true;
9577   default:
9578     // Note that ObjCBoolLiteral is NOT an object literal!
9579     return false;
9580   }
9581 }
9582 
9583 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9584   const ObjCObjectPointerType *Type =
9585     LHS->getType()->getAs<ObjCObjectPointerType>();
9586 
9587   // If this is not actually an Objective-C object, bail out.
9588   if (!Type)
9589     return false;
9590 
9591   // Get the LHS object's interface type.
9592   QualType InterfaceType = Type->getPointeeType();
9593 
9594   // If the RHS isn't an Objective-C object, bail out.
9595   if (!RHS->getType()->isObjCObjectPointerType())
9596     return false;
9597 
9598   // Try to find the -isEqual: method.
9599   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9600   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9601                                                       InterfaceType,
9602                                                       /*instance=*/true);
9603   if (!Method) {
9604     if (Type->isObjCIdType()) {
9605       // For 'id', just check the global pool.
9606       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9607                                                   /*receiverId=*/true);
9608     } else {
9609       // Check protocols.
9610       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9611                                              /*instance=*/true);
9612     }
9613   }
9614 
9615   if (!Method)
9616     return false;
9617 
9618   QualType T = Method->parameters()[0]->getType();
9619   if (!T->isObjCObjectPointerType())
9620     return false;
9621 
9622   QualType R = Method->getReturnType();
9623   if (!R->isScalarType())
9624     return false;
9625 
9626   return true;
9627 }
9628 
9629 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9630   FromE = FromE->IgnoreParenImpCasts();
9631   switch (FromE->getStmtClass()) {
9632     default:
9633       break;
9634     case Stmt::ObjCStringLiteralClass:
9635       // "string literal"
9636       return LK_String;
9637     case Stmt::ObjCArrayLiteralClass:
9638       // "array literal"
9639       return LK_Array;
9640     case Stmt::ObjCDictionaryLiteralClass:
9641       // "dictionary literal"
9642       return LK_Dictionary;
9643     case Stmt::BlockExprClass:
9644       return LK_Block;
9645     case Stmt::ObjCBoxedExprClass: {
9646       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9647       switch (Inner->getStmtClass()) {
9648         case Stmt::IntegerLiteralClass:
9649         case Stmt::FloatingLiteralClass:
9650         case Stmt::CharacterLiteralClass:
9651         case Stmt::ObjCBoolLiteralExprClass:
9652         case Stmt::CXXBoolLiteralExprClass:
9653           // "numeric literal"
9654           return LK_Numeric;
9655         case Stmt::ImplicitCastExprClass: {
9656           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9657           // Boolean literals can be represented by implicit casts.
9658           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9659             return LK_Numeric;
9660           break;
9661         }
9662         default:
9663           break;
9664       }
9665       return LK_Boxed;
9666     }
9667   }
9668   return LK_None;
9669 }
9670 
9671 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9672                                           ExprResult &LHS, ExprResult &RHS,
9673                                           BinaryOperator::Opcode Opc){
9674   Expr *Literal;
9675   Expr *Other;
9676   if (isObjCObjectLiteral(LHS)) {
9677     Literal = LHS.get();
9678     Other = RHS.get();
9679   } else {
9680     Literal = RHS.get();
9681     Other = LHS.get();
9682   }
9683 
9684   // Don't warn on comparisons against nil.
9685   Other = Other->IgnoreParenCasts();
9686   if (Other->isNullPointerConstant(S.getASTContext(),
9687                                    Expr::NPC_ValueDependentIsNotNull))
9688     return;
9689 
9690   // This should be kept in sync with warn_objc_literal_comparison.
9691   // LK_String should always be after the other literals, since it has its own
9692   // warning flag.
9693   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9694   assert(LiteralKind != Sema::LK_Block);
9695   if (LiteralKind == Sema::LK_None) {
9696     llvm_unreachable("Unknown Objective-C object literal kind");
9697   }
9698 
9699   if (LiteralKind == Sema::LK_String)
9700     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9701       << Literal->getSourceRange();
9702   else
9703     S.Diag(Loc, diag::warn_objc_literal_comparison)
9704       << LiteralKind << Literal->getSourceRange();
9705 
9706   if (BinaryOperator::isEqualityOp(Opc) &&
9707       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9708     SourceLocation Start = LHS.get()->getBeginLoc();
9709     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9710     CharSourceRange OpRange =
9711       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9712 
9713     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9714       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9715       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9716       << FixItHint::CreateInsertion(End, "]");
9717   }
9718 }
9719 
9720 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9721 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9722                                            ExprResult &RHS, SourceLocation Loc,
9723                                            BinaryOperatorKind Opc) {
9724   // Check that left hand side is !something.
9725   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9726   if (!UO || UO->getOpcode() != UO_LNot) return;
9727 
9728   // Only check if the right hand side is non-bool arithmetic type.
9729   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9730 
9731   // Make sure that the something in !something is not bool.
9732   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9733   if (SubExpr->isKnownToHaveBooleanValue()) return;
9734 
9735   // Emit warning.
9736   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9737   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9738       << Loc << IsBitwiseOp;
9739 
9740   // First note suggest !(x < y)
9741   SourceLocation FirstOpen = SubExpr->getBeginLoc();
9742   SourceLocation FirstClose = RHS.get()->getEndLoc();
9743   FirstClose = S.getLocForEndOfToken(FirstClose);
9744   if (FirstClose.isInvalid())
9745     FirstOpen = SourceLocation();
9746   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9747       << IsBitwiseOp
9748       << FixItHint::CreateInsertion(FirstOpen, "(")
9749       << FixItHint::CreateInsertion(FirstClose, ")");
9750 
9751   // Second note suggests (!x) < y
9752   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
9753   SourceLocation SecondClose = LHS.get()->getEndLoc();
9754   SecondClose = S.getLocForEndOfToken(SecondClose);
9755   if (SecondClose.isInvalid())
9756     SecondOpen = SourceLocation();
9757   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9758       << FixItHint::CreateInsertion(SecondOpen, "(")
9759       << FixItHint::CreateInsertion(SecondClose, ")");
9760 }
9761 
9762 // Get the decl for a simple expression: a reference to a variable,
9763 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9764 static ValueDecl *getCompareDecl(Expr *E) {
9765   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9766     return DR->getDecl();
9767   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9768     if (Ivar->isFreeIvar())
9769       return Ivar->getDecl();
9770   }
9771   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9772     if (Mem->isImplicitAccess())
9773       return Mem->getMemberDecl();
9774   }
9775   return nullptr;
9776 }
9777 
9778 /// Diagnose some forms of syntactically-obvious tautological comparison.
9779 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9780                                            Expr *LHS, Expr *RHS,
9781                                            BinaryOperatorKind Opc) {
9782   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9783   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9784 
9785   QualType LHSType = LHS->getType();
9786   QualType RHSType = RHS->getType();
9787   if (LHSType->hasFloatingRepresentation() ||
9788       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9789       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
9790       S.inTemplateInstantiation())
9791     return;
9792 
9793   // Comparisons between two array types are ill-formed for operator<=>, so
9794   // we shouldn't emit any additional warnings about it.
9795   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9796     return;
9797 
9798   // For non-floating point types, check for self-comparisons of the form
9799   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9800   // often indicate logic errors in the program.
9801   //
9802   // NOTE: Don't warn about comparison expressions resulting from macro
9803   // expansion. Also don't warn about comparisons which are only self
9804   // comparisons within a template instantiation. The warnings should catch
9805   // obvious cases in the definition of the template anyways. The idea is to
9806   // warn when the typed comparison operator will always evaluate to the same
9807   // result.
9808   ValueDecl *DL = getCompareDecl(LHSStripped);
9809   ValueDecl *DR = getCompareDecl(RHSStripped);
9810   if (DL && DR && declaresSameEntity(DL, DR)) {
9811     StringRef Result;
9812     switch (Opc) {
9813     case BO_EQ: case BO_LE: case BO_GE:
9814       Result = "true";
9815       break;
9816     case BO_NE: case BO_LT: case BO_GT:
9817       Result = "false";
9818       break;
9819     case BO_Cmp:
9820       Result = "'std::strong_ordering::equal'";
9821       break;
9822     default:
9823       break;
9824     }
9825     S.DiagRuntimeBehavior(Loc, nullptr,
9826                           S.PDiag(diag::warn_comparison_always)
9827                               << 0 /*self-comparison*/ << !Result.empty()
9828                               << Result);
9829   } else if (DL && DR &&
9830              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9831              !DL->isWeak() && !DR->isWeak()) {
9832     // What is it always going to evaluate to?
9833     StringRef Result;
9834     switch(Opc) {
9835     case BO_EQ: // e.g. array1 == array2
9836       Result = "false";
9837       break;
9838     case BO_NE: // e.g. array1 != array2
9839       Result = "true";
9840       break;
9841     default: // e.g. array1 <= array2
9842       // The best we can say is 'a constant'
9843       break;
9844     }
9845     S.DiagRuntimeBehavior(Loc, nullptr,
9846                           S.PDiag(diag::warn_comparison_always)
9847                               << 1 /*array comparison*/
9848                               << !Result.empty() << Result);
9849   }
9850 
9851   if (isa<CastExpr>(LHSStripped))
9852     LHSStripped = LHSStripped->IgnoreParenCasts();
9853   if (isa<CastExpr>(RHSStripped))
9854     RHSStripped = RHSStripped->IgnoreParenCasts();
9855 
9856   // Warn about comparisons against a string constant (unless the other
9857   // operand is null); the user probably wants strcmp.
9858   Expr *LiteralString = nullptr;
9859   Expr *LiteralStringStripped = nullptr;
9860   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9861       !RHSStripped->isNullPointerConstant(S.Context,
9862                                           Expr::NPC_ValueDependentIsNull)) {
9863     LiteralString = LHS;
9864     LiteralStringStripped = LHSStripped;
9865   } else if ((isa<StringLiteral>(RHSStripped) ||
9866               isa<ObjCEncodeExpr>(RHSStripped)) &&
9867              !LHSStripped->isNullPointerConstant(S.Context,
9868                                           Expr::NPC_ValueDependentIsNull)) {
9869     LiteralString = RHS;
9870     LiteralStringStripped = RHSStripped;
9871   }
9872 
9873   if (LiteralString) {
9874     S.DiagRuntimeBehavior(Loc, nullptr,
9875                           S.PDiag(diag::warn_stringcompare)
9876                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9877                               << LiteralString->getSourceRange());
9878   }
9879 }
9880 
9881 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9882   switch (CK) {
9883   default: {
9884 #ifndef NDEBUG
9885     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9886                  << "\n";
9887 #endif
9888     llvm_unreachable("unhandled cast kind");
9889   }
9890   case CK_UserDefinedConversion:
9891     return ICK_Identity;
9892   case CK_LValueToRValue:
9893     return ICK_Lvalue_To_Rvalue;
9894   case CK_ArrayToPointerDecay:
9895     return ICK_Array_To_Pointer;
9896   case CK_FunctionToPointerDecay:
9897     return ICK_Function_To_Pointer;
9898   case CK_IntegralCast:
9899     return ICK_Integral_Conversion;
9900   case CK_FloatingCast:
9901     return ICK_Floating_Conversion;
9902   case CK_IntegralToFloating:
9903   case CK_FloatingToIntegral:
9904     return ICK_Floating_Integral;
9905   case CK_IntegralComplexCast:
9906   case CK_FloatingComplexCast:
9907   case CK_FloatingComplexToIntegralComplex:
9908   case CK_IntegralComplexToFloatingComplex:
9909     return ICK_Complex_Conversion;
9910   case CK_FloatingComplexToReal:
9911   case CK_FloatingRealToComplex:
9912   case CK_IntegralComplexToReal:
9913   case CK_IntegralRealToComplex:
9914     return ICK_Complex_Real;
9915   }
9916 }
9917 
9918 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9919                                              QualType FromType,
9920                                              SourceLocation Loc) {
9921   // Check for a narrowing implicit conversion.
9922   StandardConversionSequence SCS;
9923   SCS.setAsIdentityConversion();
9924   SCS.setToType(0, FromType);
9925   SCS.setToType(1, ToType);
9926   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9927     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9928 
9929   APValue PreNarrowingValue;
9930   QualType PreNarrowingType;
9931   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9932                                PreNarrowingType,
9933                                /*IgnoreFloatToIntegralConversion*/ true)) {
9934   case NK_Dependent_Narrowing:
9935     // Implicit conversion to a narrower type, but the expression is
9936     // value-dependent so we can't tell whether it's actually narrowing.
9937   case NK_Not_Narrowing:
9938     return false;
9939 
9940   case NK_Constant_Narrowing:
9941     // Implicit conversion to a narrower type, and the value is not a constant
9942     // expression.
9943     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
9944         << /*Constant*/ 1
9945         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9946     return true;
9947 
9948   case NK_Variable_Narrowing:
9949     // Implicit conversion to a narrower type, and the value is not a constant
9950     // expression.
9951   case NK_Type_Narrowing:
9952     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
9953         << /*Constant*/ 0 << FromType << ToType;
9954     // TODO: It's not a constant expression, but what if the user intended it
9955     // to be? Can we produce notes to help them figure out why it isn't?
9956     return true;
9957   }
9958   llvm_unreachable("unhandled case in switch");
9959 }
9960 
9961 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9962                                                          ExprResult &LHS,
9963                                                          ExprResult &RHS,
9964                                                          SourceLocation Loc) {
9965   using CCT = ComparisonCategoryType;
9966 
9967   QualType LHSType = LHS.get()->getType();
9968   QualType RHSType = RHS.get()->getType();
9969   // Dig out the original argument type and expression before implicit casts
9970   // were applied. These are the types/expressions we need to check the
9971   // [expr.spaceship] requirements against.
9972   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9973   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9974   QualType LHSStrippedType = LHSStripped.get()->getType();
9975   QualType RHSStrippedType = RHSStripped.get()->getType();
9976 
9977   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9978   // other is not, the program is ill-formed.
9979   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9980     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9981     return QualType();
9982   }
9983 
9984   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9985                     RHSStrippedType->isEnumeralType();
9986   if (NumEnumArgs == 1) {
9987     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9988     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9989     if (OtherTy->hasFloatingRepresentation()) {
9990       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9991       return QualType();
9992     }
9993   }
9994   if (NumEnumArgs == 2) {
9995     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9996     // type E, the operator yields the result of converting the operands
9997     // to the underlying type of E and applying <=> to the converted operands.
9998     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9999       S.InvalidOperands(Loc, LHS, RHS);
10000       return QualType();
10001     }
10002     QualType IntType =
10003         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10004     assert(IntType->isArithmeticType());
10005 
10006     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10007     // promote the boolean type, and all other promotable integer types, to
10008     // avoid this.
10009     if (IntType->isPromotableIntegerType())
10010       IntType = S.Context.getPromotedIntegerType(IntType);
10011 
10012     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10013     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10014     LHSType = RHSType = IntType;
10015   }
10016 
10017   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10018   // usual arithmetic conversions are applied to the operands.
10019   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10020   if (LHS.isInvalid() || RHS.isInvalid())
10021     return QualType();
10022   if (Type.isNull())
10023     return S.InvalidOperands(Loc, LHS, RHS);
10024   assert(Type->isArithmeticType() || Type->isEnumeralType());
10025 
10026   bool HasNarrowing = checkThreeWayNarrowingConversion(
10027       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10028   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10029                                                    RHS.get()->getBeginLoc());
10030   if (HasNarrowing)
10031     return QualType();
10032 
10033   assert(!Type.isNull() && "composite type for <=> has not been set");
10034 
10035   auto TypeKind = [&]() {
10036     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10037       if (CT->getElementType()->hasFloatingRepresentation())
10038         return CCT::WeakEquality;
10039       return CCT::StrongEquality;
10040     }
10041     if (Type->isIntegralOrEnumerationType())
10042       return CCT::StrongOrdering;
10043     if (Type->hasFloatingRepresentation())
10044       return CCT::PartialOrdering;
10045     llvm_unreachable("other types are unimplemented");
10046   }();
10047 
10048   return S.CheckComparisonCategoryType(TypeKind, Loc);
10049 }
10050 
10051 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10052                                                  ExprResult &RHS,
10053                                                  SourceLocation Loc,
10054                                                  BinaryOperatorKind Opc) {
10055   if (Opc == BO_Cmp)
10056     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10057 
10058   // C99 6.5.8p3 / C99 6.5.9p4
10059   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10060   if (LHS.isInvalid() || RHS.isInvalid())
10061     return QualType();
10062   if (Type.isNull())
10063     return S.InvalidOperands(Loc, LHS, RHS);
10064   assert(Type->isArithmeticType() || Type->isEnumeralType());
10065 
10066   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10067 
10068   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10069     return S.InvalidOperands(Loc, LHS, RHS);
10070 
10071   // Check for comparisons of floating point operands using != and ==.
10072   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10073     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10074 
10075   // The result of comparisons is 'bool' in C++, 'int' in C.
10076   return S.Context.getLogicalOperationType();
10077 }
10078 
10079 // C99 6.5.8, C++ [expr.rel]
10080 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10081                                     SourceLocation Loc,
10082                                     BinaryOperatorKind Opc) {
10083   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10084   bool IsThreeWay = Opc == BO_Cmp;
10085   auto IsAnyPointerType = [](ExprResult E) {
10086     QualType Ty = E.get()->getType();
10087     return Ty->isPointerType() || Ty->isMemberPointerType();
10088   };
10089 
10090   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10091   // type, array-to-pointer, ..., conversions are performed on both operands to
10092   // bring them to their composite type.
10093   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10094   // any type-related checks.
10095   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10096     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10097     if (LHS.isInvalid())
10098       return QualType();
10099     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10100     if (RHS.isInvalid())
10101       return QualType();
10102   } else {
10103     LHS = DefaultLvalueConversion(LHS.get());
10104     if (LHS.isInvalid())
10105       return QualType();
10106     RHS = DefaultLvalueConversion(RHS.get());
10107     if (RHS.isInvalid())
10108       return QualType();
10109   }
10110 
10111   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10112 
10113   // Handle vector comparisons separately.
10114   if (LHS.get()->getType()->isVectorType() ||
10115       RHS.get()->getType()->isVectorType())
10116     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10117 
10118   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10119   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10120 
10121   QualType LHSType = LHS.get()->getType();
10122   QualType RHSType = RHS.get()->getType();
10123   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10124       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10125     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10126 
10127   const Expr::NullPointerConstantKind LHSNullKind =
10128       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10129   const Expr::NullPointerConstantKind RHSNullKind =
10130       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10131   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10132   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10133 
10134   auto computeResultTy = [&]() {
10135     if (Opc != BO_Cmp)
10136       return Context.getLogicalOperationType();
10137     assert(getLangOpts().CPlusPlus);
10138     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10139 
10140     QualType CompositeTy = LHS.get()->getType();
10141     assert(!CompositeTy->isReferenceType());
10142 
10143     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10144       return CheckComparisonCategoryType(Kind, Loc);
10145     };
10146 
10147     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10148     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10149     // result is of type std::strong_equality
10150     if (CompositeTy->isFunctionPointerType() ||
10151         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10152       // FIXME: consider making the function pointer case produce
10153       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10154       // and direction polls
10155       return buildResultTy(ComparisonCategoryType::StrongEquality);
10156 
10157     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10158     // pointer type, p <=> q is of type std::strong_ordering.
10159     if (CompositeTy->isPointerType()) {
10160       // P0946R0: Comparisons between a null pointer constant and an object
10161       // pointer result in std::strong_equality
10162       if (LHSIsNull != RHSIsNull)
10163         return buildResultTy(ComparisonCategoryType::StrongEquality);
10164       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10165     }
10166     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10167     // TODO: Extend support for operator<=> to ObjC types.
10168     return InvalidOperands(Loc, LHS, RHS);
10169   };
10170 
10171 
10172   if (!IsRelational && LHSIsNull != RHSIsNull) {
10173     bool IsEquality = Opc == BO_EQ;
10174     if (RHSIsNull)
10175       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10176                                    RHS.get()->getSourceRange());
10177     else
10178       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10179                                    LHS.get()->getSourceRange());
10180   }
10181 
10182   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10183       (RHSType->isIntegerType() && !RHSIsNull)) {
10184     // Skip normal pointer conversion checks in this case; we have better
10185     // diagnostics for this below.
10186   } else if (getLangOpts().CPlusPlus) {
10187     // Equality comparison of a function pointer to a void pointer is invalid,
10188     // but we allow it as an extension.
10189     // FIXME: If we really want to allow this, should it be part of composite
10190     // pointer type computation so it works in conditionals too?
10191     if (!IsRelational &&
10192         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10193          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10194       // This is a gcc extension compatibility comparison.
10195       // In a SFINAE context, we treat this as a hard error to maintain
10196       // conformance with the C++ standard.
10197       diagnoseFunctionPointerToVoidComparison(
10198           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10199 
10200       if (isSFINAEContext())
10201         return QualType();
10202 
10203       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10204       return computeResultTy();
10205     }
10206 
10207     // C++ [expr.eq]p2:
10208     //   If at least one operand is a pointer [...] bring them to their
10209     //   composite pointer type.
10210     // C++ [expr.spaceship]p6
10211     //  If at least one of the operands is of pointer type, [...] bring them
10212     //  to their composite pointer type.
10213     // C++ [expr.rel]p2:
10214     //   If both operands are pointers, [...] bring them to their composite
10215     //   pointer type.
10216     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10217             (IsRelational ? 2 : 1) &&
10218         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10219                                          RHSType->isObjCObjectPointerType()))) {
10220       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10221         return QualType();
10222       return computeResultTy();
10223     }
10224   } else if (LHSType->isPointerType() &&
10225              RHSType->isPointerType()) { // C99 6.5.8p2
10226     // All of the following pointer-related warnings are GCC extensions, except
10227     // when handling null pointer constants.
10228     QualType LCanPointeeTy =
10229       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10230     QualType RCanPointeeTy =
10231       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10232 
10233     // C99 6.5.9p2 and C99 6.5.8p2
10234     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10235                                    RCanPointeeTy.getUnqualifiedType())) {
10236       // Valid unless a relational comparison of function pointers
10237       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10238         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10239           << LHSType << RHSType << LHS.get()->getSourceRange()
10240           << RHS.get()->getSourceRange();
10241       }
10242     } else if (!IsRelational &&
10243                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10244       // Valid unless comparison between non-null pointer and function pointer
10245       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10246           && !LHSIsNull && !RHSIsNull)
10247         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10248                                                 /*isError*/false);
10249     } else {
10250       // Invalid
10251       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10252     }
10253     if (LCanPointeeTy != RCanPointeeTy) {
10254       // Treat NULL constant as a special case in OpenCL.
10255       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10256         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10257         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10258           Diag(Loc,
10259                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10260               << LHSType << RHSType << 0 /* comparison */
10261               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10262         }
10263       }
10264       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10265       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10266       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10267                                                : CK_BitCast;
10268       if (LHSIsNull && !RHSIsNull)
10269         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10270       else
10271         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10272     }
10273     return computeResultTy();
10274   }
10275 
10276   if (getLangOpts().CPlusPlus) {
10277     // C++ [expr.eq]p4:
10278     //   Two operands of type std::nullptr_t or one operand of type
10279     //   std::nullptr_t and the other a null pointer constant compare equal.
10280     if (!IsRelational && LHSIsNull && RHSIsNull) {
10281       if (LHSType->isNullPtrType()) {
10282         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10283         return computeResultTy();
10284       }
10285       if (RHSType->isNullPtrType()) {
10286         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10287         return computeResultTy();
10288       }
10289     }
10290 
10291     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10292     // These aren't covered by the composite pointer type rules.
10293     if (!IsRelational && RHSType->isNullPtrType() &&
10294         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10295       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10296       return computeResultTy();
10297     }
10298     if (!IsRelational && LHSType->isNullPtrType() &&
10299         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10300       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10301       return computeResultTy();
10302     }
10303 
10304     if (IsRelational &&
10305         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10306          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10307       // HACK: Relational comparison of nullptr_t against a pointer type is
10308       // invalid per DR583, but we allow it within std::less<> and friends,
10309       // since otherwise common uses of it break.
10310       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10311       // friends to have std::nullptr_t overload candidates.
10312       DeclContext *DC = CurContext;
10313       if (isa<FunctionDecl>(DC))
10314         DC = DC->getParent();
10315       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10316         if (CTSD->isInStdNamespace() &&
10317             llvm::StringSwitch<bool>(CTSD->getName())
10318                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10319                 .Default(false)) {
10320           if (RHSType->isNullPtrType())
10321             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10322           else
10323             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10324           return computeResultTy();
10325         }
10326       }
10327     }
10328 
10329     // C++ [expr.eq]p2:
10330     //   If at least one operand is a pointer to member, [...] bring them to
10331     //   their composite pointer type.
10332     if (!IsRelational &&
10333         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10334       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10335         return QualType();
10336       else
10337         return computeResultTy();
10338     }
10339   }
10340 
10341   // Handle block pointer types.
10342   if (!IsRelational && LHSType->isBlockPointerType() &&
10343       RHSType->isBlockPointerType()) {
10344     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10345     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10346 
10347     if (!LHSIsNull && !RHSIsNull &&
10348         !Context.typesAreCompatible(lpointee, rpointee)) {
10349       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10350         << LHSType << RHSType << LHS.get()->getSourceRange()
10351         << RHS.get()->getSourceRange();
10352     }
10353     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10354     return computeResultTy();
10355   }
10356 
10357   // Allow block pointers to be compared with null pointer constants.
10358   if (!IsRelational
10359       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10360           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10361     if (!LHSIsNull && !RHSIsNull) {
10362       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10363              ->getPointeeType()->isVoidType())
10364             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10365                 ->getPointeeType()->isVoidType())))
10366         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10367           << LHSType << RHSType << LHS.get()->getSourceRange()
10368           << RHS.get()->getSourceRange();
10369     }
10370     if (LHSIsNull && !RHSIsNull)
10371       LHS = ImpCastExprToType(LHS.get(), RHSType,
10372                               RHSType->isPointerType() ? CK_BitCast
10373                                 : CK_AnyPointerToBlockPointerCast);
10374     else
10375       RHS = ImpCastExprToType(RHS.get(), LHSType,
10376                               LHSType->isPointerType() ? CK_BitCast
10377                                 : CK_AnyPointerToBlockPointerCast);
10378     return computeResultTy();
10379   }
10380 
10381   if (LHSType->isObjCObjectPointerType() ||
10382       RHSType->isObjCObjectPointerType()) {
10383     const PointerType *LPT = LHSType->getAs<PointerType>();
10384     const PointerType *RPT = RHSType->getAs<PointerType>();
10385     if (LPT || RPT) {
10386       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10387       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10388 
10389       if (!LPtrToVoid && !RPtrToVoid &&
10390           !Context.typesAreCompatible(LHSType, RHSType)) {
10391         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10392                                           /*isError*/false);
10393       }
10394       if (LHSIsNull && !RHSIsNull) {
10395         Expr *E = LHS.get();
10396         if (getLangOpts().ObjCAutoRefCount)
10397           CheckObjCConversion(SourceRange(), RHSType, E,
10398                               CCK_ImplicitConversion);
10399         LHS = ImpCastExprToType(E, RHSType,
10400                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10401       }
10402       else {
10403         Expr *E = RHS.get();
10404         if (getLangOpts().ObjCAutoRefCount)
10405           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10406                               /*Diagnose=*/true,
10407                               /*DiagnoseCFAudited=*/false, Opc);
10408         RHS = ImpCastExprToType(E, LHSType,
10409                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10410       }
10411       return computeResultTy();
10412     }
10413     if (LHSType->isObjCObjectPointerType() &&
10414         RHSType->isObjCObjectPointerType()) {
10415       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10416         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10417                                           /*isError*/false);
10418       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10419         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10420 
10421       if (LHSIsNull && !RHSIsNull)
10422         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10423       else
10424         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10425       return computeResultTy();
10426     }
10427 
10428     if (!IsRelational && LHSType->isBlockPointerType() &&
10429         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10430       LHS = ImpCastExprToType(LHS.get(), RHSType,
10431                               CK_BlockPointerToObjCPointerCast);
10432       return computeResultTy();
10433     } else if (!IsRelational &&
10434                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10435                RHSType->isBlockPointerType()) {
10436       RHS = ImpCastExprToType(RHS.get(), LHSType,
10437                               CK_BlockPointerToObjCPointerCast);
10438       return computeResultTy();
10439     }
10440   }
10441   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10442       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10443     unsigned DiagID = 0;
10444     bool isError = false;
10445     if (LangOpts.DebuggerSupport) {
10446       // Under a debugger, allow the comparison of pointers to integers,
10447       // since users tend to want to compare addresses.
10448     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10449                (RHSIsNull && RHSType->isIntegerType())) {
10450       if (IsRelational) {
10451         isError = getLangOpts().CPlusPlus;
10452         DiagID =
10453           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10454                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10455       }
10456     } else if (getLangOpts().CPlusPlus) {
10457       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10458       isError = true;
10459     } else if (IsRelational)
10460       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10461     else
10462       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10463 
10464     if (DiagID) {
10465       Diag(Loc, DiagID)
10466         << LHSType << RHSType << LHS.get()->getSourceRange()
10467         << RHS.get()->getSourceRange();
10468       if (isError)
10469         return QualType();
10470     }
10471 
10472     if (LHSType->isIntegerType())
10473       LHS = ImpCastExprToType(LHS.get(), RHSType,
10474                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10475     else
10476       RHS = ImpCastExprToType(RHS.get(), LHSType,
10477                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10478     return computeResultTy();
10479   }
10480 
10481   // Handle block pointers.
10482   if (!IsRelational && RHSIsNull
10483       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10484     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10485     return computeResultTy();
10486   }
10487   if (!IsRelational && LHSIsNull
10488       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10489     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10490     return computeResultTy();
10491   }
10492 
10493   if (getLangOpts().OpenCLVersion >= 200) {
10494     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10495       return computeResultTy();
10496     }
10497 
10498     if (LHSIsNull && RHSType->isQueueT()) {
10499       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10500       return computeResultTy();
10501     }
10502 
10503     if (LHSType->isQueueT() && RHSIsNull) {
10504       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10505       return computeResultTy();
10506     }
10507   }
10508 
10509   return InvalidOperands(Loc, LHS, RHS);
10510 }
10511 
10512 // Return a signed ext_vector_type that is of identical size and number of
10513 // elements. For floating point vectors, return an integer type of identical
10514 // size and number of elements. In the non ext_vector_type case, search from
10515 // the largest type to the smallest type to avoid cases where long long == long,
10516 // where long gets picked over long long.
10517 QualType Sema::GetSignedVectorType(QualType V) {
10518   const VectorType *VTy = V->getAs<VectorType>();
10519   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10520 
10521   if (isa<ExtVectorType>(VTy)) {
10522     if (TypeSize == Context.getTypeSize(Context.CharTy))
10523       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10524     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10525       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10526     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10527       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10528     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10529       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10530     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10531            "Unhandled vector element size in vector compare");
10532     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10533   }
10534 
10535   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10536     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10537                                  VectorType::GenericVector);
10538   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10539     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10540                                  VectorType::GenericVector);
10541   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10542     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10543                                  VectorType::GenericVector);
10544   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10545     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10546                                  VectorType::GenericVector);
10547   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10548          "Unhandled vector element size in vector compare");
10549   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10550                                VectorType::GenericVector);
10551 }
10552 
10553 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10554 /// operates on extended vector types.  Instead of producing an IntTy result,
10555 /// like a scalar comparison, a vector comparison produces a vector of integer
10556 /// types.
10557 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10558                                           SourceLocation Loc,
10559                                           BinaryOperatorKind Opc) {
10560   // Check to make sure we're operating on vectors of the same type and width,
10561   // Allowing one side to be a scalar of element type.
10562   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10563                               /*AllowBothBool*/true,
10564                               /*AllowBoolConversions*/getLangOpts().ZVector);
10565   if (vType.isNull())
10566     return vType;
10567 
10568   QualType LHSType = LHS.get()->getType();
10569 
10570   // If AltiVec, the comparison results in a numeric type, i.e.
10571   // bool for C++, int for C
10572   if (getLangOpts().AltiVec &&
10573       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10574     return Context.getLogicalOperationType();
10575 
10576   // For non-floating point types, check for self-comparisons of the form
10577   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10578   // often indicate logic errors in the program.
10579   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10580 
10581   // Check for comparisons of floating point operands using != and ==.
10582   if (BinaryOperator::isEqualityOp(Opc) &&
10583       LHSType->hasFloatingRepresentation()) {
10584     assert(RHS.get()->getType()->hasFloatingRepresentation());
10585     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10586   }
10587 
10588   // Return a signed type for the vector.
10589   return GetSignedVectorType(vType);
10590 }
10591 
10592 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10593                                           SourceLocation Loc) {
10594   // Ensure that either both operands are of the same vector type, or
10595   // one operand is of a vector type and the other is of its element type.
10596   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10597                                        /*AllowBothBool*/true,
10598                                        /*AllowBoolConversions*/false);
10599   if (vType.isNull())
10600     return InvalidOperands(Loc, LHS, RHS);
10601   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10602       vType->hasFloatingRepresentation())
10603     return InvalidOperands(Loc, LHS, RHS);
10604   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10605   //        usage of the logical operators && and || with vectors in C. This
10606   //        check could be notionally dropped.
10607   if (!getLangOpts().CPlusPlus &&
10608       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10609     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10610 
10611   return GetSignedVectorType(LHS.get()->getType());
10612 }
10613 
10614 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10615                                            SourceLocation Loc,
10616                                            BinaryOperatorKind Opc) {
10617   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10618 
10619   bool IsCompAssign =
10620       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10621 
10622   if (LHS.get()->getType()->isVectorType() ||
10623       RHS.get()->getType()->isVectorType()) {
10624     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10625         RHS.get()->getType()->hasIntegerRepresentation())
10626       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10627                         /*AllowBothBool*/true,
10628                         /*AllowBoolConversions*/getLangOpts().ZVector);
10629     return InvalidOperands(Loc, LHS, RHS);
10630   }
10631 
10632   if (Opc == BO_And)
10633     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10634 
10635   ExprResult LHSResult = LHS, RHSResult = RHS;
10636   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10637                                                  IsCompAssign);
10638   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10639     return QualType();
10640   LHS = LHSResult.get();
10641   RHS = RHSResult.get();
10642 
10643   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10644     return compType;
10645   return InvalidOperands(Loc, LHS, RHS);
10646 }
10647 
10648 // C99 6.5.[13,14]
10649 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10650                                            SourceLocation Loc,
10651                                            BinaryOperatorKind Opc) {
10652   // Check vector operands differently.
10653   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10654     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10655 
10656   // Diagnose cases where the user write a logical and/or but probably meant a
10657   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10658   // is a constant.
10659   if (LHS.get()->getType()->isIntegerType() &&
10660       !LHS.get()->getType()->isBooleanType() &&
10661       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10662       // Don't warn in macros or template instantiations.
10663       !Loc.isMacroID() && !inTemplateInstantiation()) {
10664     // If the RHS can be constant folded, and if it constant folds to something
10665     // that isn't 0 or 1 (which indicate a potential logical operation that
10666     // happened to fold to true/false) then warn.
10667     // Parens on the RHS are ignored.
10668     llvm::APSInt Result;
10669     if (RHS.get()->EvaluateAsInt(Result, Context))
10670       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10671            !RHS.get()->getExprLoc().isMacroID()) ||
10672           (Result != 0 && Result != 1)) {
10673         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10674           << RHS.get()->getSourceRange()
10675           << (Opc == BO_LAnd ? "&&" : "||");
10676         // Suggest replacing the logical operator with the bitwise version
10677         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10678             << (Opc == BO_LAnd ? "&" : "|")
10679             << FixItHint::CreateReplacement(SourceRange(
10680                                                  Loc, getLocForEndOfToken(Loc)),
10681                                             Opc == BO_LAnd ? "&" : "|");
10682         if (Opc == BO_LAnd)
10683           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10684           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10685               << FixItHint::CreateRemoval(
10686                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10687                                  RHS.get()->getEndLoc()));
10688       }
10689   }
10690 
10691   if (!Context.getLangOpts().CPlusPlus) {
10692     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10693     // not operate on the built-in scalar and vector float types.
10694     if (Context.getLangOpts().OpenCL &&
10695         Context.getLangOpts().OpenCLVersion < 120) {
10696       if (LHS.get()->getType()->isFloatingType() ||
10697           RHS.get()->getType()->isFloatingType())
10698         return InvalidOperands(Loc, LHS, RHS);
10699     }
10700 
10701     LHS = UsualUnaryConversions(LHS.get());
10702     if (LHS.isInvalid())
10703       return QualType();
10704 
10705     RHS = UsualUnaryConversions(RHS.get());
10706     if (RHS.isInvalid())
10707       return QualType();
10708 
10709     if (!LHS.get()->getType()->isScalarType() ||
10710         !RHS.get()->getType()->isScalarType())
10711       return InvalidOperands(Loc, LHS, RHS);
10712 
10713     return Context.IntTy;
10714   }
10715 
10716   // The following is safe because we only use this method for
10717   // non-overloadable operands.
10718 
10719   // C++ [expr.log.and]p1
10720   // C++ [expr.log.or]p1
10721   // The operands are both contextually converted to type bool.
10722   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10723   if (LHSRes.isInvalid())
10724     return InvalidOperands(Loc, LHS, RHS);
10725   LHS = LHSRes;
10726 
10727   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10728   if (RHSRes.isInvalid())
10729     return InvalidOperands(Loc, LHS, RHS);
10730   RHS = RHSRes;
10731 
10732   // C++ [expr.log.and]p2
10733   // C++ [expr.log.or]p2
10734   // The result is a bool.
10735   return Context.BoolTy;
10736 }
10737 
10738 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10739   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10740   if (!ME) return false;
10741   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10742   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10743       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10744   if (!Base) return false;
10745   return Base->getMethodDecl() != nullptr;
10746 }
10747 
10748 /// Is the given expression (which must be 'const') a reference to a
10749 /// variable which was originally non-const, but which has become
10750 /// 'const' due to being captured within a block?
10751 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10752 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10753   assert(E->isLValue() && E->getType().isConstQualified());
10754   E = E->IgnoreParens();
10755 
10756   // Must be a reference to a declaration from an enclosing scope.
10757   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10758   if (!DRE) return NCCK_None;
10759   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10760 
10761   // The declaration must be a variable which is not declared 'const'.
10762   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10763   if (!var) return NCCK_None;
10764   if (var->getType().isConstQualified()) return NCCK_None;
10765   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10766 
10767   // Decide whether the first capture was for a block or a lambda.
10768   DeclContext *DC = S.CurContext, *Prev = nullptr;
10769   // Decide whether the first capture was for a block or a lambda.
10770   while (DC) {
10771     // For init-capture, it is possible that the variable belongs to the
10772     // template pattern of the current context.
10773     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10774       if (var->isInitCapture() &&
10775           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10776         break;
10777     if (DC == var->getDeclContext())
10778       break;
10779     Prev = DC;
10780     DC = DC->getParent();
10781   }
10782   // Unless we have an init-capture, we've gone one step too far.
10783   if (!var->isInitCapture())
10784     DC = Prev;
10785   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10786 }
10787 
10788 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10789   Ty = Ty.getNonReferenceType();
10790   if (IsDereference && Ty->isPointerType())
10791     Ty = Ty->getPointeeType();
10792   return !Ty.isConstQualified();
10793 }
10794 
10795 // Update err_typecheck_assign_const and note_typecheck_assign_const
10796 // when this enum is changed.
10797 enum {
10798   ConstFunction,
10799   ConstVariable,
10800   ConstMember,
10801   ConstMethod,
10802   NestedConstMember,
10803   ConstUnknown,  // Keep as last element
10804 };
10805 
10806 /// Emit the "read-only variable not assignable" error and print notes to give
10807 /// more information about why the variable is not assignable, such as pointing
10808 /// to the declaration of a const variable, showing that a method is const, or
10809 /// that the function is returning a const reference.
10810 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10811                                     SourceLocation Loc) {
10812   SourceRange ExprRange = E->getSourceRange();
10813 
10814   // Only emit one error on the first const found.  All other consts will emit
10815   // a note to the error.
10816   bool DiagnosticEmitted = false;
10817 
10818   // Track if the current expression is the result of a dereference, and if the
10819   // next checked expression is the result of a dereference.
10820   bool IsDereference = false;
10821   bool NextIsDereference = false;
10822 
10823   // Loop to process MemberExpr chains.
10824   while (true) {
10825     IsDereference = NextIsDereference;
10826 
10827     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10828     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10829       NextIsDereference = ME->isArrow();
10830       const ValueDecl *VD = ME->getMemberDecl();
10831       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10832         // Mutable fields can be modified even if the class is const.
10833         if (Field->isMutable()) {
10834           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10835           break;
10836         }
10837 
10838         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10839           if (!DiagnosticEmitted) {
10840             S.Diag(Loc, diag::err_typecheck_assign_const)
10841                 << ExprRange << ConstMember << false /*static*/ << Field
10842                 << Field->getType();
10843             DiagnosticEmitted = true;
10844           }
10845           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10846               << ConstMember << false /*static*/ << Field << Field->getType()
10847               << Field->getSourceRange();
10848         }
10849         E = ME->getBase();
10850         continue;
10851       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10852         if (VDecl->getType().isConstQualified()) {
10853           if (!DiagnosticEmitted) {
10854             S.Diag(Loc, diag::err_typecheck_assign_const)
10855                 << ExprRange << ConstMember << true /*static*/ << VDecl
10856                 << VDecl->getType();
10857             DiagnosticEmitted = true;
10858           }
10859           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10860               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10861               << VDecl->getSourceRange();
10862         }
10863         // Static fields do not inherit constness from parents.
10864         break;
10865       }
10866       break; // End MemberExpr
10867     } else if (const ArraySubscriptExpr *ASE =
10868                    dyn_cast<ArraySubscriptExpr>(E)) {
10869       E = ASE->getBase()->IgnoreParenImpCasts();
10870       continue;
10871     } else if (const ExtVectorElementExpr *EVE =
10872                    dyn_cast<ExtVectorElementExpr>(E)) {
10873       E = EVE->getBase()->IgnoreParenImpCasts();
10874       continue;
10875     }
10876     break;
10877   }
10878 
10879   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10880     // Function calls
10881     const FunctionDecl *FD = CE->getDirectCallee();
10882     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10883       if (!DiagnosticEmitted) {
10884         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10885                                                       << ConstFunction << FD;
10886         DiagnosticEmitted = true;
10887       }
10888       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10889              diag::note_typecheck_assign_const)
10890           << ConstFunction << FD << FD->getReturnType()
10891           << FD->getReturnTypeSourceRange();
10892     }
10893   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10894     // Point to variable declaration.
10895     if (const ValueDecl *VD = DRE->getDecl()) {
10896       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10897         if (!DiagnosticEmitted) {
10898           S.Diag(Loc, diag::err_typecheck_assign_const)
10899               << ExprRange << ConstVariable << VD << VD->getType();
10900           DiagnosticEmitted = true;
10901         }
10902         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10903             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10904       }
10905     }
10906   } else if (isa<CXXThisExpr>(E)) {
10907     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10908       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10909         if (MD->isConst()) {
10910           if (!DiagnosticEmitted) {
10911             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10912                                                           << ConstMethod << MD;
10913             DiagnosticEmitted = true;
10914           }
10915           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10916               << ConstMethod << MD << MD->getSourceRange();
10917         }
10918       }
10919     }
10920   }
10921 
10922   if (DiagnosticEmitted)
10923     return;
10924 
10925   // Can't determine a more specific message, so display the generic error.
10926   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10927 }
10928 
10929 enum OriginalExprKind {
10930   OEK_Variable,
10931   OEK_Member,
10932   OEK_LValue
10933 };
10934 
10935 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10936                                          const RecordType *Ty,
10937                                          SourceLocation Loc, SourceRange Range,
10938                                          OriginalExprKind OEK,
10939                                          bool &DiagnosticEmitted,
10940                                          bool IsNested = false) {
10941   // We walk the record hierarchy breadth-first to ensure that we print
10942   // diagnostics in field nesting order.
10943   // First, check every field for constness.
10944   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10945     if (Field->getType().isConstQualified()) {
10946       if (!DiagnosticEmitted) {
10947         S.Diag(Loc, diag::err_typecheck_assign_const)
10948             << Range << NestedConstMember << OEK << VD
10949             << IsNested << Field;
10950         DiagnosticEmitted = true;
10951       }
10952       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10953           << NestedConstMember << IsNested << Field
10954           << Field->getType() << Field->getSourceRange();
10955     }
10956   }
10957   // Then, recurse.
10958   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10959     QualType FTy = Field->getType();
10960     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10961       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10962                                    OEK, DiagnosticEmitted, true);
10963   }
10964 }
10965 
10966 /// Emit an error for the case where a record we are trying to assign to has a
10967 /// const-qualified field somewhere in its hierarchy.
10968 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10969                                          SourceLocation Loc) {
10970   QualType Ty = E->getType();
10971   assert(Ty->isRecordType() && "lvalue was not record?");
10972   SourceRange Range = E->getSourceRange();
10973   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10974   bool DiagEmitted = false;
10975 
10976   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10977     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10978             Range, OEK_Member, DiagEmitted);
10979   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10980     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10981             Range, OEK_Variable, DiagEmitted);
10982   else
10983     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10984             Range, OEK_LValue, DiagEmitted);
10985   if (!DiagEmitted)
10986     DiagnoseConstAssignment(S, E, Loc);
10987 }
10988 
10989 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10990 /// emit an error and return true.  If so, return false.
10991 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10992   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10993 
10994   S.CheckShadowingDeclModification(E, Loc);
10995 
10996   SourceLocation OrigLoc = Loc;
10997   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10998                                                               &Loc);
10999   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11000     IsLV = Expr::MLV_InvalidMessageExpression;
11001   if (IsLV == Expr::MLV_Valid)
11002     return false;
11003 
11004   unsigned DiagID = 0;
11005   bool NeedType = false;
11006   switch (IsLV) { // C99 6.5.16p2
11007   case Expr::MLV_ConstQualified:
11008     // Use a specialized diagnostic when we're assigning to an object
11009     // from an enclosing function or block.
11010     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11011       if (NCCK == NCCK_Block)
11012         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11013       else
11014         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11015       break;
11016     }
11017 
11018     // In ARC, use some specialized diagnostics for occasions where we
11019     // infer 'const'.  These are always pseudo-strong variables.
11020     if (S.getLangOpts().ObjCAutoRefCount) {
11021       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11022       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11023         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11024 
11025         // Use the normal diagnostic if it's pseudo-__strong but the
11026         // user actually wrote 'const'.
11027         if (var->isARCPseudoStrong() &&
11028             (!var->getTypeSourceInfo() ||
11029              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11030           // There are two pseudo-strong cases:
11031           //  - self
11032           ObjCMethodDecl *method = S.getCurMethodDecl();
11033           if (method && var == method->getSelfDecl())
11034             DiagID = method->isClassMethod()
11035               ? diag::err_typecheck_arc_assign_self_class_method
11036               : diag::err_typecheck_arc_assign_self;
11037 
11038           //  - fast enumeration variables
11039           else
11040             DiagID = diag::err_typecheck_arr_assign_enumeration;
11041 
11042           SourceRange Assign;
11043           if (Loc != OrigLoc)
11044             Assign = SourceRange(OrigLoc, OrigLoc);
11045           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11046           // We need to preserve the AST regardless, so migration tool
11047           // can do its job.
11048           return false;
11049         }
11050       }
11051     }
11052 
11053     // If none of the special cases above are triggered, then this is a
11054     // simple const assignment.
11055     if (DiagID == 0) {
11056       DiagnoseConstAssignment(S, E, Loc);
11057       return true;
11058     }
11059 
11060     break;
11061   case Expr::MLV_ConstAddrSpace:
11062     DiagnoseConstAssignment(S, E, Loc);
11063     return true;
11064   case Expr::MLV_ConstQualifiedField:
11065     DiagnoseRecursiveConstFields(S, E, Loc);
11066     return true;
11067   case Expr::MLV_ArrayType:
11068   case Expr::MLV_ArrayTemporary:
11069     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11070     NeedType = true;
11071     break;
11072   case Expr::MLV_NotObjectType:
11073     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11074     NeedType = true;
11075     break;
11076   case Expr::MLV_LValueCast:
11077     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11078     break;
11079   case Expr::MLV_Valid:
11080     llvm_unreachable("did not take early return for MLV_Valid");
11081   case Expr::MLV_InvalidExpression:
11082   case Expr::MLV_MemberFunction:
11083   case Expr::MLV_ClassTemporary:
11084     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11085     break;
11086   case Expr::MLV_IncompleteType:
11087   case Expr::MLV_IncompleteVoidType:
11088     return S.RequireCompleteType(Loc, E->getType(),
11089              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11090   case Expr::MLV_DuplicateVectorComponents:
11091     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11092     break;
11093   case Expr::MLV_NoSetterProperty:
11094     llvm_unreachable("readonly properties should be processed differently");
11095   case Expr::MLV_InvalidMessageExpression:
11096     DiagID = diag::err_readonly_message_assignment;
11097     break;
11098   case Expr::MLV_SubObjCPropertySetting:
11099     DiagID = diag::err_no_subobject_property_setting;
11100     break;
11101   }
11102 
11103   SourceRange Assign;
11104   if (Loc != OrigLoc)
11105     Assign = SourceRange(OrigLoc, OrigLoc);
11106   if (NeedType)
11107     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11108   else
11109     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11110   return true;
11111 }
11112 
11113 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11114                                          SourceLocation Loc,
11115                                          Sema &Sema) {
11116   if (Sema.inTemplateInstantiation())
11117     return;
11118   if (Sema.isUnevaluatedContext())
11119     return;
11120   if (Loc.isInvalid() || Loc.isMacroID())
11121     return;
11122   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11123     return;
11124 
11125   // C / C++ fields
11126   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11127   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11128   if (ML && MR) {
11129     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11130       return;
11131     const ValueDecl *LHSDecl =
11132         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11133     const ValueDecl *RHSDecl =
11134         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11135     if (LHSDecl != RHSDecl)
11136       return;
11137     if (LHSDecl->getType().isVolatileQualified())
11138       return;
11139     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11140       if (RefTy->getPointeeType().isVolatileQualified())
11141         return;
11142 
11143     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11144   }
11145 
11146   // Objective-C instance variables
11147   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11148   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11149   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11150     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11151     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11152     if (RL && RR && RL->getDecl() == RR->getDecl())
11153       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11154   }
11155 }
11156 
11157 // C99 6.5.16.1
11158 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11159                                        SourceLocation Loc,
11160                                        QualType CompoundType) {
11161   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11162 
11163   // Verify that LHS is a modifiable lvalue, and emit error if not.
11164   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11165     return QualType();
11166 
11167   QualType LHSType = LHSExpr->getType();
11168   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11169                                              CompoundType;
11170   // OpenCL v1.2 s6.1.1.1 p2:
11171   // The half data type can only be used to declare a pointer to a buffer that
11172   // contains half values
11173   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11174     LHSType->isHalfType()) {
11175     Diag(Loc, diag::err_opencl_half_load_store) << 1
11176         << LHSType.getUnqualifiedType();
11177     return QualType();
11178   }
11179 
11180   AssignConvertType ConvTy;
11181   if (CompoundType.isNull()) {
11182     Expr *RHSCheck = RHS.get();
11183 
11184     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11185 
11186     QualType LHSTy(LHSType);
11187     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11188     if (RHS.isInvalid())
11189       return QualType();
11190     // Special case of NSObject attributes on c-style pointer types.
11191     if (ConvTy == IncompatiblePointer &&
11192         ((Context.isObjCNSObjectType(LHSType) &&
11193           RHSType->isObjCObjectPointerType()) ||
11194          (Context.isObjCNSObjectType(RHSType) &&
11195           LHSType->isObjCObjectPointerType())))
11196       ConvTy = Compatible;
11197 
11198     if (ConvTy == Compatible &&
11199         LHSType->isObjCObjectType())
11200         Diag(Loc, diag::err_objc_object_assignment)
11201           << LHSType;
11202 
11203     // If the RHS is a unary plus or minus, check to see if they = and + are
11204     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11205     // instead of "x += 4".
11206     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11207       RHSCheck = ICE->getSubExpr();
11208     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11209       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11210           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11211           // Only if the two operators are exactly adjacent.
11212           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11213           // And there is a space or other character before the subexpr of the
11214           // unary +/-.  We don't want to warn on "x=-1".
11215           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11216           UO->getSubExpr()->getBeginLoc().isFileID()) {
11217         Diag(Loc, diag::warn_not_compound_assign)
11218           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11219           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11220       }
11221     }
11222 
11223     if (ConvTy == Compatible) {
11224       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11225         // Warn about retain cycles where a block captures the LHS, but
11226         // not if the LHS is a simple variable into which the block is
11227         // being stored...unless that variable can be captured by reference!
11228         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11229         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11230         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11231           checkRetainCycles(LHSExpr, RHS.get());
11232       }
11233 
11234       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11235           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11236         // It is safe to assign a weak reference into a strong variable.
11237         // Although this code can still have problems:
11238         //   id x = self.weakProp;
11239         //   id y = self.weakProp;
11240         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11241         // paths through the function. This should be revisited if
11242         // -Wrepeated-use-of-weak is made flow-sensitive.
11243         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11244         // variable, which will be valid for the current autorelease scope.
11245         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11246                              RHS.get()->getBeginLoc()))
11247           getCurFunction()->markSafeWeakUse(RHS.get());
11248 
11249       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11250         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11251       }
11252     }
11253   } else {
11254     // Compound assignment "x += y"
11255     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11256   }
11257 
11258   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11259                                RHS.get(), AA_Assigning))
11260     return QualType();
11261 
11262   CheckForNullPointerDereference(*this, LHSExpr);
11263 
11264   // C99 6.5.16p3: The type of an assignment expression is the type of the
11265   // left operand unless the left operand has qualified type, in which case
11266   // it is the unqualified version of the type of the left operand.
11267   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11268   // is converted to the type of the assignment expression (above).
11269   // C++ 5.17p1: the type of the assignment expression is that of its left
11270   // operand.
11271   return (getLangOpts().CPlusPlus
11272           ? LHSType : LHSType.getUnqualifiedType());
11273 }
11274 
11275 // Only ignore explicit casts to void.
11276 static bool IgnoreCommaOperand(const Expr *E) {
11277   E = E->IgnoreParens();
11278 
11279   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11280     if (CE->getCastKind() == CK_ToVoid) {
11281       return true;
11282     }
11283   }
11284 
11285   return false;
11286 }
11287 
11288 // Look for instances where it is likely the comma operator is confused with
11289 // another operator.  There is a whitelist of acceptable expressions for the
11290 // left hand side of the comma operator, otherwise emit a warning.
11291 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11292   // No warnings in macros
11293   if (Loc.isMacroID())
11294     return;
11295 
11296   // Don't warn in template instantiations.
11297   if (inTemplateInstantiation())
11298     return;
11299 
11300   // Scope isn't fine-grained enough to whitelist the specific cases, so
11301   // instead, skip more than needed, then call back into here with the
11302   // CommaVisitor in SemaStmt.cpp.
11303   // The whitelisted locations are the initialization and increment portions
11304   // of a for loop.  The additional checks are on the condition of
11305   // if statements, do/while loops, and for loops.
11306   const unsigned ForIncrementFlags =
11307       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11308   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11309   const unsigned ScopeFlags = getCurScope()->getFlags();
11310   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11311       (ScopeFlags & ForInitFlags) == ForInitFlags)
11312     return;
11313 
11314   // If there are multiple comma operators used together, get the RHS of the
11315   // of the comma operator as the LHS.
11316   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11317     if (BO->getOpcode() != BO_Comma)
11318       break;
11319     LHS = BO->getRHS();
11320   }
11321 
11322   // Only allow some expressions on LHS to not warn.
11323   if (IgnoreCommaOperand(LHS))
11324     return;
11325 
11326   Diag(Loc, diag::warn_comma_operator);
11327   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11328       << LHS->getSourceRange()
11329       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11330                                     LangOpts.CPlusPlus ? "static_cast<void>("
11331                                                        : "(void)(")
11332       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11333                                     ")");
11334 }
11335 
11336 // C99 6.5.17
11337 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11338                                    SourceLocation Loc) {
11339   LHS = S.CheckPlaceholderExpr(LHS.get());
11340   RHS = S.CheckPlaceholderExpr(RHS.get());
11341   if (LHS.isInvalid() || RHS.isInvalid())
11342     return QualType();
11343 
11344   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11345   // operands, but not unary promotions.
11346   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11347 
11348   // So we treat the LHS as a ignored value, and in C++ we allow the
11349   // containing site to determine what should be done with the RHS.
11350   LHS = S.IgnoredValueConversions(LHS.get());
11351   if (LHS.isInvalid())
11352     return QualType();
11353 
11354   S.DiagnoseUnusedExprResult(LHS.get());
11355 
11356   if (!S.getLangOpts().CPlusPlus) {
11357     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11358     if (RHS.isInvalid())
11359       return QualType();
11360     if (!RHS.get()->getType()->isVoidType())
11361       S.RequireCompleteType(Loc, RHS.get()->getType(),
11362                             diag::err_incomplete_type);
11363   }
11364 
11365   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11366     S.DiagnoseCommaOperator(LHS.get(), Loc);
11367 
11368   return RHS.get()->getType();
11369 }
11370 
11371 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11372 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11373 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11374                                                ExprValueKind &VK,
11375                                                ExprObjectKind &OK,
11376                                                SourceLocation OpLoc,
11377                                                bool IsInc, bool IsPrefix) {
11378   if (Op->isTypeDependent())
11379     return S.Context.DependentTy;
11380 
11381   QualType ResType = Op->getType();
11382   // Atomic types can be used for increment / decrement where the non-atomic
11383   // versions can, so ignore the _Atomic() specifier for the purpose of
11384   // checking.
11385   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11386     ResType = ResAtomicType->getValueType();
11387 
11388   assert(!ResType.isNull() && "no type for increment/decrement expression");
11389 
11390   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11391     // Decrement of bool is not allowed.
11392     if (!IsInc) {
11393       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11394       return QualType();
11395     }
11396     // Increment of bool sets it to true, but is deprecated.
11397     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11398                                               : diag::warn_increment_bool)
11399       << Op->getSourceRange();
11400   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11401     // Error on enum increments and decrements in C++ mode
11402     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11403     return QualType();
11404   } else if (ResType->isRealType()) {
11405     // OK!
11406   } else if (ResType->isPointerType()) {
11407     // C99 6.5.2.4p2, 6.5.6p2
11408     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11409       return QualType();
11410   } else if (ResType->isObjCObjectPointerType()) {
11411     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11412     // Otherwise, we just need a complete type.
11413     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11414         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11415       return QualType();
11416   } else if (ResType->isAnyComplexType()) {
11417     // C99 does not support ++/-- on complex types, we allow as an extension.
11418     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11419       << ResType << Op->getSourceRange();
11420   } else if (ResType->isPlaceholderType()) {
11421     ExprResult PR = S.CheckPlaceholderExpr(Op);
11422     if (PR.isInvalid()) return QualType();
11423     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11424                                           IsInc, IsPrefix);
11425   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11426     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11427   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11428              (ResType->getAs<VectorType>()->getVectorKind() !=
11429               VectorType::AltiVecBool)) {
11430     // The z vector extensions allow ++ and -- for non-bool vectors.
11431   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11432             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11433     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11434   } else {
11435     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11436       << ResType << int(IsInc) << Op->getSourceRange();
11437     return QualType();
11438   }
11439   // At this point, we know we have a real, complex or pointer type.
11440   // Now make sure the operand is a modifiable lvalue.
11441   if (CheckForModifiableLvalue(Op, OpLoc, S))
11442     return QualType();
11443   // In C++, a prefix increment is the same type as the operand. Otherwise
11444   // (in C or with postfix), the increment is the unqualified type of the
11445   // operand.
11446   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11447     VK = VK_LValue;
11448     OK = Op->getObjectKind();
11449     return ResType;
11450   } else {
11451     VK = VK_RValue;
11452     return ResType.getUnqualifiedType();
11453   }
11454 }
11455 
11456 
11457 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11458 /// This routine allows us to typecheck complex/recursive expressions
11459 /// where the declaration is needed for type checking. We only need to
11460 /// handle cases when the expression references a function designator
11461 /// or is an lvalue. Here are some examples:
11462 ///  - &(x) => x
11463 ///  - &*****f => f for f a function designator.
11464 ///  - &s.xx => s
11465 ///  - &s.zz[1].yy -> s, if zz is an array
11466 ///  - *(x + 1) -> x, if x is an array
11467 ///  - &"123"[2] -> 0
11468 ///  - & __real__ x -> x
11469 static ValueDecl *getPrimaryDecl(Expr *E) {
11470   switch (E->getStmtClass()) {
11471   case Stmt::DeclRefExprClass:
11472     return cast<DeclRefExpr>(E)->getDecl();
11473   case Stmt::MemberExprClass:
11474     // If this is an arrow operator, the address is an offset from
11475     // the base's value, so the object the base refers to is
11476     // irrelevant.
11477     if (cast<MemberExpr>(E)->isArrow())
11478       return nullptr;
11479     // Otherwise, the expression refers to a part of the base
11480     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11481   case Stmt::ArraySubscriptExprClass: {
11482     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11483     // promotion of register arrays earlier.
11484     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11485     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11486       if (ICE->getSubExpr()->getType()->isArrayType())
11487         return getPrimaryDecl(ICE->getSubExpr());
11488     }
11489     return nullptr;
11490   }
11491   case Stmt::UnaryOperatorClass: {
11492     UnaryOperator *UO = cast<UnaryOperator>(E);
11493 
11494     switch(UO->getOpcode()) {
11495     case UO_Real:
11496     case UO_Imag:
11497     case UO_Extension:
11498       return getPrimaryDecl(UO->getSubExpr());
11499     default:
11500       return nullptr;
11501     }
11502   }
11503   case Stmt::ParenExprClass:
11504     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11505   case Stmt::ImplicitCastExprClass:
11506     // If the result of an implicit cast is an l-value, we care about
11507     // the sub-expression; otherwise, the result here doesn't matter.
11508     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11509   default:
11510     return nullptr;
11511   }
11512 }
11513 
11514 namespace {
11515   enum {
11516     AO_Bit_Field = 0,
11517     AO_Vector_Element = 1,
11518     AO_Property_Expansion = 2,
11519     AO_Register_Variable = 3,
11520     AO_No_Error = 4
11521   };
11522 }
11523 /// Diagnose invalid operand for address of operations.
11524 ///
11525 /// \param Type The type of operand which cannot have its address taken.
11526 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11527                                          Expr *E, unsigned Type) {
11528   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11529 }
11530 
11531 /// CheckAddressOfOperand - The operand of & must be either a function
11532 /// designator or an lvalue designating an object. If it is an lvalue, the
11533 /// object cannot be declared with storage class register or be a bit field.
11534 /// Note: The usual conversions are *not* applied to the operand of the &
11535 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11536 /// In C++, the operand might be an overloaded function name, in which case
11537 /// we allow the '&' but retain the overloaded-function type.
11538 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11539   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11540     if (PTy->getKind() == BuiltinType::Overload) {
11541       Expr *E = OrigOp.get()->IgnoreParens();
11542       if (!isa<OverloadExpr>(E)) {
11543         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11544         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11545           << OrigOp.get()->getSourceRange();
11546         return QualType();
11547       }
11548 
11549       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11550       if (isa<UnresolvedMemberExpr>(Ovl))
11551         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11552           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11553             << OrigOp.get()->getSourceRange();
11554           return QualType();
11555         }
11556 
11557       return Context.OverloadTy;
11558     }
11559 
11560     if (PTy->getKind() == BuiltinType::UnknownAny)
11561       return Context.UnknownAnyTy;
11562 
11563     if (PTy->getKind() == BuiltinType::BoundMember) {
11564       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11565         << OrigOp.get()->getSourceRange();
11566       return QualType();
11567     }
11568 
11569     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11570     if (OrigOp.isInvalid()) return QualType();
11571   }
11572 
11573   if (OrigOp.get()->isTypeDependent())
11574     return Context.DependentTy;
11575 
11576   assert(!OrigOp.get()->getType()->isPlaceholderType());
11577 
11578   // Make sure to ignore parentheses in subsequent checks
11579   Expr *op = OrigOp.get()->IgnoreParens();
11580 
11581   // In OpenCL captures for blocks called as lambda functions
11582   // are located in the private address space. Blocks used in
11583   // enqueue_kernel can be located in a different address space
11584   // depending on a vendor implementation. Thus preventing
11585   // taking an address of the capture to avoid invalid AS casts.
11586   if (LangOpts.OpenCL) {
11587     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11588     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11589       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11590       return QualType();
11591     }
11592   }
11593 
11594   if (getLangOpts().C99) {
11595     // Implement C99-only parts of addressof rules.
11596     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11597       if (uOp->getOpcode() == UO_Deref)
11598         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11599         // (assuming the deref expression is valid).
11600         return uOp->getSubExpr()->getType();
11601     }
11602     // Technically, there should be a check for array subscript
11603     // expressions here, but the result of one is always an lvalue anyway.
11604   }
11605   ValueDecl *dcl = getPrimaryDecl(op);
11606 
11607   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11608     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11609                                            op->getBeginLoc()))
11610       return QualType();
11611 
11612   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11613   unsigned AddressOfError = AO_No_Error;
11614 
11615   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11616     bool sfinae = (bool)isSFINAEContext();
11617     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11618                                   : diag::ext_typecheck_addrof_temporary)
11619       << op->getType() << op->getSourceRange();
11620     if (sfinae)
11621       return QualType();
11622     // Materialize the temporary as an lvalue so that we can take its address.
11623     OrigOp = op =
11624         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11625   } else if (isa<ObjCSelectorExpr>(op)) {
11626     return Context.getPointerType(op->getType());
11627   } else if (lval == Expr::LV_MemberFunction) {
11628     // If it's an instance method, make a member pointer.
11629     // The expression must have exactly the form &A::foo.
11630 
11631     // If the underlying expression isn't a decl ref, give up.
11632     if (!isa<DeclRefExpr>(op)) {
11633       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11634         << OrigOp.get()->getSourceRange();
11635       return QualType();
11636     }
11637     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11638     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11639 
11640     // The id-expression was parenthesized.
11641     if (OrigOp.get() != DRE) {
11642       Diag(OpLoc, diag::err_parens_pointer_member_function)
11643         << OrigOp.get()->getSourceRange();
11644 
11645     // The method was named without a qualifier.
11646     } else if (!DRE->getQualifier()) {
11647       if (MD->getParent()->getName().empty())
11648         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11649           << op->getSourceRange();
11650       else {
11651         SmallString<32> Str;
11652         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11653         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11654           << op->getSourceRange()
11655           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11656       }
11657     }
11658 
11659     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11660     if (isa<CXXDestructorDecl>(MD))
11661       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11662 
11663     QualType MPTy = Context.getMemberPointerType(
11664         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11665     // Under the MS ABI, lock down the inheritance model now.
11666     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11667       (void)isCompleteType(OpLoc, MPTy);
11668     return MPTy;
11669   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11670     // C99 6.5.3.2p1
11671     // The operand must be either an l-value or a function designator
11672     if (!op->getType()->isFunctionType()) {
11673       // Use a special diagnostic for loads from property references.
11674       if (isa<PseudoObjectExpr>(op)) {
11675         AddressOfError = AO_Property_Expansion;
11676       } else {
11677         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11678           << op->getType() << op->getSourceRange();
11679         return QualType();
11680       }
11681     }
11682   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11683     // The operand cannot be a bit-field
11684     AddressOfError = AO_Bit_Field;
11685   } else if (op->getObjectKind() == OK_VectorComponent) {
11686     // The operand cannot be an element of a vector
11687     AddressOfError = AO_Vector_Element;
11688   } else if (dcl) { // C99 6.5.3.2p1
11689     // We have an lvalue with a decl. Make sure the decl is not declared
11690     // with the register storage-class specifier.
11691     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11692       // in C++ it is not error to take address of a register
11693       // variable (c++03 7.1.1P3)
11694       if (vd->getStorageClass() == SC_Register &&
11695           !getLangOpts().CPlusPlus) {
11696         AddressOfError = AO_Register_Variable;
11697       }
11698     } else if (isa<MSPropertyDecl>(dcl)) {
11699       AddressOfError = AO_Property_Expansion;
11700     } else if (isa<FunctionTemplateDecl>(dcl)) {
11701       return Context.OverloadTy;
11702     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11703       // Okay: we can take the address of a field.
11704       // Could be a pointer to member, though, if there is an explicit
11705       // scope qualifier for the class.
11706       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11707         DeclContext *Ctx = dcl->getDeclContext();
11708         if (Ctx && Ctx->isRecord()) {
11709           if (dcl->getType()->isReferenceType()) {
11710             Diag(OpLoc,
11711                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11712               << dcl->getDeclName() << dcl->getType();
11713             return QualType();
11714           }
11715 
11716           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11717             Ctx = Ctx->getParent();
11718 
11719           QualType MPTy = Context.getMemberPointerType(
11720               op->getType(),
11721               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11722           // Under the MS ABI, lock down the inheritance model now.
11723           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11724             (void)isCompleteType(OpLoc, MPTy);
11725           return MPTy;
11726         }
11727       }
11728     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11729                !isa<BindingDecl>(dcl))
11730       llvm_unreachable("Unknown/unexpected decl type");
11731   }
11732 
11733   if (AddressOfError != AO_No_Error) {
11734     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11735     return QualType();
11736   }
11737 
11738   if (lval == Expr::LV_IncompleteVoidType) {
11739     // Taking the address of a void variable is technically illegal, but we
11740     // allow it in cases which are otherwise valid.
11741     // Example: "extern void x; void* y = &x;".
11742     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11743   }
11744 
11745   // If the operand has type "type", the result has type "pointer to type".
11746   if (op->getType()->isObjCObjectType())
11747     return Context.getObjCObjectPointerType(op->getType());
11748 
11749   CheckAddressOfPackedMember(op);
11750 
11751   return Context.getPointerType(op->getType());
11752 }
11753 
11754 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11755   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11756   if (!DRE)
11757     return;
11758   const Decl *D = DRE->getDecl();
11759   if (!D)
11760     return;
11761   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11762   if (!Param)
11763     return;
11764   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11765     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11766       return;
11767   if (FunctionScopeInfo *FD = S.getCurFunction())
11768     if (!FD->ModifiedNonNullParams.count(Param))
11769       FD->ModifiedNonNullParams.insert(Param);
11770 }
11771 
11772 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11773 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11774                                         SourceLocation OpLoc) {
11775   if (Op->isTypeDependent())
11776     return S.Context.DependentTy;
11777 
11778   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11779   if (ConvResult.isInvalid())
11780     return QualType();
11781   Op = ConvResult.get();
11782   QualType OpTy = Op->getType();
11783   QualType Result;
11784 
11785   if (isa<CXXReinterpretCastExpr>(Op)) {
11786     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11787     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11788                                      Op->getSourceRange());
11789   }
11790 
11791   if (const PointerType *PT = OpTy->getAs<PointerType>())
11792   {
11793     Result = PT->getPointeeType();
11794   }
11795   else if (const ObjCObjectPointerType *OPT =
11796              OpTy->getAs<ObjCObjectPointerType>())
11797     Result = OPT->getPointeeType();
11798   else {
11799     ExprResult PR = S.CheckPlaceholderExpr(Op);
11800     if (PR.isInvalid()) return QualType();
11801     if (PR.get() != Op)
11802       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11803   }
11804 
11805   if (Result.isNull()) {
11806     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11807       << OpTy << Op->getSourceRange();
11808     return QualType();
11809   }
11810 
11811   // Note that per both C89 and C99, indirection is always legal, even if Result
11812   // is an incomplete type or void.  It would be possible to warn about
11813   // dereferencing a void pointer, but it's completely well-defined, and such a
11814   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11815   // for pointers to 'void' but is fine for any other pointer type:
11816   //
11817   // C++ [expr.unary.op]p1:
11818   //   [...] the expression to which [the unary * operator] is applied shall
11819   //   be a pointer to an object type, or a pointer to a function type
11820   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11821     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11822       << OpTy << Op->getSourceRange();
11823 
11824   // Dereferences are usually l-values...
11825   VK = VK_LValue;
11826 
11827   // ...except that certain expressions are never l-values in C.
11828   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11829     VK = VK_RValue;
11830 
11831   return Result;
11832 }
11833 
11834 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11835   BinaryOperatorKind Opc;
11836   switch (Kind) {
11837   default: llvm_unreachable("Unknown binop!");
11838   case tok::periodstar:           Opc = BO_PtrMemD; break;
11839   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11840   case tok::star:                 Opc = BO_Mul; break;
11841   case tok::slash:                Opc = BO_Div; break;
11842   case tok::percent:              Opc = BO_Rem; break;
11843   case tok::plus:                 Opc = BO_Add; break;
11844   case tok::minus:                Opc = BO_Sub; break;
11845   case tok::lessless:             Opc = BO_Shl; break;
11846   case tok::greatergreater:       Opc = BO_Shr; break;
11847   case tok::lessequal:            Opc = BO_LE; break;
11848   case tok::less:                 Opc = BO_LT; break;
11849   case tok::greaterequal:         Opc = BO_GE; break;
11850   case tok::greater:              Opc = BO_GT; break;
11851   case tok::exclaimequal:         Opc = BO_NE; break;
11852   case tok::equalequal:           Opc = BO_EQ; break;
11853   case tok::spaceship:            Opc = BO_Cmp; break;
11854   case tok::amp:                  Opc = BO_And; break;
11855   case tok::caret:                Opc = BO_Xor; break;
11856   case tok::pipe:                 Opc = BO_Or; break;
11857   case tok::ampamp:               Opc = BO_LAnd; break;
11858   case tok::pipepipe:             Opc = BO_LOr; break;
11859   case tok::equal:                Opc = BO_Assign; break;
11860   case tok::starequal:            Opc = BO_MulAssign; break;
11861   case tok::slashequal:           Opc = BO_DivAssign; break;
11862   case tok::percentequal:         Opc = BO_RemAssign; break;
11863   case tok::plusequal:            Opc = BO_AddAssign; break;
11864   case tok::minusequal:           Opc = BO_SubAssign; break;
11865   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11866   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11867   case tok::ampequal:             Opc = BO_AndAssign; break;
11868   case tok::caretequal:           Opc = BO_XorAssign; break;
11869   case tok::pipeequal:            Opc = BO_OrAssign; break;
11870   case tok::comma:                Opc = BO_Comma; break;
11871   }
11872   return Opc;
11873 }
11874 
11875 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11876   tok::TokenKind Kind) {
11877   UnaryOperatorKind Opc;
11878   switch (Kind) {
11879   default: llvm_unreachable("Unknown unary op!");
11880   case tok::plusplus:     Opc = UO_PreInc; break;
11881   case tok::minusminus:   Opc = UO_PreDec; break;
11882   case tok::amp:          Opc = UO_AddrOf; break;
11883   case tok::star:         Opc = UO_Deref; break;
11884   case tok::plus:         Opc = UO_Plus; break;
11885   case tok::minus:        Opc = UO_Minus; break;
11886   case tok::tilde:        Opc = UO_Not; break;
11887   case tok::exclaim:      Opc = UO_LNot; break;
11888   case tok::kw___real:    Opc = UO_Real; break;
11889   case tok::kw___imag:    Opc = UO_Imag; break;
11890   case tok::kw___extension__: Opc = UO_Extension; break;
11891   }
11892   return Opc;
11893 }
11894 
11895 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11896 /// This warning suppressed in the event of macro expansions.
11897 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11898                                    SourceLocation OpLoc, bool IsBuiltin) {
11899   if (S.inTemplateInstantiation())
11900     return;
11901   if (S.isUnevaluatedContext())
11902     return;
11903   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11904     return;
11905   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11906   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11907   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11908   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11909   if (!LHSDeclRef || !RHSDeclRef ||
11910       LHSDeclRef->getLocation().isMacroID() ||
11911       RHSDeclRef->getLocation().isMacroID())
11912     return;
11913   const ValueDecl *LHSDecl =
11914     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11915   const ValueDecl *RHSDecl =
11916     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11917   if (LHSDecl != RHSDecl)
11918     return;
11919   if (LHSDecl->getType().isVolatileQualified())
11920     return;
11921   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11922     if (RefTy->getPointeeType().isVolatileQualified())
11923       return;
11924 
11925   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11926                           : diag::warn_self_assignment_overloaded)
11927       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11928       << RHSExpr->getSourceRange();
11929 }
11930 
11931 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11932 /// is usually indicative of introspection within the Objective-C pointer.
11933 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11934                                           SourceLocation OpLoc) {
11935   if (!S.getLangOpts().ObjC1)
11936     return;
11937 
11938   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11939   const Expr *LHS = L.get();
11940   const Expr *RHS = R.get();
11941 
11942   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11943     ObjCPointerExpr = LHS;
11944     OtherExpr = RHS;
11945   }
11946   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11947     ObjCPointerExpr = RHS;
11948     OtherExpr = LHS;
11949   }
11950 
11951   // This warning is deliberately made very specific to reduce false
11952   // positives with logic that uses '&' for hashing.  This logic mainly
11953   // looks for code trying to introspect into tagged pointers, which
11954   // code should generally never do.
11955   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11956     unsigned Diag = diag::warn_objc_pointer_masking;
11957     // Determine if we are introspecting the result of performSelectorXXX.
11958     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11959     // Special case messages to -performSelector and friends, which
11960     // can return non-pointer values boxed in a pointer value.
11961     // Some clients may wish to silence warnings in this subcase.
11962     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11963       Selector S = ME->getSelector();
11964       StringRef SelArg0 = S.getNameForSlot(0);
11965       if (SelArg0.startswith("performSelector"))
11966         Diag = diag::warn_objc_pointer_masking_performSelector;
11967     }
11968 
11969     S.Diag(OpLoc, Diag)
11970       << ObjCPointerExpr->getSourceRange();
11971   }
11972 }
11973 
11974 static NamedDecl *getDeclFromExpr(Expr *E) {
11975   if (!E)
11976     return nullptr;
11977   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11978     return DRE->getDecl();
11979   if (auto *ME = dyn_cast<MemberExpr>(E))
11980     return ME->getMemberDecl();
11981   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11982     return IRE->getDecl();
11983   return nullptr;
11984 }
11985 
11986 // This helper function promotes a binary operator's operands (which are of a
11987 // half vector type) to a vector of floats and then truncates the result to
11988 // a vector of either half or short.
11989 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11990                                       BinaryOperatorKind Opc, QualType ResultTy,
11991                                       ExprValueKind VK, ExprObjectKind OK,
11992                                       bool IsCompAssign, SourceLocation OpLoc,
11993                                       FPOptions FPFeatures) {
11994   auto &Context = S.getASTContext();
11995   assert((isVector(ResultTy, Context.HalfTy) ||
11996           isVector(ResultTy, Context.ShortTy)) &&
11997          "Result must be a vector of half or short");
11998   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11999          isVector(RHS.get()->getType(), Context.HalfTy) &&
12000          "both operands expected to be a half vector");
12001 
12002   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12003   QualType BinOpResTy = RHS.get()->getType();
12004 
12005   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12006   // change BinOpResTy to a vector of ints.
12007   if (isVector(ResultTy, Context.ShortTy))
12008     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12009 
12010   if (IsCompAssign)
12011     return new (Context) CompoundAssignOperator(
12012         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12013         OpLoc, FPFeatures);
12014 
12015   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12016   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12017                                           VK, OK, OpLoc, FPFeatures);
12018   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12019 }
12020 
12021 static std::pair<ExprResult, ExprResult>
12022 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12023                            Expr *RHSExpr) {
12024   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12025   if (!S.getLangOpts().CPlusPlus) {
12026     // C cannot handle TypoExpr nodes on either side of a binop because it
12027     // doesn't handle dependent types properly, so make sure any TypoExprs have
12028     // been dealt with before checking the operands.
12029     LHS = S.CorrectDelayedTyposInExpr(LHS);
12030     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12031       if (Opc != BO_Assign)
12032         return ExprResult(E);
12033       // Avoid correcting the RHS to the same Expr as the LHS.
12034       Decl *D = getDeclFromExpr(E);
12035       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12036     });
12037   }
12038   return std::make_pair(LHS, RHS);
12039 }
12040 
12041 /// Returns true if conversion between vectors of halfs and vectors of floats
12042 /// is needed.
12043 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12044                                      QualType SrcType) {
12045   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12046          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12047          isVector(SrcType, Ctx.HalfTy);
12048 }
12049 
12050 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12051 /// operator @p Opc at location @c TokLoc. This routine only supports
12052 /// built-in operations; ActOnBinOp handles overloaded operators.
12053 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12054                                     BinaryOperatorKind Opc,
12055                                     Expr *LHSExpr, Expr *RHSExpr) {
12056   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12057     // The syntax only allows initializer lists on the RHS of assignment,
12058     // so we don't need to worry about accepting invalid code for
12059     // non-assignment operators.
12060     // C++11 5.17p9:
12061     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12062     //   of x = {} is x = T().
12063     InitializationKind Kind = InitializationKind::CreateDirectList(
12064         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12065     InitializedEntity Entity =
12066         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12067     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12068     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12069     if (Init.isInvalid())
12070       return Init;
12071     RHSExpr = Init.get();
12072   }
12073 
12074   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12075   QualType ResultTy;     // Result type of the binary operator.
12076   // The following two variables are used for compound assignment operators
12077   QualType CompLHSTy;    // Type of LHS after promotions for computation
12078   QualType CompResultTy; // Type of computation result
12079   ExprValueKind VK = VK_RValue;
12080   ExprObjectKind OK = OK_Ordinary;
12081   bool ConvertHalfVec = false;
12082 
12083   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12084   if (!LHS.isUsable() || !RHS.isUsable())
12085     return ExprError();
12086 
12087   if (getLangOpts().OpenCL) {
12088     QualType LHSTy = LHSExpr->getType();
12089     QualType RHSTy = RHSExpr->getType();
12090     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12091     // the ATOMIC_VAR_INIT macro.
12092     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12093       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12094       if (BO_Assign == Opc)
12095         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12096       else
12097         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12098       return ExprError();
12099     }
12100 
12101     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12102     // only with a builtin functions and therefore should be disallowed here.
12103     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12104         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12105         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12106         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12107       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12108       return ExprError();
12109     }
12110   }
12111 
12112   switch (Opc) {
12113   case BO_Assign:
12114     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12115     if (getLangOpts().CPlusPlus &&
12116         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12117       VK = LHS.get()->getValueKind();
12118       OK = LHS.get()->getObjectKind();
12119     }
12120     if (!ResultTy.isNull()) {
12121       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12122       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12123     }
12124     RecordModifiableNonNullParam(*this, LHS.get());
12125     break;
12126   case BO_PtrMemD:
12127   case BO_PtrMemI:
12128     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12129                                             Opc == BO_PtrMemI);
12130     break;
12131   case BO_Mul:
12132   case BO_Div:
12133     ConvertHalfVec = true;
12134     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12135                                            Opc == BO_Div);
12136     break;
12137   case BO_Rem:
12138     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12139     break;
12140   case BO_Add:
12141     ConvertHalfVec = true;
12142     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12143     break;
12144   case BO_Sub:
12145     ConvertHalfVec = true;
12146     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12147     break;
12148   case BO_Shl:
12149   case BO_Shr:
12150     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12151     break;
12152   case BO_LE:
12153   case BO_LT:
12154   case BO_GE:
12155   case BO_GT:
12156     ConvertHalfVec = true;
12157     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12158     break;
12159   case BO_EQ:
12160   case BO_NE:
12161     ConvertHalfVec = true;
12162     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12163     break;
12164   case BO_Cmp:
12165     ConvertHalfVec = true;
12166     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12167     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12168     break;
12169   case BO_And:
12170     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12171     LLVM_FALLTHROUGH;
12172   case BO_Xor:
12173   case BO_Or:
12174     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12175     break;
12176   case BO_LAnd:
12177   case BO_LOr:
12178     ConvertHalfVec = true;
12179     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12180     break;
12181   case BO_MulAssign:
12182   case BO_DivAssign:
12183     ConvertHalfVec = true;
12184     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12185                                                Opc == BO_DivAssign);
12186     CompLHSTy = CompResultTy;
12187     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12188       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12189     break;
12190   case BO_RemAssign:
12191     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12192     CompLHSTy = CompResultTy;
12193     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12194       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12195     break;
12196   case BO_AddAssign:
12197     ConvertHalfVec = true;
12198     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12199     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12200       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12201     break;
12202   case BO_SubAssign:
12203     ConvertHalfVec = true;
12204     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12205     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12206       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12207     break;
12208   case BO_ShlAssign:
12209   case BO_ShrAssign:
12210     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12211     CompLHSTy = CompResultTy;
12212     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12213       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12214     break;
12215   case BO_AndAssign:
12216   case BO_OrAssign: // fallthrough
12217     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12218     LLVM_FALLTHROUGH;
12219   case BO_XorAssign:
12220     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12221     CompLHSTy = CompResultTy;
12222     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12223       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12224     break;
12225   case BO_Comma:
12226     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12227     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12228       VK = RHS.get()->getValueKind();
12229       OK = RHS.get()->getObjectKind();
12230     }
12231     break;
12232   }
12233   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12234     return ExprError();
12235 
12236   // Some of the binary operations require promoting operands of half vector to
12237   // float vectors and truncating the result back to half vector. For now, we do
12238   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12239   // arm64).
12240   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12241          isVector(LHS.get()->getType(), Context.HalfTy) &&
12242          "both sides are half vectors or neither sides are");
12243   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12244                                             LHS.get()->getType());
12245 
12246   // Check for array bounds violations for both sides of the BinaryOperator
12247   CheckArrayAccess(LHS.get());
12248   CheckArrayAccess(RHS.get());
12249 
12250   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12251     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12252                                                  &Context.Idents.get("object_setClass"),
12253                                                  SourceLocation(), LookupOrdinaryName);
12254     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12255       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12256       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12257           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12258                                         "object_setClass(")
12259           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12260                                           ",")
12261           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12262     }
12263     else
12264       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12265   }
12266   else if (const ObjCIvarRefExpr *OIRE =
12267            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12268     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12269 
12270   // Opc is not a compound assignment if CompResultTy is null.
12271   if (CompResultTy.isNull()) {
12272     if (ConvertHalfVec)
12273       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12274                                  OpLoc, FPFeatures);
12275     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12276                                         OK, OpLoc, FPFeatures);
12277   }
12278 
12279   // Handle compound assignments.
12280   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12281       OK_ObjCProperty) {
12282     VK = VK_LValue;
12283     OK = LHS.get()->getObjectKind();
12284   }
12285 
12286   if (ConvertHalfVec)
12287     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12288                                OpLoc, FPFeatures);
12289 
12290   return new (Context) CompoundAssignOperator(
12291       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12292       OpLoc, FPFeatures);
12293 }
12294 
12295 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12296 /// operators are mixed in a way that suggests that the programmer forgot that
12297 /// comparison operators have higher precedence. The most typical example of
12298 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12299 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12300                                       SourceLocation OpLoc, Expr *LHSExpr,
12301                                       Expr *RHSExpr) {
12302   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12303   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12304 
12305   // Check that one of the sides is a comparison operator and the other isn't.
12306   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12307   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12308   if (isLeftComp == isRightComp)
12309     return;
12310 
12311   // Bitwise operations are sometimes used as eager logical ops.
12312   // Don't diagnose this.
12313   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12314   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12315   if (isLeftBitwise || isRightBitwise)
12316     return;
12317 
12318   SourceRange DiagRange = isLeftComp
12319                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12320                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12321   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12322   SourceRange ParensRange =
12323       isLeftComp
12324           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12325           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12326 
12327   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12328     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12329   SuggestParentheses(Self, OpLoc,
12330     Self.PDiag(diag::note_precedence_silence) << OpStr,
12331     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12332   SuggestParentheses(Self, OpLoc,
12333     Self.PDiag(diag::note_precedence_bitwise_first)
12334       << BinaryOperator::getOpcodeStr(Opc),
12335     ParensRange);
12336 }
12337 
12338 /// It accepts a '&&' expr that is inside a '||' one.
12339 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12340 /// in parentheses.
12341 static void
12342 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12343                                        BinaryOperator *Bop) {
12344   assert(Bop->getOpcode() == BO_LAnd);
12345   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12346       << Bop->getSourceRange() << OpLoc;
12347   SuggestParentheses(Self, Bop->getOperatorLoc(),
12348     Self.PDiag(diag::note_precedence_silence)
12349       << Bop->getOpcodeStr(),
12350     Bop->getSourceRange());
12351 }
12352 
12353 /// Returns true if the given expression can be evaluated as a constant
12354 /// 'true'.
12355 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12356   bool Res;
12357   return !E->isValueDependent() &&
12358          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12359 }
12360 
12361 /// Returns true if the given expression can be evaluated as a constant
12362 /// 'false'.
12363 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12364   bool Res;
12365   return !E->isValueDependent() &&
12366          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12367 }
12368 
12369 /// Look for '&&' in the left hand of a '||' expr.
12370 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12371                                              Expr *LHSExpr, Expr *RHSExpr) {
12372   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12373     if (Bop->getOpcode() == BO_LAnd) {
12374       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12375       if (EvaluatesAsFalse(S, RHSExpr))
12376         return;
12377       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12378       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12379         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12380     } else if (Bop->getOpcode() == BO_LOr) {
12381       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12382         // If it's "a || b && 1 || c" we didn't warn earlier for
12383         // "a || b && 1", but warn now.
12384         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12385           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12386       }
12387     }
12388   }
12389 }
12390 
12391 /// Look for '&&' in the right hand of a '||' expr.
12392 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12393                                              Expr *LHSExpr, Expr *RHSExpr) {
12394   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12395     if (Bop->getOpcode() == BO_LAnd) {
12396       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12397       if (EvaluatesAsFalse(S, LHSExpr))
12398         return;
12399       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12400       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12401         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12402     }
12403   }
12404 }
12405 
12406 /// Look for bitwise op in the left or right hand of a bitwise op with
12407 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12408 /// the '&' expression in parentheses.
12409 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12410                                          SourceLocation OpLoc, Expr *SubExpr) {
12411   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12412     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12413       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12414         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12415         << Bop->getSourceRange() << OpLoc;
12416       SuggestParentheses(S, Bop->getOperatorLoc(),
12417         S.PDiag(diag::note_precedence_silence)
12418           << Bop->getOpcodeStr(),
12419         Bop->getSourceRange());
12420     }
12421   }
12422 }
12423 
12424 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12425                                     Expr *SubExpr, StringRef Shift) {
12426   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12427     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12428       StringRef Op = Bop->getOpcodeStr();
12429       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12430           << Bop->getSourceRange() << OpLoc << Shift << Op;
12431       SuggestParentheses(S, Bop->getOperatorLoc(),
12432           S.PDiag(diag::note_precedence_silence) << Op,
12433           Bop->getSourceRange());
12434     }
12435   }
12436 }
12437 
12438 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12439                                  Expr *LHSExpr, Expr *RHSExpr) {
12440   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12441   if (!OCE)
12442     return;
12443 
12444   FunctionDecl *FD = OCE->getDirectCallee();
12445   if (!FD || !FD->isOverloadedOperator())
12446     return;
12447 
12448   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12449   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12450     return;
12451 
12452   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12453       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12454       << (Kind == OO_LessLess);
12455   SuggestParentheses(S, OCE->getOperatorLoc(),
12456                      S.PDiag(diag::note_precedence_silence)
12457                          << (Kind == OO_LessLess ? "<<" : ">>"),
12458                      OCE->getSourceRange());
12459   SuggestParentheses(
12460       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12461       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12462 }
12463 
12464 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12465 /// precedence.
12466 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12467                                     SourceLocation OpLoc, Expr *LHSExpr,
12468                                     Expr *RHSExpr){
12469   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12470   if (BinaryOperator::isBitwiseOp(Opc))
12471     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12472 
12473   // Diagnose "arg1 & arg2 | arg3"
12474   if ((Opc == BO_Or || Opc == BO_Xor) &&
12475       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12476     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12477     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12478   }
12479 
12480   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12481   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12482   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12483     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12484     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12485   }
12486 
12487   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12488       || Opc == BO_Shr) {
12489     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12490     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12491     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12492   }
12493 
12494   // Warn on overloaded shift operators and comparisons, such as:
12495   // cout << 5 == 4;
12496   if (BinaryOperator::isComparisonOp(Opc))
12497     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12498 }
12499 
12500 // Binary Operators.  'Tok' is the token for the operator.
12501 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12502                             tok::TokenKind Kind,
12503                             Expr *LHSExpr, Expr *RHSExpr) {
12504   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12505   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12506   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12507 
12508   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12509   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12510 
12511   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12512 }
12513 
12514 /// Build an overloaded binary operator expression in the given scope.
12515 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12516                                        BinaryOperatorKind Opc,
12517                                        Expr *LHS, Expr *RHS) {
12518   switch (Opc) {
12519   case BO_Assign:
12520   case BO_DivAssign:
12521   case BO_RemAssign:
12522   case BO_SubAssign:
12523   case BO_AndAssign:
12524   case BO_OrAssign:
12525   case BO_XorAssign:
12526     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12527     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12528     break;
12529   default:
12530     break;
12531   }
12532 
12533   // Find all of the overloaded operators visible from this
12534   // point. We perform both an operator-name lookup from the local
12535   // scope and an argument-dependent lookup based on the types of
12536   // the arguments.
12537   UnresolvedSet<16> Functions;
12538   OverloadedOperatorKind OverOp
12539     = BinaryOperator::getOverloadedOperator(Opc);
12540   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12541     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12542                                    RHS->getType(), Functions);
12543 
12544   // Build the (potentially-overloaded, potentially-dependent)
12545   // binary operation.
12546   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12547 }
12548 
12549 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12550                             BinaryOperatorKind Opc,
12551                             Expr *LHSExpr, Expr *RHSExpr) {
12552   ExprResult LHS, RHS;
12553   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12554   if (!LHS.isUsable() || !RHS.isUsable())
12555     return ExprError();
12556   LHSExpr = LHS.get();
12557   RHSExpr = RHS.get();
12558 
12559   // We want to end up calling one of checkPseudoObjectAssignment
12560   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12561   // both expressions are overloadable or either is type-dependent),
12562   // or CreateBuiltinBinOp (in any other case).  We also want to get
12563   // any placeholder types out of the way.
12564 
12565   // Handle pseudo-objects in the LHS.
12566   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12567     // Assignments with a pseudo-object l-value need special analysis.
12568     if (pty->getKind() == BuiltinType::PseudoObject &&
12569         BinaryOperator::isAssignmentOp(Opc))
12570       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12571 
12572     // Don't resolve overloads if the other type is overloadable.
12573     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12574       // We can't actually test that if we still have a placeholder,
12575       // though.  Fortunately, none of the exceptions we see in that
12576       // code below are valid when the LHS is an overload set.  Note
12577       // that an overload set can be dependently-typed, but it never
12578       // instantiates to having an overloadable type.
12579       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12580       if (resolvedRHS.isInvalid()) return ExprError();
12581       RHSExpr = resolvedRHS.get();
12582 
12583       if (RHSExpr->isTypeDependent() ||
12584           RHSExpr->getType()->isOverloadableType())
12585         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12586     }
12587 
12588     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12589     // template, diagnose the missing 'template' keyword instead of diagnosing
12590     // an invalid use of a bound member function.
12591     //
12592     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12593     // to C++1z [over.over]/1.4, but we already checked for that case above.
12594     if (Opc == BO_LT && inTemplateInstantiation() &&
12595         (pty->getKind() == BuiltinType::BoundMember ||
12596          pty->getKind() == BuiltinType::Overload)) {
12597       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12598       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12599           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12600             return isa<FunctionTemplateDecl>(ND);
12601           })) {
12602         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12603                                 : OE->getNameLoc(),
12604              diag::err_template_kw_missing)
12605           << OE->getName().getAsString() << "";
12606         return ExprError();
12607       }
12608     }
12609 
12610     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12611     if (LHS.isInvalid()) return ExprError();
12612     LHSExpr = LHS.get();
12613   }
12614 
12615   // Handle pseudo-objects in the RHS.
12616   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12617     // An overload in the RHS can potentially be resolved by the type
12618     // being assigned to.
12619     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12620       if (getLangOpts().CPlusPlus &&
12621           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12622            LHSExpr->getType()->isOverloadableType()))
12623         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12624 
12625       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12626     }
12627 
12628     // Don't resolve overloads if the other type is overloadable.
12629     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12630         LHSExpr->getType()->isOverloadableType())
12631       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12632 
12633     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12634     if (!resolvedRHS.isUsable()) return ExprError();
12635     RHSExpr = resolvedRHS.get();
12636   }
12637 
12638   if (getLangOpts().CPlusPlus) {
12639     // If either expression is type-dependent, always build an
12640     // overloaded op.
12641     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12642       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12643 
12644     // Otherwise, build an overloaded op if either expression has an
12645     // overloadable type.
12646     if (LHSExpr->getType()->isOverloadableType() ||
12647         RHSExpr->getType()->isOverloadableType())
12648       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12649   }
12650 
12651   // Build a built-in binary operation.
12652   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12653 }
12654 
12655 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12656   if (T.isNull() || T->isDependentType())
12657     return false;
12658 
12659   if (!T->isPromotableIntegerType())
12660     return true;
12661 
12662   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12663 }
12664 
12665 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12666                                       UnaryOperatorKind Opc,
12667                                       Expr *InputExpr) {
12668   ExprResult Input = InputExpr;
12669   ExprValueKind VK = VK_RValue;
12670   ExprObjectKind OK = OK_Ordinary;
12671   QualType resultType;
12672   bool CanOverflow = false;
12673 
12674   bool ConvertHalfVec = false;
12675   if (getLangOpts().OpenCL) {
12676     QualType Ty = InputExpr->getType();
12677     // The only legal unary operation for atomics is '&'.
12678     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12679     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12680     // only with a builtin functions and therefore should be disallowed here.
12681         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12682         || Ty->isBlockPointerType())) {
12683       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12684                        << InputExpr->getType()
12685                        << Input.get()->getSourceRange());
12686     }
12687   }
12688   switch (Opc) {
12689   case UO_PreInc:
12690   case UO_PreDec:
12691   case UO_PostInc:
12692   case UO_PostDec:
12693     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12694                                                 OpLoc,
12695                                                 Opc == UO_PreInc ||
12696                                                 Opc == UO_PostInc,
12697                                                 Opc == UO_PreInc ||
12698                                                 Opc == UO_PreDec);
12699     CanOverflow = isOverflowingIntegerType(Context, resultType);
12700     break;
12701   case UO_AddrOf:
12702     resultType = CheckAddressOfOperand(Input, OpLoc);
12703     RecordModifiableNonNullParam(*this, InputExpr);
12704     break;
12705   case UO_Deref: {
12706     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12707     if (Input.isInvalid()) return ExprError();
12708     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12709     break;
12710   }
12711   case UO_Plus:
12712   case UO_Minus:
12713     CanOverflow = Opc == UO_Minus &&
12714                   isOverflowingIntegerType(Context, Input.get()->getType());
12715     Input = UsualUnaryConversions(Input.get());
12716     if (Input.isInvalid()) return ExprError();
12717     // Unary plus and minus require promoting an operand of half vector to a
12718     // float vector and truncating the result back to a half vector. For now, we
12719     // do this only when HalfArgsAndReturns is set (that is, when the target is
12720     // arm or arm64).
12721     ConvertHalfVec =
12722         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12723 
12724     // If the operand is a half vector, promote it to a float vector.
12725     if (ConvertHalfVec)
12726       Input = convertVector(Input.get(), Context.FloatTy, *this);
12727     resultType = Input.get()->getType();
12728     if (resultType->isDependentType())
12729       break;
12730     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12731       break;
12732     else if (resultType->isVectorType() &&
12733              // The z vector extensions don't allow + or - with bool vectors.
12734              (!Context.getLangOpts().ZVector ||
12735               resultType->getAs<VectorType>()->getVectorKind() !=
12736               VectorType::AltiVecBool))
12737       break;
12738     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12739              Opc == UO_Plus &&
12740              resultType->isPointerType())
12741       break;
12742 
12743     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12744       << resultType << Input.get()->getSourceRange());
12745 
12746   case UO_Not: // bitwise complement
12747     Input = UsualUnaryConversions(Input.get());
12748     if (Input.isInvalid())
12749       return ExprError();
12750     resultType = Input.get()->getType();
12751 
12752     if (resultType->isDependentType())
12753       break;
12754     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12755     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12756       // C99 does not support '~' for complex conjugation.
12757       Diag(OpLoc, diag::ext_integer_complement_complex)
12758           << resultType << Input.get()->getSourceRange();
12759     else if (resultType->hasIntegerRepresentation())
12760       break;
12761     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12762       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12763       // on vector float types.
12764       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12765       if (!T->isIntegerType())
12766         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12767                           << resultType << Input.get()->getSourceRange());
12768     } else {
12769       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12770                        << resultType << Input.get()->getSourceRange());
12771     }
12772     break;
12773 
12774   case UO_LNot: // logical negation
12775     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12776     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12777     if (Input.isInvalid()) return ExprError();
12778     resultType = Input.get()->getType();
12779 
12780     // Though we still have to promote half FP to float...
12781     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12782       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12783       resultType = Context.FloatTy;
12784     }
12785 
12786     if (resultType->isDependentType())
12787       break;
12788     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12789       // C99 6.5.3.3p1: ok, fallthrough;
12790       if (Context.getLangOpts().CPlusPlus) {
12791         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12792         // operand contextually converted to bool.
12793         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12794                                   ScalarTypeToBooleanCastKind(resultType));
12795       } else if (Context.getLangOpts().OpenCL &&
12796                  Context.getLangOpts().OpenCLVersion < 120) {
12797         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12798         // operate on scalar float types.
12799         if (!resultType->isIntegerType() && !resultType->isPointerType())
12800           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12801                            << resultType << Input.get()->getSourceRange());
12802       }
12803     } else if (resultType->isExtVectorType()) {
12804       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 vector float types.
12808         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12809         if (!T->isIntegerType())
12810           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12811                            << resultType << Input.get()->getSourceRange());
12812       }
12813       // Vector logical not returns the signed variant of the operand type.
12814       resultType = GetSignedVectorType(resultType);
12815       break;
12816     } else {
12817       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12818       //        type in C++. We should allow that here too.
12819       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12820         << resultType << Input.get()->getSourceRange());
12821     }
12822 
12823     // LNot always has type int. C99 6.5.3.3p5.
12824     // In C++, it's bool. C++ 5.3.1p8
12825     resultType = Context.getLogicalOperationType();
12826     break;
12827   case UO_Real:
12828   case UO_Imag:
12829     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12830     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12831     // complex l-values to ordinary l-values and all other values to r-values.
12832     if (Input.isInvalid()) return ExprError();
12833     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12834       if (Input.get()->getValueKind() != VK_RValue &&
12835           Input.get()->getObjectKind() == OK_Ordinary)
12836         VK = Input.get()->getValueKind();
12837     } else if (!getLangOpts().CPlusPlus) {
12838       // In C, a volatile scalar is read by __imag. In C++, it is not.
12839       Input = DefaultLvalueConversion(Input.get());
12840     }
12841     break;
12842   case UO_Extension:
12843     resultType = Input.get()->getType();
12844     VK = Input.get()->getValueKind();
12845     OK = Input.get()->getObjectKind();
12846     break;
12847   case UO_Coawait:
12848     // It's unnecessary to represent the pass-through operator co_await in the
12849     // AST; just return the input expression instead.
12850     assert(!Input.get()->getType()->isDependentType() &&
12851                    "the co_await expression must be non-dependant before "
12852                    "building operator co_await");
12853     return Input;
12854   }
12855   if (resultType.isNull() || Input.isInvalid())
12856     return ExprError();
12857 
12858   // Check for array bounds violations in the operand of the UnaryOperator,
12859   // except for the '*' and '&' operators that have to be handled specially
12860   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12861   // that are explicitly defined as valid by the standard).
12862   if (Opc != UO_AddrOf && Opc != UO_Deref)
12863     CheckArrayAccess(Input.get());
12864 
12865   auto *UO = new (Context)
12866       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12867   // Convert the result back to a half vector.
12868   if (ConvertHalfVec)
12869     return convertVector(UO, Context.HalfTy, *this);
12870   return UO;
12871 }
12872 
12873 /// Determine whether the given expression is a qualified member
12874 /// access expression, of a form that could be turned into a pointer to member
12875 /// with the address-of operator.
12876 bool Sema::isQualifiedMemberAccess(Expr *E) {
12877   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12878     if (!DRE->getQualifier())
12879       return false;
12880 
12881     ValueDecl *VD = DRE->getDecl();
12882     if (!VD->isCXXClassMember())
12883       return false;
12884 
12885     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12886       return true;
12887     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12888       return Method->isInstance();
12889 
12890     return false;
12891   }
12892 
12893   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12894     if (!ULE->getQualifier())
12895       return false;
12896 
12897     for (NamedDecl *D : ULE->decls()) {
12898       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12899         if (Method->isInstance())
12900           return true;
12901       } else {
12902         // Overload set does not contain methods.
12903         break;
12904       }
12905     }
12906 
12907     return false;
12908   }
12909 
12910   return false;
12911 }
12912 
12913 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12914                               UnaryOperatorKind Opc, Expr *Input) {
12915   // First things first: handle placeholders so that the
12916   // overloaded-operator check considers the right type.
12917   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12918     // Increment and decrement of pseudo-object references.
12919     if (pty->getKind() == BuiltinType::PseudoObject &&
12920         UnaryOperator::isIncrementDecrementOp(Opc))
12921       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12922 
12923     // extension is always a builtin operator.
12924     if (Opc == UO_Extension)
12925       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12926 
12927     // & gets special logic for several kinds of placeholder.
12928     // The builtin code knows what to do.
12929     if (Opc == UO_AddrOf &&
12930         (pty->getKind() == BuiltinType::Overload ||
12931          pty->getKind() == BuiltinType::UnknownAny ||
12932          pty->getKind() == BuiltinType::BoundMember))
12933       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12934 
12935     // Anything else needs to be handled now.
12936     ExprResult Result = CheckPlaceholderExpr(Input);
12937     if (Result.isInvalid()) return ExprError();
12938     Input = Result.get();
12939   }
12940 
12941   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12942       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12943       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12944     // Find all of the overloaded operators visible from this
12945     // point. We perform both an operator-name lookup from the local
12946     // scope and an argument-dependent lookup based on the types of
12947     // the arguments.
12948     UnresolvedSet<16> Functions;
12949     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12950     if (S && OverOp != OO_None)
12951       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12952                                    Functions);
12953 
12954     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12955   }
12956 
12957   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12958 }
12959 
12960 // Unary Operators.  'Tok' is the token for the operator.
12961 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12962                               tok::TokenKind Op, Expr *Input) {
12963   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12964 }
12965 
12966 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12967 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12968                                 LabelDecl *TheDecl) {
12969   TheDecl->markUsed(Context);
12970   // Create the AST node.  The address of a label always has type 'void*'.
12971   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12972                                      Context.getPointerType(Context.VoidTy));
12973 }
12974 
12975 /// Given the last statement in a statement-expression, check whether
12976 /// the result is a producing expression (like a call to an
12977 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12978 /// release out of the full-expression.  Otherwise, return null.
12979 /// Cannot fail.
12980 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12981   // Should always be wrapped with one of these.
12982   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12983   if (!cleanups) return nullptr;
12984 
12985   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12986   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12987     return nullptr;
12988 
12989   // Splice out the cast.  This shouldn't modify any interesting
12990   // features of the statement.
12991   Expr *producer = cast->getSubExpr();
12992   assert(producer->getType() == cast->getType());
12993   assert(producer->getValueKind() == cast->getValueKind());
12994   cleanups->setSubExpr(producer);
12995   return cleanups;
12996 }
12997 
12998 void Sema::ActOnStartStmtExpr() {
12999   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13000 }
13001 
13002 void Sema::ActOnStmtExprError() {
13003   // Note that function is also called by TreeTransform when leaving a
13004   // StmtExpr scope without rebuilding anything.
13005 
13006   DiscardCleanupsInEvaluationContext();
13007   PopExpressionEvaluationContext();
13008 }
13009 
13010 ExprResult
13011 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13012                     SourceLocation RPLoc) { // "({..})"
13013   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13014   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13015 
13016   if (hasAnyUnrecoverableErrorsInThisFunction())
13017     DiscardCleanupsInEvaluationContext();
13018   assert(!Cleanup.exprNeedsCleanups() &&
13019          "cleanups within StmtExpr not correctly bound!");
13020   PopExpressionEvaluationContext();
13021 
13022   // FIXME: there are a variety of strange constraints to enforce here, for
13023   // example, it is not possible to goto into a stmt expression apparently.
13024   // More semantic analysis is needed.
13025 
13026   // If there are sub-stmts in the compound stmt, take the type of the last one
13027   // as the type of the stmtexpr.
13028   QualType Ty = Context.VoidTy;
13029   bool StmtExprMayBindToTemp = false;
13030   if (!Compound->body_empty()) {
13031     Stmt *LastStmt = Compound->body_back();
13032     LabelStmt *LastLabelStmt = nullptr;
13033     // If LastStmt is a label, skip down through into the body.
13034     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
13035       LastLabelStmt = Label;
13036       LastStmt = Label->getSubStmt();
13037     }
13038 
13039     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
13040       // Do function/array conversion on the last expression, but not
13041       // lvalue-to-rvalue.  However, initialize an unqualified type.
13042       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
13043       if (LastExpr.isInvalid())
13044         return ExprError();
13045       Ty = LastExpr.get()->getType().getUnqualifiedType();
13046 
13047       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
13048         // In ARC, if the final expression ends in a consume, splice
13049         // the consume out and bind it later.  In the alternate case
13050         // (when dealing with a retainable type), the result
13051         // initialization will create a produce.  In both cases the
13052         // result will be +1, and we'll need to balance that out with
13053         // a bind.
13054         if (Expr *rebuiltLastStmt
13055               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
13056           LastExpr = rebuiltLastStmt;
13057         } else {
13058           LastExpr = PerformCopyInitialization(
13059               InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13060               SourceLocation(), LastExpr);
13061         }
13062 
13063         if (LastExpr.isInvalid())
13064           return ExprError();
13065         if (LastExpr.get() != nullptr) {
13066           if (!LastLabelStmt)
13067             Compound->setLastStmt(LastExpr.get());
13068           else
13069             LastLabelStmt->setSubStmt(LastExpr.get());
13070           StmtExprMayBindToTemp = true;
13071         }
13072       }
13073     }
13074   }
13075 
13076   // FIXME: Check that expression type is complete/non-abstract; statement
13077   // expressions are not lvalues.
13078   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13079   if (StmtExprMayBindToTemp)
13080     return MaybeBindToTemporary(ResStmtExpr);
13081   return ResStmtExpr;
13082 }
13083 
13084 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13085                                       TypeSourceInfo *TInfo,
13086                                       ArrayRef<OffsetOfComponent> Components,
13087                                       SourceLocation RParenLoc) {
13088   QualType ArgTy = TInfo->getType();
13089   bool Dependent = ArgTy->isDependentType();
13090   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13091 
13092   // We must have at least one component that refers to the type, and the first
13093   // one is known to be a field designator.  Verify that the ArgTy represents
13094   // a struct/union/class.
13095   if (!Dependent && !ArgTy->isRecordType())
13096     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13097                        << ArgTy << TypeRange);
13098 
13099   // Type must be complete per C99 7.17p3 because a declaring a variable
13100   // with an incomplete type would be ill-formed.
13101   if (!Dependent
13102       && RequireCompleteType(BuiltinLoc, ArgTy,
13103                              diag::err_offsetof_incomplete_type, TypeRange))
13104     return ExprError();
13105 
13106   bool DidWarnAboutNonPOD = false;
13107   QualType CurrentType = ArgTy;
13108   SmallVector<OffsetOfNode, 4> Comps;
13109   SmallVector<Expr*, 4> Exprs;
13110   for (const OffsetOfComponent &OC : Components) {
13111     if (OC.isBrackets) {
13112       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13113       if (!CurrentType->isDependentType()) {
13114         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13115         if(!AT)
13116           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13117                            << CurrentType);
13118         CurrentType = AT->getElementType();
13119       } else
13120         CurrentType = Context.DependentTy;
13121 
13122       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13123       if (IdxRval.isInvalid())
13124         return ExprError();
13125       Expr *Idx = IdxRval.get();
13126 
13127       // The expression must be an integral expression.
13128       // FIXME: An integral constant expression?
13129       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13130           !Idx->getType()->isIntegerType())
13131         return ExprError(
13132             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13133             << Idx->getSourceRange());
13134 
13135       // Record this array index.
13136       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13137       Exprs.push_back(Idx);
13138       continue;
13139     }
13140 
13141     // Offset of a field.
13142     if (CurrentType->isDependentType()) {
13143       // We have the offset of a field, but we can't look into the dependent
13144       // type. Just record the identifier of the field.
13145       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13146       CurrentType = Context.DependentTy;
13147       continue;
13148     }
13149 
13150     // We need to have a complete type to look into.
13151     if (RequireCompleteType(OC.LocStart, CurrentType,
13152                             diag::err_offsetof_incomplete_type))
13153       return ExprError();
13154 
13155     // Look for the designated field.
13156     const RecordType *RC = CurrentType->getAs<RecordType>();
13157     if (!RC)
13158       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13159                        << CurrentType);
13160     RecordDecl *RD = RC->getDecl();
13161 
13162     // C++ [lib.support.types]p5:
13163     //   The macro offsetof accepts a restricted set of type arguments in this
13164     //   International Standard. type shall be a POD structure or a POD union
13165     //   (clause 9).
13166     // C++11 [support.types]p4:
13167     //   If type is not a standard-layout class (Clause 9), the results are
13168     //   undefined.
13169     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13170       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13171       unsigned DiagID =
13172         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13173                             : diag::ext_offsetof_non_pod_type;
13174 
13175       if (!IsSafe && !DidWarnAboutNonPOD &&
13176           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13177                               PDiag(DiagID)
13178                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13179                               << CurrentType))
13180         DidWarnAboutNonPOD = true;
13181     }
13182 
13183     // Look for the field.
13184     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13185     LookupQualifiedName(R, RD);
13186     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13187     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13188     if (!MemberDecl) {
13189       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13190         MemberDecl = IndirectMemberDecl->getAnonField();
13191     }
13192 
13193     if (!MemberDecl)
13194       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13195                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13196                                                               OC.LocEnd));
13197 
13198     // C99 7.17p3:
13199     //   (If the specified member is a bit-field, the behavior is undefined.)
13200     //
13201     // We diagnose this as an error.
13202     if (MemberDecl->isBitField()) {
13203       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13204         << MemberDecl->getDeclName()
13205         << SourceRange(BuiltinLoc, RParenLoc);
13206       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13207       return ExprError();
13208     }
13209 
13210     RecordDecl *Parent = MemberDecl->getParent();
13211     if (IndirectMemberDecl)
13212       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13213 
13214     // If the member was found in a base class, introduce OffsetOfNodes for
13215     // the base class indirections.
13216     CXXBasePaths Paths;
13217     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13218                       Paths)) {
13219       if (Paths.getDetectedVirtual()) {
13220         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13221           << MemberDecl->getDeclName()
13222           << SourceRange(BuiltinLoc, RParenLoc);
13223         return ExprError();
13224       }
13225 
13226       CXXBasePath &Path = Paths.front();
13227       for (const CXXBasePathElement &B : Path)
13228         Comps.push_back(OffsetOfNode(B.Base));
13229     }
13230 
13231     if (IndirectMemberDecl) {
13232       for (auto *FI : IndirectMemberDecl->chain()) {
13233         assert(isa<FieldDecl>(FI));
13234         Comps.push_back(OffsetOfNode(OC.LocStart,
13235                                      cast<FieldDecl>(FI), OC.LocEnd));
13236       }
13237     } else
13238       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13239 
13240     CurrentType = MemberDecl->getType().getNonReferenceType();
13241   }
13242 
13243   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13244                               Comps, Exprs, RParenLoc);
13245 }
13246 
13247 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13248                                       SourceLocation BuiltinLoc,
13249                                       SourceLocation TypeLoc,
13250                                       ParsedType ParsedArgTy,
13251                                       ArrayRef<OffsetOfComponent> Components,
13252                                       SourceLocation RParenLoc) {
13253 
13254   TypeSourceInfo *ArgTInfo;
13255   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13256   if (ArgTy.isNull())
13257     return ExprError();
13258 
13259   if (!ArgTInfo)
13260     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13261 
13262   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13263 }
13264 
13265 
13266 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13267                                  Expr *CondExpr,
13268                                  Expr *LHSExpr, Expr *RHSExpr,
13269                                  SourceLocation RPLoc) {
13270   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13271 
13272   ExprValueKind VK = VK_RValue;
13273   ExprObjectKind OK = OK_Ordinary;
13274   QualType resType;
13275   bool ValueDependent = false;
13276   bool CondIsTrue = false;
13277   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13278     resType = Context.DependentTy;
13279     ValueDependent = true;
13280   } else {
13281     // The conditional expression is required to be a constant expression.
13282     llvm::APSInt condEval(32);
13283     ExprResult CondICE
13284       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13285           diag::err_typecheck_choose_expr_requires_constant, false);
13286     if (CondICE.isInvalid())
13287       return ExprError();
13288     CondExpr = CondICE.get();
13289     CondIsTrue = condEval.getZExtValue();
13290 
13291     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13292     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13293 
13294     resType = ActiveExpr->getType();
13295     ValueDependent = ActiveExpr->isValueDependent();
13296     VK = ActiveExpr->getValueKind();
13297     OK = ActiveExpr->getObjectKind();
13298   }
13299 
13300   return new (Context)
13301       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13302                  CondIsTrue, resType->isDependentType(), ValueDependent);
13303 }
13304 
13305 //===----------------------------------------------------------------------===//
13306 // Clang Extensions.
13307 //===----------------------------------------------------------------------===//
13308 
13309 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13310 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13311   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13312 
13313   if (LangOpts.CPlusPlus) {
13314     Decl *ManglingContextDecl;
13315     if (MangleNumberingContext *MCtx =
13316             getCurrentMangleNumberContext(Block->getDeclContext(),
13317                                           ManglingContextDecl)) {
13318       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13319       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13320     }
13321   }
13322 
13323   PushBlockScope(CurScope, Block);
13324   CurContext->addDecl(Block);
13325   if (CurScope)
13326     PushDeclContext(CurScope, Block);
13327   else
13328     CurContext = Block;
13329 
13330   getCurBlock()->HasImplicitReturnType = true;
13331 
13332   // Enter a new evaluation context to insulate the block from any
13333   // cleanups from the enclosing full-expression.
13334   PushExpressionEvaluationContext(
13335       ExpressionEvaluationContext::PotentiallyEvaluated);
13336 }
13337 
13338 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13339                                Scope *CurScope) {
13340   assert(ParamInfo.getIdentifier() == nullptr &&
13341          "block-id should have no identifier!");
13342   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13343   BlockScopeInfo *CurBlock = getCurBlock();
13344 
13345   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13346   QualType T = Sig->getType();
13347 
13348   // FIXME: We should allow unexpanded parameter packs here, but that would,
13349   // in turn, make the block expression contain unexpanded parameter packs.
13350   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13351     // Drop the parameters.
13352     FunctionProtoType::ExtProtoInfo EPI;
13353     EPI.HasTrailingReturn = false;
13354     EPI.TypeQuals |= DeclSpec::TQ_const;
13355     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13356     Sig = Context.getTrivialTypeSourceInfo(T);
13357   }
13358 
13359   // GetTypeForDeclarator always produces a function type for a block
13360   // literal signature.  Furthermore, it is always a FunctionProtoType
13361   // unless the function was written with a typedef.
13362   assert(T->isFunctionType() &&
13363          "GetTypeForDeclarator made a non-function block signature");
13364 
13365   // Look for an explicit signature in that function type.
13366   FunctionProtoTypeLoc ExplicitSignature;
13367 
13368   if ((ExplicitSignature =
13369            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13370 
13371     // Check whether that explicit signature was synthesized by
13372     // GetTypeForDeclarator.  If so, don't save that as part of the
13373     // written signature.
13374     if (ExplicitSignature.getLocalRangeBegin() ==
13375         ExplicitSignature.getLocalRangeEnd()) {
13376       // This would be much cheaper if we stored TypeLocs instead of
13377       // TypeSourceInfos.
13378       TypeLoc Result = ExplicitSignature.getReturnLoc();
13379       unsigned Size = Result.getFullDataSize();
13380       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13381       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13382 
13383       ExplicitSignature = FunctionProtoTypeLoc();
13384     }
13385   }
13386 
13387   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13388   CurBlock->FunctionType = T;
13389 
13390   const FunctionType *Fn = T->getAs<FunctionType>();
13391   QualType RetTy = Fn->getReturnType();
13392   bool isVariadic =
13393     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13394 
13395   CurBlock->TheDecl->setIsVariadic(isVariadic);
13396 
13397   // Context.DependentTy is used as a placeholder for a missing block
13398   // return type.  TODO:  what should we do with declarators like:
13399   //   ^ * { ... }
13400   // If the answer is "apply template argument deduction"....
13401   if (RetTy != Context.DependentTy) {
13402     CurBlock->ReturnType = RetTy;
13403     CurBlock->TheDecl->setBlockMissingReturnType(false);
13404     CurBlock->HasImplicitReturnType = false;
13405   }
13406 
13407   // Push block parameters from the declarator if we had them.
13408   SmallVector<ParmVarDecl*, 8> Params;
13409   if (ExplicitSignature) {
13410     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13411       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13412       if (Param->getIdentifier() == nullptr &&
13413           !Param->isImplicit() &&
13414           !Param->isInvalidDecl() &&
13415           !getLangOpts().CPlusPlus)
13416         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13417       Params.push_back(Param);
13418     }
13419 
13420   // Fake up parameter variables if we have a typedef, like
13421   //   ^ fntype { ... }
13422   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13423     for (const auto &I : Fn->param_types()) {
13424       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13425           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13426       Params.push_back(Param);
13427     }
13428   }
13429 
13430   // Set the parameters on the block decl.
13431   if (!Params.empty()) {
13432     CurBlock->TheDecl->setParams(Params);
13433     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13434                              /*CheckParameterNames=*/false);
13435   }
13436 
13437   // Finally we can process decl attributes.
13438   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13439 
13440   // Put the parameter variables in scope.
13441   for (auto AI : CurBlock->TheDecl->parameters()) {
13442     AI->setOwningFunction(CurBlock->TheDecl);
13443 
13444     // If this has an identifier, add it to the scope stack.
13445     if (AI->getIdentifier()) {
13446       CheckShadow(CurBlock->TheScope, AI);
13447 
13448       PushOnScopeChains(AI, CurBlock->TheScope);
13449     }
13450   }
13451 }
13452 
13453 /// ActOnBlockError - If there is an error parsing a block, this callback
13454 /// is invoked to pop the information about the block from the action impl.
13455 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13456   // Leave the expression-evaluation context.
13457   DiscardCleanupsInEvaluationContext();
13458   PopExpressionEvaluationContext();
13459 
13460   // Pop off CurBlock, handle nested blocks.
13461   PopDeclContext();
13462   PopFunctionScopeInfo();
13463 }
13464 
13465 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13466 /// literal was successfully completed.  ^(int x){...}
13467 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13468                                     Stmt *Body, Scope *CurScope) {
13469   // If blocks are disabled, emit an error.
13470   if (!LangOpts.Blocks)
13471     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13472 
13473   // Leave the expression-evaluation context.
13474   if (hasAnyUnrecoverableErrorsInThisFunction())
13475     DiscardCleanupsInEvaluationContext();
13476   assert(!Cleanup.exprNeedsCleanups() &&
13477          "cleanups within block not correctly bound!");
13478   PopExpressionEvaluationContext();
13479 
13480   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13481   BlockDecl *BD = BSI->TheDecl;
13482 
13483   if (BSI->HasImplicitReturnType)
13484     deduceClosureReturnType(*BSI);
13485 
13486   PopDeclContext();
13487 
13488   QualType RetTy = Context.VoidTy;
13489   if (!BSI->ReturnType.isNull())
13490     RetTy = BSI->ReturnType;
13491 
13492   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13493   QualType BlockTy;
13494 
13495   // Set the captured variables on the block.
13496   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13497   SmallVector<BlockDecl::Capture, 4> Captures;
13498   for (Capture &Cap : BSI->Captures) {
13499     if (Cap.isThisCapture())
13500       continue;
13501     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13502                               Cap.isNested(), Cap.getInitExpr());
13503     Captures.push_back(NewCap);
13504   }
13505   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13506 
13507   // If the user wrote a function type in some form, try to use that.
13508   if (!BSI->FunctionType.isNull()) {
13509     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13510 
13511     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13512     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13513 
13514     // Turn protoless block types into nullary block types.
13515     if (isa<FunctionNoProtoType>(FTy)) {
13516       FunctionProtoType::ExtProtoInfo EPI;
13517       EPI.ExtInfo = Ext;
13518       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13519 
13520     // Otherwise, if we don't need to change anything about the function type,
13521     // preserve its sugar structure.
13522     } else if (FTy->getReturnType() == RetTy &&
13523                (!NoReturn || FTy->getNoReturnAttr())) {
13524       BlockTy = BSI->FunctionType;
13525 
13526     // Otherwise, make the minimal modifications to the function type.
13527     } else {
13528       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13529       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13530       EPI.TypeQuals = 0; // FIXME: silently?
13531       EPI.ExtInfo = Ext;
13532       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13533     }
13534 
13535   // If we don't have a function type, just build one from nothing.
13536   } else {
13537     FunctionProtoType::ExtProtoInfo EPI;
13538     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13539     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13540   }
13541 
13542   DiagnoseUnusedParameters(BD->parameters());
13543   BlockTy = Context.getBlockPointerType(BlockTy);
13544 
13545   // If needed, diagnose invalid gotos and switches in the block.
13546   if (getCurFunction()->NeedsScopeChecking() &&
13547       !PP.isCodeCompletionEnabled())
13548     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13549 
13550   BD->setBody(cast<CompoundStmt>(Body));
13551 
13552   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13553     DiagnoseUnguardedAvailabilityViolations(BD);
13554 
13555   // Try to apply the named return value optimization. We have to check again
13556   // if we can do this, though, because blocks keep return statements around
13557   // to deduce an implicit return type.
13558   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13559       !BD->isDependentContext())
13560     computeNRVO(Body, BSI);
13561 
13562   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13563   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13564   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13565 
13566   // If the block isn't obviously global, i.e. it captures anything at
13567   // all, then we need to do a few things in the surrounding context:
13568   if (Result->getBlockDecl()->hasCaptures()) {
13569     // First, this expression has a new cleanup object.
13570     ExprCleanupObjects.push_back(Result->getBlockDecl());
13571     Cleanup.setExprNeedsCleanups(true);
13572 
13573     // It also gets a branch-protected scope if any of the captured
13574     // variables needs destruction.
13575     for (const auto &CI : Result->getBlockDecl()->captures()) {
13576       const VarDecl *var = CI.getVariable();
13577       if (var->getType().isDestructedType() != QualType::DK_none) {
13578         setFunctionHasBranchProtectedScope();
13579         break;
13580       }
13581     }
13582   }
13583 
13584   if (getCurFunction())
13585     getCurFunction()->addBlock(BD);
13586 
13587   return Result;
13588 }
13589 
13590 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13591                             SourceLocation RPLoc) {
13592   TypeSourceInfo *TInfo;
13593   GetTypeFromParser(Ty, &TInfo);
13594   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13595 }
13596 
13597 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13598                                 Expr *E, TypeSourceInfo *TInfo,
13599                                 SourceLocation RPLoc) {
13600   Expr *OrigExpr = E;
13601   bool IsMS = false;
13602 
13603   // CUDA device code does not support varargs.
13604   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13605     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13606       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13607       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13608         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13609     }
13610   }
13611 
13612   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13613   // as Microsoft ABI on an actual Microsoft platform, where
13614   // __builtin_ms_va_list and __builtin_va_list are the same.)
13615   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13616       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13617     QualType MSVaListType = Context.getBuiltinMSVaListType();
13618     if (Context.hasSameType(MSVaListType, E->getType())) {
13619       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13620         return ExprError();
13621       IsMS = true;
13622     }
13623   }
13624 
13625   // Get the va_list type
13626   QualType VaListType = Context.getBuiltinVaListType();
13627   if (!IsMS) {
13628     if (VaListType->isArrayType()) {
13629       // Deal with implicit array decay; for example, on x86-64,
13630       // va_list is an array, but it's supposed to decay to
13631       // a pointer for va_arg.
13632       VaListType = Context.getArrayDecayedType(VaListType);
13633       // Make sure the input expression also decays appropriately.
13634       ExprResult Result = UsualUnaryConversions(E);
13635       if (Result.isInvalid())
13636         return ExprError();
13637       E = Result.get();
13638     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13639       // If va_list is a record type and we are compiling in C++ mode,
13640       // check the argument using reference binding.
13641       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13642           Context, Context.getLValueReferenceType(VaListType), false);
13643       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13644       if (Init.isInvalid())
13645         return ExprError();
13646       E = Init.getAs<Expr>();
13647     } else {
13648       // Otherwise, the va_list argument must be an l-value because
13649       // it is modified by va_arg.
13650       if (!E->isTypeDependent() &&
13651           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13652         return ExprError();
13653     }
13654   }
13655 
13656   if (!IsMS && !E->isTypeDependent() &&
13657       !Context.hasSameType(VaListType, E->getType()))
13658     return ExprError(
13659         Diag(E->getBeginLoc(),
13660              diag::err_first_argument_to_va_arg_not_of_type_va_list)
13661         << OrigExpr->getType() << E->getSourceRange());
13662 
13663   if (!TInfo->getType()->isDependentType()) {
13664     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13665                             diag::err_second_parameter_to_va_arg_incomplete,
13666                             TInfo->getTypeLoc()))
13667       return ExprError();
13668 
13669     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13670                                TInfo->getType(),
13671                                diag::err_second_parameter_to_va_arg_abstract,
13672                                TInfo->getTypeLoc()))
13673       return ExprError();
13674 
13675     if (!TInfo->getType().isPODType(Context)) {
13676       Diag(TInfo->getTypeLoc().getBeginLoc(),
13677            TInfo->getType()->isObjCLifetimeType()
13678              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13679              : diag::warn_second_parameter_to_va_arg_not_pod)
13680         << TInfo->getType()
13681         << TInfo->getTypeLoc().getSourceRange();
13682     }
13683 
13684     // Check for va_arg where arguments of the given type will be promoted
13685     // (i.e. this va_arg is guaranteed to have undefined behavior).
13686     QualType PromoteType;
13687     if (TInfo->getType()->isPromotableIntegerType()) {
13688       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13689       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13690         PromoteType = QualType();
13691     }
13692     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13693       PromoteType = Context.DoubleTy;
13694     if (!PromoteType.isNull())
13695       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13696                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13697                           << TInfo->getType()
13698                           << PromoteType
13699                           << TInfo->getTypeLoc().getSourceRange());
13700   }
13701 
13702   QualType T = TInfo->getType().getNonLValueExprType(Context);
13703   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13704 }
13705 
13706 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13707   // The type of __null will be int or long, depending on the size of
13708   // pointers on the target.
13709   QualType Ty;
13710   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13711   if (pw == Context.getTargetInfo().getIntWidth())
13712     Ty = Context.IntTy;
13713   else if (pw == Context.getTargetInfo().getLongWidth())
13714     Ty = Context.LongTy;
13715   else if (pw == Context.getTargetInfo().getLongLongWidth())
13716     Ty = Context.LongLongTy;
13717   else {
13718     llvm_unreachable("I don't know size of pointer!");
13719   }
13720 
13721   return new (Context) GNUNullExpr(Ty, TokenLoc);
13722 }
13723 
13724 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13725                                               bool Diagnose) {
13726   if (!getLangOpts().ObjC1)
13727     return false;
13728 
13729   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13730   if (!PT)
13731     return false;
13732 
13733   if (!PT->isObjCIdType()) {
13734     // Check if the destination is the 'NSString' interface.
13735     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13736     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13737       return false;
13738   }
13739 
13740   // Ignore any parens, implicit casts (should only be
13741   // array-to-pointer decays), and not-so-opaque values.  The last is
13742   // important for making this trigger for property assignments.
13743   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13744   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13745     if (OV->getSourceExpr())
13746       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13747 
13748   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13749   if (!SL || !SL->isAscii())
13750     return false;
13751   if (Diagnose) {
13752     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
13753         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
13754     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
13755   }
13756   return true;
13757 }
13758 
13759 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13760                                               const Expr *SrcExpr) {
13761   if (!DstType->isFunctionPointerType() ||
13762       !SrcExpr->getType()->isFunctionType())
13763     return false;
13764 
13765   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13766   if (!DRE)
13767     return false;
13768 
13769   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13770   if (!FD)
13771     return false;
13772 
13773   return !S.checkAddressOfFunctionIsAvailable(FD,
13774                                               /*Complain=*/true,
13775                                               SrcExpr->getBeginLoc());
13776 }
13777 
13778 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13779                                     SourceLocation Loc,
13780                                     QualType DstType, QualType SrcType,
13781                                     Expr *SrcExpr, AssignmentAction Action,
13782                                     bool *Complained) {
13783   if (Complained)
13784     *Complained = false;
13785 
13786   // Decode the result (notice that AST's are still created for extensions).
13787   bool CheckInferredResultType = false;
13788   bool isInvalid = false;
13789   unsigned DiagKind = 0;
13790   FixItHint Hint;
13791   ConversionFixItGenerator ConvHints;
13792   bool MayHaveConvFixit = false;
13793   bool MayHaveFunctionDiff = false;
13794   const ObjCInterfaceDecl *IFace = nullptr;
13795   const ObjCProtocolDecl *PDecl = nullptr;
13796 
13797   switch (ConvTy) {
13798   case Compatible:
13799       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13800       return false;
13801 
13802   case PointerToInt:
13803     DiagKind = diag::ext_typecheck_convert_pointer_int;
13804     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13805     MayHaveConvFixit = true;
13806     break;
13807   case IntToPointer:
13808     DiagKind = diag::ext_typecheck_convert_int_pointer;
13809     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13810     MayHaveConvFixit = true;
13811     break;
13812   case IncompatiblePointer:
13813     if (Action == AA_Passing_CFAudited)
13814       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13815     else if (SrcType->isFunctionPointerType() &&
13816              DstType->isFunctionPointerType())
13817       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13818     else
13819       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13820 
13821     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13822       SrcType->isObjCObjectPointerType();
13823     if (Hint.isNull() && !CheckInferredResultType) {
13824       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13825     }
13826     else if (CheckInferredResultType) {
13827       SrcType = SrcType.getUnqualifiedType();
13828       DstType = DstType.getUnqualifiedType();
13829     }
13830     MayHaveConvFixit = true;
13831     break;
13832   case IncompatiblePointerSign:
13833     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13834     break;
13835   case FunctionVoidPointer:
13836     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13837     break;
13838   case IncompatiblePointerDiscardsQualifiers: {
13839     // Perform array-to-pointer decay if necessary.
13840     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13841 
13842     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13843     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13844     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13845       DiagKind = diag::err_typecheck_incompatible_address_space;
13846       break;
13847 
13848     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13849       DiagKind = diag::err_typecheck_incompatible_ownership;
13850       break;
13851     }
13852 
13853     llvm_unreachable("unknown error case for discarding qualifiers!");
13854     // fallthrough
13855   }
13856   case CompatiblePointerDiscardsQualifiers:
13857     // If the qualifiers lost were because we were applying the
13858     // (deprecated) C++ conversion from a string literal to a char*
13859     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13860     // Ideally, this check would be performed in
13861     // checkPointerTypesForAssignment. However, that would require a
13862     // bit of refactoring (so that the second argument is an
13863     // expression, rather than a type), which should be done as part
13864     // of a larger effort to fix checkPointerTypesForAssignment for
13865     // C++ semantics.
13866     if (getLangOpts().CPlusPlus &&
13867         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13868       return false;
13869     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13870     break;
13871   case IncompatibleNestedPointerQualifiers:
13872     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13873     break;
13874   case IntToBlockPointer:
13875     DiagKind = diag::err_int_to_block_pointer;
13876     break;
13877   case IncompatibleBlockPointer:
13878     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13879     break;
13880   case IncompatibleObjCQualifiedId: {
13881     if (SrcType->isObjCQualifiedIdType()) {
13882       const ObjCObjectPointerType *srcOPT =
13883                 SrcType->getAs<ObjCObjectPointerType>();
13884       for (auto *srcProto : srcOPT->quals()) {
13885         PDecl = srcProto;
13886         break;
13887       }
13888       if (const ObjCInterfaceType *IFaceT =
13889             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13890         IFace = IFaceT->getDecl();
13891     }
13892     else if (DstType->isObjCQualifiedIdType()) {
13893       const ObjCObjectPointerType *dstOPT =
13894         DstType->getAs<ObjCObjectPointerType>();
13895       for (auto *dstProto : dstOPT->quals()) {
13896         PDecl = dstProto;
13897         break;
13898       }
13899       if (const ObjCInterfaceType *IFaceT =
13900             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13901         IFace = IFaceT->getDecl();
13902     }
13903     DiagKind = diag::warn_incompatible_qualified_id;
13904     break;
13905   }
13906   case IncompatibleVectors:
13907     DiagKind = diag::warn_incompatible_vectors;
13908     break;
13909   case IncompatibleObjCWeakRef:
13910     DiagKind = diag::err_arc_weak_unavailable_assign;
13911     break;
13912   case Incompatible:
13913     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13914       if (Complained)
13915         *Complained = true;
13916       return true;
13917     }
13918 
13919     DiagKind = diag::err_typecheck_convert_incompatible;
13920     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13921     MayHaveConvFixit = true;
13922     isInvalid = true;
13923     MayHaveFunctionDiff = true;
13924     break;
13925   }
13926 
13927   QualType FirstType, SecondType;
13928   switch (Action) {
13929   case AA_Assigning:
13930   case AA_Initializing:
13931     // The destination type comes first.
13932     FirstType = DstType;
13933     SecondType = SrcType;
13934     break;
13935 
13936   case AA_Returning:
13937   case AA_Passing:
13938   case AA_Passing_CFAudited:
13939   case AA_Converting:
13940   case AA_Sending:
13941   case AA_Casting:
13942     // The source type comes first.
13943     FirstType = SrcType;
13944     SecondType = DstType;
13945     break;
13946   }
13947 
13948   PartialDiagnostic FDiag = PDiag(DiagKind);
13949   if (Action == AA_Passing_CFAudited)
13950     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13951   else
13952     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13953 
13954   // If we can fix the conversion, suggest the FixIts.
13955   assert(ConvHints.isNull() || Hint.isNull());
13956   if (!ConvHints.isNull()) {
13957     for (FixItHint &H : ConvHints.Hints)
13958       FDiag << H;
13959   } else {
13960     FDiag << Hint;
13961   }
13962   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13963 
13964   if (MayHaveFunctionDiff)
13965     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13966 
13967   Diag(Loc, FDiag);
13968   if (DiagKind == diag::warn_incompatible_qualified_id &&
13969       PDecl && IFace && !IFace->hasDefinition())
13970       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13971         << IFace << PDecl;
13972 
13973   if (SecondType == Context.OverloadTy)
13974     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13975                               FirstType, /*TakingAddress=*/true);
13976 
13977   if (CheckInferredResultType)
13978     EmitRelatedResultTypeNote(SrcExpr);
13979 
13980   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13981     EmitRelatedResultTypeNoteForReturn(DstType);
13982 
13983   if (Complained)
13984     *Complained = true;
13985   return isInvalid;
13986 }
13987 
13988 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13989                                                  llvm::APSInt *Result) {
13990   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13991   public:
13992     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13993       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13994     }
13995   } Diagnoser;
13996 
13997   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13998 }
13999 
14000 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14001                                                  llvm::APSInt *Result,
14002                                                  unsigned DiagID,
14003                                                  bool AllowFold) {
14004   class IDDiagnoser : public VerifyICEDiagnoser {
14005     unsigned DiagID;
14006 
14007   public:
14008     IDDiagnoser(unsigned DiagID)
14009       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14010 
14011     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14012       S.Diag(Loc, DiagID) << SR;
14013     }
14014   } Diagnoser(DiagID);
14015 
14016   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14017 }
14018 
14019 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14020                                             SourceRange SR) {
14021   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14022 }
14023 
14024 ExprResult
14025 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14026                                       VerifyICEDiagnoser &Diagnoser,
14027                                       bool AllowFold) {
14028   SourceLocation DiagLoc = E->getBeginLoc();
14029 
14030   if (getLangOpts().CPlusPlus11) {
14031     // C++11 [expr.const]p5:
14032     //   If an expression of literal class type is used in a context where an
14033     //   integral constant expression is required, then that class type shall
14034     //   have a single non-explicit conversion function to an integral or
14035     //   unscoped enumeration type
14036     ExprResult Converted;
14037     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14038     public:
14039       CXX11ConvertDiagnoser(bool Silent)
14040           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14041                                 Silent, true) {}
14042 
14043       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14044                                            QualType T) override {
14045         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14046       }
14047 
14048       SemaDiagnosticBuilder diagnoseIncomplete(
14049           Sema &S, SourceLocation Loc, QualType T) override {
14050         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14051       }
14052 
14053       SemaDiagnosticBuilder diagnoseExplicitConv(
14054           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14055         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14056       }
14057 
14058       SemaDiagnosticBuilder noteExplicitConv(
14059           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14060         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14061                  << ConvTy->isEnumeralType() << ConvTy;
14062       }
14063 
14064       SemaDiagnosticBuilder diagnoseAmbiguous(
14065           Sema &S, SourceLocation Loc, QualType T) override {
14066         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14067       }
14068 
14069       SemaDiagnosticBuilder noteAmbiguous(
14070           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14071         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14072                  << ConvTy->isEnumeralType() << ConvTy;
14073       }
14074 
14075       SemaDiagnosticBuilder diagnoseConversion(
14076           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14077         llvm_unreachable("conversion functions are permitted");
14078       }
14079     } ConvertDiagnoser(Diagnoser.Suppress);
14080 
14081     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14082                                                     ConvertDiagnoser);
14083     if (Converted.isInvalid())
14084       return Converted;
14085     E = Converted.get();
14086     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14087       return ExprError();
14088   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14089     // An ICE must be of integral or unscoped enumeration type.
14090     if (!Diagnoser.Suppress)
14091       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14092     return ExprError();
14093   }
14094 
14095   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14096   // in the non-ICE case.
14097   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14098     if (Result)
14099       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14100     return E;
14101   }
14102 
14103   Expr::EvalResult EvalResult;
14104   SmallVector<PartialDiagnosticAt, 8> Notes;
14105   EvalResult.Diag = &Notes;
14106 
14107   // Try to evaluate the expression, and produce diagnostics explaining why it's
14108   // not a constant expression as a side-effect.
14109   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14110                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14111 
14112   // In C++11, we can rely on diagnostics being produced for any expression
14113   // which is not a constant expression. If no diagnostics were produced, then
14114   // this is a constant expression.
14115   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14116     if (Result)
14117       *Result = EvalResult.Val.getInt();
14118     return E;
14119   }
14120 
14121   // If our only note is the usual "invalid subexpression" note, just point
14122   // the caret at its location rather than producing an essentially
14123   // redundant note.
14124   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14125         diag::note_invalid_subexpr_in_const_expr) {
14126     DiagLoc = Notes[0].first;
14127     Notes.clear();
14128   }
14129 
14130   if (!Folded || !AllowFold) {
14131     if (!Diagnoser.Suppress) {
14132       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14133       for (const PartialDiagnosticAt &Note : Notes)
14134         Diag(Note.first, Note.second);
14135     }
14136 
14137     return ExprError();
14138   }
14139 
14140   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14141   for (const PartialDiagnosticAt &Note : Notes)
14142     Diag(Note.first, Note.second);
14143 
14144   if (Result)
14145     *Result = EvalResult.Val.getInt();
14146   return E;
14147 }
14148 
14149 namespace {
14150   // Handle the case where we conclude a expression which we speculatively
14151   // considered to be unevaluated is actually evaluated.
14152   class TransformToPE : public TreeTransform<TransformToPE> {
14153     typedef TreeTransform<TransformToPE> BaseTransform;
14154 
14155   public:
14156     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14157 
14158     // Make sure we redo semantic analysis
14159     bool AlwaysRebuild() { return true; }
14160 
14161     // Make sure we handle LabelStmts correctly.
14162     // FIXME: This does the right thing, but maybe we need a more general
14163     // fix to TreeTransform?
14164     StmtResult TransformLabelStmt(LabelStmt *S) {
14165       S->getDecl()->setStmt(nullptr);
14166       return BaseTransform::TransformLabelStmt(S);
14167     }
14168 
14169     // We need to special-case DeclRefExprs referring to FieldDecls which
14170     // are not part of a member pointer formation; normal TreeTransforming
14171     // doesn't catch this case because of the way we represent them in the AST.
14172     // FIXME: This is a bit ugly; is it really the best way to handle this
14173     // case?
14174     //
14175     // Error on DeclRefExprs referring to FieldDecls.
14176     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14177       if (isa<FieldDecl>(E->getDecl()) &&
14178           !SemaRef.isUnevaluatedContext())
14179         return SemaRef.Diag(E->getLocation(),
14180                             diag::err_invalid_non_static_member_use)
14181             << E->getDecl() << E->getSourceRange();
14182 
14183       return BaseTransform::TransformDeclRefExpr(E);
14184     }
14185 
14186     // Exception: filter out member pointer formation
14187     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14188       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14189         return E;
14190 
14191       return BaseTransform::TransformUnaryOperator(E);
14192     }
14193 
14194     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14195       // Lambdas never need to be transformed.
14196       return E;
14197     }
14198   };
14199 }
14200 
14201 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14202   assert(isUnevaluatedContext() &&
14203          "Should only transform unevaluated expressions");
14204   ExprEvalContexts.back().Context =
14205       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14206   if (isUnevaluatedContext())
14207     return E;
14208   return TransformToPE(*this).TransformExpr(E);
14209 }
14210 
14211 void
14212 Sema::PushExpressionEvaluationContext(
14213     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14214     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14215   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14216                                 LambdaContextDecl, ExprContext);
14217   Cleanup.reset();
14218   if (!MaybeODRUseExprs.empty())
14219     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14220 }
14221 
14222 void
14223 Sema::PushExpressionEvaluationContext(
14224     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14225     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14226   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14227   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14228 }
14229 
14230 void Sema::PopExpressionEvaluationContext() {
14231   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14232   unsigned NumTypos = Rec.NumTypos;
14233 
14234   if (!Rec.Lambdas.empty()) {
14235     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14236     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14237         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14238       unsigned D;
14239       if (Rec.isUnevaluated()) {
14240         // C++11 [expr.prim.lambda]p2:
14241         //   A lambda-expression shall not appear in an unevaluated operand
14242         //   (Clause 5).
14243         D = diag::err_lambda_unevaluated_operand;
14244       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14245         // C++1y [expr.const]p2:
14246         //   A conditional-expression e is a core constant expression unless the
14247         //   evaluation of e, following the rules of the abstract machine, would
14248         //   evaluate [...] a lambda-expression.
14249         D = diag::err_lambda_in_constant_expression;
14250       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14251         // C++17 [expr.prim.lamda]p2:
14252         // A lambda-expression shall not appear [...] in a template-argument.
14253         D = diag::err_lambda_in_invalid_context;
14254       } else
14255         llvm_unreachable("Couldn't infer lambda error message.");
14256 
14257       for (const auto *L : Rec.Lambdas)
14258         Diag(L->getBeginLoc(), D);
14259     } else {
14260       // Mark the capture expressions odr-used. This was deferred
14261       // during lambda expression creation.
14262       for (auto *Lambda : Rec.Lambdas) {
14263         for (auto *C : Lambda->capture_inits())
14264           MarkDeclarationsReferencedInExpr(C);
14265       }
14266     }
14267   }
14268 
14269   // When are coming out of an unevaluated context, clear out any
14270   // temporaries that we may have created as part of the evaluation of
14271   // the expression in that context: they aren't relevant because they
14272   // will never be constructed.
14273   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14274     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14275                              ExprCleanupObjects.end());
14276     Cleanup = Rec.ParentCleanup;
14277     CleanupVarDeclMarking();
14278     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14279   // Otherwise, merge the contexts together.
14280   } else {
14281     Cleanup.mergeFrom(Rec.ParentCleanup);
14282     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14283                             Rec.SavedMaybeODRUseExprs.end());
14284   }
14285 
14286   // Pop the current expression evaluation context off the stack.
14287   ExprEvalContexts.pop_back();
14288 
14289   if (!ExprEvalContexts.empty())
14290     ExprEvalContexts.back().NumTypos += NumTypos;
14291   else
14292     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14293                             "last ExpressionEvaluationContextRecord");
14294 }
14295 
14296 void Sema::DiscardCleanupsInEvaluationContext() {
14297   ExprCleanupObjects.erase(
14298          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14299          ExprCleanupObjects.end());
14300   Cleanup.reset();
14301   MaybeODRUseExprs.clear();
14302 }
14303 
14304 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14305   if (!E->getType()->isVariablyModifiedType())
14306     return E;
14307   return TransformToPotentiallyEvaluated(E);
14308 }
14309 
14310 /// Are we within a context in which some evaluation could be performed (be it
14311 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14312 /// captured by C++'s idea of an "unevaluated context".
14313 static bool isEvaluatableContext(Sema &SemaRef) {
14314   switch (SemaRef.ExprEvalContexts.back().Context) {
14315     case Sema::ExpressionEvaluationContext::Unevaluated:
14316     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14317       // Expressions in this context are never evaluated.
14318       return false;
14319 
14320     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14321     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14322     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14323     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14324       // Expressions in this context could be evaluated.
14325       return true;
14326 
14327     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14328       // Referenced declarations will only be used if the construct in the
14329       // containing expression is used, at which point we'll be given another
14330       // turn to mark them.
14331       return false;
14332   }
14333   llvm_unreachable("Invalid context");
14334 }
14335 
14336 /// Are we within a context in which references to resolved functions or to
14337 /// variables result in odr-use?
14338 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14339   // An expression in a template is not really an expression until it's been
14340   // instantiated, so it doesn't trigger odr-use.
14341   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14342     return false;
14343 
14344   switch (SemaRef.ExprEvalContexts.back().Context) {
14345     case Sema::ExpressionEvaluationContext::Unevaluated:
14346     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14347     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14348     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14349       return false;
14350 
14351     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14352     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14353       return true;
14354 
14355     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14356       return false;
14357   }
14358   llvm_unreachable("Invalid context");
14359 }
14360 
14361 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14362   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14363   return Func->isConstexpr() &&
14364          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14365 }
14366 
14367 /// Mark a function referenced, and check whether it is odr-used
14368 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14369 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14370                                   bool MightBeOdrUse) {
14371   assert(Func && "No function?");
14372 
14373   Func->setReferenced();
14374 
14375   // C++11 [basic.def.odr]p3:
14376   //   A function whose name appears as a potentially-evaluated expression is
14377   //   odr-used if it is the unique lookup result or the selected member of a
14378   //   set of overloaded functions [...].
14379   //
14380   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14381   // can just check that here.
14382   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14383 
14384   // Determine whether we require a function definition to exist, per
14385   // C++11 [temp.inst]p3:
14386   //   Unless a function template specialization has been explicitly
14387   //   instantiated or explicitly specialized, the function template
14388   //   specialization is implicitly instantiated when the specialization is
14389   //   referenced in a context that requires a function definition to exist.
14390   //
14391   // That is either when this is an odr-use, or when a usage of a constexpr
14392   // function occurs within an evaluatable context.
14393   bool NeedDefinition =
14394       OdrUse || (isEvaluatableContext(*this) &&
14395                  isImplicitlyDefinableConstexprFunction(Func));
14396 
14397   // C++14 [temp.expl.spec]p6:
14398   //   If a template [...] is explicitly specialized then that specialization
14399   //   shall be declared before the first use of that specialization that would
14400   //   cause an implicit instantiation to take place, in every translation unit
14401   //   in which such a use occurs
14402   if (NeedDefinition &&
14403       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14404        Func->getMemberSpecializationInfo()))
14405     checkSpecializationVisibility(Loc, Func);
14406 
14407   // C++14 [except.spec]p17:
14408   //   An exception-specification is considered to be needed when:
14409   //   - the function is odr-used or, if it appears in an unevaluated operand,
14410   //     would be odr-used if the expression were potentially-evaluated;
14411   //
14412   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14413   // function is a pure virtual function we're calling, and in that case the
14414   // function was selected by overload resolution and we need to resolve its
14415   // exception specification for a different reason.
14416   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14417   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14418     ResolveExceptionSpec(Loc, FPT);
14419 
14420   // If we don't need to mark the function as used, and we don't need to
14421   // try to provide a definition, there's nothing more to do.
14422   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14423       (!NeedDefinition || Func->getBody()))
14424     return;
14425 
14426   // Note that this declaration has been used.
14427   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14428     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14429     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14430       if (Constructor->isDefaultConstructor()) {
14431         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14432           return;
14433         DefineImplicitDefaultConstructor(Loc, Constructor);
14434       } else if (Constructor->isCopyConstructor()) {
14435         DefineImplicitCopyConstructor(Loc, Constructor);
14436       } else if (Constructor->isMoveConstructor()) {
14437         DefineImplicitMoveConstructor(Loc, Constructor);
14438       }
14439     } else if (Constructor->getInheritedConstructor()) {
14440       DefineInheritingConstructor(Loc, Constructor);
14441     }
14442   } else if (CXXDestructorDecl *Destructor =
14443                  dyn_cast<CXXDestructorDecl>(Func)) {
14444     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14445     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14446       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14447         return;
14448       DefineImplicitDestructor(Loc, Destructor);
14449     }
14450     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14451       MarkVTableUsed(Loc, Destructor->getParent());
14452   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14453     if (MethodDecl->isOverloadedOperator() &&
14454         MethodDecl->getOverloadedOperator() == OO_Equal) {
14455       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14456       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14457         if (MethodDecl->isCopyAssignmentOperator())
14458           DefineImplicitCopyAssignment(Loc, MethodDecl);
14459         else if (MethodDecl->isMoveAssignmentOperator())
14460           DefineImplicitMoveAssignment(Loc, MethodDecl);
14461       }
14462     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14463                MethodDecl->getParent()->isLambda()) {
14464       CXXConversionDecl *Conversion =
14465           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14466       if (Conversion->isLambdaToBlockPointerConversion())
14467         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14468       else
14469         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14470     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14471       MarkVTableUsed(Loc, MethodDecl->getParent());
14472   }
14473 
14474   // Recursive functions should be marked when used from another function.
14475   // FIXME: Is this really right?
14476   if (CurContext == Func) return;
14477 
14478   // Implicit instantiation of function templates and member functions of
14479   // class templates.
14480   if (Func->isImplicitlyInstantiable()) {
14481     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14482     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14483     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14484     if (FirstInstantiation) {
14485       PointOfInstantiation = Loc;
14486       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14487     } else if (TSK != TSK_ImplicitInstantiation) {
14488       // Use the point of use as the point of instantiation, instead of the
14489       // point of explicit instantiation (which we track as the actual point of
14490       // instantiation). This gives better backtraces in diagnostics.
14491       PointOfInstantiation = Loc;
14492     }
14493 
14494     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14495         Func->isConstexpr()) {
14496       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14497           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14498           CodeSynthesisContexts.size())
14499         PendingLocalImplicitInstantiations.push_back(
14500             std::make_pair(Func, PointOfInstantiation));
14501       else if (Func->isConstexpr())
14502         // Do not defer instantiations of constexpr functions, to avoid the
14503         // expression evaluator needing to call back into Sema if it sees a
14504         // call to such a function.
14505         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14506       else {
14507         Func->setInstantiationIsPending(true);
14508         PendingInstantiations.push_back(std::make_pair(Func,
14509                                                        PointOfInstantiation));
14510         // Notify the consumer that a function was implicitly instantiated.
14511         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14512       }
14513     }
14514   } else {
14515     // Walk redefinitions, as some of them may be instantiable.
14516     for (auto i : Func->redecls()) {
14517       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14518         MarkFunctionReferenced(Loc, i, OdrUse);
14519     }
14520   }
14521 
14522   if (!OdrUse) return;
14523 
14524   // Keep track of used but undefined functions.
14525   if (!Func->isDefined()) {
14526     if (mightHaveNonExternalLinkage(Func))
14527       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14528     else if (Func->getMostRecentDecl()->isInlined() &&
14529              !LangOpts.GNUInline &&
14530              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14531       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14532     else if (isExternalWithNoLinkageType(Func))
14533       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14534   }
14535 
14536   Func->markUsed(Context);
14537 }
14538 
14539 static void
14540 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14541                                    ValueDecl *var, DeclContext *DC) {
14542   DeclContext *VarDC = var->getDeclContext();
14543 
14544   //  If the parameter still belongs to the translation unit, then
14545   //  we're actually just using one parameter in the declaration of
14546   //  the next.
14547   if (isa<ParmVarDecl>(var) &&
14548       isa<TranslationUnitDecl>(VarDC))
14549     return;
14550 
14551   // For C code, don't diagnose about capture if we're not actually in code
14552   // right now; it's impossible to write a non-constant expression outside of
14553   // function context, so we'll get other (more useful) diagnostics later.
14554   //
14555   // For C++, things get a bit more nasty... it would be nice to suppress this
14556   // diagnostic for certain cases like using a local variable in an array bound
14557   // for a member of a local class, but the correct predicate is not obvious.
14558   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14559     return;
14560 
14561   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14562   unsigned ContextKind = 3; // unknown
14563   if (isa<CXXMethodDecl>(VarDC) &&
14564       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14565     ContextKind = 2;
14566   } else if (isa<FunctionDecl>(VarDC)) {
14567     ContextKind = 0;
14568   } else if (isa<BlockDecl>(VarDC)) {
14569     ContextKind = 1;
14570   }
14571 
14572   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14573     << var << ValueKind << ContextKind << VarDC;
14574   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14575       << var;
14576 
14577   // FIXME: Add additional diagnostic info about class etc. which prevents
14578   // capture.
14579 }
14580 
14581 
14582 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14583                                       bool &SubCapturesAreNested,
14584                                       QualType &CaptureType,
14585                                       QualType &DeclRefType) {
14586    // Check whether we've already captured it.
14587   if (CSI->CaptureMap.count(Var)) {
14588     // If we found a capture, any subcaptures are nested.
14589     SubCapturesAreNested = true;
14590 
14591     // Retrieve the capture type for this variable.
14592     CaptureType = CSI->getCapture(Var).getCaptureType();
14593 
14594     // Compute the type of an expression that refers to this variable.
14595     DeclRefType = CaptureType.getNonReferenceType();
14596 
14597     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14598     // are mutable in the sense that user can change their value - they are
14599     // private instances of the captured declarations.
14600     const Capture &Cap = CSI->getCapture(Var);
14601     if (Cap.isCopyCapture() &&
14602         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14603         !(isa<CapturedRegionScopeInfo>(CSI) &&
14604           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14605       DeclRefType.addConst();
14606     return true;
14607   }
14608   return false;
14609 }
14610 
14611 // Only block literals, captured statements, and lambda expressions can
14612 // capture; other scopes don't work.
14613 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14614                                  SourceLocation Loc,
14615                                  const bool Diagnose, Sema &S) {
14616   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14617     return getLambdaAwareParentOfDeclContext(DC);
14618   else if (Var->hasLocalStorage()) {
14619     if (Diagnose)
14620        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14621   }
14622   return nullptr;
14623 }
14624 
14625 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14626 // certain types of variables (unnamed, variably modified types etc.)
14627 // so check for eligibility.
14628 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14629                                  SourceLocation Loc,
14630                                  const bool Diagnose, Sema &S) {
14631 
14632   bool IsBlock = isa<BlockScopeInfo>(CSI);
14633   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14634 
14635   // Lambdas are not allowed to capture unnamed variables
14636   // (e.g. anonymous unions).
14637   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14638   // assuming that's the intent.
14639   if (IsLambda && !Var->getDeclName()) {
14640     if (Diagnose) {
14641       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14642       S.Diag(Var->getLocation(), diag::note_declared_at);
14643     }
14644     return false;
14645   }
14646 
14647   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14648   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14649     if (Diagnose) {
14650       S.Diag(Loc, diag::err_ref_vm_type);
14651       S.Diag(Var->getLocation(), diag::note_previous_decl)
14652         << Var->getDeclName();
14653     }
14654     return false;
14655   }
14656   // Prohibit structs with flexible array members too.
14657   // We cannot capture what is in the tail end of the struct.
14658   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14659     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14660       if (Diagnose) {
14661         if (IsBlock)
14662           S.Diag(Loc, diag::err_ref_flexarray_type);
14663         else
14664           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14665             << Var->getDeclName();
14666         S.Diag(Var->getLocation(), diag::note_previous_decl)
14667           << Var->getDeclName();
14668       }
14669       return false;
14670     }
14671   }
14672   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14673   // Lambdas and captured statements are not allowed to capture __block
14674   // variables; they don't support the expected semantics.
14675   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14676     if (Diagnose) {
14677       S.Diag(Loc, diag::err_capture_block_variable)
14678         << Var->getDeclName() << !IsLambda;
14679       S.Diag(Var->getLocation(), diag::note_previous_decl)
14680         << Var->getDeclName();
14681     }
14682     return false;
14683   }
14684   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14685   if (S.getLangOpts().OpenCL && IsBlock &&
14686       Var->getType()->isBlockPointerType()) {
14687     if (Diagnose)
14688       S.Diag(Loc, diag::err_opencl_block_ref_block);
14689     return false;
14690   }
14691 
14692   return true;
14693 }
14694 
14695 // Returns true if the capture by block was successful.
14696 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14697                                  SourceLocation Loc,
14698                                  const bool BuildAndDiagnose,
14699                                  QualType &CaptureType,
14700                                  QualType &DeclRefType,
14701                                  const bool Nested,
14702                                  Sema &S) {
14703   Expr *CopyExpr = nullptr;
14704   bool ByRef = false;
14705 
14706   // Blocks are not allowed to capture arrays, excepting OpenCL.
14707   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
14708   // (decayed to pointers).
14709   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
14710     if (BuildAndDiagnose) {
14711       S.Diag(Loc, diag::err_ref_array_type);
14712       S.Diag(Var->getLocation(), diag::note_previous_decl)
14713       << Var->getDeclName();
14714     }
14715     return false;
14716   }
14717 
14718   // Forbid the block-capture of autoreleasing variables.
14719   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14720     if (BuildAndDiagnose) {
14721       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14722         << /*block*/ 0;
14723       S.Diag(Var->getLocation(), diag::note_previous_decl)
14724         << Var->getDeclName();
14725     }
14726     return false;
14727   }
14728 
14729   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14730   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14731     // This function finds out whether there is an AttributedType of kind
14732     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
14733     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
14734     // rather than being added implicitly by the compiler.
14735     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14736       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14737         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
14738           return true;
14739 
14740         // Peel off AttributedTypes that are not of kind ObjCOwnership.
14741         Ty = AttrTy->getModifiedType();
14742       }
14743 
14744       return false;
14745     };
14746 
14747     QualType PointeeTy = PT->getPointeeType();
14748 
14749     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14750         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14751         !IsObjCOwnershipAttributedType(PointeeTy)) {
14752       if (BuildAndDiagnose) {
14753         SourceLocation VarLoc = Var->getLocation();
14754         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14755         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14756       }
14757     }
14758   }
14759 
14760   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14761   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14762       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14763     // Block capture by reference does not change the capture or
14764     // declaration reference types.
14765     ByRef = true;
14766   } else {
14767     // Block capture by copy introduces 'const'.
14768     CaptureType = CaptureType.getNonReferenceType().withConst();
14769     DeclRefType = CaptureType;
14770 
14771     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14772       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14773         // The capture logic needs the destructor, so make sure we mark it.
14774         // Usually this is unnecessary because most local variables have
14775         // their destructors marked at declaration time, but parameters are
14776         // an exception because it's technically only the call site that
14777         // actually requires the destructor.
14778         if (isa<ParmVarDecl>(Var))
14779           S.FinalizeVarWithDestructor(Var, Record);
14780 
14781         // Enter a new evaluation context to insulate the copy
14782         // full-expression.
14783         EnterExpressionEvaluationContext scope(
14784             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14785 
14786         // According to the blocks spec, the capture of a variable from
14787         // the stack requires a const copy constructor.  This is not true
14788         // of the copy/move done to move a __block variable to the heap.
14789         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14790                                                   DeclRefType.withConst(),
14791                                                   VK_LValue, Loc);
14792 
14793         ExprResult Result
14794           = S.PerformCopyInitialization(
14795               InitializedEntity::InitializeBlock(Var->getLocation(),
14796                                                   CaptureType, false),
14797               Loc, DeclRef);
14798 
14799         // Build a full-expression copy expression if initialization
14800         // succeeded and used a non-trivial constructor.  Recover from
14801         // errors by pretending that the copy isn't necessary.
14802         if (!Result.isInvalid() &&
14803             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14804                 ->isTrivial()) {
14805           Result = S.MaybeCreateExprWithCleanups(Result);
14806           CopyExpr = Result.get();
14807         }
14808       }
14809     }
14810   }
14811 
14812   // Actually capture the variable.
14813   if (BuildAndDiagnose)
14814     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14815                     SourceLocation(), CaptureType, CopyExpr);
14816 
14817   return true;
14818 
14819 }
14820 
14821 
14822 /// Capture the given variable in the captured region.
14823 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14824                                     VarDecl *Var,
14825                                     SourceLocation Loc,
14826                                     const bool BuildAndDiagnose,
14827                                     QualType &CaptureType,
14828                                     QualType &DeclRefType,
14829                                     const bool RefersToCapturedVariable,
14830                                     Sema &S) {
14831   // By default, capture variables by reference.
14832   bool ByRef = true;
14833   // Using an LValue reference type is consistent with Lambdas (see below).
14834   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14835     if (S.isOpenMPCapturedDecl(Var)) {
14836       bool HasConst = DeclRefType.isConstQualified();
14837       DeclRefType = DeclRefType.getUnqualifiedType();
14838       // Don't lose diagnostics about assignments to const.
14839       if (HasConst)
14840         DeclRefType.addConst();
14841     }
14842     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14843   }
14844 
14845   if (ByRef)
14846     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14847   else
14848     CaptureType = DeclRefType;
14849 
14850   Expr *CopyExpr = nullptr;
14851   if (BuildAndDiagnose) {
14852     // The current implementation assumes that all variables are captured
14853     // by references. Since there is no capture by copy, no expression
14854     // evaluation will be needed.
14855     RecordDecl *RD = RSI->TheRecordDecl;
14856 
14857     FieldDecl *Field
14858       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14859                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14860                           nullptr, false, ICIS_NoInit);
14861     Field->setImplicit(true);
14862     Field->setAccess(AS_private);
14863     RD->addDecl(Field);
14864     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14865       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14866 
14867     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14868                                             DeclRefType, VK_LValue, Loc);
14869     Var->setReferenced(true);
14870     Var->markUsed(S.Context);
14871   }
14872 
14873   // Actually capture the variable.
14874   if (BuildAndDiagnose)
14875     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14876                     SourceLocation(), CaptureType, CopyExpr);
14877 
14878 
14879   return true;
14880 }
14881 
14882 /// Create a field within the lambda class for the variable
14883 /// being captured.
14884 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14885                                     QualType FieldType, QualType DeclRefType,
14886                                     SourceLocation Loc,
14887                                     bool RefersToCapturedVariable) {
14888   CXXRecordDecl *Lambda = LSI->Lambda;
14889 
14890   // Build the non-static data member.
14891   FieldDecl *Field
14892     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14893                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14894                         nullptr, false, ICIS_NoInit);
14895   Field->setImplicit(true);
14896   Field->setAccess(AS_private);
14897   Lambda->addDecl(Field);
14898 }
14899 
14900 /// Capture the given variable in the lambda.
14901 static bool captureInLambda(LambdaScopeInfo *LSI,
14902                             VarDecl *Var,
14903                             SourceLocation Loc,
14904                             const bool BuildAndDiagnose,
14905                             QualType &CaptureType,
14906                             QualType &DeclRefType,
14907                             const bool RefersToCapturedVariable,
14908                             const Sema::TryCaptureKind Kind,
14909                             SourceLocation EllipsisLoc,
14910                             const bool IsTopScope,
14911                             Sema &S) {
14912 
14913   // Determine whether we are capturing by reference or by value.
14914   bool ByRef = false;
14915   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14916     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14917   } else {
14918     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14919   }
14920 
14921   // Compute the type of the field that will capture this variable.
14922   if (ByRef) {
14923     // C++11 [expr.prim.lambda]p15:
14924     //   An entity is captured by reference if it is implicitly or
14925     //   explicitly captured but not captured by copy. It is
14926     //   unspecified whether additional unnamed non-static data
14927     //   members are declared in the closure type for entities
14928     //   captured by reference.
14929     //
14930     // FIXME: It is not clear whether we want to build an lvalue reference
14931     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14932     // to do the former, while EDG does the latter. Core issue 1249 will
14933     // clarify, but for now we follow GCC because it's a more permissive and
14934     // easily defensible position.
14935     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14936   } else {
14937     // C++11 [expr.prim.lambda]p14:
14938     //   For each entity captured by copy, an unnamed non-static
14939     //   data member is declared in the closure type. The
14940     //   declaration order of these members is unspecified. The type
14941     //   of such a data member is the type of the corresponding
14942     //   captured entity if the entity is not a reference to an
14943     //   object, or the referenced type otherwise. [Note: If the
14944     //   captured entity is a reference to a function, the
14945     //   corresponding data member is also a reference to a
14946     //   function. - end note ]
14947     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14948       if (!RefType->getPointeeType()->isFunctionType())
14949         CaptureType = RefType->getPointeeType();
14950     }
14951 
14952     // Forbid the lambda copy-capture of autoreleasing variables.
14953     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14954       if (BuildAndDiagnose) {
14955         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14956         S.Diag(Var->getLocation(), diag::note_previous_decl)
14957           << Var->getDeclName();
14958       }
14959       return false;
14960     }
14961 
14962     // Make sure that by-copy captures are of a complete and non-abstract type.
14963     if (BuildAndDiagnose) {
14964       if (!CaptureType->isDependentType() &&
14965           S.RequireCompleteType(Loc, CaptureType,
14966                                 diag::err_capture_of_incomplete_type,
14967                                 Var->getDeclName()))
14968         return false;
14969 
14970       if (S.RequireNonAbstractType(Loc, CaptureType,
14971                                    diag::err_capture_of_abstract_type))
14972         return false;
14973     }
14974   }
14975 
14976   // Capture this variable in the lambda.
14977   if (BuildAndDiagnose)
14978     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14979                             RefersToCapturedVariable);
14980 
14981   // Compute the type of a reference to this captured variable.
14982   if (ByRef)
14983     DeclRefType = CaptureType.getNonReferenceType();
14984   else {
14985     // C++ [expr.prim.lambda]p5:
14986     //   The closure type for a lambda-expression has a public inline
14987     //   function call operator [...]. This function call operator is
14988     //   declared const (9.3.1) if and only if the lambda-expression's
14989     //   parameter-declaration-clause is not followed by mutable.
14990     DeclRefType = CaptureType.getNonReferenceType();
14991     if (!LSI->Mutable && !CaptureType->isReferenceType())
14992       DeclRefType.addConst();
14993   }
14994 
14995   // Add the capture.
14996   if (BuildAndDiagnose)
14997     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14998                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14999 
15000   return true;
15001 }
15002 
15003 bool Sema::tryCaptureVariable(
15004     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15005     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15006     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15007   // An init-capture is notionally from the context surrounding its
15008   // declaration, but its parent DC is the lambda class.
15009   DeclContext *VarDC = Var->getDeclContext();
15010   if (Var->isInitCapture())
15011     VarDC = VarDC->getParent();
15012 
15013   DeclContext *DC = CurContext;
15014   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15015       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15016   // We need to sync up the Declaration Context with the
15017   // FunctionScopeIndexToStopAt
15018   if (FunctionScopeIndexToStopAt) {
15019     unsigned FSIndex = FunctionScopes.size() - 1;
15020     while (FSIndex != MaxFunctionScopesIndex) {
15021       DC = getLambdaAwareParentOfDeclContext(DC);
15022       --FSIndex;
15023     }
15024   }
15025 
15026 
15027   // If the variable is declared in the current context, there is no need to
15028   // capture it.
15029   if (VarDC == DC) return true;
15030 
15031   // Capture global variables if it is required to use private copy of this
15032   // variable.
15033   bool IsGlobal = !Var->hasLocalStorage();
15034   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15035     return true;
15036   Var = Var->getCanonicalDecl();
15037 
15038   // Walk up the stack to determine whether we can capture the variable,
15039   // performing the "simple" checks that don't depend on type. We stop when
15040   // we've either hit the declared scope of the variable or find an existing
15041   // capture of that variable.  We start from the innermost capturing-entity
15042   // (the DC) and ensure that all intervening capturing-entities
15043   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15044   // declcontext can either capture the variable or have already captured
15045   // the variable.
15046   CaptureType = Var->getType();
15047   DeclRefType = CaptureType.getNonReferenceType();
15048   bool Nested = false;
15049   bool Explicit = (Kind != TryCapture_Implicit);
15050   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15051   do {
15052     // Only block literals, captured statements, and lambda expressions can
15053     // capture; other scopes don't work.
15054     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15055                                                               ExprLoc,
15056                                                               BuildAndDiagnose,
15057                                                               *this);
15058     // We need to check for the parent *first* because, if we *have*
15059     // private-captured a global variable, we need to recursively capture it in
15060     // intermediate blocks, lambdas, etc.
15061     if (!ParentDC) {
15062       if (IsGlobal) {
15063         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15064         break;
15065       }
15066       return true;
15067     }
15068 
15069     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15070     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15071 
15072 
15073     // Check whether we've already captured it.
15074     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15075                                              DeclRefType)) {
15076       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15077       break;
15078     }
15079     // If we are instantiating a generic lambda call operator body,
15080     // we do not want to capture new variables.  What was captured
15081     // during either a lambdas transformation or initial parsing
15082     // should be used.
15083     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15084       if (BuildAndDiagnose) {
15085         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15086         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15087           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15088           Diag(Var->getLocation(), diag::note_previous_decl)
15089              << Var->getDeclName();
15090           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15091         } else
15092           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15093       }
15094       return true;
15095     }
15096     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15097     // certain types of variables (unnamed, variably modified types etc.)
15098     // so check for eligibility.
15099     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15100        return true;
15101 
15102     // Try to capture variable-length arrays types.
15103     if (Var->getType()->isVariablyModifiedType()) {
15104       // We're going to walk down into the type and look for VLA
15105       // expressions.
15106       QualType QTy = Var->getType();
15107       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15108         QTy = PVD->getOriginalType();
15109       captureVariablyModifiedType(Context, QTy, CSI);
15110     }
15111 
15112     if (getLangOpts().OpenMP) {
15113       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15114         // OpenMP private variables should not be captured in outer scope, so
15115         // just break here. Similarly, global variables that are captured in a
15116         // target region should not be captured outside the scope of the region.
15117         if (RSI->CapRegionKind == CR_OpenMP) {
15118           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15119           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15120                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15121           // When we detect target captures we are looking from inside the
15122           // target region, therefore we need to propagate the capture from the
15123           // enclosing region. Therefore, the capture is not initially nested.
15124           if (IsTargetCap)
15125             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15126 
15127           if (IsTargetCap || IsOpenMPPrivateDecl) {
15128             Nested = !IsTargetCap;
15129             DeclRefType = DeclRefType.getUnqualifiedType();
15130             CaptureType = Context.getLValueReferenceType(DeclRefType);
15131             break;
15132           }
15133         }
15134       }
15135     }
15136     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15137       // No capture-default, and this is not an explicit capture
15138       // so cannot capture this variable.
15139       if (BuildAndDiagnose) {
15140         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15141         Diag(Var->getLocation(), diag::note_previous_decl)
15142           << Var->getDeclName();
15143         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15144           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15145                diag::note_lambda_decl);
15146         // FIXME: If we error out because an outer lambda can not implicitly
15147         // capture a variable that an inner lambda explicitly captures, we
15148         // should have the inner lambda do the explicit capture - because
15149         // it makes for cleaner diagnostics later.  This would purely be done
15150         // so that the diagnostic does not misleadingly claim that a variable
15151         // can not be captured by a lambda implicitly even though it is captured
15152         // explicitly.  Suggestion:
15153         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15154         //    at the function head
15155         //  - cache the StartingDeclContext - this must be a lambda
15156         //  - captureInLambda in the innermost lambda the variable.
15157       }
15158       return true;
15159     }
15160 
15161     FunctionScopesIndex--;
15162     DC = ParentDC;
15163     Explicit = false;
15164   } while (!VarDC->Equals(DC));
15165 
15166   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15167   // computing the type of the capture at each step, checking type-specific
15168   // requirements, and adding captures if requested.
15169   // If the variable had already been captured previously, we start capturing
15170   // at the lambda nested within that one.
15171   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15172        ++I) {
15173     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15174 
15175     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15176       if (!captureInBlock(BSI, Var, ExprLoc,
15177                           BuildAndDiagnose, CaptureType,
15178                           DeclRefType, Nested, *this))
15179         return true;
15180       Nested = true;
15181     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15182       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15183                                    BuildAndDiagnose, CaptureType,
15184                                    DeclRefType, Nested, *this))
15185         return true;
15186       Nested = true;
15187     } else {
15188       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15189       if (!captureInLambda(LSI, Var, ExprLoc,
15190                            BuildAndDiagnose, CaptureType,
15191                            DeclRefType, Nested, Kind, EllipsisLoc,
15192                             /*IsTopScope*/I == N - 1, *this))
15193         return true;
15194       Nested = true;
15195     }
15196   }
15197   return false;
15198 }
15199 
15200 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15201                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15202   QualType CaptureType;
15203   QualType DeclRefType;
15204   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15205                             /*BuildAndDiagnose=*/true, CaptureType,
15206                             DeclRefType, nullptr);
15207 }
15208 
15209 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15210   QualType CaptureType;
15211   QualType DeclRefType;
15212   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15213                              /*BuildAndDiagnose=*/false, CaptureType,
15214                              DeclRefType, nullptr);
15215 }
15216 
15217 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15218   QualType CaptureType;
15219   QualType DeclRefType;
15220 
15221   // Determine whether we can capture this variable.
15222   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15223                          /*BuildAndDiagnose=*/false, CaptureType,
15224                          DeclRefType, nullptr))
15225     return QualType();
15226 
15227   return DeclRefType;
15228 }
15229 
15230 
15231 
15232 // If either the type of the variable or the initializer is dependent,
15233 // return false. Otherwise, determine whether the variable is a constant
15234 // expression. Use this if you need to know if a variable that might or
15235 // might not be dependent is truly a constant expression.
15236 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15237     ASTContext &Context) {
15238 
15239   if (Var->getType()->isDependentType())
15240     return false;
15241   const VarDecl *DefVD = nullptr;
15242   Var->getAnyInitializer(DefVD);
15243   if (!DefVD)
15244     return false;
15245   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15246   Expr *Init = cast<Expr>(Eval->Value);
15247   if (Init->isValueDependent())
15248     return false;
15249   return IsVariableAConstantExpression(Var, Context);
15250 }
15251 
15252 
15253 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15254   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15255   // an object that satisfies the requirements for appearing in a
15256   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15257   // is immediately applied."  This function handles the lvalue-to-rvalue
15258   // conversion part.
15259   MaybeODRUseExprs.erase(E->IgnoreParens());
15260 
15261   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15262   // to a variable that is a constant expression, and if so, identify it as
15263   // a reference to a variable that does not involve an odr-use of that
15264   // variable.
15265   if (LambdaScopeInfo *LSI = getCurLambda()) {
15266     Expr *SansParensExpr = E->IgnoreParens();
15267     VarDecl *Var = nullptr;
15268     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15269       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15270     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15271       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15272 
15273     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15274       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15275   }
15276 }
15277 
15278 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15279   Res = CorrectDelayedTyposInExpr(Res);
15280 
15281   if (!Res.isUsable())
15282     return Res;
15283 
15284   // If a constant-expression is a reference to a variable where we delay
15285   // deciding whether it is an odr-use, just assume we will apply the
15286   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15287   // (a non-type template argument), we have special handling anyway.
15288   UpdateMarkingForLValueToRValue(Res.get());
15289   return Res;
15290 }
15291 
15292 void Sema::CleanupVarDeclMarking() {
15293   for (Expr *E : MaybeODRUseExprs) {
15294     VarDecl *Var;
15295     SourceLocation Loc;
15296     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15297       Var = cast<VarDecl>(DRE->getDecl());
15298       Loc = DRE->getLocation();
15299     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15300       Var = cast<VarDecl>(ME->getMemberDecl());
15301       Loc = ME->getMemberLoc();
15302     } else {
15303       llvm_unreachable("Unexpected expression");
15304     }
15305 
15306     MarkVarDeclODRUsed(Var, Loc, *this,
15307                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15308   }
15309 
15310   MaybeODRUseExprs.clear();
15311 }
15312 
15313 
15314 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15315                                     VarDecl *Var, Expr *E) {
15316   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15317          "Invalid Expr argument to DoMarkVarDeclReferenced");
15318   Var->setReferenced();
15319 
15320   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15321 
15322   bool OdrUseContext = isOdrUseContext(SemaRef);
15323   bool UsableInConstantExpr =
15324       Var->isUsableInConstantExpressions(SemaRef.Context);
15325   bool NeedDefinition =
15326       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15327 
15328   VarTemplateSpecializationDecl *VarSpec =
15329       dyn_cast<VarTemplateSpecializationDecl>(Var);
15330   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15331          "Can't instantiate a partial template specialization.");
15332 
15333   // If this might be a member specialization of a static data member, check
15334   // the specialization is visible. We already did the checks for variable
15335   // template specializations when we created them.
15336   if (NeedDefinition && TSK != TSK_Undeclared &&
15337       !isa<VarTemplateSpecializationDecl>(Var))
15338     SemaRef.checkSpecializationVisibility(Loc, Var);
15339 
15340   // Perform implicit instantiation of static data members, static data member
15341   // templates of class templates, and variable template specializations. Delay
15342   // instantiations of variable templates, except for those that could be used
15343   // in a constant expression.
15344   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15345     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15346     // instantiation declaration if a variable is usable in a constant
15347     // expression (among other cases).
15348     bool TryInstantiating =
15349         TSK == TSK_ImplicitInstantiation ||
15350         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15351 
15352     if (TryInstantiating) {
15353       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15354       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15355       if (FirstInstantiation) {
15356         PointOfInstantiation = Loc;
15357         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15358       }
15359 
15360       bool InstantiationDependent = false;
15361       bool IsNonDependent =
15362           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15363                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15364                   : true;
15365 
15366       // Do not instantiate specializations that are still type-dependent.
15367       if (IsNonDependent) {
15368         if (UsableInConstantExpr) {
15369           // Do not defer instantiations of variables that could be used in a
15370           // constant expression.
15371           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15372         } else if (FirstInstantiation ||
15373                    isa<VarTemplateSpecializationDecl>(Var)) {
15374           // FIXME: For a specialization of a variable template, we don't
15375           // distinguish between "declaration and type implicitly instantiated"
15376           // and "implicit instantiation of definition requested", so we have
15377           // no direct way to avoid enqueueing the pending instantiation
15378           // multiple times.
15379           SemaRef.PendingInstantiations
15380               .push_back(std::make_pair(Var, PointOfInstantiation));
15381         }
15382       }
15383     }
15384   }
15385 
15386   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15387   // the requirements for appearing in a constant expression (5.19) and, if
15388   // it is an object, the lvalue-to-rvalue conversion (4.1)
15389   // is immediately applied."  We check the first part here, and
15390   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15391   // Note that we use the C++11 definition everywhere because nothing in
15392   // C++03 depends on whether we get the C++03 version correct. The second
15393   // part does not apply to references, since they are not objects.
15394   if (OdrUseContext && E &&
15395       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15396     // A reference initialized by a constant expression can never be
15397     // odr-used, so simply ignore it.
15398     if (!Var->getType()->isReferenceType() ||
15399         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15400       SemaRef.MaybeODRUseExprs.insert(E);
15401   } else if (OdrUseContext) {
15402     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15403                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15404   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15405     // If this is a dependent context, we don't need to mark variables as
15406     // odr-used, but we may still need to track them for lambda capture.
15407     // FIXME: Do we also need to do this inside dependent typeid expressions
15408     // (which are modeled as unevaluated at this point)?
15409     const bool RefersToEnclosingScope =
15410         (SemaRef.CurContext != Var->getDeclContext() &&
15411          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15412     if (RefersToEnclosingScope) {
15413       LambdaScopeInfo *const LSI =
15414           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15415       if (LSI && (!LSI->CallOperator ||
15416                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15417         // If a variable could potentially be odr-used, defer marking it so
15418         // until we finish analyzing the full expression for any
15419         // lvalue-to-rvalue
15420         // or discarded value conversions that would obviate odr-use.
15421         // Add it to the list of potential captures that will be analyzed
15422         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15423         // unless the variable is a reference that was initialized by a constant
15424         // expression (this will never need to be captured or odr-used).
15425         assert(E && "Capture variable should be used in an expression.");
15426         if (!Var->getType()->isReferenceType() ||
15427             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15428           LSI->addPotentialCapture(E->IgnoreParens());
15429       }
15430     }
15431   }
15432 }
15433 
15434 /// Mark a variable referenced, and check whether it is odr-used
15435 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15436 /// used directly for normal expressions referring to VarDecl.
15437 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15438   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15439 }
15440 
15441 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15442                                Decl *D, Expr *E, bool MightBeOdrUse) {
15443   if (SemaRef.isInOpenMPDeclareTargetContext())
15444     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15445 
15446   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15447     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15448     return;
15449   }
15450 
15451   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15452 
15453   // If this is a call to a method via a cast, also mark the method in the
15454   // derived class used in case codegen can devirtualize the call.
15455   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15456   if (!ME)
15457     return;
15458   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15459   if (!MD)
15460     return;
15461   // Only attempt to devirtualize if this is truly a virtual call.
15462   bool IsVirtualCall = MD->isVirtual() &&
15463                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15464   if (!IsVirtualCall)
15465     return;
15466 
15467   // If it's possible to devirtualize the call, mark the called function
15468   // referenced.
15469   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15470       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15471   if (DM)
15472     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15473 }
15474 
15475 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15476 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15477   // TODO: update this with DR# once a defect report is filed.
15478   // C++11 defect. The address of a pure member should not be an ODR use, even
15479   // if it's a qualified reference.
15480   bool OdrUse = true;
15481   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15482     if (Method->isVirtual() &&
15483         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15484       OdrUse = false;
15485   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15486 }
15487 
15488 /// Perform reference-marking and odr-use handling for a MemberExpr.
15489 void Sema::MarkMemberReferenced(MemberExpr *E) {
15490   // C++11 [basic.def.odr]p2:
15491   //   A non-overloaded function whose name appears as a potentially-evaluated
15492   //   expression or a member of a set of candidate functions, if selected by
15493   //   overload resolution when referred to from a potentially-evaluated
15494   //   expression, is odr-used, unless it is a pure virtual function and its
15495   //   name is not explicitly qualified.
15496   bool MightBeOdrUse = true;
15497   if (E->performsVirtualDispatch(getLangOpts())) {
15498     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15499       if (Method->isPure())
15500         MightBeOdrUse = false;
15501   }
15502   SourceLocation Loc =
15503       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15504   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15505 }
15506 
15507 /// Perform marking for a reference to an arbitrary declaration.  It
15508 /// marks the declaration referenced, and performs odr-use checking for
15509 /// functions and variables. This method should not be used when building a
15510 /// normal expression which refers to a variable.
15511 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15512                                  bool MightBeOdrUse) {
15513   if (MightBeOdrUse) {
15514     if (auto *VD = dyn_cast<VarDecl>(D)) {
15515       MarkVariableReferenced(Loc, VD);
15516       return;
15517     }
15518   }
15519   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15520     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15521     return;
15522   }
15523   D->setReferenced();
15524 }
15525 
15526 namespace {
15527   // Mark all of the declarations used by a type as referenced.
15528   // FIXME: Not fully implemented yet! We need to have a better understanding
15529   // of when we're entering a context we should not recurse into.
15530   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15531   // TreeTransforms rebuilding the type in a new context. Rather than
15532   // duplicating the TreeTransform logic, we should consider reusing it here.
15533   // Currently that causes problems when rebuilding LambdaExprs.
15534   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15535     Sema &S;
15536     SourceLocation Loc;
15537 
15538   public:
15539     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15540 
15541     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15542 
15543     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15544   };
15545 }
15546 
15547 bool MarkReferencedDecls::TraverseTemplateArgument(
15548     const TemplateArgument &Arg) {
15549   {
15550     // A non-type template argument is a constant-evaluated context.
15551     EnterExpressionEvaluationContext Evaluated(
15552         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15553     if (Arg.getKind() == TemplateArgument::Declaration) {
15554       if (Decl *D = Arg.getAsDecl())
15555         S.MarkAnyDeclReferenced(Loc, D, true);
15556     } else if (Arg.getKind() == TemplateArgument::Expression) {
15557       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15558     }
15559   }
15560 
15561   return Inherited::TraverseTemplateArgument(Arg);
15562 }
15563 
15564 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15565   MarkReferencedDecls Marker(*this, Loc);
15566   Marker.TraverseType(T);
15567 }
15568 
15569 namespace {
15570   /// Helper class that marks all of the declarations referenced by
15571   /// potentially-evaluated subexpressions as "referenced".
15572   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15573     Sema &S;
15574     bool SkipLocalVariables;
15575 
15576   public:
15577     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15578 
15579     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15580       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15581 
15582     void VisitDeclRefExpr(DeclRefExpr *E) {
15583       // If we were asked not to visit local variables, don't.
15584       if (SkipLocalVariables) {
15585         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15586           if (VD->hasLocalStorage())
15587             return;
15588       }
15589 
15590       S.MarkDeclRefReferenced(E);
15591     }
15592 
15593     void VisitMemberExpr(MemberExpr *E) {
15594       S.MarkMemberReferenced(E);
15595       Inherited::VisitMemberExpr(E);
15596     }
15597 
15598     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15599       S.MarkFunctionReferenced(
15600           E->getBeginLoc(),
15601           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15602       Visit(E->getSubExpr());
15603     }
15604 
15605     void VisitCXXNewExpr(CXXNewExpr *E) {
15606       if (E->getOperatorNew())
15607         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
15608       if (E->getOperatorDelete())
15609         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15610       Inherited::VisitCXXNewExpr(E);
15611     }
15612 
15613     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15614       if (E->getOperatorDelete())
15615         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15616       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15617       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15618         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15619         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
15620       }
15621 
15622       Inherited::VisitCXXDeleteExpr(E);
15623     }
15624 
15625     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15626       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
15627       Inherited::VisitCXXConstructExpr(E);
15628     }
15629 
15630     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15631       Visit(E->getExpr());
15632     }
15633 
15634     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15635       Inherited::VisitImplicitCastExpr(E);
15636 
15637       if (E->getCastKind() == CK_LValueToRValue)
15638         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15639     }
15640   };
15641 }
15642 
15643 /// Mark any declarations that appear within this expression or any
15644 /// potentially-evaluated subexpressions as "referenced".
15645 ///
15646 /// \param SkipLocalVariables If true, don't mark local variables as
15647 /// 'referenced'.
15648 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15649                                             bool SkipLocalVariables) {
15650   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15651 }
15652 
15653 /// Emit a diagnostic that describes an effect on the run-time behavior
15654 /// of the program being compiled.
15655 ///
15656 /// This routine emits the given diagnostic when the code currently being
15657 /// type-checked is "potentially evaluated", meaning that there is a
15658 /// possibility that the code will actually be executable. Code in sizeof()
15659 /// expressions, code used only during overload resolution, etc., are not
15660 /// potentially evaluated. This routine will suppress such diagnostics or,
15661 /// in the absolutely nutty case of potentially potentially evaluated
15662 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15663 /// later.
15664 ///
15665 /// This routine should be used for all diagnostics that describe the run-time
15666 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15667 /// Failure to do so will likely result in spurious diagnostics or failures
15668 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15669 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15670                                const PartialDiagnostic &PD) {
15671   switch (ExprEvalContexts.back().Context) {
15672   case ExpressionEvaluationContext::Unevaluated:
15673   case ExpressionEvaluationContext::UnevaluatedList:
15674   case ExpressionEvaluationContext::UnevaluatedAbstract:
15675   case ExpressionEvaluationContext::DiscardedStatement:
15676     // The argument will never be evaluated, so don't complain.
15677     break;
15678 
15679   case ExpressionEvaluationContext::ConstantEvaluated:
15680     // Relevant diagnostics should be produced by constant evaluation.
15681     break;
15682 
15683   case ExpressionEvaluationContext::PotentiallyEvaluated:
15684   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15685     if (Statement && getCurFunctionOrMethodDecl()) {
15686       FunctionScopes.back()->PossiblyUnreachableDiags.
15687         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15688       return true;
15689     }
15690 
15691     // The initializer of a constexpr variable or of the first declaration of a
15692     // static data member is not syntactically a constant evaluated constant,
15693     // but nonetheless is always required to be a constant expression, so we
15694     // can skip diagnosing.
15695     // FIXME: Using the mangling context here is a hack.
15696     if (auto *VD = dyn_cast_or_null<VarDecl>(
15697             ExprEvalContexts.back().ManglingContextDecl)) {
15698       if (VD->isConstexpr() ||
15699           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15700         break;
15701       // FIXME: For any other kind of variable, we should build a CFG for its
15702       // initializer and check whether the context in question is reachable.
15703     }
15704 
15705     Diag(Loc, PD);
15706     return true;
15707   }
15708 
15709   return false;
15710 }
15711 
15712 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15713                                CallExpr *CE, FunctionDecl *FD) {
15714   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15715     return false;
15716 
15717   // If we're inside a decltype's expression, don't check for a valid return
15718   // type or construct temporaries until we know whether this is the last call.
15719   if (ExprEvalContexts.back().ExprContext ==
15720       ExpressionEvaluationContextRecord::EK_Decltype) {
15721     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15722     return false;
15723   }
15724 
15725   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15726     FunctionDecl *FD;
15727     CallExpr *CE;
15728 
15729   public:
15730     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15731       : FD(FD), CE(CE) { }
15732 
15733     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15734       if (!FD) {
15735         S.Diag(Loc, diag::err_call_incomplete_return)
15736           << T << CE->getSourceRange();
15737         return;
15738       }
15739 
15740       S.Diag(Loc, diag::err_call_function_incomplete_return)
15741         << CE->getSourceRange() << FD->getDeclName() << T;
15742       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15743           << FD->getDeclName();
15744     }
15745   } Diagnoser(FD, CE);
15746 
15747   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15748     return true;
15749 
15750   return false;
15751 }
15752 
15753 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15754 // will prevent this condition from triggering, which is what we want.
15755 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15756   SourceLocation Loc;
15757 
15758   unsigned diagnostic = diag::warn_condition_is_assignment;
15759   bool IsOrAssign = false;
15760 
15761   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15762     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15763       return;
15764 
15765     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15766 
15767     // Greylist some idioms by putting them into a warning subcategory.
15768     if (ObjCMessageExpr *ME
15769           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15770       Selector Sel = ME->getSelector();
15771 
15772       // self = [<foo> init...]
15773       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15774         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15775 
15776       // <foo> = [<bar> nextObject]
15777       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15778         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15779     }
15780 
15781     Loc = Op->getOperatorLoc();
15782   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15783     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15784       return;
15785 
15786     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15787     Loc = Op->getOperatorLoc();
15788   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15789     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15790   else {
15791     // Not an assignment.
15792     return;
15793   }
15794 
15795   Diag(Loc, diagnostic) << E->getSourceRange();
15796 
15797   SourceLocation Open = E->getBeginLoc();
15798   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15799   Diag(Loc, diag::note_condition_assign_silence)
15800         << FixItHint::CreateInsertion(Open, "(")
15801         << FixItHint::CreateInsertion(Close, ")");
15802 
15803   if (IsOrAssign)
15804     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15805       << FixItHint::CreateReplacement(Loc, "!=");
15806   else
15807     Diag(Loc, diag::note_condition_assign_to_comparison)
15808       << FixItHint::CreateReplacement(Loc, "==");
15809 }
15810 
15811 /// Redundant parentheses over an equality comparison can indicate
15812 /// that the user intended an assignment used as condition.
15813 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15814   // Don't warn if the parens came from a macro.
15815   SourceLocation parenLoc = ParenE->getBeginLoc();
15816   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15817     return;
15818   // Don't warn for dependent expressions.
15819   if (ParenE->isTypeDependent())
15820     return;
15821 
15822   Expr *E = ParenE->IgnoreParens();
15823 
15824   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15825     if (opE->getOpcode() == BO_EQ &&
15826         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15827                                                            == Expr::MLV_Valid) {
15828       SourceLocation Loc = opE->getOperatorLoc();
15829 
15830       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15831       SourceRange ParenERange = ParenE->getSourceRange();
15832       Diag(Loc, diag::note_equality_comparison_silence)
15833         << FixItHint::CreateRemoval(ParenERange.getBegin())
15834         << FixItHint::CreateRemoval(ParenERange.getEnd());
15835       Diag(Loc, diag::note_equality_comparison_to_assign)
15836         << FixItHint::CreateReplacement(Loc, "=");
15837     }
15838 }
15839 
15840 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15841                                        bool IsConstexpr) {
15842   DiagnoseAssignmentAsCondition(E);
15843   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15844     DiagnoseEqualityWithExtraParens(parenE);
15845 
15846   ExprResult result = CheckPlaceholderExpr(E);
15847   if (result.isInvalid()) return ExprError();
15848   E = result.get();
15849 
15850   if (!E->isTypeDependent()) {
15851     if (getLangOpts().CPlusPlus)
15852       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15853 
15854     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15855     if (ERes.isInvalid())
15856       return ExprError();
15857     E = ERes.get();
15858 
15859     QualType T = E->getType();
15860     if (!T->isScalarType()) { // C99 6.8.4.1p1
15861       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15862         << T << E->getSourceRange();
15863       return ExprError();
15864     }
15865     CheckBoolLikeConversion(E, Loc);
15866   }
15867 
15868   return E;
15869 }
15870 
15871 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15872                                            Expr *SubExpr, ConditionKind CK) {
15873   // Empty conditions are valid in for-statements.
15874   if (!SubExpr)
15875     return ConditionResult();
15876 
15877   ExprResult Cond;
15878   switch (CK) {
15879   case ConditionKind::Boolean:
15880     Cond = CheckBooleanCondition(Loc, SubExpr);
15881     break;
15882 
15883   case ConditionKind::ConstexprIf:
15884     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15885     break;
15886 
15887   case ConditionKind::Switch:
15888     Cond = CheckSwitchCondition(Loc, SubExpr);
15889     break;
15890   }
15891   if (Cond.isInvalid())
15892     return ConditionError();
15893 
15894   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15895   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15896   if (!FullExpr.get())
15897     return ConditionError();
15898 
15899   return ConditionResult(*this, nullptr, FullExpr,
15900                          CK == ConditionKind::ConstexprIf);
15901 }
15902 
15903 namespace {
15904   /// A visitor for rebuilding a call to an __unknown_any expression
15905   /// to have an appropriate type.
15906   struct RebuildUnknownAnyFunction
15907     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15908 
15909     Sema &S;
15910 
15911     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15912 
15913     ExprResult VisitStmt(Stmt *S) {
15914       llvm_unreachable("unexpected statement!");
15915     }
15916 
15917     ExprResult VisitExpr(Expr *E) {
15918       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15919         << E->getSourceRange();
15920       return ExprError();
15921     }
15922 
15923     /// Rebuild an expression which simply semantically wraps another
15924     /// expression which it shares the type and value kind of.
15925     template <class T> ExprResult rebuildSugarExpr(T *E) {
15926       ExprResult SubResult = Visit(E->getSubExpr());
15927       if (SubResult.isInvalid()) return ExprError();
15928 
15929       Expr *SubExpr = SubResult.get();
15930       E->setSubExpr(SubExpr);
15931       E->setType(SubExpr->getType());
15932       E->setValueKind(SubExpr->getValueKind());
15933       assert(E->getObjectKind() == OK_Ordinary);
15934       return E;
15935     }
15936 
15937     ExprResult VisitParenExpr(ParenExpr *E) {
15938       return rebuildSugarExpr(E);
15939     }
15940 
15941     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15942       return rebuildSugarExpr(E);
15943     }
15944 
15945     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15946       ExprResult SubResult = Visit(E->getSubExpr());
15947       if (SubResult.isInvalid()) return ExprError();
15948 
15949       Expr *SubExpr = SubResult.get();
15950       E->setSubExpr(SubExpr);
15951       E->setType(S.Context.getPointerType(SubExpr->getType()));
15952       assert(E->getValueKind() == VK_RValue);
15953       assert(E->getObjectKind() == OK_Ordinary);
15954       return E;
15955     }
15956 
15957     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15958       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15959 
15960       E->setType(VD->getType());
15961 
15962       assert(E->getValueKind() == VK_RValue);
15963       if (S.getLangOpts().CPlusPlus &&
15964           !(isa<CXXMethodDecl>(VD) &&
15965             cast<CXXMethodDecl>(VD)->isInstance()))
15966         E->setValueKind(VK_LValue);
15967 
15968       return E;
15969     }
15970 
15971     ExprResult VisitMemberExpr(MemberExpr *E) {
15972       return resolveDecl(E, E->getMemberDecl());
15973     }
15974 
15975     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15976       return resolveDecl(E, E->getDecl());
15977     }
15978   };
15979 }
15980 
15981 /// Given a function expression of unknown-any type, try to rebuild it
15982 /// to have a function type.
15983 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15984   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15985   if (Result.isInvalid()) return ExprError();
15986   return S.DefaultFunctionArrayConversion(Result.get());
15987 }
15988 
15989 namespace {
15990   /// A visitor for rebuilding an expression of type __unknown_anytype
15991   /// into one which resolves the type directly on the referring
15992   /// expression.  Strict preservation of the original source
15993   /// structure is not a goal.
15994   struct RebuildUnknownAnyExpr
15995     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15996 
15997     Sema &S;
15998 
15999     /// The current destination type.
16000     QualType DestType;
16001 
16002     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16003       : S(S), DestType(CastType) {}
16004 
16005     ExprResult VisitStmt(Stmt *S) {
16006       llvm_unreachable("unexpected statement!");
16007     }
16008 
16009     ExprResult VisitExpr(Expr *E) {
16010       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16011         << E->getSourceRange();
16012       return ExprError();
16013     }
16014 
16015     ExprResult VisitCallExpr(CallExpr *E);
16016     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16017 
16018     /// Rebuild an expression which simply semantically wraps another
16019     /// expression which it shares the type and value kind of.
16020     template <class T> ExprResult rebuildSugarExpr(T *E) {
16021       ExprResult SubResult = Visit(E->getSubExpr());
16022       if (SubResult.isInvalid()) return ExprError();
16023       Expr *SubExpr = SubResult.get();
16024       E->setSubExpr(SubExpr);
16025       E->setType(SubExpr->getType());
16026       E->setValueKind(SubExpr->getValueKind());
16027       assert(E->getObjectKind() == OK_Ordinary);
16028       return E;
16029     }
16030 
16031     ExprResult VisitParenExpr(ParenExpr *E) {
16032       return rebuildSugarExpr(E);
16033     }
16034 
16035     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16036       return rebuildSugarExpr(E);
16037     }
16038 
16039     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16040       const PointerType *Ptr = DestType->getAs<PointerType>();
16041       if (!Ptr) {
16042         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16043           << E->getSourceRange();
16044         return ExprError();
16045       }
16046 
16047       if (isa<CallExpr>(E->getSubExpr())) {
16048         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16049           << E->getSourceRange();
16050         return ExprError();
16051       }
16052 
16053       assert(E->getValueKind() == VK_RValue);
16054       assert(E->getObjectKind() == OK_Ordinary);
16055       E->setType(DestType);
16056 
16057       // Build the sub-expression as if it were an object of the pointee type.
16058       DestType = Ptr->getPointeeType();
16059       ExprResult SubResult = Visit(E->getSubExpr());
16060       if (SubResult.isInvalid()) return ExprError();
16061       E->setSubExpr(SubResult.get());
16062       return E;
16063     }
16064 
16065     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16066 
16067     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16068 
16069     ExprResult VisitMemberExpr(MemberExpr *E) {
16070       return resolveDecl(E, E->getMemberDecl());
16071     }
16072 
16073     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16074       return resolveDecl(E, E->getDecl());
16075     }
16076   };
16077 }
16078 
16079 /// Rebuilds a call expression which yielded __unknown_anytype.
16080 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16081   Expr *CalleeExpr = E->getCallee();
16082 
16083   enum FnKind {
16084     FK_MemberFunction,
16085     FK_FunctionPointer,
16086     FK_BlockPointer
16087   };
16088 
16089   FnKind Kind;
16090   QualType CalleeType = CalleeExpr->getType();
16091   if (CalleeType == S.Context.BoundMemberTy) {
16092     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16093     Kind = FK_MemberFunction;
16094     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16095   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16096     CalleeType = Ptr->getPointeeType();
16097     Kind = FK_FunctionPointer;
16098   } else {
16099     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16100     Kind = FK_BlockPointer;
16101   }
16102   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16103 
16104   // Verify that this is a legal result type of a function.
16105   if (DestType->isArrayType() || DestType->isFunctionType()) {
16106     unsigned diagID = diag::err_func_returning_array_function;
16107     if (Kind == FK_BlockPointer)
16108       diagID = diag::err_block_returning_array_function;
16109 
16110     S.Diag(E->getExprLoc(), diagID)
16111       << DestType->isFunctionType() << DestType;
16112     return ExprError();
16113   }
16114 
16115   // Otherwise, go ahead and set DestType as the call's result.
16116   E->setType(DestType.getNonLValueExprType(S.Context));
16117   E->setValueKind(Expr::getValueKindForType(DestType));
16118   assert(E->getObjectKind() == OK_Ordinary);
16119 
16120   // Rebuild the function type, replacing the result type with DestType.
16121   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16122   if (Proto) {
16123     // __unknown_anytype(...) is a special case used by the debugger when
16124     // it has no idea what a function's signature is.
16125     //
16126     // We want to build this call essentially under the K&R
16127     // unprototyped rules, but making a FunctionNoProtoType in C++
16128     // would foul up all sorts of assumptions.  However, we cannot
16129     // simply pass all arguments as variadic arguments, nor can we
16130     // portably just call the function under a non-variadic type; see
16131     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16132     // However, it turns out that in practice it is generally safe to
16133     // call a function declared as "A foo(B,C,D);" under the prototype
16134     // "A foo(B,C,D,...);".  The only known exception is with the
16135     // Windows ABI, where any variadic function is implicitly cdecl
16136     // regardless of its normal CC.  Therefore we change the parameter
16137     // types to match the types of the arguments.
16138     //
16139     // This is a hack, but it is far superior to moving the
16140     // corresponding target-specific code from IR-gen to Sema/AST.
16141 
16142     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16143     SmallVector<QualType, 8> ArgTypes;
16144     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16145       ArgTypes.reserve(E->getNumArgs());
16146       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16147         Expr *Arg = E->getArg(i);
16148         QualType ArgType = Arg->getType();
16149         if (E->isLValue()) {
16150           ArgType = S.Context.getLValueReferenceType(ArgType);
16151         } else if (E->isXValue()) {
16152           ArgType = S.Context.getRValueReferenceType(ArgType);
16153         }
16154         ArgTypes.push_back(ArgType);
16155       }
16156       ParamTypes = ArgTypes;
16157     }
16158     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16159                                          Proto->getExtProtoInfo());
16160   } else {
16161     DestType = S.Context.getFunctionNoProtoType(DestType,
16162                                                 FnType->getExtInfo());
16163   }
16164 
16165   // Rebuild the appropriate pointer-to-function type.
16166   switch (Kind) {
16167   case FK_MemberFunction:
16168     // Nothing to do.
16169     break;
16170 
16171   case FK_FunctionPointer:
16172     DestType = S.Context.getPointerType(DestType);
16173     break;
16174 
16175   case FK_BlockPointer:
16176     DestType = S.Context.getBlockPointerType(DestType);
16177     break;
16178   }
16179 
16180   // Finally, we can recurse.
16181   ExprResult CalleeResult = Visit(CalleeExpr);
16182   if (!CalleeResult.isUsable()) return ExprError();
16183   E->setCallee(CalleeResult.get());
16184 
16185   // Bind a temporary if necessary.
16186   return S.MaybeBindToTemporary(E);
16187 }
16188 
16189 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16190   // Verify that this is a legal result type of a call.
16191   if (DestType->isArrayType() || DestType->isFunctionType()) {
16192     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16193       << DestType->isFunctionType() << DestType;
16194     return ExprError();
16195   }
16196 
16197   // Rewrite the method result type if available.
16198   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16199     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16200     Method->setReturnType(DestType);
16201   }
16202 
16203   // Change the type of the message.
16204   E->setType(DestType.getNonReferenceType());
16205   E->setValueKind(Expr::getValueKindForType(DestType));
16206 
16207   return S.MaybeBindToTemporary(E);
16208 }
16209 
16210 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16211   // The only case we should ever see here is a function-to-pointer decay.
16212   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16213     assert(E->getValueKind() == VK_RValue);
16214     assert(E->getObjectKind() == OK_Ordinary);
16215 
16216     E->setType(DestType);
16217 
16218     // Rebuild the sub-expression as the pointee (function) type.
16219     DestType = DestType->castAs<PointerType>()->getPointeeType();
16220 
16221     ExprResult Result = Visit(E->getSubExpr());
16222     if (!Result.isUsable()) return ExprError();
16223 
16224     E->setSubExpr(Result.get());
16225     return E;
16226   } else if (E->getCastKind() == CK_LValueToRValue) {
16227     assert(E->getValueKind() == VK_RValue);
16228     assert(E->getObjectKind() == OK_Ordinary);
16229 
16230     assert(isa<BlockPointerType>(E->getType()));
16231 
16232     E->setType(DestType);
16233 
16234     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16235     DestType = S.Context.getLValueReferenceType(DestType);
16236 
16237     ExprResult Result = Visit(E->getSubExpr());
16238     if (!Result.isUsable()) return ExprError();
16239 
16240     E->setSubExpr(Result.get());
16241     return E;
16242   } else {
16243     llvm_unreachable("Unhandled cast type!");
16244   }
16245 }
16246 
16247 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16248   ExprValueKind ValueKind = VK_LValue;
16249   QualType Type = DestType;
16250 
16251   // We know how to make this work for certain kinds of decls:
16252 
16253   //  - functions
16254   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16255     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16256       DestType = Ptr->getPointeeType();
16257       ExprResult Result = resolveDecl(E, VD);
16258       if (Result.isInvalid()) return ExprError();
16259       return S.ImpCastExprToType(Result.get(), Type,
16260                                  CK_FunctionToPointerDecay, VK_RValue);
16261     }
16262 
16263     if (!Type->isFunctionType()) {
16264       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16265         << VD << E->getSourceRange();
16266       return ExprError();
16267     }
16268     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16269       // We must match the FunctionDecl's type to the hack introduced in
16270       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16271       // type. See the lengthy commentary in that routine.
16272       QualType FDT = FD->getType();
16273       const FunctionType *FnType = FDT->castAs<FunctionType>();
16274       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16275       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16276       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16277         SourceLocation Loc = FD->getLocation();
16278         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16279                                       FD->getDeclContext(),
16280                                       Loc, Loc, FD->getNameInfo().getName(),
16281                                       DestType, FD->getTypeSourceInfo(),
16282                                       SC_None, false/*isInlineSpecified*/,
16283                                       FD->hasPrototype(),
16284                                       false/*isConstexprSpecified*/);
16285 
16286         if (FD->getQualifier())
16287           NewFD->setQualifierInfo(FD->getQualifierLoc());
16288 
16289         SmallVector<ParmVarDecl*, 16> Params;
16290         for (const auto &AI : FT->param_types()) {
16291           ParmVarDecl *Param =
16292             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16293           Param->setScopeInfo(0, Params.size());
16294           Params.push_back(Param);
16295         }
16296         NewFD->setParams(Params);
16297         DRE->setDecl(NewFD);
16298         VD = DRE->getDecl();
16299       }
16300     }
16301 
16302     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16303       if (MD->isInstance()) {
16304         ValueKind = VK_RValue;
16305         Type = S.Context.BoundMemberTy;
16306       }
16307 
16308     // Function references aren't l-values in C.
16309     if (!S.getLangOpts().CPlusPlus)
16310       ValueKind = VK_RValue;
16311 
16312   //  - variables
16313   } else if (isa<VarDecl>(VD)) {
16314     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16315       Type = RefTy->getPointeeType();
16316     } else if (Type->isFunctionType()) {
16317       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16318         << VD << E->getSourceRange();
16319       return ExprError();
16320     }
16321 
16322   //  - nothing else
16323   } else {
16324     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16325       << VD << E->getSourceRange();
16326     return ExprError();
16327   }
16328 
16329   // Modifying the declaration like this is friendly to IR-gen but
16330   // also really dangerous.
16331   VD->setType(DestType);
16332   E->setType(Type);
16333   E->setValueKind(ValueKind);
16334   return E;
16335 }
16336 
16337 /// Check a cast of an unknown-any type.  We intentionally only
16338 /// trigger this for C-style casts.
16339 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16340                                      Expr *CastExpr, CastKind &CastKind,
16341                                      ExprValueKind &VK, CXXCastPath &Path) {
16342   // The type we're casting to must be either void or complete.
16343   if (!CastType->isVoidType() &&
16344       RequireCompleteType(TypeRange.getBegin(), CastType,
16345                           diag::err_typecheck_cast_to_incomplete))
16346     return ExprError();
16347 
16348   // Rewrite the casted expression from scratch.
16349   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16350   if (!result.isUsable()) return ExprError();
16351 
16352   CastExpr = result.get();
16353   VK = CastExpr->getValueKind();
16354   CastKind = CK_NoOp;
16355 
16356   return CastExpr;
16357 }
16358 
16359 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16360   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16361 }
16362 
16363 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16364                                     Expr *arg, QualType &paramType) {
16365   // If the syntactic form of the argument is not an explicit cast of
16366   // any sort, just do default argument promotion.
16367   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16368   if (!castArg) {
16369     ExprResult result = DefaultArgumentPromotion(arg);
16370     if (result.isInvalid()) return ExprError();
16371     paramType = result.get()->getType();
16372     return result;
16373   }
16374 
16375   // Otherwise, use the type that was written in the explicit cast.
16376   assert(!arg->hasPlaceholderType());
16377   paramType = castArg->getTypeAsWritten();
16378 
16379   // Copy-initialize a parameter of that type.
16380   InitializedEntity entity =
16381     InitializedEntity::InitializeParameter(Context, paramType,
16382                                            /*consumed*/ false);
16383   return PerformCopyInitialization(entity, callLoc, arg);
16384 }
16385 
16386 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16387   Expr *orig = E;
16388   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16389   while (true) {
16390     E = E->IgnoreParenImpCasts();
16391     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16392       E = call->getCallee();
16393       diagID = diag::err_uncasted_call_of_unknown_any;
16394     } else {
16395       break;
16396     }
16397   }
16398 
16399   SourceLocation loc;
16400   NamedDecl *d;
16401   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16402     loc = ref->getLocation();
16403     d = ref->getDecl();
16404   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16405     loc = mem->getMemberLoc();
16406     d = mem->getMemberDecl();
16407   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16408     diagID = diag::err_uncasted_call_of_unknown_any;
16409     loc = msg->getSelectorStartLoc();
16410     d = msg->getMethodDecl();
16411     if (!d) {
16412       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16413         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16414         << orig->getSourceRange();
16415       return ExprError();
16416     }
16417   } else {
16418     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16419       << E->getSourceRange();
16420     return ExprError();
16421   }
16422 
16423   S.Diag(loc, diagID) << d << orig->getSourceRange();
16424 
16425   // Never recoverable.
16426   return ExprError();
16427 }
16428 
16429 /// Check for operands with placeholder types and complain if found.
16430 /// Returns ExprError() if there was an error and no recovery was possible.
16431 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16432   if (!getLangOpts().CPlusPlus) {
16433     // C cannot handle TypoExpr nodes on either side of a binop because it
16434     // doesn't handle dependent types properly, so make sure any TypoExprs have
16435     // been dealt with before checking the operands.
16436     ExprResult Result = CorrectDelayedTyposInExpr(E);
16437     if (!Result.isUsable()) return ExprError();
16438     E = Result.get();
16439   }
16440 
16441   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16442   if (!placeholderType) return E;
16443 
16444   switch (placeholderType->getKind()) {
16445 
16446   // Overloaded expressions.
16447   case BuiltinType::Overload: {
16448     // Try to resolve a single function template specialization.
16449     // This is obligatory.
16450     ExprResult Result = E;
16451     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16452       return Result;
16453 
16454     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16455     // leaves Result unchanged on failure.
16456     Result = E;
16457     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16458       return Result;
16459 
16460     // If that failed, try to recover with a call.
16461     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16462                          /*complain*/ true);
16463     return Result;
16464   }
16465 
16466   // Bound member functions.
16467   case BuiltinType::BoundMember: {
16468     ExprResult result = E;
16469     const Expr *BME = E->IgnoreParens();
16470     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16471     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16472     if (isa<CXXPseudoDestructorExpr>(BME)) {
16473       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16474     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16475       if (ME->getMemberNameInfo().getName().getNameKind() ==
16476           DeclarationName::CXXDestructorName)
16477         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16478     }
16479     tryToRecoverWithCall(result, PD,
16480                          /*complain*/ true);
16481     return result;
16482   }
16483 
16484   // ARC unbridged casts.
16485   case BuiltinType::ARCUnbridgedCast: {
16486     Expr *realCast = stripARCUnbridgedCast(E);
16487     diagnoseARCUnbridgedCast(realCast);
16488     return realCast;
16489   }
16490 
16491   // Expressions of unknown type.
16492   case BuiltinType::UnknownAny:
16493     return diagnoseUnknownAnyExpr(*this, E);
16494 
16495   // Pseudo-objects.
16496   case BuiltinType::PseudoObject:
16497     return checkPseudoObjectRValue(E);
16498 
16499   case BuiltinType::BuiltinFn: {
16500     // Accept __noop without parens by implicitly converting it to a call expr.
16501     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16502     if (DRE) {
16503       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16504       if (FD->getBuiltinID() == Builtin::BI__noop) {
16505         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16506                               CK_BuiltinFnToFnPtr).get();
16507         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16508                                       VK_RValue, SourceLocation());
16509       }
16510     }
16511 
16512     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16513     return ExprError();
16514   }
16515 
16516   // Expressions of unknown type.
16517   case BuiltinType::OMPArraySection:
16518     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16519     return ExprError();
16520 
16521   // Everything else should be impossible.
16522 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16523   case BuiltinType::Id:
16524 #include "clang/Basic/OpenCLImageTypes.def"
16525 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16526 #define PLACEHOLDER_TYPE(Id, SingletonId)
16527 #include "clang/AST/BuiltinTypes.def"
16528     break;
16529   }
16530 
16531   llvm_unreachable("invalid placeholder type!");
16532 }
16533 
16534 bool Sema::CheckCaseExpression(Expr *E) {
16535   if (E->isTypeDependent())
16536     return true;
16537   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16538     return E->getType()->isIntegralOrEnumerationType();
16539   return false;
16540 }
16541 
16542 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16543 ExprResult
16544 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16545   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16546          "Unknown Objective-C Boolean value!");
16547   QualType BoolT = Context.ObjCBuiltinBoolTy;
16548   if (!Context.getBOOLDecl()) {
16549     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16550                         Sema::LookupOrdinaryName);
16551     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16552       NamedDecl *ND = Result.getFoundDecl();
16553       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16554         Context.setBOOLDecl(TD);
16555     }
16556   }
16557   if (Context.getBOOLDecl())
16558     BoolT = Context.getBOOLType();
16559   return new (Context)
16560       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16561 }
16562 
16563 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16564     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16565     SourceLocation RParen) {
16566 
16567   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16568 
16569   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16570                            [&](const AvailabilitySpec &Spec) {
16571                              return Spec.getPlatform() == Platform;
16572                            });
16573 
16574   VersionTuple Version;
16575   if (Spec != AvailSpecs.end())
16576     Version = Spec->getVersion();
16577 
16578   // The use of `@available` in the enclosing function should be analyzed to
16579   // warn when it's used inappropriately (i.e. not if(@available)).
16580   if (getCurFunctionOrMethodDecl())
16581     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16582   else if (getCurBlock() || getCurLambda())
16583     getCurFunction()->HasPotentialAvailabilityViolations = true;
16584 
16585   return new (Context)
16586       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16587 }
16588