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/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97 
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105 
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message);
109 
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message);
117         continue;
118       }
119     }
120     break;
121   }
122 
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message);
128     }
129   }
130 
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message);
136     }
137 
138   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142 
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158 
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161 
162   return Result;
163 }
164 
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173 
174     if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
175       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
176       return;
177     }
178 
179     const ObjCPropertyDecl *ObjCPDecl = nullptr;
180     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183         if (PDeclResult == Result)
184           ObjCPDecl = PD;
185       }
186     }
187 
188     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189                               ObjCPDecl, ObjCPropertyAccess);
190   }
191 }
192 
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195   assert(Decl->isDeleted());
196 
197   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
198 
199   if (Method && Method->isDeleted() && Method->isDefaulted()) {
200     // If the method was explicitly defaulted, point at that declaration.
201     if (!Method->isImplicit())
202       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
203 
204     // Try to diagnose why this special member function was implicitly
205     // deleted. This might fail, if that reason no longer applies.
206     CXXSpecialMember CSM = getSpecialMember(Method);
207     if (CSM != CXXInvalid)
208       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
209 
210     return;
211   }
212 
213   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214   if (Ctor && Ctor->isInheritingConstructor())
215     return NoteDeletedInheritingConstructor(Ctor);
216 
217   Diag(Decl->getLocation(), diag::note_availability_specified_here)
218     << Decl << true;
219 }
220 
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224   for (auto I : D->redecls()) {
225     if (I->getStorageClass() != SC_None)
226       return true;
227   }
228   return false;
229 }
230 
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
233 ///
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
240                                                       const NamedDecl *D,
241                                                       SourceLocation Loc) {
242   // This is disabled under C++; there are too many ways for this to fire in
243   // contexts where the warning is a false positive, or where it is technically
244   // correct but benign.
245   if (S.getLangOpts().CPlusPlus)
246     return;
247 
248   // Check if this is an inlined function or method.
249   FunctionDecl *Current = S.getCurFunctionDecl();
250   if (!Current)
251     return;
252   if (!Current->isInlined())
253     return;
254   if (!Current->isExternallyVisible())
255     return;
256 
257   // Check if the decl has internal linkage.
258   if (D->getFormalLinkage() != InternalLinkage)
259     return;
260 
261   // Downgrade from ExtWarn to Extension if
262   //  (1) the supposedly external inline function is in the main file,
263   //      and probably won't be included anywhere else.
264   //  (2) the thing we're referencing is a pure function.
265   //  (3) the thing we're referencing is another inline function.
266   // This last can give us false negatives, but it's better than warning on
267   // wrappers for simple C library functions.
268   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270   if (!DowngradeWarning && UsedFn)
271     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
272 
273   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274                                : diag::ext_internal_in_extern_inline)
275     << /*IsVar=*/!UsedFn << D;
276 
277   S.MaybeSuggestAddingStaticToDecl(Current);
278 
279   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
280       << D;
281 }
282 
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284   const FunctionDecl *First = Cur->getFirstDecl();
285 
286   // Suggest "static" on the function, if possible.
287   if (!hasAnyExplicitStorageClass(First)) {
288     SourceLocation DeclBegin = First->getSourceRange().getBegin();
289     Diag(DeclBegin, diag::note_convert_inline_to_static)
290       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
291   }
292 }
293 
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
296 ///
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
302 ///
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
305 ///
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307                              const ObjCInterfaceDecl *UnknownObjCClass,
308                              bool ObjCPropertyAccess) {
309   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310     // If there were any diagnostics suppressed by template argument deduction,
311     // emit them now.
312     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313     if (Pos != SuppressedDiagnostics.end()) {
314       for (const PartialDiagnosticAt &Suppressed : Pos->second)
315         Diag(Suppressed.first, Suppressed.second);
316 
317       // Clear out the list of suppressed diagnostics, so that we don't emit
318       // them again for this specialization. However, we don't obsolete this
319       // entry from the table, because we want to avoid ever emitting these
320       // diagnostics again.
321       Pos->second.clear();
322     }
323 
324     // C++ [basic.start.main]p3:
325     //   The function 'main' shall not be used within a program.
326     if (cast<FunctionDecl>(D)->isMain())
327       Diag(Loc, diag::ext_main_used);
328   }
329 
330   // See if this is an auto-typed variable whose initializer we are parsing.
331   if (ParsingInitForAutoVars.count(D)) {
332     if (isa<BindingDecl>(D)) {
333       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
334         << D->getDeclName();
335     } else {
336       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
337         << D->getDeclName() << cast<VarDecl>(D)->getType();
338     }
339     return true;
340   }
341 
342   // See if this is a deleted function.
343   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
344     if (FD->isDeleted()) {
345       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
346       if (Ctor && Ctor->isInheritingConstructor())
347         Diag(Loc, diag::err_deleted_inherited_ctor_use)
348             << Ctor->getParent()
349             << Ctor->getInheritedConstructor().getConstructor()->getParent();
350       else
351         Diag(Loc, diag::err_deleted_function_use);
352       NoteDeletedFunction(FD);
353       return true;
354     }
355 
356     // If the function has a deduced return type, and we can't deduce it,
357     // then we can't use it either.
358     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
359         DeduceReturnType(FD, Loc))
360       return true;
361 
362     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
363       return true;
364 
365     if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
366       return true;
367   }
368 
369   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
370   // Only the variables omp_in and omp_out are allowed in the combiner.
371   // Only the variables omp_priv and omp_orig are allowed in the
372   // initializer-clause.
373   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
374   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
375       isa<VarDecl>(D)) {
376     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
377         << getCurFunction()->HasOMPDeclareReductionCombiner;
378     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
379     return true;
380   }
381 
382   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
383                              ObjCPropertyAccess);
384 
385   DiagnoseUnusedOfDecl(*this, D, Loc);
386 
387   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
388 
389   return false;
390 }
391 
392 /// \brief Retrieve the message suffix that should be added to a
393 /// diagnostic complaining about the given function being deleted or
394 /// unavailable.
395 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
396   std::string Message;
397   if (FD->getAvailability(&Message))
398     return ": " + Message;
399 
400   return std::string();
401 }
402 
403 /// DiagnoseSentinelCalls - This routine checks whether a call or
404 /// message-send is to a declaration with the sentinel attribute, and
405 /// if so, it checks that the requirements of the sentinel are
406 /// satisfied.
407 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
408                                  ArrayRef<Expr *> Args) {
409   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
410   if (!attr)
411     return;
412 
413   // The number of formal parameters of the declaration.
414   unsigned numFormalParams;
415 
416   // The kind of declaration.  This is also an index into a %select in
417   // the diagnostic.
418   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
419 
420   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
421     numFormalParams = MD->param_size();
422     calleeType = CT_Method;
423   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
424     numFormalParams = FD->param_size();
425     calleeType = CT_Function;
426   } else if (isa<VarDecl>(D)) {
427     QualType type = cast<ValueDecl>(D)->getType();
428     const FunctionType *fn = nullptr;
429     if (const PointerType *ptr = type->getAs<PointerType>()) {
430       fn = ptr->getPointeeType()->getAs<FunctionType>();
431       if (!fn) return;
432       calleeType = CT_Function;
433     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
434       fn = ptr->getPointeeType()->castAs<FunctionType>();
435       calleeType = CT_Block;
436     } else {
437       return;
438     }
439 
440     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
441       numFormalParams = proto->getNumParams();
442     } else {
443       numFormalParams = 0;
444     }
445   } else {
446     return;
447   }
448 
449   // "nullPos" is the number of formal parameters at the end which
450   // effectively count as part of the variadic arguments.  This is
451   // useful if you would prefer to not have *any* formal parameters,
452   // but the language forces you to have at least one.
453   unsigned nullPos = attr->getNullPos();
454   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
455   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
456 
457   // The number of arguments which should follow the sentinel.
458   unsigned numArgsAfterSentinel = attr->getSentinel();
459 
460   // If there aren't enough arguments for all the formal parameters,
461   // the sentinel, and the args after the sentinel, complain.
462   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
463     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
464     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
465     return;
466   }
467 
468   // Otherwise, find the sentinel expression.
469   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
470   if (!sentinelExpr) return;
471   if (sentinelExpr->isValueDependent()) return;
472   if (Context.isSentinelNullExpr(sentinelExpr)) return;
473 
474   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
475   // or 'NULL' if those are actually defined in the context.  Only use
476   // 'nil' for ObjC methods, where it's much more likely that the
477   // variadic arguments form a list of object pointers.
478   SourceLocation MissingNilLoc
479     = getLocForEndOfToken(sentinelExpr->getLocEnd());
480   std::string NullValue;
481   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
482     NullValue = "nil";
483   else if (getLangOpts().CPlusPlus11)
484     NullValue = "nullptr";
485   else if (PP.isMacroDefined("NULL"))
486     NullValue = "NULL";
487   else
488     NullValue = "(void*) 0";
489 
490   if (MissingNilLoc.isInvalid())
491     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
492   else
493     Diag(MissingNilLoc, diag::warn_missing_sentinel)
494       << int(calleeType)
495       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
496   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
497 }
498 
499 SourceRange Sema::getExprRange(Expr *E) const {
500   return E ? E->getSourceRange() : SourceRange();
501 }
502 
503 //===----------------------------------------------------------------------===//
504 //  Standard Promotions and Conversions
505 //===----------------------------------------------------------------------===//
506 
507 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
508 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
509   // Handle any placeholder expressions which made it here.
510   if (E->getType()->isPlaceholderType()) {
511     ExprResult result = CheckPlaceholderExpr(E);
512     if (result.isInvalid()) return ExprError();
513     E = result.get();
514   }
515 
516   QualType Ty = E->getType();
517   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
518 
519   if (Ty->isFunctionType()) {
520     // If we are here, we are not calling a function but taking
521     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
522     if (getLangOpts().OpenCL) {
523       if (Diagnose)
524         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
525       return ExprError();
526     }
527 
528     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
530         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
531           return ExprError();
532 
533     E = ImpCastExprToType(E, Context.getPointerType(Ty),
534                           CK_FunctionToPointerDecay).get();
535   } else if (Ty->isArrayType()) {
536     // In C90 mode, arrays only promote to pointers if the array expression is
537     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538     // type 'array of type' is converted to an expression that has type 'pointer
539     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
540     // that has type 'array of type' ...".  The relevant change is "an lvalue"
541     // (C90) to "an expression" (C99).
542     //
543     // C++ 4.2p1:
544     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545     // T" can be converted to an rvalue of type "pointer to T".
546     //
547     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
548       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
549                             CK_ArrayToPointerDecay).get();
550   }
551   return E;
552 }
553 
554 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
555   // Check to see if we are dereferencing a null pointer.  If so,
556   // and if not volatile-qualified, this is undefined behavior that the
557   // optimizer will delete, so warn about it.  People sometimes try to use this
558   // to get a deterministic trap and are surprised by clang's behavior.  This
559   // only handles the pattern "*null", which is a very syntactic check.
560   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
561     if (UO->getOpcode() == UO_Deref &&
562         UO->getSubExpr()->IgnoreParenCasts()->
563           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
564         !UO->getType().isVolatileQualified()) {
565     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
566                           S.PDiag(diag::warn_indirection_through_null)
567                             << UO->getSubExpr()->getSourceRange());
568     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
569                         S.PDiag(diag::note_indirection_through_null));
570   }
571 }
572 
573 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
574                                     SourceLocation AssignLoc,
575                                     const Expr* RHS) {
576   const ObjCIvarDecl *IV = OIRE->getDecl();
577   if (!IV)
578     return;
579 
580   DeclarationName MemberName = IV->getDeclName();
581   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
582   if (!Member || !Member->isStr("isa"))
583     return;
584 
585   const Expr *Base = OIRE->getBase();
586   QualType BaseType = Base->getType();
587   if (OIRE->isArrow())
588     BaseType = BaseType->getPointeeType();
589   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
590     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
591       ObjCInterfaceDecl *ClassDeclared = nullptr;
592       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
593       if (!ClassDeclared->getSuperClass()
594           && (*ClassDeclared->ivar_begin()) == IV) {
595         if (RHS) {
596           NamedDecl *ObjectSetClass =
597             S.LookupSingleName(S.TUScope,
598                                &S.Context.Idents.get("object_setClass"),
599                                SourceLocation(), S.LookupOrdinaryName);
600           if (ObjectSetClass) {
601             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
602             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
603             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
604             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
605                                                      AssignLoc), ",") <<
606             FixItHint::CreateInsertion(RHSLocEnd, ")");
607           }
608           else
609             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
610         } else {
611           NamedDecl *ObjectGetClass =
612             S.LookupSingleName(S.TUScope,
613                                &S.Context.Idents.get("object_getClass"),
614                                SourceLocation(), S.LookupOrdinaryName);
615           if (ObjectGetClass)
616             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
617             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
618             FixItHint::CreateReplacement(
619                                          SourceRange(OIRE->getOpLoc(),
620                                                      OIRE->getLocEnd()), ")");
621           else
622             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
623         }
624         S.Diag(IV->getLocation(), diag::note_ivar_decl);
625       }
626     }
627 }
628 
629 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
630   // Handle any placeholder expressions which made it here.
631   if (E->getType()->isPlaceholderType()) {
632     ExprResult result = CheckPlaceholderExpr(E);
633     if (result.isInvalid()) return ExprError();
634     E = result.get();
635   }
636 
637   // C++ [conv.lval]p1:
638   //   A glvalue of a non-function, non-array type T can be
639   //   converted to a prvalue.
640   if (!E->isGLValue()) return E;
641 
642   QualType T = E->getType();
643   assert(!T.isNull() && "r-value conversion on typeless expression?");
644 
645   // We don't want to throw lvalue-to-rvalue casts on top of
646   // expressions of certain types in C++.
647   if (getLangOpts().CPlusPlus &&
648       (E->getType() == Context.OverloadTy ||
649        T->isDependentType() ||
650        T->isRecordType()))
651     return E;
652 
653   // The C standard is actually really unclear on this point, and
654   // DR106 tells us what the result should be but not why.  It's
655   // generally best to say that void types just doesn't undergo
656   // lvalue-to-rvalue at all.  Note that expressions of unqualified
657   // 'void' type are never l-values, but qualified void can be.
658   if (T->isVoidType())
659     return E;
660 
661   // OpenCL usually rejects direct accesses to values of 'half' type.
662   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
663       T->isHalfType()) {
664     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
665       << 0 << T;
666     return ExprError();
667   }
668 
669   CheckForNullPointerDereference(*this, E);
670   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
671     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
672                                      &Context.Idents.get("object_getClass"),
673                                      SourceLocation(), LookupOrdinaryName);
674     if (ObjectGetClass)
675       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
676         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
677         FixItHint::CreateReplacement(
678                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
679     else
680       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
681   }
682   else if (const ObjCIvarRefExpr *OIRE =
683             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
684     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
685 
686   // C++ [conv.lval]p1:
687   //   [...] If T is a non-class type, the type of the prvalue is the
688   //   cv-unqualified version of T. Otherwise, the type of the
689   //   rvalue is T.
690   //
691   // C99 6.3.2.1p2:
692   //   If the lvalue has qualified type, the value has the unqualified
693   //   version of the type of the lvalue; otherwise, the value has the
694   //   type of the lvalue.
695   if (T.hasQualifiers())
696     T = T.getUnqualifiedType();
697 
698   // Under the MS ABI, lock down the inheritance model now.
699   if (T->isMemberPointerType() &&
700       Context.getTargetInfo().getCXXABI().isMicrosoft())
701     (void)isCompleteType(E->getExprLoc(), T);
702 
703   UpdateMarkingForLValueToRValue(E);
704 
705   // Loading a __weak object implicitly retains the value, so we need a cleanup to
706   // balance that.
707   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
708     Cleanup.setExprNeedsCleanups(true);
709 
710   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
711                                             nullptr, VK_RValue);
712 
713   // C11 6.3.2.1p2:
714   //   ... if the lvalue has atomic type, the value has the non-atomic version
715   //   of the type of the lvalue ...
716   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
717     T = Atomic->getValueType().getUnqualifiedType();
718     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
719                                    nullptr, VK_RValue);
720   }
721 
722   return Res;
723 }
724 
725 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
726   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
727   if (Res.isInvalid())
728     return ExprError();
729   Res = DefaultLvalueConversion(Res.get());
730   if (Res.isInvalid())
731     return ExprError();
732   return Res;
733 }
734 
735 /// CallExprUnaryConversions - a special case of an unary conversion
736 /// performed on a function designator of a call expression.
737 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
738   QualType Ty = E->getType();
739   ExprResult Res = E;
740   // Only do implicit cast for a function type, but not for a pointer
741   // to function type.
742   if (Ty->isFunctionType()) {
743     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
744                             CK_FunctionToPointerDecay).get();
745     if (Res.isInvalid())
746       return ExprError();
747   }
748   Res = DefaultLvalueConversion(Res.get());
749   if (Res.isInvalid())
750     return ExprError();
751   return Res.get();
752 }
753 
754 /// UsualUnaryConversions - Performs various conversions that are common to most
755 /// operators (C99 6.3). The conversions of array and function types are
756 /// sometimes suppressed. For example, the array->pointer conversion doesn't
757 /// apply if the array is an argument to the sizeof or address (&) operators.
758 /// In these instances, this routine should *not* be called.
759 ExprResult Sema::UsualUnaryConversions(Expr *E) {
760   // First, convert to an r-value.
761   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
762   if (Res.isInvalid())
763     return ExprError();
764   E = Res.get();
765 
766   QualType Ty = E->getType();
767   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
768 
769   // Half FP have to be promoted to float unless it is natively supported
770   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
771     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
772 
773   // Try to perform integral promotions if the object has a theoretically
774   // promotable type.
775   if (Ty->isIntegralOrUnscopedEnumerationType()) {
776     // C99 6.3.1.1p2:
777     //
778     //   The following may be used in an expression wherever an int or
779     //   unsigned int may be used:
780     //     - an object or expression with an integer type whose integer
781     //       conversion rank is less than or equal to the rank of int
782     //       and unsigned int.
783     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
784     //
785     //   If an int can represent all values of the original type, the
786     //   value is converted to an int; otherwise, it is converted to an
787     //   unsigned int. These are called the integer promotions. All
788     //   other types are unchanged by the integer promotions.
789 
790     QualType PTy = Context.isPromotableBitField(E);
791     if (!PTy.isNull()) {
792       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
793       return E;
794     }
795     if (Ty->isPromotableIntegerType()) {
796       QualType PT = Context.getPromotedIntegerType(Ty);
797       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
798       return E;
799     }
800   }
801   return E;
802 }
803 
804 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
805 /// do not have a prototype. Arguments that have type float or __fp16
806 /// are promoted to double. All other argument types are converted by
807 /// UsualUnaryConversions().
808 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
809   QualType Ty = E->getType();
810   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
811 
812   ExprResult Res = UsualUnaryConversions(E);
813   if (Res.isInvalid())
814     return ExprError();
815   E = Res.get();
816 
817   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
818   // double.
819   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
820   if (BTy && (BTy->getKind() == BuiltinType::Half ||
821               BTy->getKind() == BuiltinType::Float)) {
822     if (getLangOpts().OpenCL &&
823         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
824         if (BTy->getKind() == BuiltinType::Half) {
825             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
826         }
827     } else {
828       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
829     }
830   }
831 
832   // C++ performs lvalue-to-rvalue conversion as a default argument
833   // promotion, even on class types, but note:
834   //   C++11 [conv.lval]p2:
835   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
836   //     operand or a subexpression thereof the value contained in the
837   //     referenced object is not accessed. Otherwise, if the glvalue
838   //     has a class type, the conversion copy-initializes a temporary
839   //     of type T from the glvalue and the result of the conversion
840   //     is a prvalue for the temporary.
841   // FIXME: add some way to gate this entire thing for correctness in
842   // potentially potentially evaluated contexts.
843   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
844     ExprResult Temp = PerformCopyInitialization(
845                        InitializedEntity::InitializeTemporary(E->getType()),
846                                                 E->getExprLoc(), E);
847     if (Temp.isInvalid())
848       return ExprError();
849     E = Temp.get();
850   }
851 
852   return E;
853 }
854 
855 /// Determine the degree of POD-ness for an expression.
856 /// Incomplete types are considered POD, since this check can be performed
857 /// when we're in an unevaluated context.
858 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
859   if (Ty->isIncompleteType()) {
860     // C++11 [expr.call]p7:
861     //   After these conversions, if the argument does not have arithmetic,
862     //   enumeration, pointer, pointer to member, or class type, the program
863     //   is ill-formed.
864     //
865     // Since we've already performed array-to-pointer and function-to-pointer
866     // decay, the only such type in C++ is cv void. This also handles
867     // initializer lists as variadic arguments.
868     if (Ty->isVoidType())
869       return VAK_Invalid;
870 
871     if (Ty->isObjCObjectType())
872       return VAK_Invalid;
873     return VAK_Valid;
874   }
875 
876   if (Ty.isCXX98PODType(Context))
877     return VAK_Valid;
878 
879   // C++11 [expr.call]p7:
880   //   Passing a potentially-evaluated argument of class type (Clause 9)
881   //   having a non-trivial copy constructor, a non-trivial move constructor,
882   //   or a non-trivial destructor, with no corresponding parameter,
883   //   is conditionally-supported with implementation-defined semantics.
884   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
885     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
886       if (!Record->hasNonTrivialCopyConstructor() &&
887           !Record->hasNonTrivialMoveConstructor() &&
888           !Record->hasNonTrivialDestructor())
889         return VAK_ValidInCXX11;
890 
891   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
892     return VAK_Valid;
893 
894   if (Ty->isObjCObjectType())
895     return VAK_Invalid;
896 
897   if (getLangOpts().MSVCCompat)
898     return VAK_MSVCUndefined;
899 
900   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
901   // permitted to reject them. We should consider doing so.
902   return VAK_Undefined;
903 }
904 
905 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
906   // Don't allow one to pass an Objective-C interface to a vararg.
907   const QualType &Ty = E->getType();
908   VarArgKind VAK = isValidVarArgType(Ty);
909 
910   // Complain about passing non-POD types through varargs.
911   switch (VAK) {
912   case VAK_ValidInCXX11:
913     DiagRuntimeBehavior(
914         E->getLocStart(), nullptr,
915         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
916           << Ty << CT);
917     // Fall through.
918   case VAK_Valid:
919     if (Ty->isRecordType()) {
920       // This is unlikely to be what the user intended. If the class has a
921       // 'c_str' member function, the user probably meant to call that.
922       DiagRuntimeBehavior(E->getLocStart(), nullptr,
923                           PDiag(diag::warn_pass_class_arg_to_vararg)
924                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
925     }
926     break;
927 
928   case VAK_Undefined:
929   case VAK_MSVCUndefined:
930     DiagRuntimeBehavior(
931         E->getLocStart(), nullptr,
932         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
933           << getLangOpts().CPlusPlus11 << Ty << CT);
934     break;
935 
936   case VAK_Invalid:
937     if (Ty->isObjCObjectType())
938       DiagRuntimeBehavior(
939           E->getLocStart(), nullptr,
940           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
941             << Ty << CT);
942     else
943       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
944         << isa<InitListExpr>(E) << Ty << CT;
945     break;
946   }
947 }
948 
949 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
950 /// will create a trap if the resulting type is not a POD type.
951 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
952                                                   FunctionDecl *FDecl) {
953   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
954     // Strip the unbridged-cast placeholder expression off, if applicable.
955     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
956         (CT == VariadicMethod ||
957          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
958       E = stripARCUnbridgedCast(E);
959 
960     // Otherwise, do normal placeholder checking.
961     } else {
962       ExprResult ExprRes = CheckPlaceholderExpr(E);
963       if (ExprRes.isInvalid())
964         return ExprError();
965       E = ExprRes.get();
966     }
967   }
968 
969   ExprResult ExprRes = DefaultArgumentPromotion(E);
970   if (ExprRes.isInvalid())
971     return ExprError();
972   E = ExprRes.get();
973 
974   // Diagnostics regarding non-POD argument types are
975   // emitted along with format string checking in Sema::CheckFunctionCall().
976   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977     // Turn this into a trap.
978     CXXScopeSpec SS;
979     SourceLocation TemplateKWLoc;
980     UnqualifiedId Name;
981     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
982                        E->getLocStart());
983     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
984                                           Name, true, false);
985     if (TrapFn.isInvalid())
986       return ExprError();
987 
988     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
989                                     E->getLocStart(), None,
990                                     E->getLocEnd());
991     if (Call.isInvalid())
992       return ExprError();
993 
994     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
995                                   Call.get(), E);
996     if (Comma.isInvalid())
997       return ExprError();
998     return Comma.get();
999   }
1000 
1001   if (!getLangOpts().CPlusPlus &&
1002       RequireCompleteType(E->getExprLoc(), E->getType(),
1003                           diag::err_call_incomplete_argument))
1004     return ExprError();
1005 
1006   return E;
1007 }
1008 
1009 /// \brief Converts an integer to complex float type.  Helper function of
1010 /// UsualArithmeticConversions()
1011 ///
1012 /// \return false if the integer expression is an integer type and is
1013 /// successfully converted to the complex type.
1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015                                                   ExprResult &ComplexExpr,
1016                                                   QualType IntTy,
1017                                                   QualType ComplexTy,
1018                                                   bool SkipCast) {
1019   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020   if (SkipCast) return false;
1021   if (IntTy->isIntegerType()) {
1022     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025                                   CK_FloatingRealToComplex);
1026   } else {
1027     assert(IntTy->isComplexIntegerType());
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029                                   CK_IntegralComplexToFloatingComplex);
1030   }
1031   return false;
1032 }
1033 
1034 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1035 /// UsualArithmeticConversions()
1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037                                              ExprResult &RHS, QualType LHSType,
1038                                              QualType RHSType,
1039                                              bool IsCompAssign) {
1040   // if we have an integer operand, the result is the complex type.
1041   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1042                                              /*skipCast*/false))
1043     return LHSType;
1044   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045                                              /*skipCast*/IsCompAssign))
1046     return RHSType;
1047 
1048   // This handles complex/complex, complex/float, or float/complex.
1049   // When both operands are complex, the shorter operand is converted to the
1050   // type of the longer, and that is the type of the result. This corresponds
1051   // to what is done when combining two real floating-point operands.
1052   // The fun begins when size promotion occur across type domains.
1053   // From H&S 6.3.4: When one operand is complex and the other is a real
1054   // floating-point type, the less precise type is converted, within it's
1055   // real or complex domain, to the precision of the other type. For example,
1056   // when combining a "long double" with a "double _Complex", the
1057   // "double _Complex" is promoted to "long double _Complex".
1058 
1059   // Compute the rank of the two types, regardless of whether they are complex.
1060   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061 
1062   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064   QualType LHSElementType =
1065       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066   QualType RHSElementType =
1067       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1068 
1069   QualType ResultType = S.Context.getComplexType(LHSElementType);
1070   if (Order < 0) {
1071     // Promote the precision of the LHS if not an assignment.
1072     ResultType = S.Context.getComplexType(RHSElementType);
1073     if (!IsCompAssign) {
1074       if (LHSComplexType)
1075         LHS =
1076             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1077       else
1078         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1079     }
1080   } else if (Order > 0) {
1081     // Promote the precision of the RHS.
1082     if (RHSComplexType)
1083       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1084     else
1085       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1086   }
1087   return ResultType;
1088 }
1089 
1090 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1091 /// of UsualArithmeticConversions()
1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093                                            ExprResult &IntExpr,
1094                                            QualType FloatTy, QualType IntTy,
1095                                            bool ConvertFloat, bool ConvertInt) {
1096   if (IntTy->isIntegerType()) {
1097     if (ConvertInt)
1098       // Convert intExpr to the lhs floating point type.
1099       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100                                     CK_IntegralToFloating);
1101     return FloatTy;
1102   }
1103 
1104   // Convert both sides to the appropriate complex float.
1105   assert(IntTy->isComplexIntegerType());
1106   QualType result = S.Context.getComplexType(FloatTy);
1107 
1108   // _Complex int -> _Complex float
1109   if (ConvertInt)
1110     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111                                   CK_IntegralComplexToFloatingComplex);
1112 
1113   // float -> _Complex float
1114   if (ConvertFloat)
1115     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116                                     CK_FloatingRealToComplex);
1117 
1118   return result;
1119 }
1120 
1121 /// \brief Handle arithmethic conversion with floating point types.  Helper
1122 /// function of UsualArithmeticConversions()
1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124                                       ExprResult &RHS, QualType LHSType,
1125                                       QualType RHSType, bool IsCompAssign) {
1126   bool LHSFloat = LHSType->isRealFloatingType();
1127   bool RHSFloat = RHSType->isRealFloatingType();
1128 
1129   // If we have two real floating types, convert the smaller operand
1130   // to the bigger result.
1131   if (LHSFloat && RHSFloat) {
1132     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1133     if (order > 0) {
1134       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1135       return LHSType;
1136     }
1137 
1138     assert(order < 0 && "illegal float comparison");
1139     if (!IsCompAssign)
1140       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1141     return RHSType;
1142   }
1143 
1144   if (LHSFloat) {
1145     // Half FP has to be promoted to float unless it is natively supported
1146     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1147       LHSType = S.Context.FloatTy;
1148 
1149     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1150                                       /*convertFloat=*/!IsCompAssign,
1151                                       /*convertInt=*/ true);
1152   }
1153   assert(RHSFloat);
1154   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1155                                     /*convertInt=*/ true,
1156                                     /*convertFloat=*/!IsCompAssign);
1157 }
1158 
1159 /// \brief Diagnose attempts to convert between __float128 and long double if
1160 /// there is no support for such conversion. Helper function of
1161 /// UsualArithmeticConversions().
1162 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1163                                       QualType RHSType) {
1164   /*  No issue converting if at least one of the types is not a floating point
1165       type or the two types have the same rank.
1166   */
1167   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1168       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1169     return false;
1170 
1171   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1172          "The remaining types must be floating point types.");
1173 
1174   auto *LHSComplex = LHSType->getAs<ComplexType>();
1175   auto *RHSComplex = RHSType->getAs<ComplexType>();
1176 
1177   QualType LHSElemType = LHSComplex ?
1178     LHSComplex->getElementType() : LHSType;
1179   QualType RHSElemType = RHSComplex ?
1180     RHSComplex->getElementType() : RHSType;
1181 
1182   // No issue if the two types have the same representation
1183   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1184       &S.Context.getFloatTypeSemantics(RHSElemType))
1185     return false;
1186 
1187   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1188                                 RHSElemType == S.Context.LongDoubleTy);
1189   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1190                             RHSElemType == S.Context.Float128Ty);
1191 
1192   /* We've handled the situation where __float128 and long double have the same
1193      representation. The only other allowable conversion is if long double is
1194      really just double.
1195   */
1196   return Float128AndLongDouble &&
1197     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1198      &llvm::APFloat::IEEEdouble());
1199 }
1200 
1201 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1202 
1203 namespace {
1204 /// These helper callbacks are placed in an anonymous namespace to
1205 /// permit their use as function template parameters.
1206 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1207   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1208 }
1209 
1210 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1211   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1212                              CK_IntegralComplexCast);
1213 }
1214 }
1215 
1216 /// \brief Handle integer arithmetic conversions.  Helper function of
1217 /// UsualArithmeticConversions()
1218 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1219 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1220                                         ExprResult &RHS, QualType LHSType,
1221                                         QualType RHSType, bool IsCompAssign) {
1222   // The rules for this case are in C99 6.3.1.8
1223   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1224   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1225   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1226   if (LHSSigned == RHSSigned) {
1227     // Same signedness; use the higher-ranked type
1228     if (order >= 0) {
1229       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1230       return LHSType;
1231     } else if (!IsCompAssign)
1232       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1233     return RHSType;
1234   } else if (order != (LHSSigned ? 1 : -1)) {
1235     // The unsigned type has greater than or equal rank to the
1236     // signed type, so use the unsigned type
1237     if (RHSSigned) {
1238       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1239       return LHSType;
1240     } else if (!IsCompAssign)
1241       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1242     return RHSType;
1243   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1244     // The two types are different widths; if we are here, that
1245     // means the signed type is larger than the unsigned type, so
1246     // use the signed type.
1247     if (LHSSigned) {
1248       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1249       return LHSType;
1250     } else if (!IsCompAssign)
1251       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1252     return RHSType;
1253   } else {
1254     // The signed type is higher-ranked than the unsigned type,
1255     // but isn't actually any bigger (like unsigned int and long
1256     // on most 32-bit systems).  Use the unsigned type corresponding
1257     // to the signed type.
1258     QualType result =
1259       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1260     RHS = (*doRHSCast)(S, RHS.get(), result);
1261     if (!IsCompAssign)
1262       LHS = (*doLHSCast)(S, LHS.get(), result);
1263     return result;
1264   }
1265 }
1266 
1267 /// \brief Handle conversions with GCC complex int extension.  Helper function
1268 /// of UsualArithmeticConversions()
1269 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1270                                            ExprResult &RHS, QualType LHSType,
1271                                            QualType RHSType,
1272                                            bool IsCompAssign) {
1273   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1274   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1275 
1276   if (LHSComplexInt && RHSComplexInt) {
1277     QualType LHSEltType = LHSComplexInt->getElementType();
1278     QualType RHSEltType = RHSComplexInt->getElementType();
1279     QualType ScalarType =
1280       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1281         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1282 
1283     return S.Context.getComplexType(ScalarType);
1284   }
1285 
1286   if (LHSComplexInt) {
1287     QualType LHSEltType = LHSComplexInt->getElementType();
1288     QualType ScalarType =
1289       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1290         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1291     QualType ComplexType = S.Context.getComplexType(ScalarType);
1292     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1293                               CK_IntegralRealToComplex);
1294 
1295     return ComplexType;
1296   }
1297 
1298   assert(RHSComplexInt);
1299 
1300   QualType RHSEltType = RHSComplexInt->getElementType();
1301   QualType ScalarType =
1302     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1303       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1304   QualType ComplexType = S.Context.getComplexType(ScalarType);
1305 
1306   if (!IsCompAssign)
1307     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1308                               CK_IntegralRealToComplex);
1309   return ComplexType;
1310 }
1311 
1312 /// UsualArithmeticConversions - Performs various conversions that are common to
1313 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1314 /// routine returns the first non-arithmetic type found. The client is
1315 /// responsible for emitting appropriate error diagnostics.
1316 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1317                                           bool IsCompAssign) {
1318   if (!IsCompAssign) {
1319     LHS = UsualUnaryConversions(LHS.get());
1320     if (LHS.isInvalid())
1321       return QualType();
1322   }
1323 
1324   RHS = UsualUnaryConversions(RHS.get());
1325   if (RHS.isInvalid())
1326     return QualType();
1327 
1328   // For conversion purposes, we ignore any qualifiers.
1329   // For example, "const float" and "float" are equivalent.
1330   QualType LHSType =
1331     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1332   QualType RHSType =
1333     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1334 
1335   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1336   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1337     LHSType = AtomicLHS->getValueType();
1338 
1339   // If both types are identical, no conversion is needed.
1340   if (LHSType == RHSType)
1341     return LHSType;
1342 
1343   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1344   // The caller can deal with this (e.g. pointer + int).
1345   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1346     return QualType();
1347 
1348   // Apply unary and bitfield promotions to the LHS's type.
1349   QualType LHSUnpromotedType = LHSType;
1350   if (LHSType->isPromotableIntegerType())
1351     LHSType = Context.getPromotedIntegerType(LHSType);
1352   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1353   if (!LHSBitfieldPromoteTy.isNull())
1354     LHSType = LHSBitfieldPromoteTy;
1355   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1356     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1357 
1358   // If both types are identical, no conversion is needed.
1359   if (LHSType == RHSType)
1360     return LHSType;
1361 
1362   // At this point, we have two different arithmetic types.
1363 
1364   // Diagnose attempts to convert between __float128 and long double where
1365   // such conversions currently can't be handled.
1366   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1367     return QualType();
1368 
1369   // Handle complex types first (C99 6.3.1.8p1).
1370   if (LHSType->isComplexType() || RHSType->isComplexType())
1371     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1372                                         IsCompAssign);
1373 
1374   // Now handle "real" floating types (i.e. float, double, long double).
1375   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1376     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1377                                  IsCompAssign);
1378 
1379   // Handle GCC complex int extension.
1380   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1381     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1382                                       IsCompAssign);
1383 
1384   // Finally, we have two differing integer types.
1385   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1386            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1387 }
1388 
1389 
1390 //===----------------------------------------------------------------------===//
1391 //  Semantic Analysis for various Expression Types
1392 //===----------------------------------------------------------------------===//
1393 
1394 
1395 ExprResult
1396 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1397                                 SourceLocation DefaultLoc,
1398                                 SourceLocation RParenLoc,
1399                                 Expr *ControllingExpr,
1400                                 ArrayRef<ParsedType> ArgTypes,
1401                                 ArrayRef<Expr *> ArgExprs) {
1402   unsigned NumAssocs = ArgTypes.size();
1403   assert(NumAssocs == ArgExprs.size());
1404 
1405   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1406   for (unsigned i = 0; i < NumAssocs; ++i) {
1407     if (ArgTypes[i])
1408       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1409     else
1410       Types[i] = nullptr;
1411   }
1412 
1413   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1414                                              ControllingExpr,
1415                                              llvm::makeArrayRef(Types, NumAssocs),
1416                                              ArgExprs);
1417   delete [] Types;
1418   return ER;
1419 }
1420 
1421 ExprResult
1422 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1423                                  SourceLocation DefaultLoc,
1424                                  SourceLocation RParenLoc,
1425                                  Expr *ControllingExpr,
1426                                  ArrayRef<TypeSourceInfo *> Types,
1427                                  ArrayRef<Expr *> Exprs) {
1428   unsigned NumAssocs = Types.size();
1429   assert(NumAssocs == Exprs.size());
1430 
1431   // Decay and strip qualifiers for the controlling expression type, and handle
1432   // placeholder type replacement. See committee discussion from WG14 DR423.
1433   {
1434     EnterExpressionEvaluationContext Unevaluated(
1435         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1436     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1437     if (R.isInvalid())
1438       return ExprError();
1439     ControllingExpr = R.get();
1440   }
1441 
1442   // The controlling expression is an unevaluated operand, so side effects are
1443   // likely unintended.
1444   if (!inTemplateInstantiation() &&
1445       ControllingExpr->HasSideEffects(Context, false))
1446     Diag(ControllingExpr->getExprLoc(),
1447          diag::warn_side_effects_unevaluated_context);
1448 
1449   bool TypeErrorFound = false,
1450        IsResultDependent = ControllingExpr->isTypeDependent(),
1451        ContainsUnexpandedParameterPack
1452          = ControllingExpr->containsUnexpandedParameterPack();
1453 
1454   for (unsigned i = 0; i < NumAssocs; ++i) {
1455     if (Exprs[i]->containsUnexpandedParameterPack())
1456       ContainsUnexpandedParameterPack = true;
1457 
1458     if (Types[i]) {
1459       if (Types[i]->getType()->containsUnexpandedParameterPack())
1460         ContainsUnexpandedParameterPack = true;
1461 
1462       if (Types[i]->getType()->isDependentType()) {
1463         IsResultDependent = true;
1464       } else {
1465         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1466         // complete object type other than a variably modified type."
1467         unsigned D = 0;
1468         if (Types[i]->getType()->isIncompleteType())
1469           D = diag::err_assoc_type_incomplete;
1470         else if (!Types[i]->getType()->isObjectType())
1471           D = diag::err_assoc_type_nonobject;
1472         else if (Types[i]->getType()->isVariablyModifiedType())
1473           D = diag::err_assoc_type_variably_modified;
1474 
1475         if (D != 0) {
1476           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1477             << Types[i]->getTypeLoc().getSourceRange()
1478             << Types[i]->getType();
1479           TypeErrorFound = true;
1480         }
1481 
1482         // C11 6.5.1.1p2 "No two generic associations in the same generic
1483         // selection shall specify compatible types."
1484         for (unsigned j = i+1; j < NumAssocs; ++j)
1485           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1486               Context.typesAreCompatible(Types[i]->getType(),
1487                                          Types[j]->getType())) {
1488             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1489                  diag::err_assoc_compatible_types)
1490               << Types[j]->getTypeLoc().getSourceRange()
1491               << Types[j]->getType()
1492               << Types[i]->getType();
1493             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1494                  diag::note_compat_assoc)
1495               << Types[i]->getTypeLoc().getSourceRange()
1496               << Types[i]->getType();
1497             TypeErrorFound = true;
1498           }
1499       }
1500     }
1501   }
1502   if (TypeErrorFound)
1503     return ExprError();
1504 
1505   // If we determined that the generic selection is result-dependent, don't
1506   // try to compute the result expression.
1507   if (IsResultDependent)
1508     return new (Context) GenericSelectionExpr(
1509         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1510         ContainsUnexpandedParameterPack);
1511 
1512   SmallVector<unsigned, 1> CompatIndices;
1513   unsigned DefaultIndex = -1U;
1514   for (unsigned i = 0; i < NumAssocs; ++i) {
1515     if (!Types[i])
1516       DefaultIndex = i;
1517     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1518                                         Types[i]->getType()))
1519       CompatIndices.push_back(i);
1520   }
1521 
1522   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1523   // type compatible with at most one of the types named in its generic
1524   // association list."
1525   if (CompatIndices.size() > 1) {
1526     // We strip parens here because the controlling expression is typically
1527     // parenthesized in macro definitions.
1528     ControllingExpr = ControllingExpr->IgnoreParens();
1529     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1530       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1531       << (unsigned) CompatIndices.size();
1532     for (unsigned I : CompatIndices) {
1533       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1534            diag::note_compat_assoc)
1535         << Types[I]->getTypeLoc().getSourceRange()
1536         << Types[I]->getType();
1537     }
1538     return ExprError();
1539   }
1540 
1541   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1542   // its controlling expression shall have type compatible with exactly one of
1543   // the types named in its generic association list."
1544   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1545     // We strip parens here because the controlling expression is typically
1546     // parenthesized in macro definitions.
1547     ControllingExpr = ControllingExpr->IgnoreParens();
1548     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1549       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1550     return ExprError();
1551   }
1552 
1553   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1554   // type name that is compatible with the type of the controlling expression,
1555   // then the result expression of the generic selection is the expression
1556   // in that generic association. Otherwise, the result expression of the
1557   // generic selection is the expression in the default generic association."
1558   unsigned ResultIndex =
1559     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1560 
1561   return new (Context) GenericSelectionExpr(
1562       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1563       ContainsUnexpandedParameterPack, ResultIndex);
1564 }
1565 
1566 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1567 /// location of the token and the offset of the ud-suffix within it.
1568 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1569                                      unsigned Offset) {
1570   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1571                                         S.getLangOpts());
1572 }
1573 
1574 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1575 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1576 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1577                                                  IdentifierInfo *UDSuffix,
1578                                                  SourceLocation UDSuffixLoc,
1579                                                  ArrayRef<Expr*> Args,
1580                                                  SourceLocation LitEndLoc) {
1581   assert(Args.size() <= 2 && "too many arguments for literal operator");
1582 
1583   QualType ArgTy[2];
1584   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1585     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1586     if (ArgTy[ArgIdx]->isArrayType())
1587       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1588   }
1589 
1590   DeclarationName OpName =
1591     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1592   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1593   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1594 
1595   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1596   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1597                               /*AllowRaw*/false, /*AllowTemplate*/false,
1598                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1599     return ExprError();
1600 
1601   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1602 }
1603 
1604 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1605 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1606 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1607 /// multiple tokens.  However, the common case is that StringToks points to one
1608 /// string.
1609 ///
1610 ExprResult
1611 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1612   assert(!StringToks.empty() && "Must have at least one string!");
1613 
1614   StringLiteralParser Literal(StringToks, PP);
1615   if (Literal.hadError)
1616     return ExprError();
1617 
1618   SmallVector<SourceLocation, 4> StringTokLocs;
1619   for (const Token &Tok : StringToks)
1620     StringTokLocs.push_back(Tok.getLocation());
1621 
1622   QualType CharTy = Context.CharTy;
1623   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1624   if (Literal.isWide()) {
1625     CharTy = Context.getWideCharType();
1626     Kind = StringLiteral::Wide;
1627   } else if (Literal.isUTF8()) {
1628     Kind = StringLiteral::UTF8;
1629   } else if (Literal.isUTF16()) {
1630     CharTy = Context.Char16Ty;
1631     Kind = StringLiteral::UTF16;
1632   } else if (Literal.isUTF32()) {
1633     CharTy = Context.Char32Ty;
1634     Kind = StringLiteral::UTF32;
1635   } else if (Literal.isPascal()) {
1636     CharTy = Context.UnsignedCharTy;
1637   }
1638 
1639   QualType CharTyConst = CharTy;
1640   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1641   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1642     CharTyConst.addConst();
1643 
1644   // Get an array type for the string, according to C99 6.4.5.  This includes
1645   // the nul terminator character as well as the string length for pascal
1646   // strings.
1647   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1648                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1649                                  ArrayType::Normal, 0);
1650 
1651   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1652   if (getLangOpts().OpenCL) {
1653     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1654   }
1655 
1656   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1657   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1658                                              Kind, Literal.Pascal, StrTy,
1659                                              &StringTokLocs[0],
1660                                              StringTokLocs.size());
1661   if (Literal.getUDSuffix().empty())
1662     return Lit;
1663 
1664   // We're building a user-defined literal.
1665   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1666   SourceLocation UDSuffixLoc =
1667     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1668                    Literal.getUDSuffixOffset());
1669 
1670   // Make sure we're allowed user-defined literals here.
1671   if (!UDLScope)
1672     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1673 
1674   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1675   //   operator "" X (str, len)
1676   QualType SizeType = Context.getSizeType();
1677 
1678   DeclarationName OpName =
1679     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1680   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1681   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1682 
1683   QualType ArgTy[] = {
1684     Context.getArrayDecayedType(StrTy), SizeType
1685   };
1686 
1687   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1688   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1689                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1690                                 /*AllowStringTemplate*/true)) {
1691 
1692   case LOLR_Cooked: {
1693     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1694     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1695                                                     StringTokLocs[0]);
1696     Expr *Args[] = { Lit, LenArg };
1697 
1698     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1699   }
1700 
1701   case LOLR_StringTemplate: {
1702     TemplateArgumentListInfo ExplicitArgs;
1703 
1704     unsigned CharBits = Context.getIntWidth(CharTy);
1705     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1706     llvm::APSInt Value(CharBits, CharIsUnsigned);
1707 
1708     TemplateArgument TypeArg(CharTy);
1709     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1710     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1711 
1712     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1713       Value = Lit->getCodeUnit(I);
1714       TemplateArgument Arg(Context, Value, CharTy);
1715       TemplateArgumentLocInfo ArgInfo;
1716       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1717     }
1718     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1719                                     &ExplicitArgs);
1720   }
1721   case LOLR_Raw:
1722   case LOLR_Template:
1723     llvm_unreachable("unexpected literal operator lookup result");
1724   case LOLR_Error:
1725     return ExprError();
1726   }
1727   llvm_unreachable("unexpected literal operator lookup result");
1728 }
1729 
1730 ExprResult
1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1732                        SourceLocation Loc,
1733                        const CXXScopeSpec *SS) {
1734   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1735   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1736 }
1737 
1738 /// BuildDeclRefExpr - Build an expression that references a
1739 /// declaration that does not require a closure capture.
1740 ExprResult
1741 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1742                        const DeclarationNameInfo &NameInfo,
1743                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1744                        const TemplateArgumentListInfo *TemplateArgs) {
1745   bool RefersToCapturedVariable =
1746       isa<VarDecl>(D) &&
1747       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1748 
1749   DeclRefExpr *E;
1750   if (isa<VarTemplateSpecializationDecl>(D)) {
1751     VarTemplateSpecializationDecl *VarSpec =
1752         cast<VarTemplateSpecializationDecl>(D);
1753 
1754     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1755                                         : NestedNameSpecifierLoc(),
1756                             VarSpec->getTemplateKeywordLoc(), D,
1757                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1758                             FoundD, TemplateArgs);
1759   } else {
1760     assert(!TemplateArgs && "No template arguments for non-variable"
1761                             " template specialization references");
1762     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1763                                         : NestedNameSpecifierLoc(),
1764                             SourceLocation(), D, RefersToCapturedVariable,
1765                             NameInfo, Ty, VK, FoundD);
1766   }
1767 
1768   MarkDeclRefReferenced(E);
1769 
1770   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1771       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1772       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1773       recordUseOfEvaluatedWeak(E);
1774 
1775   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1776     UnusedPrivateFields.remove(FD);
1777     // Just in case we're building an illegal pointer-to-member.
1778     if (FD->isBitField())
1779       E->setObjectKind(OK_BitField);
1780   }
1781 
1782   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1783   // designates a bit-field.
1784   if (auto *BD = dyn_cast<BindingDecl>(D))
1785     if (auto *BE = BD->getBinding())
1786       E->setObjectKind(BE->getObjectKind());
1787 
1788   return E;
1789 }
1790 
1791 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1792 /// possibly a list of template arguments.
1793 ///
1794 /// If this produces template arguments, it is permitted to call
1795 /// DecomposeTemplateName.
1796 ///
1797 /// This actually loses a lot of source location information for
1798 /// non-standard name kinds; we should consider preserving that in
1799 /// some way.
1800 void
1801 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1802                              TemplateArgumentListInfo &Buffer,
1803                              DeclarationNameInfo &NameInfo,
1804                              const TemplateArgumentListInfo *&TemplateArgs) {
1805   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1806     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1807     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1808 
1809     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1810                                        Id.TemplateId->NumArgs);
1811     translateTemplateArguments(TemplateArgsPtr, Buffer);
1812 
1813     TemplateName TName = Id.TemplateId->Template.get();
1814     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1815     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1816     TemplateArgs = &Buffer;
1817   } else {
1818     NameInfo = GetNameFromUnqualifiedId(Id);
1819     TemplateArgs = nullptr;
1820   }
1821 }
1822 
1823 static void emitEmptyLookupTypoDiagnostic(
1824     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1825     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1826     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1827   DeclContext *Ctx =
1828       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1829   if (!TC) {
1830     // Emit a special diagnostic for failed member lookups.
1831     // FIXME: computing the declaration context might fail here (?)
1832     if (Ctx)
1833       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1834                                                  << SS.getRange();
1835     else
1836       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1837     return;
1838   }
1839 
1840   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1841   bool DroppedSpecifier =
1842       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1843   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1844                         ? diag::note_implicit_param_decl
1845                         : diag::note_previous_decl;
1846   if (!Ctx)
1847     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1848                          SemaRef.PDiag(NoteID));
1849   else
1850     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1851                                  << Typo << Ctx << DroppedSpecifier
1852                                  << SS.getRange(),
1853                          SemaRef.PDiag(NoteID));
1854 }
1855 
1856 /// Diagnose an empty lookup.
1857 ///
1858 /// \return false if new lookup candidates were found
1859 bool
1860 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1861                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1862                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1863                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1864   DeclarationName Name = R.getLookupName();
1865 
1866   unsigned diagnostic = diag::err_undeclared_var_use;
1867   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1868   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1869       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1870       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1871     diagnostic = diag::err_undeclared_use;
1872     diagnostic_suggest = diag::err_undeclared_use_suggest;
1873   }
1874 
1875   // If the original lookup was an unqualified lookup, fake an
1876   // unqualified lookup.  This is useful when (for example) the
1877   // original lookup would not have found something because it was a
1878   // dependent name.
1879   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1880   while (DC) {
1881     if (isa<CXXRecordDecl>(DC)) {
1882       LookupQualifiedName(R, DC);
1883 
1884       if (!R.empty()) {
1885         // Don't give errors about ambiguities in this lookup.
1886         R.suppressDiagnostics();
1887 
1888         // During a default argument instantiation the CurContext points
1889         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1890         // function parameter list, hence add an explicit check.
1891         bool isDefaultArgument =
1892             !CodeSynthesisContexts.empty() &&
1893             CodeSynthesisContexts.back().Kind ==
1894                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1895         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1896         bool isInstance = CurMethod &&
1897                           CurMethod->isInstance() &&
1898                           DC == CurMethod->getParent() && !isDefaultArgument;
1899 
1900         // Give a code modification hint to insert 'this->'.
1901         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1902         // Actually quite difficult!
1903         if (getLangOpts().MSVCCompat)
1904           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1905         if (isInstance) {
1906           Diag(R.getNameLoc(), diagnostic) << Name
1907             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1908           CheckCXXThisCapture(R.getNameLoc());
1909         } else {
1910           Diag(R.getNameLoc(), diagnostic) << Name;
1911         }
1912 
1913         // Do we really want to note all of these?
1914         for (NamedDecl *D : R)
1915           Diag(D->getLocation(), diag::note_dependent_var_use);
1916 
1917         // Return true if we are inside a default argument instantiation
1918         // and the found name refers to an instance member function, otherwise
1919         // the function calling DiagnoseEmptyLookup will try to create an
1920         // implicit member call and this is wrong for default argument.
1921         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1922           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1923           return true;
1924         }
1925 
1926         // Tell the callee to try to recover.
1927         return false;
1928       }
1929 
1930       R.clear();
1931     }
1932 
1933     // In Microsoft mode, if we are performing lookup from within a friend
1934     // function definition declared at class scope then we must set
1935     // DC to the lexical parent to be able to search into the parent
1936     // class.
1937     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1938         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1939         DC->getLexicalParent()->isRecord())
1940       DC = DC->getLexicalParent();
1941     else
1942       DC = DC->getParent();
1943   }
1944 
1945   // We didn't find anything, so try to correct for a typo.
1946   TypoCorrection Corrected;
1947   if (S && Out) {
1948     SourceLocation TypoLoc = R.getNameLoc();
1949     assert(!ExplicitTemplateArgs &&
1950            "Diagnosing an empty lookup with explicit template args!");
1951     *Out = CorrectTypoDelayed(
1952         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1953         [=](const TypoCorrection &TC) {
1954           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1955                                         diagnostic, diagnostic_suggest);
1956         },
1957         nullptr, CTK_ErrorRecovery);
1958     if (*Out)
1959       return true;
1960   } else if (S && (Corrected =
1961                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1962                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1963     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1964     bool DroppedSpecifier =
1965         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1966     R.setLookupName(Corrected.getCorrection());
1967 
1968     bool AcceptableWithRecovery = false;
1969     bool AcceptableWithoutRecovery = false;
1970     NamedDecl *ND = Corrected.getFoundDecl();
1971     if (ND) {
1972       if (Corrected.isOverloaded()) {
1973         OverloadCandidateSet OCS(R.getNameLoc(),
1974                                  OverloadCandidateSet::CSK_Normal);
1975         OverloadCandidateSet::iterator Best;
1976         for (NamedDecl *CD : Corrected) {
1977           if (FunctionTemplateDecl *FTD =
1978                    dyn_cast<FunctionTemplateDecl>(CD))
1979             AddTemplateOverloadCandidate(
1980                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1981                 Args, OCS);
1982           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1983             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1984               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1985                                    Args, OCS);
1986         }
1987         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1988         case OR_Success:
1989           ND = Best->FoundDecl;
1990           Corrected.setCorrectionDecl(ND);
1991           break;
1992         default:
1993           // FIXME: Arbitrarily pick the first declaration for the note.
1994           Corrected.setCorrectionDecl(ND);
1995           break;
1996         }
1997       }
1998       R.addDecl(ND);
1999       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2000         CXXRecordDecl *Record = nullptr;
2001         if (Corrected.getCorrectionSpecifier()) {
2002           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2003           Record = Ty->getAsCXXRecordDecl();
2004         }
2005         if (!Record)
2006           Record = cast<CXXRecordDecl>(
2007               ND->getDeclContext()->getRedeclContext());
2008         R.setNamingClass(Record);
2009       }
2010 
2011       auto *UnderlyingND = ND->getUnderlyingDecl();
2012       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2013                                isa<FunctionTemplateDecl>(UnderlyingND);
2014       // FIXME: If we ended up with a typo for a type name or
2015       // Objective-C class name, we're in trouble because the parser
2016       // is in the wrong place to recover. Suggest the typo
2017       // correction, but don't make it a fix-it since we're not going
2018       // to recover well anyway.
2019       AcceptableWithoutRecovery =
2020           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2021     } else {
2022       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2023       // because we aren't able to recover.
2024       AcceptableWithoutRecovery = true;
2025     }
2026 
2027     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2028       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2029                             ? diag::note_implicit_param_decl
2030                             : diag::note_previous_decl;
2031       if (SS.isEmpty())
2032         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2033                      PDiag(NoteID), AcceptableWithRecovery);
2034       else
2035         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2036                                   << Name << computeDeclContext(SS, false)
2037                                   << DroppedSpecifier << SS.getRange(),
2038                      PDiag(NoteID), AcceptableWithRecovery);
2039 
2040       // Tell the callee whether to try to recover.
2041       return !AcceptableWithRecovery;
2042     }
2043   }
2044   R.clear();
2045 
2046   // Emit a special diagnostic for failed member lookups.
2047   // FIXME: computing the declaration context might fail here (?)
2048   if (!SS.isEmpty()) {
2049     Diag(R.getNameLoc(), diag::err_no_member)
2050       << Name << computeDeclContext(SS, false)
2051       << SS.getRange();
2052     return true;
2053   }
2054 
2055   // Give up, we can't recover.
2056   Diag(R.getNameLoc(), diagnostic) << Name;
2057   return true;
2058 }
2059 
2060 /// In Microsoft mode, if we are inside a template class whose parent class has
2061 /// dependent base classes, and we can't resolve an unqualified identifier, then
2062 /// assume the identifier is a member of a dependent base class.  We can only
2063 /// recover successfully in static methods, instance methods, and other contexts
2064 /// where 'this' is available.  This doesn't precisely match MSVC's
2065 /// instantiation model, but it's close enough.
2066 static Expr *
2067 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2068                                DeclarationNameInfo &NameInfo,
2069                                SourceLocation TemplateKWLoc,
2070                                const TemplateArgumentListInfo *TemplateArgs) {
2071   // Only try to recover from lookup into dependent bases in static methods or
2072   // contexts where 'this' is available.
2073   QualType ThisType = S.getCurrentThisType();
2074   const CXXRecordDecl *RD = nullptr;
2075   if (!ThisType.isNull())
2076     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2077   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2078     RD = MD->getParent();
2079   if (!RD || !RD->hasAnyDependentBases())
2080     return nullptr;
2081 
2082   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2083   // is available, suggest inserting 'this->' as a fixit.
2084   SourceLocation Loc = NameInfo.getLoc();
2085   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2086   DB << NameInfo.getName() << RD;
2087 
2088   if (!ThisType.isNull()) {
2089     DB << FixItHint::CreateInsertion(Loc, "this->");
2090     return CXXDependentScopeMemberExpr::Create(
2091         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2092         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2093         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2094   }
2095 
2096   // Synthesize a fake NNS that points to the derived class.  This will
2097   // perform name lookup during template instantiation.
2098   CXXScopeSpec SS;
2099   auto *NNS =
2100       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2101   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2102   return DependentScopeDeclRefExpr::Create(
2103       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2104       TemplateArgs);
2105 }
2106 
2107 ExprResult
2108 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2109                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2110                         bool HasTrailingLParen, bool IsAddressOfOperand,
2111                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2112                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2113   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2114          "cannot be direct & operand and have a trailing lparen");
2115   if (SS.isInvalid())
2116     return ExprError();
2117 
2118   TemplateArgumentListInfo TemplateArgsBuffer;
2119 
2120   // Decompose the UnqualifiedId into the following data.
2121   DeclarationNameInfo NameInfo;
2122   const TemplateArgumentListInfo *TemplateArgs;
2123   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2124 
2125   DeclarationName Name = NameInfo.getName();
2126   IdentifierInfo *II = Name.getAsIdentifierInfo();
2127   SourceLocation NameLoc = NameInfo.getLoc();
2128 
2129   // C++ [temp.dep.expr]p3:
2130   //   An id-expression is type-dependent if it contains:
2131   //     -- an identifier that was declared with a dependent type,
2132   //        (note: handled after lookup)
2133   //     -- a template-id that is dependent,
2134   //        (note: handled in BuildTemplateIdExpr)
2135   //     -- a conversion-function-id that specifies a dependent type,
2136   //     -- a nested-name-specifier that contains a class-name that
2137   //        names a dependent type.
2138   // Determine whether this is a member of an unknown specialization;
2139   // we need to handle these differently.
2140   bool DependentID = false;
2141   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2142       Name.getCXXNameType()->isDependentType()) {
2143     DependentID = true;
2144   } else if (SS.isSet()) {
2145     if (DeclContext *DC = computeDeclContext(SS, false)) {
2146       if (RequireCompleteDeclContext(SS, DC))
2147         return ExprError();
2148     } else {
2149       DependentID = true;
2150     }
2151   }
2152 
2153   if (DependentID)
2154     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2155                                       IsAddressOfOperand, TemplateArgs);
2156 
2157   // Perform the required lookup.
2158   LookupResult R(*this, NameInfo,
2159                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2160                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2161   if (TemplateArgs) {
2162     // Lookup the template name again to correctly establish the context in
2163     // which it was found. This is really unfortunate as we already did the
2164     // lookup to determine that it was a template name in the first place. If
2165     // this becomes a performance hit, we can work harder to preserve those
2166     // results until we get here but it's likely not worth it.
2167     bool MemberOfUnknownSpecialization;
2168     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2169                        MemberOfUnknownSpecialization);
2170 
2171     if (MemberOfUnknownSpecialization ||
2172         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2173       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2174                                         IsAddressOfOperand, TemplateArgs);
2175   } else {
2176     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2177     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2178 
2179     // If the result might be in a dependent base class, this is a dependent
2180     // id-expression.
2181     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2182       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2183                                         IsAddressOfOperand, TemplateArgs);
2184 
2185     // If this reference is in an Objective-C method, then we need to do
2186     // some special Objective-C lookup, too.
2187     if (IvarLookupFollowUp) {
2188       ExprResult E(LookupInObjCMethod(R, S, II, true));
2189       if (E.isInvalid())
2190         return ExprError();
2191 
2192       if (Expr *Ex = E.getAs<Expr>())
2193         return Ex;
2194     }
2195   }
2196 
2197   if (R.isAmbiguous())
2198     return ExprError();
2199 
2200   // This could be an implicitly declared function reference (legal in C90,
2201   // extension in C99, forbidden in C++).
2202   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2203     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2204     if (D) R.addDecl(D);
2205   }
2206 
2207   // Determine whether this name might be a candidate for
2208   // argument-dependent lookup.
2209   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2210 
2211   if (R.empty() && !ADL) {
2212     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2213       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2214                                                    TemplateKWLoc, TemplateArgs))
2215         return E;
2216     }
2217 
2218     // Don't diagnose an empty lookup for inline assembly.
2219     if (IsInlineAsmIdentifier)
2220       return ExprError();
2221 
2222     // If this name wasn't predeclared and if this is not a function
2223     // call, diagnose the problem.
2224     TypoExpr *TE = nullptr;
2225     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2226         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2227     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2228     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2229            "Typo correction callback misconfigured");
2230     if (CCC) {
2231       // Make sure the callback knows what the typo being diagnosed is.
2232       CCC->setTypoName(II);
2233       if (SS.isValid())
2234         CCC->setTypoNNS(SS.getScopeRep());
2235     }
2236     if (DiagnoseEmptyLookup(S, SS, R,
2237                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2238                             nullptr, None, &TE)) {
2239       if (TE && KeywordReplacement) {
2240         auto &State = getTypoExprState(TE);
2241         auto BestTC = State.Consumer->getNextCorrection();
2242         if (BestTC.isKeyword()) {
2243           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2244           if (State.DiagHandler)
2245             State.DiagHandler(BestTC);
2246           KeywordReplacement->startToken();
2247           KeywordReplacement->setKind(II->getTokenID());
2248           KeywordReplacement->setIdentifierInfo(II);
2249           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2250           // Clean up the state associated with the TypoExpr, since it has
2251           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2252           clearDelayedTypo(TE);
2253           // Signal that a correction to a keyword was performed by returning a
2254           // valid-but-null ExprResult.
2255           return (Expr*)nullptr;
2256         }
2257         State.Consumer->resetCorrectionStream();
2258       }
2259       return TE ? TE : ExprError();
2260     }
2261 
2262     assert(!R.empty() &&
2263            "DiagnoseEmptyLookup returned false but added no results");
2264 
2265     // If we found an Objective-C instance variable, let
2266     // LookupInObjCMethod build the appropriate expression to
2267     // reference the ivar.
2268     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2269       R.clear();
2270       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2271       // In a hopelessly buggy code, Objective-C instance variable
2272       // lookup fails and no expression will be built to reference it.
2273       if (!E.isInvalid() && !E.get())
2274         return ExprError();
2275       return E;
2276     }
2277   }
2278 
2279   // This is guaranteed from this point on.
2280   assert(!R.empty() || ADL);
2281 
2282   // Check whether this might be a C++ implicit instance member access.
2283   // C++ [class.mfct.non-static]p3:
2284   //   When an id-expression that is not part of a class member access
2285   //   syntax and not used to form a pointer to member is used in the
2286   //   body of a non-static member function of class X, if name lookup
2287   //   resolves the name in the id-expression to a non-static non-type
2288   //   member of some class C, the id-expression is transformed into a
2289   //   class member access expression using (*this) as the
2290   //   postfix-expression to the left of the . operator.
2291   //
2292   // But we don't actually need to do this for '&' operands if R
2293   // resolved to a function or overloaded function set, because the
2294   // expression is ill-formed if it actually works out to be a
2295   // non-static member function:
2296   //
2297   // C++ [expr.ref]p4:
2298   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2299   //   [t]he expression can be used only as the left-hand operand of a
2300   //   member function call.
2301   //
2302   // There are other safeguards against such uses, but it's important
2303   // to get this right here so that we don't end up making a
2304   // spuriously dependent expression if we're inside a dependent
2305   // instance method.
2306   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2307     bool MightBeImplicitMember;
2308     if (!IsAddressOfOperand)
2309       MightBeImplicitMember = true;
2310     else if (!SS.isEmpty())
2311       MightBeImplicitMember = false;
2312     else if (R.isOverloadedResult())
2313       MightBeImplicitMember = false;
2314     else if (R.isUnresolvableResult())
2315       MightBeImplicitMember = true;
2316     else
2317       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2318                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2319                               isa<MSPropertyDecl>(R.getFoundDecl());
2320 
2321     if (MightBeImplicitMember)
2322       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2323                                              R, TemplateArgs, S);
2324   }
2325 
2326   if (TemplateArgs || TemplateKWLoc.isValid()) {
2327 
2328     // In C++1y, if this is a variable template id, then check it
2329     // in BuildTemplateIdExpr().
2330     // The single lookup result must be a variable template declaration.
2331     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2332         Id.TemplateId->Kind == TNK_Var_template) {
2333       assert(R.getAsSingle<VarTemplateDecl>() &&
2334              "There should only be one declaration found.");
2335     }
2336 
2337     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2338   }
2339 
2340   return BuildDeclarationNameExpr(SS, R, ADL);
2341 }
2342 
2343 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2344 /// declaration name, generally during template instantiation.
2345 /// There's a large number of things which don't need to be done along
2346 /// this path.
2347 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2348     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2349     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2350   DeclContext *DC = computeDeclContext(SS, false);
2351   if (!DC)
2352     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2353                                      NameInfo, /*TemplateArgs=*/nullptr);
2354 
2355   if (RequireCompleteDeclContext(SS, DC))
2356     return ExprError();
2357 
2358   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2359   LookupQualifiedName(R, DC);
2360 
2361   if (R.isAmbiguous())
2362     return ExprError();
2363 
2364   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2365     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2366                                      NameInfo, /*TemplateArgs=*/nullptr);
2367 
2368   if (R.empty()) {
2369     Diag(NameInfo.getLoc(), diag::err_no_member)
2370       << NameInfo.getName() << DC << SS.getRange();
2371     return ExprError();
2372   }
2373 
2374   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2375     // Diagnose a missing typename if this resolved unambiguously to a type in
2376     // a dependent context.  If we can recover with a type, downgrade this to
2377     // a warning in Microsoft compatibility mode.
2378     unsigned DiagID = diag::err_typename_missing;
2379     if (RecoveryTSI && getLangOpts().MSVCCompat)
2380       DiagID = diag::ext_typename_missing;
2381     SourceLocation Loc = SS.getBeginLoc();
2382     auto D = Diag(Loc, DiagID);
2383     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2384       << SourceRange(Loc, NameInfo.getEndLoc());
2385 
2386     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2387     // context.
2388     if (!RecoveryTSI)
2389       return ExprError();
2390 
2391     // Only issue the fixit if we're prepared to recover.
2392     D << FixItHint::CreateInsertion(Loc, "typename ");
2393 
2394     // Recover by pretending this was an elaborated type.
2395     QualType Ty = Context.getTypeDeclType(TD);
2396     TypeLocBuilder TLB;
2397     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2398 
2399     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2400     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2401     QTL.setElaboratedKeywordLoc(SourceLocation());
2402     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2403 
2404     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2405 
2406     return ExprEmpty();
2407   }
2408 
2409   // Defend against this resolving to an implicit member access. We usually
2410   // won't get here if this might be a legitimate a class member (we end up in
2411   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2412   // a pointer-to-member or in an unevaluated context in C++11.
2413   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2414     return BuildPossibleImplicitMemberExpr(SS,
2415                                            /*TemplateKWLoc=*/SourceLocation(),
2416                                            R, /*TemplateArgs=*/nullptr, S);
2417 
2418   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2419 }
2420 
2421 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2422 /// detected that we're currently inside an ObjC method.  Perform some
2423 /// additional lookup.
2424 ///
2425 /// Ideally, most of this would be done by lookup, but there's
2426 /// actually quite a lot of extra work involved.
2427 ///
2428 /// Returns a null sentinel to indicate trivial success.
2429 ExprResult
2430 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2431                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2432   SourceLocation Loc = Lookup.getNameLoc();
2433   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2434 
2435   // Check for error condition which is already reported.
2436   if (!CurMethod)
2437     return ExprError();
2438 
2439   // There are two cases to handle here.  1) scoped lookup could have failed,
2440   // in which case we should look for an ivar.  2) scoped lookup could have
2441   // found a decl, but that decl is outside the current instance method (i.e.
2442   // a global variable).  In these two cases, we do a lookup for an ivar with
2443   // this name, if the lookup sucedes, we replace it our current decl.
2444 
2445   // If we're in a class method, we don't normally want to look for
2446   // ivars.  But if we don't find anything else, and there's an
2447   // ivar, that's an error.
2448   bool IsClassMethod = CurMethod->isClassMethod();
2449 
2450   bool LookForIvars;
2451   if (Lookup.empty())
2452     LookForIvars = true;
2453   else if (IsClassMethod)
2454     LookForIvars = false;
2455   else
2456     LookForIvars = (Lookup.isSingleResult() &&
2457                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2458   ObjCInterfaceDecl *IFace = nullptr;
2459   if (LookForIvars) {
2460     IFace = CurMethod->getClassInterface();
2461     ObjCInterfaceDecl *ClassDeclared;
2462     ObjCIvarDecl *IV = nullptr;
2463     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2464       // Diagnose using an ivar in a class method.
2465       if (IsClassMethod)
2466         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2467                          << IV->getDeclName());
2468 
2469       // If we're referencing an invalid decl, just return this as a silent
2470       // error node.  The error diagnostic was already emitted on the decl.
2471       if (IV->isInvalidDecl())
2472         return ExprError();
2473 
2474       // Check if referencing a field with __attribute__((deprecated)).
2475       if (DiagnoseUseOfDecl(IV, Loc))
2476         return ExprError();
2477 
2478       // Diagnose the use of an ivar outside of the declaring class.
2479       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2480           !declaresSameEntity(ClassDeclared, IFace) &&
2481           !getLangOpts().DebuggerSupport)
2482         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2483 
2484       // FIXME: This should use a new expr for a direct reference, don't
2485       // turn this into Self->ivar, just return a BareIVarExpr or something.
2486       IdentifierInfo &II = Context.Idents.get("self");
2487       UnqualifiedId SelfName;
2488       SelfName.setIdentifier(&II, SourceLocation());
2489       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2490       CXXScopeSpec SelfScopeSpec;
2491       SourceLocation TemplateKWLoc;
2492       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2493                                               SelfName, false, false);
2494       if (SelfExpr.isInvalid())
2495         return ExprError();
2496 
2497       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2498       if (SelfExpr.isInvalid())
2499         return ExprError();
2500 
2501       MarkAnyDeclReferenced(Loc, IV, true);
2502 
2503       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2504       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2505           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2506         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2507 
2508       ObjCIvarRefExpr *Result = new (Context)
2509           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2510                           IV->getLocation(), SelfExpr.get(), true, true);
2511 
2512       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2513         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2514           recordUseOfEvaluatedWeak(Result);
2515       }
2516       if (getLangOpts().ObjCAutoRefCount) {
2517         if (CurContext->isClosure())
2518           Diag(Loc, diag::warn_implicitly_retains_self)
2519             << FixItHint::CreateInsertion(Loc, "self->");
2520       }
2521 
2522       return Result;
2523     }
2524   } else if (CurMethod->isInstanceMethod()) {
2525     // We should warn if a local variable hides an ivar.
2526     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2527       ObjCInterfaceDecl *ClassDeclared;
2528       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2529         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2530             declaresSameEntity(IFace, ClassDeclared))
2531           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2532       }
2533     }
2534   } else if (Lookup.isSingleResult() &&
2535              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2536     // If accessing a stand-alone ivar in a class method, this is an error.
2537     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2538       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2539                        << IV->getDeclName());
2540   }
2541 
2542   if (Lookup.empty() && II && AllowBuiltinCreation) {
2543     // FIXME. Consolidate this with similar code in LookupName.
2544     if (unsigned BuiltinID = II->getBuiltinID()) {
2545       if (!(getLangOpts().CPlusPlus &&
2546             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2547         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2548                                            S, Lookup.isForRedeclaration(),
2549                                            Lookup.getNameLoc());
2550         if (D) Lookup.addDecl(D);
2551       }
2552     }
2553   }
2554   // Sentinel value saying that we didn't do anything special.
2555   return ExprResult((Expr *)nullptr);
2556 }
2557 
2558 /// \brief Cast a base object to a member's actual type.
2559 ///
2560 /// Logically this happens in three phases:
2561 ///
2562 /// * First we cast from the base type to the naming class.
2563 ///   The naming class is the class into which we were looking
2564 ///   when we found the member;  it's the qualifier type if a
2565 ///   qualifier was provided, and otherwise it's the base type.
2566 ///
2567 /// * Next we cast from the naming class to the declaring class.
2568 ///   If the member we found was brought into a class's scope by
2569 ///   a using declaration, this is that class;  otherwise it's
2570 ///   the class declaring the member.
2571 ///
2572 /// * Finally we cast from the declaring class to the "true"
2573 ///   declaring class of the member.  This conversion does not
2574 ///   obey access control.
2575 ExprResult
2576 Sema::PerformObjectMemberConversion(Expr *From,
2577                                     NestedNameSpecifier *Qualifier,
2578                                     NamedDecl *FoundDecl,
2579                                     NamedDecl *Member) {
2580   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2581   if (!RD)
2582     return From;
2583 
2584   QualType DestRecordType;
2585   QualType DestType;
2586   QualType FromRecordType;
2587   QualType FromType = From->getType();
2588   bool PointerConversions = false;
2589   if (isa<FieldDecl>(Member)) {
2590     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2591 
2592     if (FromType->getAs<PointerType>()) {
2593       DestType = Context.getPointerType(DestRecordType);
2594       FromRecordType = FromType->getPointeeType();
2595       PointerConversions = true;
2596     } else {
2597       DestType = DestRecordType;
2598       FromRecordType = FromType;
2599     }
2600   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2601     if (Method->isStatic())
2602       return From;
2603 
2604     DestType = Method->getThisType(Context);
2605     DestRecordType = DestType->getPointeeType();
2606 
2607     if (FromType->getAs<PointerType>()) {
2608       FromRecordType = FromType->getPointeeType();
2609       PointerConversions = true;
2610     } else {
2611       FromRecordType = FromType;
2612       DestType = DestRecordType;
2613     }
2614   } else {
2615     // No conversion necessary.
2616     return From;
2617   }
2618 
2619   if (DestType->isDependentType() || FromType->isDependentType())
2620     return From;
2621 
2622   // If the unqualified types are the same, no conversion is necessary.
2623   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2624     return From;
2625 
2626   SourceRange FromRange = From->getSourceRange();
2627   SourceLocation FromLoc = FromRange.getBegin();
2628 
2629   ExprValueKind VK = From->getValueKind();
2630 
2631   // C++ [class.member.lookup]p8:
2632   //   [...] Ambiguities can often be resolved by qualifying a name with its
2633   //   class name.
2634   //
2635   // If the member was a qualified name and the qualified referred to a
2636   // specific base subobject type, we'll cast to that intermediate type
2637   // first and then to the object in which the member is declared. That allows
2638   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2639   //
2640   //   class Base { public: int x; };
2641   //   class Derived1 : public Base { };
2642   //   class Derived2 : public Base { };
2643   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2644   //
2645   //   void VeryDerived::f() {
2646   //     x = 17; // error: ambiguous base subobjects
2647   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2648   //   }
2649   if (Qualifier && Qualifier->getAsType()) {
2650     QualType QType = QualType(Qualifier->getAsType(), 0);
2651     assert(QType->isRecordType() && "lookup done with non-record type");
2652 
2653     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2654 
2655     // In C++98, the qualifier type doesn't actually have to be a base
2656     // type of the object type, in which case we just ignore it.
2657     // Otherwise build the appropriate casts.
2658     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2659       CXXCastPath BasePath;
2660       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2661                                        FromLoc, FromRange, &BasePath))
2662         return ExprError();
2663 
2664       if (PointerConversions)
2665         QType = Context.getPointerType(QType);
2666       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2667                                VK, &BasePath).get();
2668 
2669       FromType = QType;
2670       FromRecordType = QRecordType;
2671 
2672       // If the qualifier type was the same as the destination type,
2673       // we're done.
2674       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2675         return From;
2676     }
2677   }
2678 
2679   bool IgnoreAccess = false;
2680 
2681   // If we actually found the member through a using declaration, cast
2682   // down to the using declaration's type.
2683   //
2684   // Pointer equality is fine here because only one declaration of a
2685   // class ever has member declarations.
2686   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2687     assert(isa<UsingShadowDecl>(FoundDecl));
2688     QualType URecordType = Context.getTypeDeclType(
2689                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2690 
2691     // We only need to do this if the naming-class to declaring-class
2692     // conversion is non-trivial.
2693     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2694       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2695       CXXCastPath BasePath;
2696       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2697                                        FromLoc, FromRange, &BasePath))
2698         return ExprError();
2699 
2700       QualType UType = URecordType;
2701       if (PointerConversions)
2702         UType = Context.getPointerType(UType);
2703       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2704                                VK, &BasePath).get();
2705       FromType = UType;
2706       FromRecordType = URecordType;
2707     }
2708 
2709     // We don't do access control for the conversion from the
2710     // declaring class to the true declaring class.
2711     IgnoreAccess = true;
2712   }
2713 
2714   CXXCastPath BasePath;
2715   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2716                                    FromLoc, FromRange, &BasePath,
2717                                    IgnoreAccess))
2718     return ExprError();
2719 
2720   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2721                            VK, &BasePath);
2722 }
2723 
2724 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2725                                       const LookupResult &R,
2726                                       bool HasTrailingLParen) {
2727   // Only when used directly as the postfix-expression of a call.
2728   if (!HasTrailingLParen)
2729     return false;
2730 
2731   // Never if a scope specifier was provided.
2732   if (SS.isSet())
2733     return false;
2734 
2735   // Only in C++ or ObjC++.
2736   if (!getLangOpts().CPlusPlus)
2737     return false;
2738 
2739   // Turn off ADL when we find certain kinds of declarations during
2740   // normal lookup:
2741   for (NamedDecl *D : R) {
2742     // C++0x [basic.lookup.argdep]p3:
2743     //     -- a declaration of a class member
2744     // Since using decls preserve this property, we check this on the
2745     // original decl.
2746     if (D->isCXXClassMember())
2747       return false;
2748 
2749     // C++0x [basic.lookup.argdep]p3:
2750     //     -- a block-scope function declaration that is not a
2751     //        using-declaration
2752     // NOTE: we also trigger this for function templates (in fact, we
2753     // don't check the decl type at all, since all other decl types
2754     // turn off ADL anyway).
2755     if (isa<UsingShadowDecl>(D))
2756       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2757     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2758       return false;
2759 
2760     // C++0x [basic.lookup.argdep]p3:
2761     //     -- a declaration that is neither a function or a function
2762     //        template
2763     // And also for builtin functions.
2764     if (isa<FunctionDecl>(D)) {
2765       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2766 
2767       // But also builtin functions.
2768       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2769         return false;
2770     } else if (!isa<FunctionTemplateDecl>(D))
2771       return false;
2772   }
2773 
2774   return true;
2775 }
2776 
2777 
2778 /// Diagnoses obvious problems with the use of the given declaration
2779 /// as an expression.  This is only actually called for lookups that
2780 /// were not overloaded, and it doesn't promise that the declaration
2781 /// will in fact be used.
2782 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2783   if (D->isInvalidDecl())
2784     return true;
2785 
2786   if (isa<TypedefNameDecl>(D)) {
2787     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2788     return true;
2789   }
2790 
2791   if (isa<ObjCInterfaceDecl>(D)) {
2792     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2793     return true;
2794   }
2795 
2796   if (isa<NamespaceDecl>(D)) {
2797     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2798     return true;
2799   }
2800 
2801   return false;
2802 }
2803 
2804 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2805                                           LookupResult &R, bool NeedsADL,
2806                                           bool AcceptInvalidDecl) {
2807   // If this is a single, fully-resolved result and we don't need ADL,
2808   // just build an ordinary singleton decl ref.
2809   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2810     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2811                                     R.getRepresentativeDecl(), nullptr,
2812                                     AcceptInvalidDecl);
2813 
2814   // We only need to check the declaration if there's exactly one
2815   // result, because in the overloaded case the results can only be
2816   // functions and function templates.
2817   if (R.isSingleResult() &&
2818       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2819     return ExprError();
2820 
2821   // Otherwise, just build an unresolved lookup expression.  Suppress
2822   // any lookup-related diagnostics; we'll hash these out later, when
2823   // we've picked a target.
2824   R.suppressDiagnostics();
2825 
2826   UnresolvedLookupExpr *ULE
2827     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2828                                    SS.getWithLocInContext(Context),
2829                                    R.getLookupNameInfo(),
2830                                    NeedsADL, R.isOverloadedResult(),
2831                                    R.begin(), R.end());
2832 
2833   return ULE;
2834 }
2835 
2836 static void
2837 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2838                                    ValueDecl *var, DeclContext *DC);
2839 
2840 /// \brief Complete semantic analysis for a reference to the given declaration.
2841 ExprResult Sema::BuildDeclarationNameExpr(
2842     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2843     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2844     bool AcceptInvalidDecl) {
2845   assert(D && "Cannot refer to a NULL declaration");
2846   assert(!isa<FunctionTemplateDecl>(D) &&
2847          "Cannot refer unambiguously to a function template");
2848 
2849   SourceLocation Loc = NameInfo.getLoc();
2850   if (CheckDeclInExpr(*this, Loc, D))
2851     return ExprError();
2852 
2853   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2854     // Specifically diagnose references to class templates that are missing
2855     // a template argument list.
2856     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2857                                            << Template << SS.getRange();
2858     Diag(Template->getLocation(), diag::note_template_decl_here);
2859     return ExprError();
2860   }
2861 
2862   // Make sure that we're referring to a value.
2863   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2864   if (!VD) {
2865     Diag(Loc, diag::err_ref_non_value)
2866       << D << SS.getRange();
2867     Diag(D->getLocation(), diag::note_declared_at);
2868     return ExprError();
2869   }
2870 
2871   // Check whether this declaration can be used. Note that we suppress
2872   // this check when we're going to perform argument-dependent lookup
2873   // on this function name, because this might not be the function
2874   // that overload resolution actually selects.
2875   if (DiagnoseUseOfDecl(VD, Loc))
2876     return ExprError();
2877 
2878   // Only create DeclRefExpr's for valid Decl's.
2879   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2880     return ExprError();
2881 
2882   // Handle members of anonymous structs and unions.  If we got here,
2883   // and the reference is to a class member indirect field, then this
2884   // must be the subject of a pointer-to-member expression.
2885   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2886     if (!indirectField->isCXXClassMember())
2887       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2888                                                       indirectField);
2889 
2890   {
2891     QualType type = VD->getType();
2892     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2893       // C++ [except.spec]p17:
2894       //   An exception-specification is considered to be needed when:
2895       //   - in an expression, the function is the unique lookup result or
2896       //     the selected member of a set of overloaded functions.
2897       ResolveExceptionSpec(Loc, FPT);
2898       type = VD->getType();
2899     }
2900     ExprValueKind valueKind = VK_RValue;
2901 
2902     switch (D->getKind()) {
2903     // Ignore all the non-ValueDecl kinds.
2904 #define ABSTRACT_DECL(kind)
2905 #define VALUE(type, base)
2906 #define DECL(type, base) \
2907     case Decl::type:
2908 #include "clang/AST/DeclNodes.inc"
2909       llvm_unreachable("invalid value decl kind");
2910 
2911     // These shouldn't make it here.
2912     case Decl::ObjCAtDefsField:
2913     case Decl::ObjCIvar:
2914       llvm_unreachable("forming non-member reference to ivar?");
2915 
2916     // Enum constants are always r-values and never references.
2917     // Unresolved using declarations are dependent.
2918     case Decl::EnumConstant:
2919     case Decl::UnresolvedUsingValue:
2920     case Decl::OMPDeclareReduction:
2921       valueKind = VK_RValue;
2922       break;
2923 
2924     // Fields and indirect fields that got here must be for
2925     // pointer-to-member expressions; we just call them l-values for
2926     // internal consistency, because this subexpression doesn't really
2927     // exist in the high-level semantics.
2928     case Decl::Field:
2929     case Decl::IndirectField:
2930       assert(getLangOpts().CPlusPlus &&
2931              "building reference to field in C?");
2932 
2933       // These can't have reference type in well-formed programs, but
2934       // for internal consistency we do this anyway.
2935       type = type.getNonReferenceType();
2936       valueKind = VK_LValue;
2937       break;
2938 
2939     // Non-type template parameters are either l-values or r-values
2940     // depending on the type.
2941     case Decl::NonTypeTemplateParm: {
2942       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2943         type = reftype->getPointeeType();
2944         valueKind = VK_LValue; // even if the parameter is an r-value reference
2945         break;
2946       }
2947 
2948       // For non-references, we need to strip qualifiers just in case
2949       // the template parameter was declared as 'const int' or whatever.
2950       valueKind = VK_RValue;
2951       type = type.getUnqualifiedType();
2952       break;
2953     }
2954 
2955     case Decl::Var:
2956     case Decl::VarTemplateSpecialization:
2957     case Decl::VarTemplatePartialSpecialization:
2958     case Decl::Decomposition:
2959     case Decl::OMPCapturedExpr:
2960       // In C, "extern void blah;" is valid and is an r-value.
2961       if (!getLangOpts().CPlusPlus &&
2962           !type.hasQualifiers() &&
2963           type->isVoidType()) {
2964         valueKind = VK_RValue;
2965         break;
2966       }
2967       // fallthrough
2968 
2969     case Decl::ImplicitParam:
2970     case Decl::ParmVar: {
2971       // These are always l-values.
2972       valueKind = VK_LValue;
2973       type = type.getNonReferenceType();
2974 
2975       // FIXME: Does the addition of const really only apply in
2976       // potentially-evaluated contexts? Since the variable isn't actually
2977       // captured in an unevaluated context, it seems that the answer is no.
2978       if (!isUnevaluatedContext()) {
2979         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2980         if (!CapturedType.isNull())
2981           type = CapturedType;
2982       }
2983 
2984       break;
2985     }
2986 
2987     case Decl::Binding: {
2988       // These are always lvalues.
2989       valueKind = VK_LValue;
2990       type = type.getNonReferenceType();
2991       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2992       // decides how that's supposed to work.
2993       auto *BD = cast<BindingDecl>(VD);
2994       if (BD->getDeclContext()->isFunctionOrMethod() &&
2995           BD->getDeclContext() != CurContext)
2996         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2997       break;
2998     }
2999 
3000     case Decl::Function: {
3001       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3002         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3003           type = Context.BuiltinFnTy;
3004           valueKind = VK_RValue;
3005           break;
3006         }
3007       }
3008 
3009       const FunctionType *fty = type->castAs<FunctionType>();
3010 
3011       // If we're referring to a function with an __unknown_anytype
3012       // result type, make the entire expression __unknown_anytype.
3013       if (fty->getReturnType() == Context.UnknownAnyTy) {
3014         type = Context.UnknownAnyTy;
3015         valueKind = VK_RValue;
3016         break;
3017       }
3018 
3019       // Functions are l-values in C++.
3020       if (getLangOpts().CPlusPlus) {
3021         valueKind = VK_LValue;
3022         break;
3023       }
3024 
3025       // C99 DR 316 says that, if a function type comes from a
3026       // function definition (without a prototype), that type is only
3027       // used for checking compatibility. Therefore, when referencing
3028       // the function, we pretend that we don't have the full function
3029       // type.
3030       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3031           isa<FunctionProtoType>(fty))
3032         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3033                                               fty->getExtInfo());
3034 
3035       // Functions are r-values in C.
3036       valueKind = VK_RValue;
3037       break;
3038     }
3039 
3040     case Decl::CXXDeductionGuide:
3041       llvm_unreachable("building reference to deduction guide");
3042 
3043     case Decl::MSProperty:
3044       valueKind = VK_LValue;
3045       break;
3046 
3047     case Decl::CXXMethod:
3048       // If we're referring to a method with an __unknown_anytype
3049       // result type, make the entire expression __unknown_anytype.
3050       // This should only be possible with a type written directly.
3051       if (const FunctionProtoType *proto
3052             = dyn_cast<FunctionProtoType>(VD->getType()))
3053         if (proto->getReturnType() == Context.UnknownAnyTy) {
3054           type = Context.UnknownAnyTy;
3055           valueKind = VK_RValue;
3056           break;
3057         }
3058 
3059       // C++ methods are l-values if static, r-values if non-static.
3060       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3061         valueKind = VK_LValue;
3062         break;
3063       }
3064       // fallthrough
3065 
3066     case Decl::CXXConversion:
3067     case Decl::CXXDestructor:
3068     case Decl::CXXConstructor:
3069       valueKind = VK_RValue;
3070       break;
3071     }
3072 
3073     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3074                             TemplateArgs);
3075   }
3076 }
3077 
3078 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3079                                     SmallString<32> &Target) {
3080   Target.resize(CharByteWidth * (Source.size() + 1));
3081   char *ResultPtr = &Target[0];
3082   const llvm::UTF8 *ErrorPtr;
3083   bool success =
3084       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3085   (void)success;
3086   assert(success);
3087   Target.resize(ResultPtr - &Target[0]);
3088 }
3089 
3090 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3091                                      PredefinedExpr::IdentType IT) {
3092   // Pick the current block, lambda, captured statement or function.
3093   Decl *currentDecl = nullptr;
3094   if (const BlockScopeInfo *BSI = getCurBlock())
3095     currentDecl = BSI->TheDecl;
3096   else if (const LambdaScopeInfo *LSI = getCurLambda())
3097     currentDecl = LSI->CallOperator;
3098   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3099     currentDecl = CSI->TheCapturedDecl;
3100   else
3101     currentDecl = getCurFunctionOrMethodDecl();
3102 
3103   if (!currentDecl) {
3104     Diag(Loc, diag::ext_predef_outside_function);
3105     currentDecl = Context.getTranslationUnitDecl();
3106   }
3107 
3108   QualType ResTy;
3109   StringLiteral *SL = nullptr;
3110   if (cast<DeclContext>(currentDecl)->isDependentContext())
3111     ResTy = Context.DependentTy;
3112   else {
3113     // Pre-defined identifiers are of type char[x], where x is the length of
3114     // the string.
3115     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3116     unsigned Length = Str.length();
3117 
3118     llvm::APInt LengthI(32, Length + 1);
3119     if (IT == PredefinedExpr::LFunction) {
3120       ResTy = Context.WideCharTy.withConst();
3121       SmallString<32> RawChars;
3122       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3123                               Str, RawChars);
3124       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3125                                            /*IndexTypeQuals*/ 0);
3126       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3127                                  /*Pascal*/ false, ResTy, Loc);
3128     } else {
3129       ResTy = Context.CharTy.withConst();
3130       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3131                                            /*IndexTypeQuals*/ 0);
3132       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3133                                  /*Pascal*/ false, ResTy, Loc);
3134     }
3135   }
3136 
3137   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3138 }
3139 
3140 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3141   PredefinedExpr::IdentType IT;
3142 
3143   switch (Kind) {
3144   default: llvm_unreachable("Unknown simple primary expr!");
3145   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3146   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3147   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3148   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3149   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3150   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3151   }
3152 
3153   return BuildPredefinedExpr(Loc, IT);
3154 }
3155 
3156 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3157   SmallString<16> CharBuffer;
3158   bool Invalid = false;
3159   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3160   if (Invalid)
3161     return ExprError();
3162 
3163   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3164                             PP, Tok.getKind());
3165   if (Literal.hadError())
3166     return ExprError();
3167 
3168   QualType Ty;
3169   if (Literal.isWide())
3170     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3171   else if (Literal.isUTF16())
3172     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3173   else if (Literal.isUTF32())
3174     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3175   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3176     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3177   else
3178     Ty = Context.CharTy;  // 'x' -> char in C++
3179 
3180   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3181   if (Literal.isWide())
3182     Kind = CharacterLiteral::Wide;
3183   else if (Literal.isUTF16())
3184     Kind = CharacterLiteral::UTF16;
3185   else if (Literal.isUTF32())
3186     Kind = CharacterLiteral::UTF32;
3187   else if (Literal.isUTF8())
3188     Kind = CharacterLiteral::UTF8;
3189 
3190   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3191                                              Tok.getLocation());
3192 
3193   if (Literal.getUDSuffix().empty())
3194     return Lit;
3195 
3196   // We're building a user-defined literal.
3197   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3198   SourceLocation UDSuffixLoc =
3199     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3200 
3201   // Make sure we're allowed user-defined literals here.
3202   if (!UDLScope)
3203     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3204 
3205   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3206   //   operator "" X (ch)
3207   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3208                                         Lit, Tok.getLocation());
3209 }
3210 
3211 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3212   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3213   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3214                                 Context.IntTy, Loc);
3215 }
3216 
3217 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3218                                   QualType Ty, SourceLocation Loc) {
3219   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3220 
3221   using llvm::APFloat;
3222   APFloat Val(Format);
3223 
3224   APFloat::opStatus result = Literal.GetFloatValue(Val);
3225 
3226   // Overflow is always an error, but underflow is only an error if
3227   // we underflowed to zero (APFloat reports denormals as underflow).
3228   if ((result & APFloat::opOverflow) ||
3229       ((result & APFloat::opUnderflow) && Val.isZero())) {
3230     unsigned diagnostic;
3231     SmallString<20> buffer;
3232     if (result & APFloat::opOverflow) {
3233       diagnostic = diag::warn_float_overflow;
3234       APFloat::getLargest(Format).toString(buffer);
3235     } else {
3236       diagnostic = diag::warn_float_underflow;
3237       APFloat::getSmallest(Format).toString(buffer);
3238     }
3239 
3240     S.Diag(Loc, diagnostic)
3241       << Ty
3242       << StringRef(buffer.data(), buffer.size());
3243   }
3244 
3245   bool isExact = (result == APFloat::opOK);
3246   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3247 }
3248 
3249 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3250   assert(E && "Invalid expression");
3251 
3252   if (E->isValueDependent())
3253     return false;
3254 
3255   QualType QT = E->getType();
3256   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3257     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3258     return true;
3259   }
3260 
3261   llvm::APSInt ValueAPS;
3262   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3263 
3264   if (R.isInvalid())
3265     return true;
3266 
3267   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3268   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3269     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3270         << ValueAPS.toString(10) << ValueIsPositive;
3271     return true;
3272   }
3273 
3274   return false;
3275 }
3276 
3277 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3278   // Fast path for a single digit (which is quite common).  A single digit
3279   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3280   if (Tok.getLength() == 1) {
3281     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3282     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3283   }
3284 
3285   SmallString<128> SpellingBuffer;
3286   // NumericLiteralParser wants to overread by one character.  Add padding to
3287   // the buffer in case the token is copied to the buffer.  If getSpelling()
3288   // returns a StringRef to the memory buffer, it should have a null char at
3289   // the EOF, so it is also safe.
3290   SpellingBuffer.resize(Tok.getLength() + 1);
3291 
3292   // Get the spelling of the token, which eliminates trigraphs, etc.
3293   bool Invalid = false;
3294   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3295   if (Invalid)
3296     return ExprError();
3297 
3298   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3299   if (Literal.hadError)
3300     return ExprError();
3301 
3302   if (Literal.hasUDSuffix()) {
3303     // We're building a user-defined literal.
3304     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3305     SourceLocation UDSuffixLoc =
3306       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3307 
3308     // Make sure we're allowed user-defined literals here.
3309     if (!UDLScope)
3310       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3311 
3312     QualType CookedTy;
3313     if (Literal.isFloatingLiteral()) {
3314       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3315       // long double, the literal is treated as a call of the form
3316       //   operator "" X (f L)
3317       CookedTy = Context.LongDoubleTy;
3318     } else {
3319       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3320       // unsigned long long, the literal is treated as a call of the form
3321       //   operator "" X (n ULL)
3322       CookedTy = Context.UnsignedLongLongTy;
3323     }
3324 
3325     DeclarationName OpName =
3326       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3327     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3328     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3329 
3330     SourceLocation TokLoc = Tok.getLocation();
3331 
3332     // Perform literal operator lookup to determine if we're building a raw
3333     // literal or a cooked one.
3334     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3335     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3336                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3337                                   /*AllowStringTemplate*/false)) {
3338     case LOLR_Error:
3339       return ExprError();
3340 
3341     case LOLR_Cooked: {
3342       Expr *Lit;
3343       if (Literal.isFloatingLiteral()) {
3344         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3345       } else {
3346         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3347         if (Literal.GetIntegerValue(ResultVal))
3348           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3349               << /* Unsigned */ 1;
3350         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3351                                      Tok.getLocation());
3352       }
3353       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3354     }
3355 
3356     case LOLR_Raw: {
3357       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3358       // literal is treated as a call of the form
3359       //   operator "" X ("n")
3360       unsigned Length = Literal.getUDSuffixOffset();
3361       QualType StrTy = Context.getConstantArrayType(
3362           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3363           ArrayType::Normal, 0);
3364       Expr *Lit = StringLiteral::Create(
3365           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3366           /*Pascal*/false, StrTy, &TokLoc, 1);
3367       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3368     }
3369 
3370     case LOLR_Template: {
3371       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3372       // template), L is treated as a call fo the form
3373       //   operator "" X <'c1', 'c2', ... 'ck'>()
3374       // where n is the source character sequence c1 c2 ... ck.
3375       TemplateArgumentListInfo ExplicitArgs;
3376       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3377       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3378       llvm::APSInt Value(CharBits, CharIsUnsigned);
3379       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3380         Value = TokSpelling[I];
3381         TemplateArgument Arg(Context, Value, Context.CharTy);
3382         TemplateArgumentLocInfo ArgInfo;
3383         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3384       }
3385       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3386                                       &ExplicitArgs);
3387     }
3388     case LOLR_StringTemplate:
3389       llvm_unreachable("unexpected literal operator lookup result");
3390     }
3391   }
3392 
3393   Expr *Res;
3394 
3395   if (Literal.isFloatingLiteral()) {
3396     QualType Ty;
3397     if (Literal.isHalf){
3398       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3399         Ty = Context.HalfTy;
3400       else {
3401         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3402         return ExprError();
3403       }
3404     } else if (Literal.isFloat)
3405       Ty = Context.FloatTy;
3406     else if (Literal.isLong)
3407       Ty = Context.LongDoubleTy;
3408     else if (Literal.isFloat128)
3409       Ty = Context.Float128Ty;
3410     else
3411       Ty = Context.DoubleTy;
3412 
3413     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3414 
3415     if (Ty == Context.DoubleTy) {
3416       if (getLangOpts().SinglePrecisionConstants) {
3417         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3418         if (BTy->getKind() != BuiltinType::Float) {
3419           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3420         }
3421       } else if (getLangOpts().OpenCL &&
3422                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3423         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3424         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3425         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3426       }
3427     }
3428   } else if (!Literal.isIntegerLiteral()) {
3429     return ExprError();
3430   } else {
3431     QualType Ty;
3432 
3433     // 'long long' is a C99 or C++11 feature.
3434     if (!getLangOpts().C99 && Literal.isLongLong) {
3435       if (getLangOpts().CPlusPlus)
3436         Diag(Tok.getLocation(),
3437              getLangOpts().CPlusPlus11 ?
3438              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3439       else
3440         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3441     }
3442 
3443     // Get the value in the widest-possible width.
3444     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3445     llvm::APInt ResultVal(MaxWidth, 0);
3446 
3447     if (Literal.GetIntegerValue(ResultVal)) {
3448       // If this value didn't fit into uintmax_t, error and force to ull.
3449       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3450           << /* Unsigned */ 1;
3451       Ty = Context.UnsignedLongLongTy;
3452       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3453              "long long is not intmax_t?");
3454     } else {
3455       // If this value fits into a ULL, try to figure out what else it fits into
3456       // according to the rules of C99 6.4.4.1p5.
3457 
3458       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3459       // be an unsigned int.
3460       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3461 
3462       // Check from smallest to largest, picking the smallest type we can.
3463       unsigned Width = 0;
3464 
3465       // Microsoft specific integer suffixes are explicitly sized.
3466       if (Literal.MicrosoftInteger) {
3467         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3468           Width = 8;
3469           Ty = Context.CharTy;
3470         } else {
3471           Width = Literal.MicrosoftInteger;
3472           Ty = Context.getIntTypeForBitwidth(Width,
3473                                              /*Signed=*/!Literal.isUnsigned);
3474         }
3475       }
3476 
3477       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3478         // Are int/unsigned possibilities?
3479         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3480 
3481         // Does it fit in a unsigned int?
3482         if (ResultVal.isIntN(IntSize)) {
3483           // Does it fit in a signed int?
3484           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3485             Ty = Context.IntTy;
3486           else if (AllowUnsigned)
3487             Ty = Context.UnsignedIntTy;
3488           Width = IntSize;
3489         }
3490       }
3491 
3492       // Are long/unsigned long possibilities?
3493       if (Ty.isNull() && !Literal.isLongLong) {
3494         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3495 
3496         // Does it fit in a unsigned long?
3497         if (ResultVal.isIntN(LongSize)) {
3498           // Does it fit in a signed long?
3499           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3500             Ty = Context.LongTy;
3501           else if (AllowUnsigned)
3502             Ty = Context.UnsignedLongTy;
3503           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3504           // is compatible.
3505           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3506             const unsigned LongLongSize =
3507                 Context.getTargetInfo().getLongLongWidth();
3508             Diag(Tok.getLocation(),
3509                  getLangOpts().CPlusPlus
3510                      ? Literal.isLong
3511                            ? diag::warn_old_implicitly_unsigned_long_cxx
3512                            : /*C++98 UB*/ diag::
3513                                  ext_old_implicitly_unsigned_long_cxx
3514                      : diag::warn_old_implicitly_unsigned_long)
3515                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3516                                             : /*will be ill-formed*/ 1);
3517             Ty = Context.UnsignedLongTy;
3518           }
3519           Width = LongSize;
3520         }
3521       }
3522 
3523       // Check long long if needed.
3524       if (Ty.isNull()) {
3525         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3526 
3527         // Does it fit in a unsigned long long?
3528         if (ResultVal.isIntN(LongLongSize)) {
3529           // Does it fit in a signed long long?
3530           // To be compatible with MSVC, hex integer literals ending with the
3531           // LL or i64 suffix are always signed in Microsoft mode.
3532           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3533               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3534             Ty = Context.LongLongTy;
3535           else if (AllowUnsigned)
3536             Ty = Context.UnsignedLongLongTy;
3537           Width = LongLongSize;
3538         }
3539       }
3540 
3541       // If we still couldn't decide a type, we probably have something that
3542       // does not fit in a signed long long, but has no U suffix.
3543       if (Ty.isNull()) {
3544         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3545         Ty = Context.UnsignedLongLongTy;
3546         Width = Context.getTargetInfo().getLongLongWidth();
3547       }
3548 
3549       if (ResultVal.getBitWidth() != Width)
3550         ResultVal = ResultVal.trunc(Width);
3551     }
3552     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3553   }
3554 
3555   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3556   if (Literal.isImaginary)
3557     Res = new (Context) ImaginaryLiteral(Res,
3558                                         Context.getComplexType(Res->getType()));
3559 
3560   return Res;
3561 }
3562 
3563 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3564   assert(E && "ActOnParenExpr() missing expr");
3565   return new (Context) ParenExpr(L, R, E);
3566 }
3567 
3568 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3569                                          SourceLocation Loc,
3570                                          SourceRange ArgRange) {
3571   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3572   // scalar or vector data type argument..."
3573   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3574   // type (C99 6.2.5p18) or void.
3575   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3576     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3577       << T << ArgRange;
3578     return true;
3579   }
3580 
3581   assert((T->isVoidType() || !T->isIncompleteType()) &&
3582          "Scalar types should always be complete");
3583   return false;
3584 }
3585 
3586 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3587                                            SourceLocation Loc,
3588                                            SourceRange ArgRange,
3589                                            UnaryExprOrTypeTrait TraitKind) {
3590   // Invalid types must be hard errors for SFINAE in C++.
3591   if (S.LangOpts.CPlusPlus)
3592     return true;
3593 
3594   // C99 6.5.3.4p1:
3595   if (T->isFunctionType() &&
3596       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3597     // sizeof(function)/alignof(function) is allowed as an extension.
3598     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3599       << TraitKind << ArgRange;
3600     return false;
3601   }
3602 
3603   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3604   // this is an error (OpenCL v1.1 s6.3.k)
3605   if (T->isVoidType()) {
3606     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3607                                         : diag::ext_sizeof_alignof_void_type;
3608     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3609     return false;
3610   }
3611 
3612   return true;
3613 }
3614 
3615 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3616                                              SourceLocation Loc,
3617                                              SourceRange ArgRange,
3618                                              UnaryExprOrTypeTrait TraitKind) {
3619   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3620   // runtime doesn't allow it.
3621   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3622     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3623       << T << (TraitKind == UETT_SizeOf)
3624       << ArgRange;
3625     return true;
3626   }
3627 
3628   return false;
3629 }
3630 
3631 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3632 /// pointer type is equal to T) and emit a warning if it is.
3633 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3634                                      Expr *E) {
3635   // Don't warn if the operation changed the type.
3636   if (T != E->getType())
3637     return;
3638 
3639   // Now look for array decays.
3640   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3641   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3642     return;
3643 
3644   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3645                                              << ICE->getType()
3646                                              << ICE->getSubExpr()->getType();
3647 }
3648 
3649 /// \brief Check the constraints on expression operands to unary type expression
3650 /// and type traits.
3651 ///
3652 /// Completes any types necessary and validates the constraints on the operand
3653 /// expression. The logic mostly mirrors the type-based overload, but may modify
3654 /// the expression as it completes the type for that expression through template
3655 /// instantiation, etc.
3656 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3657                                             UnaryExprOrTypeTrait ExprKind) {
3658   QualType ExprTy = E->getType();
3659   assert(!ExprTy->isReferenceType());
3660 
3661   if (ExprKind == UETT_VecStep)
3662     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3663                                         E->getSourceRange());
3664 
3665   // Whitelist some types as extensions
3666   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3667                                       E->getSourceRange(), ExprKind))
3668     return false;
3669 
3670   // 'alignof' applied to an expression only requires the base element type of
3671   // the expression to be complete. 'sizeof' requires the expression's type to
3672   // be complete (and will attempt to complete it if it's an array of unknown
3673   // bound).
3674   if (ExprKind == UETT_AlignOf) {
3675     if (RequireCompleteType(E->getExprLoc(),
3676                             Context.getBaseElementType(E->getType()),
3677                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3678                             E->getSourceRange()))
3679       return true;
3680   } else {
3681     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3682                                 ExprKind, E->getSourceRange()))
3683       return true;
3684   }
3685 
3686   // Completing the expression's type may have changed it.
3687   ExprTy = E->getType();
3688   assert(!ExprTy->isReferenceType());
3689 
3690   if (ExprTy->isFunctionType()) {
3691     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3692       << ExprKind << E->getSourceRange();
3693     return true;
3694   }
3695 
3696   // The operand for sizeof and alignof is in an unevaluated expression context,
3697   // so side effects could result in unintended consequences.
3698   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3699       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3700     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3701 
3702   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3703                                        E->getSourceRange(), ExprKind))
3704     return true;
3705 
3706   if (ExprKind == UETT_SizeOf) {
3707     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3708       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3709         QualType OType = PVD->getOriginalType();
3710         QualType Type = PVD->getType();
3711         if (Type->isPointerType() && OType->isArrayType()) {
3712           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3713             << Type << OType;
3714           Diag(PVD->getLocation(), diag::note_declared_at);
3715         }
3716       }
3717     }
3718 
3719     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3720     // decays into a pointer and returns an unintended result. This is most
3721     // likely a typo for "sizeof(array) op x".
3722     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3723       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3724                                BO->getLHS());
3725       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3726                                BO->getRHS());
3727     }
3728   }
3729 
3730   return false;
3731 }
3732 
3733 /// \brief Check the constraints on operands to unary expression and type
3734 /// traits.
3735 ///
3736 /// This will complete any types necessary, and validate the various constraints
3737 /// on those operands.
3738 ///
3739 /// The UsualUnaryConversions() function is *not* called by this routine.
3740 /// C99 6.3.2.1p[2-4] all state:
3741 ///   Except when it is the operand of the sizeof operator ...
3742 ///
3743 /// C++ [expr.sizeof]p4
3744 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3745 ///   standard conversions are not applied to the operand of sizeof.
3746 ///
3747 /// This policy is followed for all of the unary trait expressions.
3748 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3749                                             SourceLocation OpLoc,
3750                                             SourceRange ExprRange,
3751                                             UnaryExprOrTypeTrait ExprKind) {
3752   if (ExprType->isDependentType())
3753     return false;
3754 
3755   // C++ [expr.sizeof]p2:
3756   //     When applied to a reference or a reference type, the result
3757   //     is the size of the referenced type.
3758   // C++11 [expr.alignof]p3:
3759   //     When alignof is applied to a reference type, the result
3760   //     shall be the alignment of the referenced type.
3761   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3762     ExprType = Ref->getPointeeType();
3763 
3764   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3765   //   When alignof or _Alignof is applied to an array type, the result
3766   //   is the alignment of the element type.
3767   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3768     ExprType = Context.getBaseElementType(ExprType);
3769 
3770   if (ExprKind == UETT_VecStep)
3771     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3772 
3773   // Whitelist some types as extensions
3774   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3775                                       ExprKind))
3776     return false;
3777 
3778   if (RequireCompleteType(OpLoc, ExprType,
3779                           diag::err_sizeof_alignof_incomplete_type,
3780                           ExprKind, ExprRange))
3781     return true;
3782 
3783   if (ExprType->isFunctionType()) {
3784     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3785       << ExprKind << ExprRange;
3786     return true;
3787   }
3788 
3789   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3790                                        ExprKind))
3791     return true;
3792 
3793   return false;
3794 }
3795 
3796 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3797   E = E->IgnoreParens();
3798 
3799   // Cannot know anything else if the expression is dependent.
3800   if (E->isTypeDependent())
3801     return false;
3802 
3803   if (E->getObjectKind() == OK_BitField) {
3804     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3805        << 1 << E->getSourceRange();
3806     return true;
3807   }
3808 
3809   ValueDecl *D = nullptr;
3810   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3811     D = DRE->getDecl();
3812   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3813     D = ME->getMemberDecl();
3814   }
3815 
3816   // If it's a field, require the containing struct to have a
3817   // complete definition so that we can compute the layout.
3818   //
3819   // This can happen in C++11 onwards, either by naming the member
3820   // in a way that is not transformed into a member access expression
3821   // (in an unevaluated operand, for instance), or by naming the member
3822   // in a trailing-return-type.
3823   //
3824   // For the record, since __alignof__ on expressions is a GCC
3825   // extension, GCC seems to permit this but always gives the
3826   // nonsensical answer 0.
3827   //
3828   // We don't really need the layout here --- we could instead just
3829   // directly check for all the appropriate alignment-lowing
3830   // attributes --- but that would require duplicating a lot of
3831   // logic that just isn't worth duplicating for such a marginal
3832   // use-case.
3833   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3834     // Fast path this check, since we at least know the record has a
3835     // definition if we can find a member of it.
3836     if (!FD->getParent()->isCompleteDefinition()) {
3837       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3838         << E->getSourceRange();
3839       return true;
3840     }
3841 
3842     // Otherwise, if it's a field, and the field doesn't have
3843     // reference type, then it must have a complete type (or be a
3844     // flexible array member, which we explicitly want to
3845     // white-list anyway), which makes the following checks trivial.
3846     if (!FD->getType()->isReferenceType())
3847       return false;
3848   }
3849 
3850   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3851 }
3852 
3853 bool Sema::CheckVecStepExpr(Expr *E) {
3854   E = E->IgnoreParens();
3855 
3856   // Cannot know anything else if the expression is dependent.
3857   if (E->isTypeDependent())
3858     return false;
3859 
3860   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3861 }
3862 
3863 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3864                                         CapturingScopeInfo *CSI) {
3865   assert(T->isVariablyModifiedType());
3866   assert(CSI != nullptr);
3867 
3868   // We're going to walk down into the type and look for VLA expressions.
3869   do {
3870     const Type *Ty = T.getTypePtr();
3871     switch (Ty->getTypeClass()) {
3872 #define TYPE(Class, Base)
3873 #define ABSTRACT_TYPE(Class, Base)
3874 #define NON_CANONICAL_TYPE(Class, Base)
3875 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3876 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3877 #include "clang/AST/TypeNodes.def"
3878       T = QualType();
3879       break;
3880     // These types are never variably-modified.
3881     case Type::Builtin:
3882     case Type::Complex:
3883     case Type::Vector:
3884     case Type::ExtVector:
3885     case Type::Record:
3886     case Type::Enum:
3887     case Type::Elaborated:
3888     case Type::TemplateSpecialization:
3889     case Type::ObjCObject:
3890     case Type::ObjCInterface:
3891     case Type::ObjCObjectPointer:
3892     case Type::ObjCTypeParam:
3893     case Type::Pipe:
3894       llvm_unreachable("type class is never variably-modified!");
3895     case Type::Adjusted:
3896       T = cast<AdjustedType>(Ty)->getOriginalType();
3897       break;
3898     case Type::Decayed:
3899       T = cast<DecayedType>(Ty)->getPointeeType();
3900       break;
3901     case Type::Pointer:
3902       T = cast<PointerType>(Ty)->getPointeeType();
3903       break;
3904     case Type::BlockPointer:
3905       T = cast<BlockPointerType>(Ty)->getPointeeType();
3906       break;
3907     case Type::LValueReference:
3908     case Type::RValueReference:
3909       T = cast<ReferenceType>(Ty)->getPointeeType();
3910       break;
3911     case Type::MemberPointer:
3912       T = cast<MemberPointerType>(Ty)->getPointeeType();
3913       break;
3914     case Type::ConstantArray:
3915     case Type::IncompleteArray:
3916       // Losing element qualification here is fine.
3917       T = cast<ArrayType>(Ty)->getElementType();
3918       break;
3919     case Type::VariableArray: {
3920       // Losing element qualification here is fine.
3921       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3922 
3923       // Unknown size indication requires no size computation.
3924       // Otherwise, evaluate and record it.
3925       if (auto Size = VAT->getSizeExpr()) {
3926         if (!CSI->isVLATypeCaptured(VAT)) {
3927           RecordDecl *CapRecord = nullptr;
3928           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3929             CapRecord = LSI->Lambda;
3930           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3931             CapRecord = CRSI->TheRecordDecl;
3932           }
3933           if (CapRecord) {
3934             auto ExprLoc = Size->getExprLoc();
3935             auto SizeType = Context.getSizeType();
3936             // Build the non-static data member.
3937             auto Field =
3938                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3939                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3940                                   /*BW*/ nullptr, /*Mutable*/ false,
3941                                   /*InitStyle*/ ICIS_NoInit);
3942             Field->setImplicit(true);
3943             Field->setAccess(AS_private);
3944             Field->setCapturedVLAType(VAT);
3945             CapRecord->addDecl(Field);
3946 
3947             CSI->addVLATypeCapture(ExprLoc, SizeType);
3948           }
3949         }
3950       }
3951       T = VAT->getElementType();
3952       break;
3953     }
3954     case Type::FunctionProto:
3955     case Type::FunctionNoProto:
3956       T = cast<FunctionType>(Ty)->getReturnType();
3957       break;
3958     case Type::Paren:
3959     case Type::TypeOf:
3960     case Type::UnaryTransform:
3961     case Type::Attributed:
3962     case Type::SubstTemplateTypeParm:
3963     case Type::PackExpansion:
3964       // Keep walking after single level desugaring.
3965       T = T.getSingleStepDesugaredType(Context);
3966       break;
3967     case Type::Typedef:
3968       T = cast<TypedefType>(Ty)->desugar();
3969       break;
3970     case Type::Decltype:
3971       T = cast<DecltypeType>(Ty)->desugar();
3972       break;
3973     case Type::Auto:
3974     case Type::DeducedTemplateSpecialization:
3975       T = cast<DeducedType>(Ty)->getDeducedType();
3976       break;
3977     case Type::TypeOfExpr:
3978       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3979       break;
3980     case Type::Atomic:
3981       T = cast<AtomicType>(Ty)->getValueType();
3982       break;
3983     }
3984   } while (!T.isNull() && T->isVariablyModifiedType());
3985 }
3986 
3987 /// \brief Build a sizeof or alignof expression given a type operand.
3988 ExprResult
3989 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3990                                      SourceLocation OpLoc,
3991                                      UnaryExprOrTypeTrait ExprKind,
3992                                      SourceRange R) {
3993   if (!TInfo)
3994     return ExprError();
3995 
3996   QualType T = TInfo->getType();
3997 
3998   if (!T->isDependentType() &&
3999       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4000     return ExprError();
4001 
4002   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4003     if (auto *TT = T->getAs<TypedefType>()) {
4004       for (auto I = FunctionScopes.rbegin(),
4005                 E = std::prev(FunctionScopes.rend());
4006            I != E; ++I) {
4007         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4008         if (CSI == nullptr)
4009           break;
4010         DeclContext *DC = nullptr;
4011         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4012           DC = LSI->CallOperator;
4013         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4014           DC = CRSI->TheCapturedDecl;
4015         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4016           DC = BSI->TheDecl;
4017         if (DC) {
4018           if (DC->containsDecl(TT->getDecl()))
4019             break;
4020           captureVariablyModifiedType(Context, T, CSI);
4021         }
4022       }
4023     }
4024   }
4025 
4026   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4027   return new (Context) UnaryExprOrTypeTraitExpr(
4028       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4029 }
4030 
4031 /// \brief Build a sizeof or alignof expression given an expression
4032 /// operand.
4033 ExprResult
4034 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4035                                      UnaryExprOrTypeTrait ExprKind) {
4036   ExprResult PE = CheckPlaceholderExpr(E);
4037   if (PE.isInvalid())
4038     return ExprError();
4039 
4040   E = PE.get();
4041 
4042   // Verify that the operand is valid.
4043   bool isInvalid = false;
4044   if (E->isTypeDependent()) {
4045     // Delay type-checking for type-dependent expressions.
4046   } else if (ExprKind == UETT_AlignOf) {
4047     isInvalid = CheckAlignOfExpr(*this, E);
4048   } else if (ExprKind == UETT_VecStep) {
4049     isInvalid = CheckVecStepExpr(E);
4050   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4051       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4052       isInvalid = true;
4053   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4054     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4055     isInvalid = true;
4056   } else {
4057     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4058   }
4059 
4060   if (isInvalid)
4061     return ExprError();
4062 
4063   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4064     PE = TransformToPotentiallyEvaluated(E);
4065     if (PE.isInvalid()) return ExprError();
4066     E = PE.get();
4067   }
4068 
4069   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4070   return new (Context) UnaryExprOrTypeTraitExpr(
4071       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4072 }
4073 
4074 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4075 /// expr and the same for @c alignof and @c __alignof
4076 /// Note that the ArgRange is invalid if isType is false.
4077 ExprResult
4078 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4079                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4080                                     void *TyOrEx, SourceRange ArgRange) {
4081   // If error parsing type, ignore.
4082   if (!TyOrEx) return ExprError();
4083 
4084   if (IsType) {
4085     TypeSourceInfo *TInfo;
4086     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4087     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4088   }
4089 
4090   Expr *ArgEx = (Expr *)TyOrEx;
4091   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4092   return Result;
4093 }
4094 
4095 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4096                                      bool IsReal) {
4097   if (V.get()->isTypeDependent())
4098     return S.Context.DependentTy;
4099 
4100   // _Real and _Imag are only l-values for normal l-values.
4101   if (V.get()->getObjectKind() != OK_Ordinary) {
4102     V = S.DefaultLvalueConversion(V.get());
4103     if (V.isInvalid())
4104       return QualType();
4105   }
4106 
4107   // These operators return the element type of a complex type.
4108   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4109     return CT->getElementType();
4110 
4111   // Otherwise they pass through real integer and floating point types here.
4112   if (V.get()->getType()->isArithmeticType())
4113     return V.get()->getType();
4114 
4115   // Test for placeholders.
4116   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4117   if (PR.isInvalid()) return QualType();
4118   if (PR.get() != V.get()) {
4119     V = PR;
4120     return CheckRealImagOperand(S, V, Loc, IsReal);
4121   }
4122 
4123   // Reject anything else.
4124   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4125     << (IsReal ? "__real" : "__imag");
4126   return QualType();
4127 }
4128 
4129 
4130 
4131 ExprResult
4132 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4133                           tok::TokenKind Kind, Expr *Input) {
4134   UnaryOperatorKind Opc;
4135   switch (Kind) {
4136   default: llvm_unreachable("Unknown unary op!");
4137   case tok::plusplus:   Opc = UO_PostInc; break;
4138   case tok::minusminus: Opc = UO_PostDec; break;
4139   }
4140 
4141   // Since this might is a postfix expression, get rid of ParenListExprs.
4142   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4143   if (Result.isInvalid()) return ExprError();
4144   Input = Result.get();
4145 
4146   return BuildUnaryOp(S, OpLoc, Opc, Input);
4147 }
4148 
4149 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4150 ///
4151 /// \return true on error
4152 static bool checkArithmeticOnObjCPointer(Sema &S,
4153                                          SourceLocation opLoc,
4154                                          Expr *op) {
4155   assert(op->getType()->isObjCObjectPointerType());
4156   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4157       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4158     return false;
4159 
4160   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4161     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4162     << op->getSourceRange();
4163   return true;
4164 }
4165 
4166 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4167   auto *BaseNoParens = Base->IgnoreParens();
4168   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4169     return MSProp->getPropertyDecl()->getType()->isArrayType();
4170   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4171 }
4172 
4173 ExprResult
4174 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4175                               Expr *idx, SourceLocation rbLoc) {
4176   if (base && !base->getType().isNull() &&
4177       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4178     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4179                                     /*Length=*/nullptr, rbLoc);
4180 
4181   // Since this might be a postfix expression, get rid of ParenListExprs.
4182   if (isa<ParenListExpr>(base)) {
4183     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4184     if (result.isInvalid()) return ExprError();
4185     base = result.get();
4186   }
4187 
4188   // Handle any non-overload placeholder types in the base and index
4189   // expressions.  We can't handle overloads here because the other
4190   // operand might be an overloadable type, in which case the overload
4191   // resolution for the operator overload should get the first crack
4192   // at the overload.
4193   bool IsMSPropertySubscript = false;
4194   if (base->getType()->isNonOverloadPlaceholderType()) {
4195     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4196     if (!IsMSPropertySubscript) {
4197       ExprResult result = CheckPlaceholderExpr(base);
4198       if (result.isInvalid())
4199         return ExprError();
4200       base = result.get();
4201     }
4202   }
4203   if (idx->getType()->isNonOverloadPlaceholderType()) {
4204     ExprResult result = CheckPlaceholderExpr(idx);
4205     if (result.isInvalid()) return ExprError();
4206     idx = result.get();
4207   }
4208 
4209   // Build an unanalyzed expression if either operand is type-dependent.
4210   if (getLangOpts().CPlusPlus &&
4211       (base->isTypeDependent() || idx->isTypeDependent())) {
4212     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4213                                             VK_LValue, OK_Ordinary, rbLoc);
4214   }
4215 
4216   // MSDN, property (C++)
4217   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4218   // This attribute can also be used in the declaration of an empty array in a
4219   // class or structure definition. For example:
4220   // __declspec(property(get=GetX, put=PutX)) int x[];
4221   // The above statement indicates that x[] can be used with one or more array
4222   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4223   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4224   if (IsMSPropertySubscript) {
4225     // Build MS property subscript expression if base is MS property reference
4226     // or MS property subscript.
4227     return new (Context) MSPropertySubscriptExpr(
4228         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4229   }
4230 
4231   // Use C++ overloaded-operator rules if either operand has record
4232   // type.  The spec says to do this if either type is *overloadable*,
4233   // but enum types can't declare subscript operators or conversion
4234   // operators, so there's nothing interesting for overload resolution
4235   // to do if there aren't any record types involved.
4236   //
4237   // ObjC pointers have their own subscripting logic that is not tied
4238   // to overload resolution and so should not take this path.
4239   if (getLangOpts().CPlusPlus &&
4240       (base->getType()->isRecordType() ||
4241        (!base->getType()->isObjCObjectPointerType() &&
4242         idx->getType()->isRecordType()))) {
4243     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4244   }
4245 
4246   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4247 }
4248 
4249 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4250                                           Expr *LowerBound,
4251                                           SourceLocation ColonLoc, Expr *Length,
4252                                           SourceLocation RBLoc) {
4253   if (Base->getType()->isPlaceholderType() &&
4254       !Base->getType()->isSpecificPlaceholderType(
4255           BuiltinType::OMPArraySection)) {
4256     ExprResult Result = CheckPlaceholderExpr(Base);
4257     if (Result.isInvalid())
4258       return ExprError();
4259     Base = Result.get();
4260   }
4261   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4262     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4263     if (Result.isInvalid())
4264       return ExprError();
4265     Result = DefaultLvalueConversion(Result.get());
4266     if (Result.isInvalid())
4267       return ExprError();
4268     LowerBound = Result.get();
4269   }
4270   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4271     ExprResult Result = CheckPlaceholderExpr(Length);
4272     if (Result.isInvalid())
4273       return ExprError();
4274     Result = DefaultLvalueConversion(Result.get());
4275     if (Result.isInvalid())
4276       return ExprError();
4277     Length = Result.get();
4278   }
4279 
4280   // Build an unanalyzed expression if either operand is type-dependent.
4281   if (Base->isTypeDependent() ||
4282       (LowerBound &&
4283        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4284       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4285     return new (Context)
4286         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4287                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4288   }
4289 
4290   // Perform default conversions.
4291   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4292   QualType ResultTy;
4293   if (OriginalTy->isAnyPointerType()) {
4294     ResultTy = OriginalTy->getPointeeType();
4295   } else if (OriginalTy->isArrayType()) {
4296     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4297   } else {
4298     return ExprError(
4299         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4300         << Base->getSourceRange());
4301   }
4302   // C99 6.5.2.1p1
4303   if (LowerBound) {
4304     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4305                                                       LowerBound);
4306     if (Res.isInvalid())
4307       return ExprError(Diag(LowerBound->getExprLoc(),
4308                             diag::err_omp_typecheck_section_not_integer)
4309                        << 0 << LowerBound->getSourceRange());
4310     LowerBound = Res.get();
4311 
4312     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4313         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4314       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4315           << 0 << LowerBound->getSourceRange();
4316   }
4317   if (Length) {
4318     auto Res =
4319         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4320     if (Res.isInvalid())
4321       return ExprError(Diag(Length->getExprLoc(),
4322                             diag::err_omp_typecheck_section_not_integer)
4323                        << 1 << Length->getSourceRange());
4324     Length = Res.get();
4325 
4326     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4327         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4328       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4329           << 1 << Length->getSourceRange();
4330   }
4331 
4332   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4333   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4334   // type. Note that functions are not objects, and that (in C99 parlance)
4335   // incomplete types are not object types.
4336   if (ResultTy->isFunctionType()) {
4337     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4338         << ResultTy << Base->getSourceRange();
4339     return ExprError();
4340   }
4341 
4342   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4343                           diag::err_omp_section_incomplete_type, Base))
4344     return ExprError();
4345 
4346   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4347     llvm::APSInt LowerBoundValue;
4348     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4349       // OpenMP 4.5, [2.4 Array Sections]
4350       // The array section must be a subset of the original array.
4351       if (LowerBoundValue.isNegative()) {
4352         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4353             << LowerBound->getSourceRange();
4354         return ExprError();
4355       }
4356     }
4357   }
4358 
4359   if (Length) {
4360     llvm::APSInt LengthValue;
4361     if (Length->EvaluateAsInt(LengthValue, Context)) {
4362       // OpenMP 4.5, [2.4 Array Sections]
4363       // The length must evaluate to non-negative integers.
4364       if (LengthValue.isNegative()) {
4365         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4366             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4367             << Length->getSourceRange();
4368         return ExprError();
4369       }
4370     }
4371   } else if (ColonLoc.isValid() &&
4372              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4373                                       !OriginalTy->isVariableArrayType()))) {
4374     // OpenMP 4.5, [2.4 Array Sections]
4375     // When the size of the array dimension is not known, the length must be
4376     // specified explicitly.
4377     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4378         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4379     return ExprError();
4380   }
4381 
4382   if (!Base->getType()->isSpecificPlaceholderType(
4383           BuiltinType::OMPArraySection)) {
4384     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4385     if (Result.isInvalid())
4386       return ExprError();
4387     Base = Result.get();
4388   }
4389   return new (Context)
4390       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4391                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4392 }
4393 
4394 ExprResult
4395 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4396                                       Expr *Idx, SourceLocation RLoc) {
4397   Expr *LHSExp = Base;
4398   Expr *RHSExp = Idx;
4399 
4400   ExprValueKind VK = VK_LValue;
4401   ExprObjectKind OK = OK_Ordinary;
4402 
4403   // Per C++ core issue 1213, the result is an xvalue if either operand is
4404   // a non-lvalue array, and an lvalue otherwise.
4405   if (getLangOpts().CPlusPlus11 &&
4406       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4407        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4408     VK = VK_XValue;
4409 
4410   // Perform default conversions.
4411   if (!LHSExp->getType()->getAs<VectorType>()) {
4412     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4413     if (Result.isInvalid())
4414       return ExprError();
4415     LHSExp = Result.get();
4416   }
4417   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4418   if (Result.isInvalid())
4419     return ExprError();
4420   RHSExp = Result.get();
4421 
4422   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4423 
4424   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4425   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4426   // in the subscript position. As a result, we need to derive the array base
4427   // and index from the expression types.
4428   Expr *BaseExpr, *IndexExpr;
4429   QualType ResultType;
4430   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4431     BaseExpr = LHSExp;
4432     IndexExpr = RHSExp;
4433     ResultType = Context.DependentTy;
4434   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4435     BaseExpr = LHSExp;
4436     IndexExpr = RHSExp;
4437     ResultType = PTy->getPointeeType();
4438   } else if (const ObjCObjectPointerType *PTy =
4439                LHSTy->getAs<ObjCObjectPointerType>()) {
4440     BaseExpr = LHSExp;
4441     IndexExpr = RHSExp;
4442 
4443     // Use custom logic if this should be the pseudo-object subscript
4444     // expression.
4445     if (!LangOpts.isSubscriptPointerArithmetic())
4446       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4447                                           nullptr);
4448 
4449     ResultType = PTy->getPointeeType();
4450   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4451      // Handle the uncommon case of "123[Ptr]".
4452     BaseExpr = RHSExp;
4453     IndexExpr = LHSExp;
4454     ResultType = PTy->getPointeeType();
4455   } else if (const ObjCObjectPointerType *PTy =
4456                RHSTy->getAs<ObjCObjectPointerType>()) {
4457      // Handle the uncommon case of "123[Ptr]".
4458     BaseExpr = RHSExp;
4459     IndexExpr = LHSExp;
4460     ResultType = PTy->getPointeeType();
4461     if (!LangOpts.isSubscriptPointerArithmetic()) {
4462       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4463         << ResultType << BaseExpr->getSourceRange();
4464       return ExprError();
4465     }
4466   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4467     BaseExpr = LHSExp;    // vectors: V[123]
4468     IndexExpr = RHSExp;
4469     VK = LHSExp->getValueKind();
4470     if (VK != VK_RValue)
4471       OK = OK_VectorComponent;
4472 
4473     // FIXME: need to deal with const...
4474     ResultType = VTy->getElementType();
4475   } else if (LHSTy->isArrayType()) {
4476     // If we see an array that wasn't promoted by
4477     // DefaultFunctionArrayLvalueConversion, it must be an array that
4478     // wasn't promoted because of the C90 rule that doesn't
4479     // allow promoting non-lvalue arrays.  Warn, then
4480     // force the promotion here.
4481     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4482         LHSExp->getSourceRange();
4483     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4484                                CK_ArrayToPointerDecay).get();
4485     LHSTy = LHSExp->getType();
4486 
4487     BaseExpr = LHSExp;
4488     IndexExpr = RHSExp;
4489     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4490   } else if (RHSTy->isArrayType()) {
4491     // Same as previous, except for 123[f().a] case
4492     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4493         RHSExp->getSourceRange();
4494     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4495                                CK_ArrayToPointerDecay).get();
4496     RHSTy = RHSExp->getType();
4497 
4498     BaseExpr = RHSExp;
4499     IndexExpr = LHSExp;
4500     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4501   } else {
4502     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4503        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4504   }
4505   // C99 6.5.2.1p1
4506   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4507     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4508                      << IndexExpr->getSourceRange());
4509 
4510   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4511        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4512          && !IndexExpr->isTypeDependent())
4513     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4514 
4515   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4516   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4517   // type. Note that Functions are not objects, and that (in C99 parlance)
4518   // incomplete types are not object types.
4519   if (ResultType->isFunctionType()) {
4520     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4521       << ResultType << BaseExpr->getSourceRange();
4522     return ExprError();
4523   }
4524 
4525   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4526     // GNU extension: subscripting on pointer to void
4527     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4528       << BaseExpr->getSourceRange();
4529 
4530     // C forbids expressions of unqualified void type from being l-values.
4531     // See IsCForbiddenLValueType.
4532     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4533   } else if (!ResultType->isDependentType() &&
4534       RequireCompleteType(LLoc, ResultType,
4535                           diag::err_subscript_incomplete_type, BaseExpr))
4536     return ExprError();
4537 
4538   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4539          !ResultType.isCForbiddenLValueType());
4540 
4541   return new (Context)
4542       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4543 }
4544 
4545 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4546                                   ParmVarDecl *Param) {
4547   if (Param->hasUnparsedDefaultArg()) {
4548     Diag(CallLoc,
4549          diag::err_use_of_default_argument_to_function_declared_later) <<
4550       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4551     Diag(UnparsedDefaultArgLocs[Param],
4552          diag::note_default_argument_declared_here);
4553     return true;
4554   }
4555 
4556   if (Param->hasUninstantiatedDefaultArg()) {
4557     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4558 
4559     EnterExpressionEvaluationContext EvalContext(
4560         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4561 
4562     // Instantiate the expression.
4563     MultiLevelTemplateArgumentList MutiLevelArgList
4564       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4565 
4566     InstantiatingTemplate Inst(*this, CallLoc, Param,
4567                                MutiLevelArgList.getInnermost());
4568     if (Inst.isInvalid())
4569       return true;
4570     if (Inst.isAlreadyInstantiating()) {
4571       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4572       Param->setInvalidDecl();
4573       return true;
4574     }
4575 
4576     ExprResult Result;
4577     {
4578       // C++ [dcl.fct.default]p5:
4579       //   The names in the [default argument] expression are bound, and
4580       //   the semantic constraints are checked, at the point where the
4581       //   default argument expression appears.
4582       ContextRAII SavedContext(*this, FD);
4583       LocalInstantiationScope Local(*this);
4584       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4585                                 /*DirectInit*/false);
4586     }
4587     if (Result.isInvalid())
4588       return true;
4589 
4590     // Check the expression as an initializer for the parameter.
4591     InitializedEntity Entity
4592       = InitializedEntity::InitializeParameter(Context, Param);
4593     InitializationKind Kind
4594       = InitializationKind::CreateCopy(Param->getLocation(),
4595              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4596     Expr *ResultE = Result.getAs<Expr>();
4597 
4598     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4599     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4600     if (Result.isInvalid())
4601       return true;
4602 
4603     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4604                                  Param->getOuterLocStart());
4605     if (Result.isInvalid())
4606       return true;
4607 
4608     // Remember the instantiated default argument.
4609     Param->setDefaultArg(Result.getAs<Expr>());
4610     if (ASTMutationListener *L = getASTMutationListener()) {
4611       L->DefaultArgumentInstantiated(Param);
4612     }
4613   }
4614 
4615   // If the default argument expression is not set yet, we are building it now.
4616   if (!Param->hasInit()) {
4617     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4618     Param->setInvalidDecl();
4619     return true;
4620   }
4621 
4622   // If the default expression creates temporaries, we need to
4623   // push them to the current stack of expression temporaries so they'll
4624   // be properly destroyed.
4625   // FIXME: We should really be rebuilding the default argument with new
4626   // bound temporaries; see the comment in PR5810.
4627   // We don't need to do that with block decls, though, because
4628   // blocks in default argument expression can never capture anything.
4629   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4630     // Set the "needs cleanups" bit regardless of whether there are
4631     // any explicit objects.
4632     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4633 
4634     // Append all the objects to the cleanup list.  Right now, this
4635     // should always be a no-op, because blocks in default argument
4636     // expressions should never be able to capture anything.
4637     assert(!Init->getNumObjects() &&
4638            "default argument expression has capturing blocks?");
4639   }
4640 
4641   // We already type-checked the argument, so we know it works.
4642   // Just mark all of the declarations in this potentially-evaluated expression
4643   // as being "referenced".
4644   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4645                                    /*SkipLocalVariables=*/true);
4646   return false;
4647 }
4648 
4649 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4650                                         FunctionDecl *FD, ParmVarDecl *Param) {
4651   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4652     return ExprError();
4653   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4654 }
4655 
4656 Sema::VariadicCallType
4657 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4658                           Expr *Fn) {
4659   if (Proto && Proto->isVariadic()) {
4660     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4661       return VariadicConstructor;
4662     else if (Fn && Fn->getType()->isBlockPointerType())
4663       return VariadicBlock;
4664     else if (FDecl) {
4665       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4666         if (Method->isInstance())
4667           return VariadicMethod;
4668     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4669       return VariadicMethod;
4670     return VariadicFunction;
4671   }
4672   return VariadicDoesNotApply;
4673 }
4674 
4675 namespace {
4676 class FunctionCallCCC : public FunctionCallFilterCCC {
4677 public:
4678   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4679                   unsigned NumArgs, MemberExpr *ME)
4680       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4681         FunctionName(FuncName) {}
4682 
4683   bool ValidateCandidate(const TypoCorrection &candidate) override {
4684     if (!candidate.getCorrectionSpecifier() ||
4685         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4686       return false;
4687     }
4688 
4689     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4690   }
4691 
4692 private:
4693   const IdentifierInfo *const FunctionName;
4694 };
4695 }
4696 
4697 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4698                                                FunctionDecl *FDecl,
4699                                                ArrayRef<Expr *> Args) {
4700   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4701   DeclarationName FuncName = FDecl->getDeclName();
4702   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4703 
4704   if (TypoCorrection Corrected = S.CorrectTypo(
4705           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4706           S.getScopeForContext(S.CurContext), nullptr,
4707           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4708                                              Args.size(), ME),
4709           Sema::CTK_ErrorRecovery)) {
4710     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4711       if (Corrected.isOverloaded()) {
4712         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4713         OverloadCandidateSet::iterator Best;
4714         for (NamedDecl *CD : Corrected) {
4715           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4716             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4717                                    OCS);
4718         }
4719         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4720         case OR_Success:
4721           ND = Best->FoundDecl;
4722           Corrected.setCorrectionDecl(ND);
4723           break;
4724         default:
4725           break;
4726         }
4727       }
4728       ND = ND->getUnderlyingDecl();
4729       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4730         return Corrected;
4731     }
4732   }
4733   return TypoCorrection();
4734 }
4735 
4736 /// ConvertArgumentsForCall - Converts the arguments specified in
4737 /// Args/NumArgs to the parameter types of the function FDecl with
4738 /// function prototype Proto. Call is the call expression itself, and
4739 /// Fn is the function expression. For a C++ member function, this
4740 /// routine does not attempt to convert the object argument. Returns
4741 /// true if the call is ill-formed.
4742 bool
4743 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4744                               FunctionDecl *FDecl,
4745                               const FunctionProtoType *Proto,
4746                               ArrayRef<Expr *> Args,
4747                               SourceLocation RParenLoc,
4748                               bool IsExecConfig) {
4749   // Bail out early if calling a builtin with custom typechecking.
4750   if (FDecl)
4751     if (unsigned ID = FDecl->getBuiltinID())
4752       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4753         return false;
4754 
4755   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4756   // assignment, to the types of the corresponding parameter, ...
4757   unsigned NumParams = Proto->getNumParams();
4758   bool Invalid = false;
4759   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4760   unsigned FnKind = Fn->getType()->isBlockPointerType()
4761                        ? 1 /* block */
4762                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4763                                        : 0 /* function */);
4764 
4765   // If too few arguments are available (and we don't have default
4766   // arguments for the remaining parameters), don't make the call.
4767   if (Args.size() < NumParams) {
4768     if (Args.size() < MinArgs) {
4769       TypoCorrection TC;
4770       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4771         unsigned diag_id =
4772             MinArgs == NumParams && !Proto->isVariadic()
4773                 ? diag::err_typecheck_call_too_few_args_suggest
4774                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4775         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4776                                         << static_cast<unsigned>(Args.size())
4777                                         << TC.getCorrectionRange());
4778       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4779         Diag(RParenLoc,
4780              MinArgs == NumParams && !Proto->isVariadic()
4781                  ? diag::err_typecheck_call_too_few_args_one
4782                  : diag::err_typecheck_call_too_few_args_at_least_one)
4783             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4784       else
4785         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4786                             ? diag::err_typecheck_call_too_few_args
4787                             : diag::err_typecheck_call_too_few_args_at_least)
4788             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4789             << Fn->getSourceRange();
4790 
4791       // Emit the location of the prototype.
4792       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4793         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4794           << FDecl;
4795 
4796       return true;
4797     }
4798     Call->setNumArgs(Context, NumParams);
4799   }
4800 
4801   // If too many are passed and not variadic, error on the extras and drop
4802   // them.
4803   if (Args.size() > NumParams) {
4804     if (!Proto->isVariadic()) {
4805       TypoCorrection TC;
4806       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4807         unsigned diag_id =
4808             MinArgs == NumParams && !Proto->isVariadic()
4809                 ? diag::err_typecheck_call_too_many_args_suggest
4810                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4811         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4812                                         << static_cast<unsigned>(Args.size())
4813                                         << TC.getCorrectionRange());
4814       } else if (NumParams == 1 && FDecl &&
4815                  FDecl->getParamDecl(0)->getDeclName())
4816         Diag(Args[NumParams]->getLocStart(),
4817              MinArgs == NumParams
4818                  ? diag::err_typecheck_call_too_many_args_one
4819                  : diag::err_typecheck_call_too_many_args_at_most_one)
4820             << FnKind << FDecl->getParamDecl(0)
4821             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4822             << SourceRange(Args[NumParams]->getLocStart(),
4823                            Args.back()->getLocEnd());
4824       else
4825         Diag(Args[NumParams]->getLocStart(),
4826              MinArgs == NumParams
4827                  ? diag::err_typecheck_call_too_many_args
4828                  : diag::err_typecheck_call_too_many_args_at_most)
4829             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4830             << Fn->getSourceRange()
4831             << SourceRange(Args[NumParams]->getLocStart(),
4832                            Args.back()->getLocEnd());
4833 
4834       // Emit the location of the prototype.
4835       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4836         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4837           << FDecl;
4838 
4839       // This deletes the extra arguments.
4840       Call->setNumArgs(Context, NumParams);
4841       return true;
4842     }
4843   }
4844   SmallVector<Expr *, 8> AllArgs;
4845   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4846 
4847   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4848                                    Proto, 0, Args, AllArgs, CallType);
4849   if (Invalid)
4850     return true;
4851   unsigned TotalNumArgs = AllArgs.size();
4852   for (unsigned i = 0; i < TotalNumArgs; ++i)
4853     Call->setArg(i, AllArgs[i]);
4854 
4855   return false;
4856 }
4857 
4858 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4859                                   const FunctionProtoType *Proto,
4860                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4861                                   SmallVectorImpl<Expr *> &AllArgs,
4862                                   VariadicCallType CallType, bool AllowExplicit,
4863                                   bool IsListInitialization) {
4864   unsigned NumParams = Proto->getNumParams();
4865   bool Invalid = false;
4866   size_t ArgIx = 0;
4867   // Continue to check argument types (even if we have too few/many args).
4868   for (unsigned i = FirstParam; i < NumParams; i++) {
4869     QualType ProtoArgType = Proto->getParamType(i);
4870 
4871     Expr *Arg;
4872     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4873     if (ArgIx < Args.size()) {
4874       Arg = Args[ArgIx++];
4875 
4876       if (RequireCompleteType(Arg->getLocStart(),
4877                               ProtoArgType,
4878                               diag::err_call_incomplete_argument, Arg))
4879         return true;
4880 
4881       // Strip the unbridged-cast placeholder expression off, if applicable.
4882       bool CFAudited = false;
4883       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4884           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4885           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4886         Arg = stripARCUnbridgedCast(Arg);
4887       else if (getLangOpts().ObjCAutoRefCount &&
4888                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4889                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4890         CFAudited = true;
4891 
4892       InitializedEntity Entity =
4893           Param ? InitializedEntity::InitializeParameter(Context, Param,
4894                                                          ProtoArgType)
4895                 : InitializedEntity::InitializeParameter(
4896                       Context, ProtoArgType, Proto->isParamConsumed(i));
4897 
4898       // Remember that parameter belongs to a CF audited API.
4899       if (CFAudited)
4900         Entity.setParameterCFAudited();
4901 
4902       ExprResult ArgE = PerformCopyInitialization(
4903           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4904       if (ArgE.isInvalid())
4905         return true;
4906 
4907       Arg = ArgE.getAs<Expr>();
4908     } else {
4909       assert(Param && "can't use default arguments without a known callee");
4910 
4911       ExprResult ArgExpr =
4912         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4913       if (ArgExpr.isInvalid())
4914         return true;
4915 
4916       Arg = ArgExpr.getAs<Expr>();
4917     }
4918 
4919     // Check for array bounds violations for each argument to the call. This
4920     // check only triggers warnings when the argument isn't a more complex Expr
4921     // with its own checking, such as a BinaryOperator.
4922     CheckArrayAccess(Arg);
4923 
4924     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4925     CheckStaticArrayArgument(CallLoc, Param, Arg);
4926 
4927     AllArgs.push_back(Arg);
4928   }
4929 
4930   // If this is a variadic call, handle args passed through "...".
4931   if (CallType != VariadicDoesNotApply) {
4932     // Assume that extern "C" functions with variadic arguments that
4933     // return __unknown_anytype aren't *really* variadic.
4934     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4935         FDecl->isExternC()) {
4936       for (Expr *A : Args.slice(ArgIx)) {
4937         QualType paramType; // ignored
4938         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4939         Invalid |= arg.isInvalid();
4940         AllArgs.push_back(arg.get());
4941       }
4942 
4943     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4944     } else {
4945       for (Expr *A : Args.slice(ArgIx)) {
4946         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4947         Invalid |= Arg.isInvalid();
4948         AllArgs.push_back(Arg.get());
4949       }
4950     }
4951 
4952     // Check for array bounds violations.
4953     for (Expr *A : Args.slice(ArgIx))
4954       CheckArrayAccess(A);
4955   }
4956   return Invalid;
4957 }
4958 
4959 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4960   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4961   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4962     TL = DTL.getOriginalLoc();
4963   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4964     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4965       << ATL.getLocalSourceRange();
4966 }
4967 
4968 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4969 /// array parameter, check that it is non-null, and that if it is formed by
4970 /// array-to-pointer decay, the underlying array is sufficiently large.
4971 ///
4972 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4973 /// array type derivation, then for each call to the function, the value of the
4974 /// corresponding actual argument shall provide access to the first element of
4975 /// an array with at least as many elements as specified by the size expression.
4976 void
4977 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4978                                ParmVarDecl *Param,
4979                                const Expr *ArgExpr) {
4980   // Static array parameters are not supported in C++.
4981   if (!Param || getLangOpts().CPlusPlus)
4982     return;
4983 
4984   QualType OrigTy = Param->getOriginalType();
4985 
4986   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4987   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4988     return;
4989 
4990   if (ArgExpr->isNullPointerConstant(Context,
4991                                      Expr::NPC_NeverValueDependent)) {
4992     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4993     DiagnoseCalleeStaticArrayParam(*this, Param);
4994     return;
4995   }
4996 
4997   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4998   if (!CAT)
4999     return;
5000 
5001   const ConstantArrayType *ArgCAT =
5002     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5003   if (!ArgCAT)
5004     return;
5005 
5006   if (ArgCAT->getSize().ult(CAT->getSize())) {
5007     Diag(CallLoc, diag::warn_static_array_too_small)
5008       << ArgExpr->getSourceRange()
5009       << (unsigned) ArgCAT->getSize().getZExtValue()
5010       << (unsigned) CAT->getSize().getZExtValue();
5011     DiagnoseCalleeStaticArrayParam(*this, Param);
5012   }
5013 }
5014 
5015 /// Given a function expression of unknown-any type, try to rebuild it
5016 /// to have a function type.
5017 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5018 
5019 /// Is the given type a placeholder that we need to lower out
5020 /// immediately during argument processing?
5021 static bool isPlaceholderToRemoveAsArg(QualType type) {
5022   // Placeholders are never sugared.
5023   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5024   if (!placeholder) return false;
5025 
5026   switch (placeholder->getKind()) {
5027   // Ignore all the non-placeholder types.
5028 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5029   case BuiltinType::Id:
5030 #include "clang/Basic/OpenCLImageTypes.def"
5031 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5032 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5033 #include "clang/AST/BuiltinTypes.def"
5034     return false;
5035 
5036   // We cannot lower out overload sets; they might validly be resolved
5037   // by the call machinery.
5038   case BuiltinType::Overload:
5039     return false;
5040 
5041   // Unbridged casts in ARC can be handled in some call positions and
5042   // should be left in place.
5043   case BuiltinType::ARCUnbridgedCast:
5044     return false;
5045 
5046   // Pseudo-objects should be converted as soon as possible.
5047   case BuiltinType::PseudoObject:
5048     return true;
5049 
5050   // The debugger mode could theoretically but currently does not try
5051   // to resolve unknown-typed arguments based on known parameter types.
5052   case BuiltinType::UnknownAny:
5053     return true;
5054 
5055   // These are always invalid as call arguments and should be reported.
5056   case BuiltinType::BoundMember:
5057   case BuiltinType::BuiltinFn:
5058   case BuiltinType::OMPArraySection:
5059     return true;
5060 
5061   }
5062   llvm_unreachable("bad builtin type kind");
5063 }
5064 
5065 /// Check an argument list for placeholders that we won't try to
5066 /// handle later.
5067 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5068   // Apply this processing to all the arguments at once instead of
5069   // dying at the first failure.
5070   bool hasInvalid = false;
5071   for (size_t i = 0, e = args.size(); i != e; i++) {
5072     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5073       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5074       if (result.isInvalid()) hasInvalid = true;
5075       else args[i] = result.get();
5076     } else if (hasInvalid) {
5077       (void)S.CorrectDelayedTyposInExpr(args[i]);
5078     }
5079   }
5080   return hasInvalid;
5081 }
5082 
5083 /// If a builtin function has a pointer argument with no explicit address
5084 /// space, then it should be able to accept a pointer to any address
5085 /// space as input.  In order to do this, we need to replace the
5086 /// standard builtin declaration with one that uses the same address space
5087 /// as the call.
5088 ///
5089 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5090 ///                  it does not contain any pointer arguments without
5091 ///                  an address space qualifer.  Otherwise the rewritten
5092 ///                  FunctionDecl is returned.
5093 /// TODO: Handle pointer return types.
5094 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5095                                                 const FunctionDecl *FDecl,
5096                                                 MultiExprArg ArgExprs) {
5097 
5098   QualType DeclType = FDecl->getType();
5099   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5100 
5101   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5102       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5103     return nullptr;
5104 
5105   bool NeedsNewDecl = false;
5106   unsigned i = 0;
5107   SmallVector<QualType, 8> OverloadParams;
5108 
5109   for (QualType ParamType : FT->param_types()) {
5110 
5111     // Convert array arguments to pointer to simplify type lookup.
5112     ExprResult ArgRes =
5113         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5114     if (ArgRes.isInvalid())
5115       return nullptr;
5116     Expr *Arg = ArgRes.get();
5117     QualType ArgType = Arg->getType();
5118     if (!ParamType->isPointerType() ||
5119         ParamType.getQualifiers().hasAddressSpace() ||
5120         !ArgType->isPointerType() ||
5121         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5122       OverloadParams.push_back(ParamType);
5123       continue;
5124     }
5125 
5126     NeedsNewDecl = true;
5127     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5128 
5129     QualType PointeeType = ParamType->getPointeeType();
5130     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5131     OverloadParams.push_back(Context.getPointerType(PointeeType));
5132   }
5133 
5134   if (!NeedsNewDecl)
5135     return nullptr;
5136 
5137   FunctionProtoType::ExtProtoInfo EPI;
5138   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5139                                                 OverloadParams, EPI);
5140   DeclContext *Parent = Context.getTranslationUnitDecl();
5141   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5142                                                     FDecl->getLocation(),
5143                                                     FDecl->getLocation(),
5144                                                     FDecl->getIdentifier(),
5145                                                     OverloadTy,
5146                                                     /*TInfo=*/nullptr,
5147                                                     SC_Extern, false,
5148                                                     /*hasPrototype=*/true);
5149   SmallVector<ParmVarDecl*, 16> Params;
5150   FT = cast<FunctionProtoType>(OverloadTy);
5151   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5152     QualType ParamType = FT->getParamType(i);
5153     ParmVarDecl *Parm =
5154         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5155                                 SourceLocation(), nullptr, ParamType,
5156                                 /*TInfo=*/nullptr, SC_None, nullptr);
5157     Parm->setScopeInfo(0, i);
5158     Params.push_back(Parm);
5159   }
5160   OverloadDecl->setParams(Params);
5161   return OverloadDecl;
5162 }
5163 
5164 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5165                                     FunctionDecl *Callee,
5166                                     MultiExprArg ArgExprs) {
5167   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5168   // similar attributes) really don't like it when functions are called with an
5169   // invalid number of args.
5170   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5171                          /*PartialOverloading=*/false) &&
5172       !Callee->isVariadic())
5173     return;
5174   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5175     return;
5176 
5177   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5178     S.Diag(Fn->getLocStart(),
5179            isa<CXXMethodDecl>(Callee)
5180                ? diag::err_ovl_no_viable_member_function_in_call
5181                : diag::err_ovl_no_viable_function_in_call)
5182         << Callee << Callee->getSourceRange();
5183     S.Diag(Callee->getLocation(),
5184            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5185         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5186     return;
5187   }
5188 }
5189 
5190 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5191 /// This provides the location of the left/right parens and a list of comma
5192 /// locations.
5193 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5194                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5195                                Expr *ExecConfig, bool IsExecConfig) {
5196   // Since this might be a postfix expression, get rid of ParenListExprs.
5197   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5198   if (Result.isInvalid()) return ExprError();
5199   Fn = Result.get();
5200 
5201   if (checkArgsForPlaceholders(*this, ArgExprs))
5202     return ExprError();
5203 
5204   if (getLangOpts().CPlusPlus) {
5205     // If this is a pseudo-destructor expression, build the call immediately.
5206     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5207       if (!ArgExprs.empty()) {
5208         // Pseudo-destructor calls should not have any arguments.
5209         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5210             << FixItHint::CreateRemoval(
5211                    SourceRange(ArgExprs.front()->getLocStart(),
5212                                ArgExprs.back()->getLocEnd()));
5213       }
5214 
5215       return new (Context)
5216           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5217     }
5218     if (Fn->getType() == Context.PseudoObjectTy) {
5219       ExprResult result = CheckPlaceholderExpr(Fn);
5220       if (result.isInvalid()) return ExprError();
5221       Fn = result.get();
5222     }
5223 
5224     // Determine whether this is a dependent call inside a C++ template,
5225     // in which case we won't do any semantic analysis now.
5226     bool Dependent = false;
5227     if (Fn->isTypeDependent())
5228       Dependent = true;
5229     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5230       Dependent = true;
5231 
5232     if (Dependent) {
5233       if (ExecConfig) {
5234         return new (Context) CUDAKernelCallExpr(
5235             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5236             Context.DependentTy, VK_RValue, RParenLoc);
5237       } else {
5238         return new (Context) CallExpr(
5239             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5240       }
5241     }
5242 
5243     // Determine whether this is a call to an object (C++ [over.call.object]).
5244     if (Fn->getType()->isRecordType())
5245       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5246                                           RParenLoc);
5247 
5248     if (Fn->getType() == Context.UnknownAnyTy) {
5249       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5250       if (result.isInvalid()) return ExprError();
5251       Fn = result.get();
5252     }
5253 
5254     if (Fn->getType() == Context.BoundMemberTy) {
5255       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5256                                        RParenLoc);
5257     }
5258   }
5259 
5260   // Check for overloaded calls.  This can happen even in C due to extensions.
5261   if (Fn->getType() == Context.OverloadTy) {
5262     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5263 
5264     // We aren't supposed to apply this logic for if there'Scope an '&'
5265     // involved.
5266     if (!find.HasFormOfMemberPointer) {
5267       OverloadExpr *ovl = find.Expression;
5268       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5269         return BuildOverloadedCallExpr(
5270             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5271             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5272       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5273                                        RParenLoc);
5274     }
5275   }
5276 
5277   // If we're directly calling a function, get the appropriate declaration.
5278   if (Fn->getType() == Context.UnknownAnyTy) {
5279     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5280     if (result.isInvalid()) return ExprError();
5281     Fn = result.get();
5282   }
5283 
5284   Expr *NakedFn = Fn->IgnoreParens();
5285 
5286   bool CallingNDeclIndirectly = false;
5287   NamedDecl *NDecl = nullptr;
5288   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5289     if (UnOp->getOpcode() == UO_AddrOf) {
5290       CallingNDeclIndirectly = true;
5291       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5292     }
5293   }
5294 
5295   if (isa<DeclRefExpr>(NakedFn)) {
5296     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5297 
5298     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5299     if (FDecl && FDecl->getBuiltinID()) {
5300       // Rewrite the function decl for this builtin by replacing parameters
5301       // with no explicit address space with the address space of the arguments
5302       // in ArgExprs.
5303       if ((FDecl =
5304                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5305         NDecl = FDecl;
5306         Fn = DeclRefExpr::Create(
5307             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5308             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5309       }
5310     }
5311   } else if (isa<MemberExpr>(NakedFn))
5312     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5313 
5314   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5315     if (CallingNDeclIndirectly &&
5316         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5317                                            Fn->getLocStart()))
5318       return ExprError();
5319 
5320     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5321       return ExprError();
5322 
5323     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5324   }
5325 
5326   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5327                                ExecConfig, IsExecConfig);
5328 }
5329 
5330 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5331 ///
5332 /// __builtin_astype( value, dst type )
5333 ///
5334 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5335                                  SourceLocation BuiltinLoc,
5336                                  SourceLocation RParenLoc) {
5337   ExprValueKind VK = VK_RValue;
5338   ExprObjectKind OK = OK_Ordinary;
5339   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5340   QualType SrcTy = E->getType();
5341   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5342     return ExprError(Diag(BuiltinLoc,
5343                           diag::err_invalid_astype_of_different_size)
5344                      << DstTy
5345                      << SrcTy
5346                      << E->getSourceRange());
5347   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5348 }
5349 
5350 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5351 /// provided arguments.
5352 ///
5353 /// __builtin_convertvector( value, dst type )
5354 ///
5355 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5356                                         SourceLocation BuiltinLoc,
5357                                         SourceLocation RParenLoc) {
5358   TypeSourceInfo *TInfo;
5359   GetTypeFromParser(ParsedDestTy, &TInfo);
5360   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5361 }
5362 
5363 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5364 /// i.e. an expression not of \p OverloadTy.  The expression should
5365 /// unary-convert to an expression of function-pointer or
5366 /// block-pointer type.
5367 ///
5368 /// \param NDecl the declaration being called, if available
5369 ExprResult
5370 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5371                             SourceLocation LParenLoc,
5372                             ArrayRef<Expr *> Args,
5373                             SourceLocation RParenLoc,
5374                             Expr *Config, bool IsExecConfig) {
5375   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5376   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5377 
5378   // Functions with 'interrupt' attribute cannot be called directly.
5379   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5380     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5381     return ExprError();
5382   }
5383 
5384   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5385   // so there's some risk when calling out to non-interrupt handler functions
5386   // that the callee might not preserve them. This is easy to diagnose here,
5387   // but can be very challenging to debug.
5388   if (auto *Caller = getCurFunctionDecl())
5389     if (Caller->hasAttr<ARMInterruptAttr>())
5390       if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())
5391         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5392 
5393   // Promote the function operand.
5394   // We special-case function promotion here because we only allow promoting
5395   // builtin functions to function pointers in the callee of a call.
5396   ExprResult Result;
5397   if (BuiltinID &&
5398       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5399     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5400                                CK_BuiltinFnToFnPtr).get();
5401   } else {
5402     Result = CallExprUnaryConversions(Fn);
5403   }
5404   if (Result.isInvalid())
5405     return ExprError();
5406   Fn = Result.get();
5407 
5408   // Make the call expr early, before semantic checks.  This guarantees cleanup
5409   // of arguments and function on error.
5410   CallExpr *TheCall;
5411   if (Config)
5412     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5413                                                cast<CallExpr>(Config), Args,
5414                                                Context.BoolTy, VK_RValue,
5415                                                RParenLoc);
5416   else
5417     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5418                                      VK_RValue, RParenLoc);
5419 
5420   if (!getLangOpts().CPlusPlus) {
5421     // C cannot always handle TypoExpr nodes in builtin calls and direct
5422     // function calls as their argument checking don't necessarily handle
5423     // dependent types properly, so make sure any TypoExprs have been
5424     // dealt with.
5425     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5426     if (!Result.isUsable()) return ExprError();
5427     TheCall = dyn_cast<CallExpr>(Result.get());
5428     if (!TheCall) return Result;
5429     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5430   }
5431 
5432   // Bail out early if calling a builtin with custom typechecking.
5433   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5434     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5435 
5436  retry:
5437   const FunctionType *FuncT;
5438   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5439     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5440     // have type pointer to function".
5441     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5442     if (!FuncT)
5443       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5444                          << Fn->getType() << Fn->getSourceRange());
5445   } else if (const BlockPointerType *BPT =
5446                Fn->getType()->getAs<BlockPointerType>()) {
5447     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5448   } else {
5449     // Handle calls to expressions of unknown-any type.
5450     if (Fn->getType() == Context.UnknownAnyTy) {
5451       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5452       if (rewrite.isInvalid()) return ExprError();
5453       Fn = rewrite.get();
5454       TheCall->setCallee(Fn);
5455       goto retry;
5456     }
5457 
5458     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5459       << Fn->getType() << Fn->getSourceRange());
5460   }
5461 
5462   if (getLangOpts().CUDA) {
5463     if (Config) {
5464       // CUDA: Kernel calls must be to global functions
5465       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5466         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5467             << FDecl->getName() << Fn->getSourceRange());
5468 
5469       // CUDA: Kernel function must have 'void' return type
5470       if (!FuncT->getReturnType()->isVoidType())
5471         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5472             << Fn->getType() << Fn->getSourceRange());
5473     } else {
5474       // CUDA: Calls to global functions must be configured
5475       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5476         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5477             << FDecl->getName() << Fn->getSourceRange());
5478     }
5479   }
5480 
5481   // Check for a valid return type
5482   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5483                           FDecl))
5484     return ExprError();
5485 
5486   // We know the result type of the call, set it.
5487   TheCall->setType(FuncT->getCallResultType(Context));
5488   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5489 
5490   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5491   if (Proto) {
5492     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5493                                 IsExecConfig))
5494       return ExprError();
5495   } else {
5496     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5497 
5498     if (FDecl) {
5499       // Check if we have too few/too many template arguments, based
5500       // on our knowledge of the function definition.
5501       const FunctionDecl *Def = nullptr;
5502       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5503         Proto = Def->getType()->getAs<FunctionProtoType>();
5504        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5505           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5506           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5507       }
5508 
5509       // If the function we're calling isn't a function prototype, but we have
5510       // a function prototype from a prior declaratiom, use that prototype.
5511       if (!FDecl->hasPrototype())
5512         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5513     }
5514 
5515     // Promote the arguments (C99 6.5.2.2p6).
5516     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5517       Expr *Arg = Args[i];
5518 
5519       if (Proto && i < Proto->getNumParams()) {
5520         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5521             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5522         ExprResult ArgE =
5523             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5524         if (ArgE.isInvalid())
5525           return true;
5526 
5527         Arg = ArgE.getAs<Expr>();
5528 
5529       } else {
5530         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5531 
5532         if (ArgE.isInvalid())
5533           return true;
5534 
5535         Arg = ArgE.getAs<Expr>();
5536       }
5537 
5538       if (RequireCompleteType(Arg->getLocStart(),
5539                               Arg->getType(),
5540                               diag::err_call_incomplete_argument, Arg))
5541         return ExprError();
5542 
5543       TheCall->setArg(i, Arg);
5544     }
5545   }
5546 
5547   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5548     if (!Method->isStatic())
5549       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5550         << Fn->getSourceRange());
5551 
5552   // Check for sentinels
5553   if (NDecl)
5554     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5555 
5556   // Do special checking on direct calls to functions.
5557   if (FDecl) {
5558     if (CheckFunctionCall(FDecl, TheCall, Proto))
5559       return ExprError();
5560 
5561     if (BuiltinID)
5562       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5563   } else if (NDecl) {
5564     if (CheckPointerCall(NDecl, TheCall, Proto))
5565       return ExprError();
5566   } else {
5567     if (CheckOtherCall(TheCall, Proto))
5568       return ExprError();
5569   }
5570 
5571   return MaybeBindToTemporary(TheCall);
5572 }
5573 
5574 ExprResult
5575 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5576                            SourceLocation RParenLoc, Expr *InitExpr) {
5577   assert(Ty && "ActOnCompoundLiteral(): missing type");
5578   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5579 
5580   TypeSourceInfo *TInfo;
5581   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5582   if (!TInfo)
5583     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5584 
5585   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5586 }
5587 
5588 ExprResult
5589 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5590                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5591   QualType literalType = TInfo->getType();
5592 
5593   if (literalType->isArrayType()) {
5594     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5595           diag::err_illegal_decl_array_incomplete_type,
5596           SourceRange(LParenLoc,
5597                       LiteralExpr->getSourceRange().getEnd())))
5598       return ExprError();
5599     if (literalType->isVariableArrayType())
5600       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5601         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5602   } else if (!literalType->isDependentType() &&
5603              RequireCompleteType(LParenLoc, literalType,
5604                diag::err_typecheck_decl_incomplete_type,
5605                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5606     return ExprError();
5607 
5608   InitializedEntity Entity
5609     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5610   InitializationKind Kind
5611     = InitializationKind::CreateCStyleCast(LParenLoc,
5612                                            SourceRange(LParenLoc, RParenLoc),
5613                                            /*InitList=*/true);
5614   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5615   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5616                                       &literalType);
5617   if (Result.isInvalid())
5618     return ExprError();
5619   LiteralExpr = Result.get();
5620 
5621   bool isFileScope = !CurContext->isFunctionOrMethod();
5622   if (isFileScope &&
5623       !LiteralExpr->isTypeDependent() &&
5624       !LiteralExpr->isValueDependent() &&
5625       !literalType->isDependentType()) { // 6.5.2.5p3
5626     if (CheckForConstantInitializer(LiteralExpr, literalType))
5627       return ExprError();
5628   }
5629 
5630   // In C, compound literals are l-values for some reason.
5631   // For GCC compatibility, in C++, file-scope array compound literals with
5632   // constant initializers are also l-values, and compound literals are
5633   // otherwise prvalues.
5634   //
5635   // (GCC also treats C++ list-initialized file-scope array prvalues with
5636   // constant initializers as l-values, but that's non-conforming, so we don't
5637   // follow it there.)
5638   //
5639   // FIXME: It would be better to handle the lvalue cases as materializing and
5640   // lifetime-extending a temporary object, but our materialized temporaries
5641   // representation only supports lifetime extension from a variable, not "out
5642   // of thin air".
5643   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5644   // is bound to the result of applying array-to-pointer decay to the compound
5645   // literal.
5646   // FIXME: GCC supports compound literals of reference type, which should
5647   // obviously have a value kind derived from the kind of reference involved.
5648   ExprValueKind VK =
5649       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5650           ? VK_RValue
5651           : VK_LValue;
5652 
5653   return MaybeBindToTemporary(
5654       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5655                                         VK, LiteralExpr, isFileScope));
5656 }
5657 
5658 ExprResult
5659 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5660                     SourceLocation RBraceLoc) {
5661   // Immediately handle non-overload placeholders.  Overloads can be
5662   // resolved contextually, but everything else here can't.
5663   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5664     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5665       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5666 
5667       // Ignore failures; dropping the entire initializer list because
5668       // of one failure would be terrible for indexing/etc.
5669       if (result.isInvalid()) continue;
5670 
5671       InitArgList[I] = result.get();
5672     }
5673   }
5674 
5675   // Semantic analysis for initializers is done by ActOnDeclarator() and
5676   // CheckInitializer() - it requires knowledge of the object being intialized.
5677 
5678   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5679                                                RBraceLoc);
5680   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5681   return E;
5682 }
5683 
5684 /// Do an explicit extend of the given block pointer if we're in ARC.
5685 void Sema::maybeExtendBlockObject(ExprResult &E) {
5686   assert(E.get()->getType()->isBlockPointerType());
5687   assert(E.get()->isRValue());
5688 
5689   // Only do this in an r-value context.
5690   if (!getLangOpts().ObjCAutoRefCount) return;
5691 
5692   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5693                                CK_ARCExtendBlockObject, E.get(),
5694                                /*base path*/ nullptr, VK_RValue);
5695   Cleanup.setExprNeedsCleanups(true);
5696 }
5697 
5698 /// Prepare a conversion of the given expression to an ObjC object
5699 /// pointer type.
5700 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5701   QualType type = E.get()->getType();
5702   if (type->isObjCObjectPointerType()) {
5703     return CK_BitCast;
5704   } else if (type->isBlockPointerType()) {
5705     maybeExtendBlockObject(E);
5706     return CK_BlockPointerToObjCPointerCast;
5707   } else {
5708     assert(type->isPointerType());
5709     return CK_CPointerToObjCPointerCast;
5710   }
5711 }
5712 
5713 /// Prepares for a scalar cast, performing all the necessary stages
5714 /// except the final cast and returning the kind required.
5715 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5716   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5717   // Also, callers should have filtered out the invalid cases with
5718   // pointers.  Everything else should be possible.
5719 
5720   QualType SrcTy = Src.get()->getType();
5721   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5722     return CK_NoOp;
5723 
5724   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5725   case Type::STK_MemberPointer:
5726     llvm_unreachable("member pointer type in C");
5727 
5728   case Type::STK_CPointer:
5729   case Type::STK_BlockPointer:
5730   case Type::STK_ObjCObjectPointer:
5731     switch (DestTy->getScalarTypeKind()) {
5732     case Type::STK_CPointer: {
5733       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5734       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5735       if (SrcAS != DestAS)
5736         return CK_AddressSpaceConversion;
5737       return CK_BitCast;
5738     }
5739     case Type::STK_BlockPointer:
5740       return (SrcKind == Type::STK_BlockPointer
5741                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5742     case Type::STK_ObjCObjectPointer:
5743       if (SrcKind == Type::STK_ObjCObjectPointer)
5744         return CK_BitCast;
5745       if (SrcKind == Type::STK_CPointer)
5746         return CK_CPointerToObjCPointerCast;
5747       maybeExtendBlockObject(Src);
5748       return CK_BlockPointerToObjCPointerCast;
5749     case Type::STK_Bool:
5750       return CK_PointerToBoolean;
5751     case Type::STK_Integral:
5752       return CK_PointerToIntegral;
5753     case Type::STK_Floating:
5754     case Type::STK_FloatingComplex:
5755     case Type::STK_IntegralComplex:
5756     case Type::STK_MemberPointer:
5757       llvm_unreachable("illegal cast from pointer");
5758     }
5759     llvm_unreachable("Should have returned before this");
5760 
5761   case Type::STK_Bool: // casting from bool is like casting from an integer
5762   case Type::STK_Integral:
5763     switch (DestTy->getScalarTypeKind()) {
5764     case Type::STK_CPointer:
5765     case Type::STK_ObjCObjectPointer:
5766     case Type::STK_BlockPointer:
5767       if (Src.get()->isNullPointerConstant(Context,
5768                                            Expr::NPC_ValueDependentIsNull))
5769         return CK_NullToPointer;
5770       return CK_IntegralToPointer;
5771     case Type::STK_Bool:
5772       return CK_IntegralToBoolean;
5773     case Type::STK_Integral:
5774       return CK_IntegralCast;
5775     case Type::STK_Floating:
5776       return CK_IntegralToFloating;
5777     case Type::STK_IntegralComplex:
5778       Src = ImpCastExprToType(Src.get(),
5779                       DestTy->castAs<ComplexType>()->getElementType(),
5780                       CK_IntegralCast);
5781       return CK_IntegralRealToComplex;
5782     case Type::STK_FloatingComplex:
5783       Src = ImpCastExprToType(Src.get(),
5784                       DestTy->castAs<ComplexType>()->getElementType(),
5785                       CK_IntegralToFloating);
5786       return CK_FloatingRealToComplex;
5787     case Type::STK_MemberPointer:
5788       llvm_unreachable("member pointer type in C");
5789     }
5790     llvm_unreachable("Should have returned before this");
5791 
5792   case Type::STK_Floating:
5793     switch (DestTy->getScalarTypeKind()) {
5794     case Type::STK_Floating:
5795       return CK_FloatingCast;
5796     case Type::STK_Bool:
5797       return CK_FloatingToBoolean;
5798     case Type::STK_Integral:
5799       return CK_FloatingToIntegral;
5800     case Type::STK_FloatingComplex:
5801       Src = ImpCastExprToType(Src.get(),
5802                               DestTy->castAs<ComplexType>()->getElementType(),
5803                               CK_FloatingCast);
5804       return CK_FloatingRealToComplex;
5805     case Type::STK_IntegralComplex:
5806       Src = ImpCastExprToType(Src.get(),
5807                               DestTy->castAs<ComplexType>()->getElementType(),
5808                               CK_FloatingToIntegral);
5809       return CK_IntegralRealToComplex;
5810     case Type::STK_CPointer:
5811     case Type::STK_ObjCObjectPointer:
5812     case Type::STK_BlockPointer:
5813       llvm_unreachable("valid float->pointer cast?");
5814     case Type::STK_MemberPointer:
5815       llvm_unreachable("member pointer type in C");
5816     }
5817     llvm_unreachable("Should have returned before this");
5818 
5819   case Type::STK_FloatingComplex:
5820     switch (DestTy->getScalarTypeKind()) {
5821     case Type::STK_FloatingComplex:
5822       return CK_FloatingComplexCast;
5823     case Type::STK_IntegralComplex:
5824       return CK_FloatingComplexToIntegralComplex;
5825     case Type::STK_Floating: {
5826       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5827       if (Context.hasSameType(ET, DestTy))
5828         return CK_FloatingComplexToReal;
5829       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5830       return CK_FloatingCast;
5831     }
5832     case Type::STK_Bool:
5833       return CK_FloatingComplexToBoolean;
5834     case Type::STK_Integral:
5835       Src = ImpCastExprToType(Src.get(),
5836                               SrcTy->castAs<ComplexType>()->getElementType(),
5837                               CK_FloatingComplexToReal);
5838       return CK_FloatingToIntegral;
5839     case Type::STK_CPointer:
5840     case Type::STK_ObjCObjectPointer:
5841     case Type::STK_BlockPointer:
5842       llvm_unreachable("valid complex float->pointer cast?");
5843     case Type::STK_MemberPointer:
5844       llvm_unreachable("member pointer type in C");
5845     }
5846     llvm_unreachable("Should have returned before this");
5847 
5848   case Type::STK_IntegralComplex:
5849     switch (DestTy->getScalarTypeKind()) {
5850     case Type::STK_FloatingComplex:
5851       return CK_IntegralComplexToFloatingComplex;
5852     case Type::STK_IntegralComplex:
5853       return CK_IntegralComplexCast;
5854     case Type::STK_Integral: {
5855       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5856       if (Context.hasSameType(ET, DestTy))
5857         return CK_IntegralComplexToReal;
5858       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5859       return CK_IntegralCast;
5860     }
5861     case Type::STK_Bool:
5862       return CK_IntegralComplexToBoolean;
5863     case Type::STK_Floating:
5864       Src = ImpCastExprToType(Src.get(),
5865                               SrcTy->castAs<ComplexType>()->getElementType(),
5866                               CK_IntegralComplexToReal);
5867       return CK_IntegralToFloating;
5868     case Type::STK_CPointer:
5869     case Type::STK_ObjCObjectPointer:
5870     case Type::STK_BlockPointer:
5871       llvm_unreachable("valid complex int->pointer cast?");
5872     case Type::STK_MemberPointer:
5873       llvm_unreachable("member pointer type in C");
5874     }
5875     llvm_unreachable("Should have returned before this");
5876   }
5877 
5878   llvm_unreachable("Unhandled scalar cast");
5879 }
5880 
5881 static bool breakDownVectorType(QualType type, uint64_t &len,
5882                                 QualType &eltType) {
5883   // Vectors are simple.
5884   if (const VectorType *vecType = type->getAs<VectorType>()) {
5885     len = vecType->getNumElements();
5886     eltType = vecType->getElementType();
5887     assert(eltType->isScalarType());
5888     return true;
5889   }
5890 
5891   // We allow lax conversion to and from non-vector types, but only if
5892   // they're real types (i.e. non-complex, non-pointer scalar types).
5893   if (!type->isRealType()) return false;
5894 
5895   len = 1;
5896   eltType = type;
5897   return true;
5898 }
5899 
5900 /// Are the two types lax-compatible vector types?  That is, given
5901 /// that one of them is a vector, do they have equal storage sizes,
5902 /// where the storage size is the number of elements times the element
5903 /// size?
5904 ///
5905 /// This will also return false if either of the types is neither a
5906 /// vector nor a real type.
5907 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5908   assert(destTy->isVectorType() || srcTy->isVectorType());
5909 
5910   // Disallow lax conversions between scalars and ExtVectors (these
5911   // conversions are allowed for other vector types because common headers
5912   // depend on them).  Most scalar OP ExtVector cases are handled by the
5913   // splat path anyway, which does what we want (convert, not bitcast).
5914   // What this rules out for ExtVectors is crazy things like char4*float.
5915   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5916   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5917 
5918   uint64_t srcLen, destLen;
5919   QualType srcEltTy, destEltTy;
5920   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5921   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5922 
5923   // ASTContext::getTypeSize will return the size rounded up to a
5924   // power of 2, so instead of using that, we need to use the raw
5925   // element size multiplied by the element count.
5926   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5927   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5928 
5929   return (srcLen * srcEltSize == destLen * destEltSize);
5930 }
5931 
5932 /// Is this a legal conversion between two types, one of which is
5933 /// known to be a vector type?
5934 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5935   assert(destTy->isVectorType() || srcTy->isVectorType());
5936 
5937   if (!Context.getLangOpts().LaxVectorConversions)
5938     return false;
5939   return areLaxCompatibleVectorTypes(srcTy, destTy);
5940 }
5941 
5942 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5943                            CastKind &Kind) {
5944   assert(VectorTy->isVectorType() && "Not a vector type!");
5945 
5946   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5947     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5948       return Diag(R.getBegin(),
5949                   Ty->isVectorType() ?
5950                   diag::err_invalid_conversion_between_vectors :
5951                   diag::err_invalid_conversion_between_vector_and_integer)
5952         << VectorTy << Ty << R;
5953   } else
5954     return Diag(R.getBegin(),
5955                 diag::err_invalid_conversion_between_vector_and_scalar)
5956       << VectorTy << Ty << R;
5957 
5958   Kind = CK_BitCast;
5959   return false;
5960 }
5961 
5962 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5963   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5964 
5965   if (DestElemTy == SplattedExpr->getType())
5966     return SplattedExpr;
5967 
5968   assert(DestElemTy->isFloatingType() ||
5969          DestElemTy->isIntegralOrEnumerationType());
5970 
5971   CastKind CK;
5972   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5973     // OpenCL requires that we convert `true` boolean expressions to -1, but
5974     // only when splatting vectors.
5975     if (DestElemTy->isFloatingType()) {
5976       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5977       // in two steps: boolean to signed integral, then to floating.
5978       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5979                                                  CK_BooleanToSignedIntegral);
5980       SplattedExpr = CastExprRes.get();
5981       CK = CK_IntegralToFloating;
5982     } else {
5983       CK = CK_BooleanToSignedIntegral;
5984     }
5985   } else {
5986     ExprResult CastExprRes = SplattedExpr;
5987     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5988     if (CastExprRes.isInvalid())
5989       return ExprError();
5990     SplattedExpr = CastExprRes.get();
5991   }
5992   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5993 }
5994 
5995 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5996                                     Expr *CastExpr, CastKind &Kind) {
5997   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5998 
5999   QualType SrcTy = CastExpr->getType();
6000 
6001   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6002   // an ExtVectorType.
6003   // In OpenCL, casts between vectors of different types are not allowed.
6004   // (See OpenCL 6.2).
6005   if (SrcTy->isVectorType()) {
6006     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6007         || (getLangOpts().OpenCL &&
6008             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6009       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6010         << DestTy << SrcTy << R;
6011       return ExprError();
6012     }
6013     Kind = CK_BitCast;
6014     return CastExpr;
6015   }
6016 
6017   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6018   // conversion will take place first from scalar to elt type, and then
6019   // splat from elt type to vector.
6020   if (SrcTy->isPointerType())
6021     return Diag(R.getBegin(),
6022                 diag::err_invalid_conversion_between_vector_and_scalar)
6023       << DestTy << SrcTy << R;
6024 
6025   Kind = CK_VectorSplat;
6026   return prepareVectorSplat(DestTy, CastExpr);
6027 }
6028 
6029 ExprResult
6030 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6031                     Declarator &D, ParsedType &Ty,
6032                     SourceLocation RParenLoc, Expr *CastExpr) {
6033   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6034          "ActOnCastExpr(): missing type or expr");
6035 
6036   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6037   if (D.isInvalidType())
6038     return ExprError();
6039 
6040   if (getLangOpts().CPlusPlus) {
6041     // Check that there are no default arguments (C++ only).
6042     CheckExtraCXXDefaultArguments(D);
6043   } else {
6044     // Make sure any TypoExprs have been dealt with.
6045     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6046     if (!Res.isUsable())
6047       return ExprError();
6048     CastExpr = Res.get();
6049   }
6050 
6051   checkUnusedDeclAttributes(D);
6052 
6053   QualType castType = castTInfo->getType();
6054   Ty = CreateParsedType(castType, castTInfo);
6055 
6056   bool isVectorLiteral = false;
6057 
6058   // Check for an altivec or OpenCL literal,
6059   // i.e. all the elements are integer constants.
6060   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6061   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6062   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6063        && castType->isVectorType() && (PE || PLE)) {
6064     if (PLE && PLE->getNumExprs() == 0) {
6065       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6066       return ExprError();
6067     }
6068     if (PE || PLE->getNumExprs() == 1) {
6069       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6070       if (!E->getType()->isVectorType())
6071         isVectorLiteral = true;
6072     }
6073     else
6074       isVectorLiteral = true;
6075   }
6076 
6077   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6078   // then handle it as such.
6079   if (isVectorLiteral)
6080     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6081 
6082   // If the Expr being casted is a ParenListExpr, handle it specially.
6083   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6084   // sequence of BinOp comma operators.
6085   if (isa<ParenListExpr>(CastExpr)) {
6086     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6087     if (Result.isInvalid()) return ExprError();
6088     CastExpr = Result.get();
6089   }
6090 
6091   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6092       !getSourceManager().isInSystemMacro(LParenLoc))
6093     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6094 
6095   CheckTollFreeBridgeCast(castType, CastExpr);
6096 
6097   CheckObjCBridgeRelatedCast(castType, CastExpr);
6098 
6099   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6100 
6101   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6102 }
6103 
6104 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6105                                     SourceLocation RParenLoc, Expr *E,
6106                                     TypeSourceInfo *TInfo) {
6107   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6108          "Expected paren or paren list expression");
6109 
6110   Expr **exprs;
6111   unsigned numExprs;
6112   Expr *subExpr;
6113   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6114   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6115     LiteralLParenLoc = PE->getLParenLoc();
6116     LiteralRParenLoc = PE->getRParenLoc();
6117     exprs = PE->getExprs();
6118     numExprs = PE->getNumExprs();
6119   } else { // isa<ParenExpr> by assertion at function entrance
6120     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6121     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6122     subExpr = cast<ParenExpr>(E)->getSubExpr();
6123     exprs = &subExpr;
6124     numExprs = 1;
6125   }
6126 
6127   QualType Ty = TInfo->getType();
6128   assert(Ty->isVectorType() && "Expected vector type");
6129 
6130   SmallVector<Expr *, 8> initExprs;
6131   const VectorType *VTy = Ty->getAs<VectorType>();
6132   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6133 
6134   // '(...)' form of vector initialization in AltiVec: the number of
6135   // initializers must be one or must match the size of the vector.
6136   // If a single value is specified in the initializer then it will be
6137   // replicated to all the components of the vector
6138   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6139     // The number of initializers must be one or must match the size of the
6140     // vector. If a single value is specified in the initializer then it will
6141     // be replicated to all the components of the vector
6142     if (numExprs == 1) {
6143       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6144       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6145       if (Literal.isInvalid())
6146         return ExprError();
6147       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6148                                   PrepareScalarCast(Literal, ElemTy));
6149       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6150     }
6151     else if (numExprs < numElems) {
6152       Diag(E->getExprLoc(),
6153            diag::err_incorrect_number_of_vector_initializers);
6154       return ExprError();
6155     }
6156     else
6157       initExprs.append(exprs, exprs + numExprs);
6158   }
6159   else {
6160     // For OpenCL, when the number of initializers is a single value,
6161     // it will be replicated to all components of the vector.
6162     if (getLangOpts().OpenCL &&
6163         VTy->getVectorKind() == VectorType::GenericVector &&
6164         numExprs == 1) {
6165         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6166         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6167         if (Literal.isInvalid())
6168           return ExprError();
6169         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6170                                     PrepareScalarCast(Literal, ElemTy));
6171         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6172     }
6173 
6174     initExprs.append(exprs, exprs + numExprs);
6175   }
6176   // FIXME: This means that pretty-printing the final AST will produce curly
6177   // braces instead of the original commas.
6178   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6179                                                    initExprs, LiteralRParenLoc);
6180   initE->setType(Ty);
6181   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6182 }
6183 
6184 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6185 /// the ParenListExpr into a sequence of comma binary operators.
6186 ExprResult
6187 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6188   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6189   if (!E)
6190     return OrigExpr;
6191 
6192   ExprResult Result(E->getExpr(0));
6193 
6194   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6195     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6196                         E->getExpr(i));
6197 
6198   if (Result.isInvalid()) return ExprError();
6199 
6200   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6201 }
6202 
6203 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6204                                     SourceLocation R,
6205                                     MultiExprArg Val) {
6206   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6207   return expr;
6208 }
6209 
6210 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6211 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6212 /// emitted.
6213 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6214                                       SourceLocation QuestionLoc) {
6215   Expr *NullExpr = LHSExpr;
6216   Expr *NonPointerExpr = RHSExpr;
6217   Expr::NullPointerConstantKind NullKind =
6218       NullExpr->isNullPointerConstant(Context,
6219                                       Expr::NPC_ValueDependentIsNotNull);
6220 
6221   if (NullKind == Expr::NPCK_NotNull) {
6222     NullExpr = RHSExpr;
6223     NonPointerExpr = LHSExpr;
6224     NullKind =
6225         NullExpr->isNullPointerConstant(Context,
6226                                         Expr::NPC_ValueDependentIsNotNull);
6227   }
6228 
6229   if (NullKind == Expr::NPCK_NotNull)
6230     return false;
6231 
6232   if (NullKind == Expr::NPCK_ZeroExpression)
6233     return false;
6234 
6235   if (NullKind == Expr::NPCK_ZeroLiteral) {
6236     // In this case, check to make sure that we got here from a "NULL"
6237     // string in the source code.
6238     NullExpr = NullExpr->IgnoreParenImpCasts();
6239     SourceLocation loc = NullExpr->getExprLoc();
6240     if (!findMacroSpelling(loc, "NULL"))
6241       return false;
6242   }
6243 
6244   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6245   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6246       << NonPointerExpr->getType() << DiagType
6247       << NonPointerExpr->getSourceRange();
6248   return true;
6249 }
6250 
6251 /// \brief Return false if the condition expression is valid, true otherwise.
6252 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6253   QualType CondTy = Cond->getType();
6254 
6255   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6256   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6257     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6258       << CondTy << Cond->getSourceRange();
6259     return true;
6260   }
6261 
6262   // C99 6.5.15p2
6263   if (CondTy->isScalarType()) return false;
6264 
6265   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6266     << CondTy << Cond->getSourceRange();
6267   return true;
6268 }
6269 
6270 /// \brief Handle when one or both operands are void type.
6271 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6272                                          ExprResult &RHS) {
6273     Expr *LHSExpr = LHS.get();
6274     Expr *RHSExpr = RHS.get();
6275 
6276     if (!LHSExpr->getType()->isVoidType())
6277       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6278         << RHSExpr->getSourceRange();
6279     if (!RHSExpr->getType()->isVoidType())
6280       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6281         << LHSExpr->getSourceRange();
6282     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6283     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6284     return S.Context.VoidTy;
6285 }
6286 
6287 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6288 /// true otherwise.
6289 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6290                                         QualType PointerTy) {
6291   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6292       !NullExpr.get()->isNullPointerConstant(S.Context,
6293                                             Expr::NPC_ValueDependentIsNull))
6294     return true;
6295 
6296   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6297   return false;
6298 }
6299 
6300 /// \brief Checks compatibility between two pointers and return the resulting
6301 /// type.
6302 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6303                                                      ExprResult &RHS,
6304                                                      SourceLocation Loc) {
6305   QualType LHSTy = LHS.get()->getType();
6306   QualType RHSTy = RHS.get()->getType();
6307 
6308   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6309     // Two identical pointers types are always compatible.
6310     return LHSTy;
6311   }
6312 
6313   QualType lhptee, rhptee;
6314 
6315   // Get the pointee types.
6316   bool IsBlockPointer = false;
6317   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6318     lhptee = LHSBTy->getPointeeType();
6319     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6320     IsBlockPointer = true;
6321   } else {
6322     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6323     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6324   }
6325 
6326   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6327   // differently qualified versions of compatible types, the result type is
6328   // a pointer to an appropriately qualified version of the composite
6329   // type.
6330 
6331   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6332   // clause doesn't make sense for our extensions. E.g. address space 2 should
6333   // be incompatible with address space 3: they may live on different devices or
6334   // anything.
6335   Qualifiers lhQual = lhptee.getQualifiers();
6336   Qualifiers rhQual = rhptee.getQualifiers();
6337 
6338   unsigned ResultAddrSpace = 0;
6339   unsigned LAddrSpace = lhQual.getAddressSpace();
6340   unsigned RAddrSpace = rhQual.getAddressSpace();
6341   if (S.getLangOpts().OpenCL) {
6342     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6343     // spaces is disallowed.
6344     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6345       ResultAddrSpace = LAddrSpace;
6346     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6347       ResultAddrSpace = RAddrSpace;
6348     else {
6349       S.Diag(Loc,
6350              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6351           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6352           << RHS.get()->getSourceRange();
6353       return QualType();
6354     }
6355   }
6356 
6357   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6358   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6359   lhQual.removeCVRQualifiers();
6360   rhQual.removeCVRQualifiers();
6361 
6362   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6363   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6364   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6365   // qual types are compatible iff
6366   //  * corresponded types are compatible
6367   //  * CVR qualifiers are equal
6368   //  * address spaces are equal
6369   // Thus for conditional operator we merge CVR and address space unqualified
6370   // pointees and if there is a composite type we return a pointer to it with
6371   // merged qualifiers.
6372   if (S.getLangOpts().OpenCL) {
6373     LHSCastKind = LAddrSpace == ResultAddrSpace
6374                       ? CK_BitCast
6375                       : CK_AddressSpaceConversion;
6376     RHSCastKind = RAddrSpace == ResultAddrSpace
6377                       ? CK_BitCast
6378                       : CK_AddressSpaceConversion;
6379     lhQual.removeAddressSpace();
6380     rhQual.removeAddressSpace();
6381   }
6382 
6383   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6384   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6385 
6386   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6387 
6388   if (CompositeTy.isNull()) {
6389     // In this situation, we assume void* type. No especially good
6390     // reason, but this is what gcc does, and we do have to pick
6391     // to get a consistent AST.
6392     QualType incompatTy;
6393     incompatTy = S.Context.getPointerType(
6394         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6395     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6396     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6397     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6398     // for casts between types with incompatible address space qualifiers.
6399     // For the following code the compiler produces casts between global and
6400     // local address spaces of the corresponded innermost pointees:
6401     // local int *global *a;
6402     // global int *global *b;
6403     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6404     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6405         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6406         << RHS.get()->getSourceRange();
6407     return incompatTy;
6408   }
6409 
6410   // The pointer types are compatible.
6411   // In case of OpenCL ResultTy should have the address space qualifier
6412   // which is a superset of address spaces of both the 2nd and the 3rd
6413   // operands of the conditional operator.
6414   QualType ResultTy = [&, ResultAddrSpace]() {
6415     if (S.getLangOpts().OpenCL) {
6416       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6417       CompositeQuals.setAddressSpace(ResultAddrSpace);
6418       return S.Context
6419           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6420           .withCVRQualifiers(MergedCVRQual);
6421     } else
6422       return CompositeTy.withCVRQualifiers(MergedCVRQual);
6423   }();
6424   if (IsBlockPointer)
6425     ResultTy = S.Context.getBlockPointerType(ResultTy);
6426   else {
6427     ResultTy = S.Context.getPointerType(ResultTy);
6428   }
6429 
6430   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6431   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6432   return ResultTy;
6433 }
6434 
6435 /// \brief Return the resulting type when the operands are both block pointers.
6436 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6437                                                           ExprResult &LHS,
6438                                                           ExprResult &RHS,
6439                                                           SourceLocation Loc) {
6440   QualType LHSTy = LHS.get()->getType();
6441   QualType RHSTy = RHS.get()->getType();
6442 
6443   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6444     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6445       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6446       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6447       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6448       return destType;
6449     }
6450     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6451       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6452       << RHS.get()->getSourceRange();
6453     return QualType();
6454   }
6455 
6456   // We have 2 block pointer types.
6457   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6458 }
6459 
6460 /// \brief Return the resulting type when the operands are both pointers.
6461 static QualType
6462 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6463                                             ExprResult &RHS,
6464                                             SourceLocation Loc) {
6465   // get the pointer types
6466   QualType LHSTy = LHS.get()->getType();
6467   QualType RHSTy = RHS.get()->getType();
6468 
6469   // get the "pointed to" types
6470   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6471   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6472 
6473   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6474   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6475     // Figure out necessary qualifiers (C99 6.5.15p6)
6476     QualType destPointee
6477       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6478     QualType destType = S.Context.getPointerType(destPointee);
6479     // Add qualifiers if necessary.
6480     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6481     // Promote to void*.
6482     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6483     return destType;
6484   }
6485   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6486     QualType destPointee
6487       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6488     QualType destType = S.Context.getPointerType(destPointee);
6489     // Add qualifiers if necessary.
6490     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6491     // Promote to void*.
6492     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6493     return destType;
6494   }
6495 
6496   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6497 }
6498 
6499 /// \brief Return false if the first expression is not an integer and the second
6500 /// expression is not a pointer, true otherwise.
6501 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6502                                         Expr* PointerExpr, SourceLocation Loc,
6503                                         bool IsIntFirstExpr) {
6504   if (!PointerExpr->getType()->isPointerType() ||
6505       !Int.get()->getType()->isIntegerType())
6506     return false;
6507 
6508   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6509   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6510 
6511   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6512     << Expr1->getType() << Expr2->getType()
6513     << Expr1->getSourceRange() << Expr2->getSourceRange();
6514   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6515                             CK_IntegralToPointer);
6516   return true;
6517 }
6518 
6519 /// \brief Simple conversion between integer and floating point types.
6520 ///
6521 /// Used when handling the OpenCL conditional operator where the
6522 /// condition is a vector while the other operands are scalar.
6523 ///
6524 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6525 /// types are either integer or floating type. Between the two
6526 /// operands, the type with the higher rank is defined as the "result
6527 /// type". The other operand needs to be promoted to the same type. No
6528 /// other type promotion is allowed. We cannot use
6529 /// UsualArithmeticConversions() for this purpose, since it always
6530 /// promotes promotable types.
6531 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6532                                             ExprResult &RHS,
6533                                             SourceLocation QuestionLoc) {
6534   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6535   if (LHS.isInvalid())
6536     return QualType();
6537   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6538   if (RHS.isInvalid())
6539     return QualType();
6540 
6541   // For conversion purposes, we ignore any qualifiers.
6542   // For example, "const float" and "float" are equivalent.
6543   QualType LHSType =
6544     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6545   QualType RHSType =
6546     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6547 
6548   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6549     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6550       << LHSType << LHS.get()->getSourceRange();
6551     return QualType();
6552   }
6553 
6554   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6555     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6556       << RHSType << RHS.get()->getSourceRange();
6557     return QualType();
6558   }
6559 
6560   // If both types are identical, no conversion is needed.
6561   if (LHSType == RHSType)
6562     return LHSType;
6563 
6564   // Now handle "real" floating types (i.e. float, double, long double).
6565   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6566     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6567                                  /*IsCompAssign = */ false);
6568 
6569   // Finally, we have two differing integer types.
6570   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6571   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6572 }
6573 
6574 /// \brief Convert scalar operands to a vector that matches the
6575 ///        condition in length.
6576 ///
6577 /// Used when handling the OpenCL conditional operator where the
6578 /// condition is a vector while the other operands are scalar.
6579 ///
6580 /// We first compute the "result type" for the scalar operands
6581 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6582 /// into a vector of that type where the length matches the condition
6583 /// vector type. s6.11.6 requires that the element types of the result
6584 /// and the condition must have the same number of bits.
6585 static QualType
6586 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6587                               QualType CondTy, SourceLocation QuestionLoc) {
6588   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6589   if (ResTy.isNull()) return QualType();
6590 
6591   const VectorType *CV = CondTy->getAs<VectorType>();
6592   assert(CV);
6593 
6594   // Determine the vector result type
6595   unsigned NumElements = CV->getNumElements();
6596   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6597 
6598   // Ensure that all types have the same number of bits
6599   if (S.Context.getTypeSize(CV->getElementType())
6600       != S.Context.getTypeSize(ResTy)) {
6601     // Since VectorTy is created internally, it does not pretty print
6602     // with an OpenCL name. Instead, we just print a description.
6603     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6604     SmallString<64> Str;
6605     llvm::raw_svector_ostream OS(Str);
6606     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6607     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6608       << CondTy << OS.str();
6609     return QualType();
6610   }
6611 
6612   // Convert operands to the vector result type
6613   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6614   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6615 
6616   return VectorTy;
6617 }
6618 
6619 /// \brief Return false if this is a valid OpenCL condition vector
6620 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6621                                        SourceLocation QuestionLoc) {
6622   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6623   // integral type.
6624   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6625   assert(CondTy);
6626   QualType EleTy = CondTy->getElementType();
6627   if (EleTy->isIntegerType()) return false;
6628 
6629   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6630     << Cond->getType() << Cond->getSourceRange();
6631   return true;
6632 }
6633 
6634 /// \brief Return false if the vector condition type and the vector
6635 ///        result type are compatible.
6636 ///
6637 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6638 /// number of elements, and their element types have the same number
6639 /// of bits.
6640 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6641                               SourceLocation QuestionLoc) {
6642   const VectorType *CV = CondTy->getAs<VectorType>();
6643   const VectorType *RV = VecResTy->getAs<VectorType>();
6644   assert(CV && RV);
6645 
6646   if (CV->getNumElements() != RV->getNumElements()) {
6647     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6648       << CondTy << VecResTy;
6649     return true;
6650   }
6651 
6652   QualType CVE = CV->getElementType();
6653   QualType RVE = RV->getElementType();
6654 
6655   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6656     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6657       << CondTy << VecResTy;
6658     return true;
6659   }
6660 
6661   return false;
6662 }
6663 
6664 /// \brief Return the resulting type for the conditional operator in
6665 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6666 ///        s6.3.i) when the condition is a vector type.
6667 static QualType
6668 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6669                              ExprResult &LHS, ExprResult &RHS,
6670                              SourceLocation QuestionLoc) {
6671   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6672   if (Cond.isInvalid())
6673     return QualType();
6674   QualType CondTy = Cond.get()->getType();
6675 
6676   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6677     return QualType();
6678 
6679   // If either operand is a vector then find the vector type of the
6680   // result as specified in OpenCL v1.1 s6.3.i.
6681   if (LHS.get()->getType()->isVectorType() ||
6682       RHS.get()->getType()->isVectorType()) {
6683     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6684                                               /*isCompAssign*/false,
6685                                               /*AllowBothBool*/true,
6686                                               /*AllowBoolConversions*/false);
6687     if (VecResTy.isNull()) return QualType();
6688     // The result type must match the condition type as specified in
6689     // OpenCL v1.1 s6.11.6.
6690     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6691       return QualType();
6692     return VecResTy;
6693   }
6694 
6695   // Both operands are scalar.
6696   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6697 }
6698 
6699 /// \brief Return true if the Expr is block type
6700 static bool checkBlockType(Sema &S, const Expr *E) {
6701   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6702     QualType Ty = CE->getCallee()->getType();
6703     if (Ty->isBlockPointerType()) {
6704       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6705       return true;
6706     }
6707   }
6708   return false;
6709 }
6710 
6711 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6712 /// In that case, LHS = cond.
6713 /// C99 6.5.15
6714 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6715                                         ExprResult &RHS, ExprValueKind &VK,
6716                                         ExprObjectKind &OK,
6717                                         SourceLocation QuestionLoc) {
6718 
6719   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6720   if (!LHSResult.isUsable()) return QualType();
6721   LHS = LHSResult;
6722 
6723   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6724   if (!RHSResult.isUsable()) return QualType();
6725   RHS = RHSResult;
6726 
6727   // C++ is sufficiently different to merit its own checker.
6728   if (getLangOpts().CPlusPlus)
6729     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6730 
6731   VK = VK_RValue;
6732   OK = OK_Ordinary;
6733 
6734   // The OpenCL operator with a vector condition is sufficiently
6735   // different to merit its own checker.
6736   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6737     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6738 
6739   // First, check the condition.
6740   Cond = UsualUnaryConversions(Cond.get());
6741   if (Cond.isInvalid())
6742     return QualType();
6743   if (checkCondition(*this, Cond.get(), QuestionLoc))
6744     return QualType();
6745 
6746   // Now check the two expressions.
6747   if (LHS.get()->getType()->isVectorType() ||
6748       RHS.get()->getType()->isVectorType())
6749     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6750                                /*AllowBothBool*/true,
6751                                /*AllowBoolConversions*/false);
6752 
6753   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6754   if (LHS.isInvalid() || RHS.isInvalid())
6755     return QualType();
6756 
6757   QualType LHSTy = LHS.get()->getType();
6758   QualType RHSTy = RHS.get()->getType();
6759 
6760   // Diagnose attempts to convert between __float128 and long double where
6761   // such conversions currently can't be handled.
6762   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6763     Diag(QuestionLoc,
6764          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6765       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6766     return QualType();
6767   }
6768 
6769   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6770   // selection operator (?:).
6771   if (getLangOpts().OpenCL &&
6772       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6773     return QualType();
6774   }
6775 
6776   // If both operands have arithmetic type, do the usual arithmetic conversions
6777   // to find a common type: C99 6.5.15p3,5.
6778   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6779     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6780     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6781 
6782     return ResTy;
6783   }
6784 
6785   // If both operands are the same structure or union type, the result is that
6786   // type.
6787   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6788     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6789       if (LHSRT->getDecl() == RHSRT->getDecl())
6790         // "If both the operands have structure or union type, the result has
6791         // that type."  This implies that CV qualifiers are dropped.
6792         return LHSTy.getUnqualifiedType();
6793     // FIXME: Type of conditional expression must be complete in C mode.
6794   }
6795 
6796   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6797   // The following || allows only one side to be void (a GCC-ism).
6798   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6799     return checkConditionalVoidType(*this, LHS, RHS);
6800   }
6801 
6802   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6803   // the type of the other operand."
6804   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6805   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6806 
6807   // All objective-c pointer type analysis is done here.
6808   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6809                                                         QuestionLoc);
6810   if (LHS.isInvalid() || RHS.isInvalid())
6811     return QualType();
6812   if (!compositeType.isNull())
6813     return compositeType;
6814 
6815 
6816   // Handle block pointer types.
6817   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6818     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6819                                                      QuestionLoc);
6820 
6821   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6822   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6823     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6824                                                        QuestionLoc);
6825 
6826   // GCC compatibility: soften pointer/integer mismatch.  Note that
6827   // null pointers have been filtered out by this point.
6828   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6829       /*isIntFirstExpr=*/true))
6830     return RHSTy;
6831   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6832       /*isIntFirstExpr=*/false))
6833     return LHSTy;
6834 
6835   // Emit a better diagnostic if one of the expressions is a null pointer
6836   // constant and the other is not a pointer type. In this case, the user most
6837   // likely forgot to take the address of the other expression.
6838   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6839     return QualType();
6840 
6841   // Otherwise, the operands are not compatible.
6842   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6843     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6844     << RHS.get()->getSourceRange();
6845   return QualType();
6846 }
6847 
6848 /// FindCompositeObjCPointerType - Helper method to find composite type of
6849 /// two objective-c pointer types of the two input expressions.
6850 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6851                                             SourceLocation QuestionLoc) {
6852   QualType LHSTy = LHS.get()->getType();
6853   QualType RHSTy = RHS.get()->getType();
6854 
6855   // Handle things like Class and struct objc_class*.  Here we case the result
6856   // to the pseudo-builtin, because that will be implicitly cast back to the
6857   // redefinition type if an attempt is made to access its fields.
6858   if (LHSTy->isObjCClassType() &&
6859       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6860     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6861     return LHSTy;
6862   }
6863   if (RHSTy->isObjCClassType() &&
6864       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6865     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6866     return RHSTy;
6867   }
6868   // And the same for struct objc_object* / id
6869   if (LHSTy->isObjCIdType() &&
6870       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6871     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6872     return LHSTy;
6873   }
6874   if (RHSTy->isObjCIdType() &&
6875       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6876     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6877     return RHSTy;
6878   }
6879   // And the same for struct objc_selector* / SEL
6880   if (Context.isObjCSelType(LHSTy) &&
6881       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6882     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6883     return LHSTy;
6884   }
6885   if (Context.isObjCSelType(RHSTy) &&
6886       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6887     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6888     return RHSTy;
6889   }
6890   // Check constraints for Objective-C object pointers types.
6891   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6892 
6893     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6894       // Two identical object pointer types are always compatible.
6895       return LHSTy;
6896     }
6897     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6898     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6899     QualType compositeType = LHSTy;
6900 
6901     // If both operands are interfaces and either operand can be
6902     // assigned to the other, use that type as the composite
6903     // type. This allows
6904     //   xxx ? (A*) a : (B*) b
6905     // where B is a subclass of A.
6906     //
6907     // Additionally, as for assignment, if either type is 'id'
6908     // allow silent coercion. Finally, if the types are
6909     // incompatible then make sure to use 'id' as the composite
6910     // type so the result is acceptable for sending messages to.
6911 
6912     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6913     // It could return the composite type.
6914     if (!(compositeType =
6915           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6916       // Nothing more to do.
6917     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6918       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6919     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6920       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6921     } else if ((LHSTy->isObjCQualifiedIdType() ||
6922                 RHSTy->isObjCQualifiedIdType()) &&
6923                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6924       // Need to handle "id<xx>" explicitly.
6925       // GCC allows qualified id and any Objective-C type to devolve to
6926       // id. Currently localizing to here until clear this should be
6927       // part of ObjCQualifiedIdTypesAreCompatible.
6928       compositeType = Context.getObjCIdType();
6929     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6930       compositeType = Context.getObjCIdType();
6931     } else {
6932       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6933       << LHSTy << RHSTy
6934       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6935       QualType incompatTy = Context.getObjCIdType();
6936       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6937       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6938       return incompatTy;
6939     }
6940     // The object pointer types are compatible.
6941     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6942     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6943     return compositeType;
6944   }
6945   // Check Objective-C object pointer types and 'void *'
6946   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6947     if (getLangOpts().ObjCAutoRefCount) {
6948       // ARC forbids the implicit conversion of object pointers to 'void *',
6949       // so these types are not compatible.
6950       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6951           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6952       LHS = RHS = true;
6953       return QualType();
6954     }
6955     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6956     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6957     QualType destPointee
6958     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6959     QualType destType = Context.getPointerType(destPointee);
6960     // Add qualifiers if necessary.
6961     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6962     // Promote to void*.
6963     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6964     return destType;
6965   }
6966   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6967     if (getLangOpts().ObjCAutoRefCount) {
6968       // ARC forbids the implicit conversion of object pointers to 'void *',
6969       // so these types are not compatible.
6970       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6971           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6972       LHS = RHS = true;
6973       return QualType();
6974     }
6975     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6976     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6977     QualType destPointee
6978     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6979     QualType destType = Context.getPointerType(destPointee);
6980     // Add qualifiers if necessary.
6981     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6982     // Promote to void*.
6983     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6984     return destType;
6985   }
6986   return QualType();
6987 }
6988 
6989 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6990 /// ParenRange in parentheses.
6991 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6992                                const PartialDiagnostic &Note,
6993                                SourceRange ParenRange) {
6994   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6995   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6996       EndLoc.isValid()) {
6997     Self.Diag(Loc, Note)
6998       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6999       << FixItHint::CreateInsertion(EndLoc, ")");
7000   } else {
7001     // We can't display the parentheses, so just show the bare note.
7002     Self.Diag(Loc, Note) << ParenRange;
7003   }
7004 }
7005 
7006 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7007   return BinaryOperator::isAdditiveOp(Opc) ||
7008          BinaryOperator::isMultiplicativeOp(Opc) ||
7009          BinaryOperator::isShiftOp(Opc);
7010 }
7011 
7012 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7013 /// expression, either using a built-in or overloaded operator,
7014 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7015 /// expression.
7016 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7017                                    Expr **RHSExprs) {
7018   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7019   E = E->IgnoreImpCasts();
7020   E = E->IgnoreConversionOperator();
7021   E = E->IgnoreImpCasts();
7022 
7023   // Built-in binary operator.
7024   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7025     if (IsArithmeticOp(OP->getOpcode())) {
7026       *Opcode = OP->getOpcode();
7027       *RHSExprs = OP->getRHS();
7028       return true;
7029     }
7030   }
7031 
7032   // Overloaded operator.
7033   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7034     if (Call->getNumArgs() != 2)
7035       return false;
7036 
7037     // Make sure this is really a binary operator that is safe to pass into
7038     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7039     OverloadedOperatorKind OO = Call->getOperator();
7040     if (OO < OO_Plus || OO > OO_Arrow ||
7041         OO == OO_PlusPlus || OO == OO_MinusMinus)
7042       return false;
7043 
7044     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7045     if (IsArithmeticOp(OpKind)) {
7046       *Opcode = OpKind;
7047       *RHSExprs = Call->getArg(1);
7048       return true;
7049     }
7050   }
7051 
7052   return false;
7053 }
7054 
7055 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7056 /// or is a logical expression such as (x==y) which has int type, but is
7057 /// commonly interpreted as boolean.
7058 static bool ExprLooksBoolean(Expr *E) {
7059   E = E->IgnoreParenImpCasts();
7060 
7061   if (E->getType()->isBooleanType())
7062     return true;
7063   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7064     return OP->isComparisonOp() || OP->isLogicalOp();
7065   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7066     return OP->getOpcode() == UO_LNot;
7067   if (E->getType()->isPointerType())
7068     return true;
7069 
7070   return false;
7071 }
7072 
7073 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7074 /// and binary operator are mixed in a way that suggests the programmer assumed
7075 /// the conditional operator has higher precedence, for example:
7076 /// "int x = a + someBinaryCondition ? 1 : 2".
7077 static void DiagnoseConditionalPrecedence(Sema &Self,
7078                                           SourceLocation OpLoc,
7079                                           Expr *Condition,
7080                                           Expr *LHSExpr,
7081                                           Expr *RHSExpr) {
7082   BinaryOperatorKind CondOpcode;
7083   Expr *CondRHS;
7084 
7085   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7086     return;
7087   if (!ExprLooksBoolean(CondRHS))
7088     return;
7089 
7090   // The condition is an arithmetic binary expression, with a right-
7091   // hand side that looks boolean, so warn.
7092 
7093   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7094       << Condition->getSourceRange()
7095       << BinaryOperator::getOpcodeStr(CondOpcode);
7096 
7097   SuggestParentheses(Self, OpLoc,
7098     Self.PDiag(diag::note_precedence_silence)
7099       << BinaryOperator::getOpcodeStr(CondOpcode),
7100     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7101 
7102   SuggestParentheses(Self, OpLoc,
7103     Self.PDiag(diag::note_precedence_conditional_first),
7104     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7105 }
7106 
7107 /// Compute the nullability of a conditional expression.
7108 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7109                                               QualType LHSTy, QualType RHSTy,
7110                                               ASTContext &Ctx) {
7111   if (!ResTy->isAnyPointerType())
7112     return ResTy;
7113 
7114   auto GetNullability = [&Ctx](QualType Ty) {
7115     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7116     if (Kind)
7117       return *Kind;
7118     return NullabilityKind::Unspecified;
7119   };
7120 
7121   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7122   NullabilityKind MergedKind;
7123 
7124   // Compute nullability of a binary conditional expression.
7125   if (IsBin) {
7126     if (LHSKind == NullabilityKind::NonNull)
7127       MergedKind = NullabilityKind::NonNull;
7128     else
7129       MergedKind = RHSKind;
7130   // Compute nullability of a normal conditional expression.
7131   } else {
7132     if (LHSKind == NullabilityKind::Nullable ||
7133         RHSKind == NullabilityKind::Nullable)
7134       MergedKind = NullabilityKind::Nullable;
7135     else if (LHSKind == NullabilityKind::NonNull)
7136       MergedKind = RHSKind;
7137     else if (RHSKind == NullabilityKind::NonNull)
7138       MergedKind = LHSKind;
7139     else
7140       MergedKind = NullabilityKind::Unspecified;
7141   }
7142 
7143   // Return if ResTy already has the correct nullability.
7144   if (GetNullability(ResTy) == MergedKind)
7145     return ResTy;
7146 
7147   // Strip all nullability from ResTy.
7148   while (ResTy->getNullability(Ctx))
7149     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7150 
7151   // Create a new AttributedType with the new nullability kind.
7152   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7153   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7154 }
7155 
7156 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7157 /// in the case of a the GNU conditional expr extension.
7158 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7159                                     SourceLocation ColonLoc,
7160                                     Expr *CondExpr, Expr *LHSExpr,
7161                                     Expr *RHSExpr) {
7162   if (!getLangOpts().CPlusPlus) {
7163     // C cannot handle TypoExpr nodes in the condition because it
7164     // doesn't handle dependent types properly, so make sure any TypoExprs have
7165     // been dealt with before checking the operands.
7166     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7167     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7168     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7169 
7170     if (!CondResult.isUsable())
7171       return ExprError();
7172 
7173     if (LHSExpr) {
7174       if (!LHSResult.isUsable())
7175         return ExprError();
7176     }
7177 
7178     if (!RHSResult.isUsable())
7179       return ExprError();
7180 
7181     CondExpr = CondResult.get();
7182     LHSExpr = LHSResult.get();
7183     RHSExpr = RHSResult.get();
7184   }
7185 
7186   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7187   // was the condition.
7188   OpaqueValueExpr *opaqueValue = nullptr;
7189   Expr *commonExpr = nullptr;
7190   if (!LHSExpr) {
7191     commonExpr = CondExpr;
7192     // Lower out placeholder types first.  This is important so that we don't
7193     // try to capture a placeholder. This happens in few cases in C++; such
7194     // as Objective-C++'s dictionary subscripting syntax.
7195     if (commonExpr->hasPlaceholderType()) {
7196       ExprResult result = CheckPlaceholderExpr(commonExpr);
7197       if (!result.isUsable()) return ExprError();
7198       commonExpr = result.get();
7199     }
7200     // We usually want to apply unary conversions *before* saving, except
7201     // in the special case of a C++ l-value conditional.
7202     if (!(getLangOpts().CPlusPlus
7203           && !commonExpr->isTypeDependent()
7204           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7205           && commonExpr->isGLValue()
7206           && commonExpr->isOrdinaryOrBitFieldObject()
7207           && RHSExpr->isOrdinaryOrBitFieldObject()
7208           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7209       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7210       if (commonRes.isInvalid())
7211         return ExprError();
7212       commonExpr = commonRes.get();
7213     }
7214 
7215     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7216                                                 commonExpr->getType(),
7217                                                 commonExpr->getValueKind(),
7218                                                 commonExpr->getObjectKind(),
7219                                                 commonExpr);
7220     LHSExpr = CondExpr = opaqueValue;
7221   }
7222 
7223   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7224   ExprValueKind VK = VK_RValue;
7225   ExprObjectKind OK = OK_Ordinary;
7226   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7227   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7228                                              VK, OK, QuestionLoc);
7229   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7230       RHS.isInvalid())
7231     return ExprError();
7232 
7233   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7234                                 RHS.get());
7235 
7236   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7237 
7238   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7239                                          Context);
7240 
7241   if (!commonExpr)
7242     return new (Context)
7243         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7244                             RHS.get(), result, VK, OK);
7245 
7246   return new (Context) BinaryConditionalOperator(
7247       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7248       ColonLoc, result, VK, OK);
7249 }
7250 
7251 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7252 // being closely modeled after the C99 spec:-). The odd characteristic of this
7253 // routine is it effectively iqnores the qualifiers on the top level pointee.
7254 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7255 // FIXME: add a couple examples in this comment.
7256 static Sema::AssignConvertType
7257 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7258   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7259   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7260 
7261   // get the "pointed to" type (ignoring qualifiers at the top level)
7262   const Type *lhptee, *rhptee;
7263   Qualifiers lhq, rhq;
7264   std::tie(lhptee, lhq) =
7265       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7266   std::tie(rhptee, rhq) =
7267       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7268 
7269   Sema::AssignConvertType ConvTy = Sema::Compatible;
7270 
7271   // C99 6.5.16.1p1: This following citation is common to constraints
7272   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7273   // qualifiers of the type *pointed to* by the right;
7274 
7275   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7276   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7277       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7278     // Ignore lifetime for further calculation.
7279     lhq.removeObjCLifetime();
7280     rhq.removeObjCLifetime();
7281   }
7282 
7283   if (!lhq.compatiblyIncludes(rhq)) {
7284     // Treat address-space mismatches as fatal.  TODO: address subspaces
7285     if (!lhq.isAddressSpaceSupersetOf(rhq))
7286       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7287 
7288     // It's okay to add or remove GC or lifetime qualifiers when converting to
7289     // and from void*.
7290     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7291                         .compatiblyIncludes(
7292                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7293              && (lhptee->isVoidType() || rhptee->isVoidType()))
7294       ; // keep old
7295 
7296     // Treat lifetime mismatches as fatal.
7297     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7298       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7299 
7300     // For GCC/MS compatibility, other qualifier mismatches are treated
7301     // as still compatible in C.
7302     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7303   }
7304 
7305   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7306   // incomplete type and the other is a pointer to a qualified or unqualified
7307   // version of void...
7308   if (lhptee->isVoidType()) {
7309     if (rhptee->isIncompleteOrObjectType())
7310       return ConvTy;
7311 
7312     // As an extension, we allow cast to/from void* to function pointer.
7313     assert(rhptee->isFunctionType());
7314     return Sema::FunctionVoidPointer;
7315   }
7316 
7317   if (rhptee->isVoidType()) {
7318     if (lhptee->isIncompleteOrObjectType())
7319       return ConvTy;
7320 
7321     // As an extension, we allow cast to/from void* to function pointer.
7322     assert(lhptee->isFunctionType());
7323     return Sema::FunctionVoidPointer;
7324   }
7325 
7326   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7327   // unqualified versions of compatible types, ...
7328   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7329   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7330     // Check if the pointee types are compatible ignoring the sign.
7331     // We explicitly check for char so that we catch "char" vs
7332     // "unsigned char" on systems where "char" is unsigned.
7333     if (lhptee->isCharType())
7334       ltrans = S.Context.UnsignedCharTy;
7335     else if (lhptee->hasSignedIntegerRepresentation())
7336       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7337 
7338     if (rhptee->isCharType())
7339       rtrans = S.Context.UnsignedCharTy;
7340     else if (rhptee->hasSignedIntegerRepresentation())
7341       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7342 
7343     if (ltrans == rtrans) {
7344       // Types are compatible ignoring the sign. Qualifier incompatibility
7345       // takes priority over sign incompatibility because the sign
7346       // warning can be disabled.
7347       if (ConvTy != Sema::Compatible)
7348         return ConvTy;
7349 
7350       return Sema::IncompatiblePointerSign;
7351     }
7352 
7353     // If we are a multi-level pointer, it's possible that our issue is simply
7354     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7355     // the eventual target type is the same and the pointers have the same
7356     // level of indirection, this must be the issue.
7357     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7358       do {
7359         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7360         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7361       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7362 
7363       if (lhptee == rhptee)
7364         return Sema::IncompatibleNestedPointerQualifiers;
7365     }
7366 
7367     // General pointer incompatibility takes priority over qualifiers.
7368     return Sema::IncompatiblePointer;
7369   }
7370   if (!S.getLangOpts().CPlusPlus &&
7371       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7372     return Sema::IncompatiblePointer;
7373   return ConvTy;
7374 }
7375 
7376 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7377 /// block pointer types are compatible or whether a block and normal pointer
7378 /// are compatible. It is more restrict than comparing two function pointer
7379 // types.
7380 static Sema::AssignConvertType
7381 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7382                                     QualType RHSType) {
7383   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7384   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7385 
7386   QualType lhptee, rhptee;
7387 
7388   // get the "pointed to" type (ignoring qualifiers at the top level)
7389   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7390   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7391 
7392   // In C++, the types have to match exactly.
7393   if (S.getLangOpts().CPlusPlus)
7394     return Sema::IncompatibleBlockPointer;
7395 
7396   Sema::AssignConvertType ConvTy = Sema::Compatible;
7397 
7398   // For blocks we enforce that qualifiers are identical.
7399   Qualifiers LQuals = lhptee.getLocalQualifiers();
7400   Qualifiers RQuals = rhptee.getLocalQualifiers();
7401   if (S.getLangOpts().OpenCL) {
7402     LQuals.removeAddressSpace();
7403     RQuals.removeAddressSpace();
7404   }
7405   if (LQuals != RQuals)
7406     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7407 
7408   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7409   // assignment.
7410   // The current behavior is similar to C++ lambdas. A block might be
7411   // assigned to a variable iff its return type and parameters are compatible
7412   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7413   // an assignment. Presumably it should behave in way that a function pointer
7414   // assignment does in C, so for each parameter and return type:
7415   //  * CVR and address space of LHS should be a superset of CVR and address
7416   //  space of RHS.
7417   //  * unqualified types should be compatible.
7418   if (S.getLangOpts().OpenCL) {
7419     if (!S.Context.typesAreBlockPointerCompatible(
7420             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7421             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7422       return Sema::IncompatibleBlockPointer;
7423   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7424     return Sema::IncompatibleBlockPointer;
7425 
7426   return ConvTy;
7427 }
7428 
7429 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7430 /// for assignment compatibility.
7431 static Sema::AssignConvertType
7432 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7433                                    QualType RHSType) {
7434   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7435   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7436 
7437   if (LHSType->isObjCBuiltinType()) {
7438     // Class is not compatible with ObjC object pointers.
7439     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7440         !RHSType->isObjCQualifiedClassType())
7441       return Sema::IncompatiblePointer;
7442     return Sema::Compatible;
7443   }
7444   if (RHSType->isObjCBuiltinType()) {
7445     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7446         !LHSType->isObjCQualifiedClassType())
7447       return Sema::IncompatiblePointer;
7448     return Sema::Compatible;
7449   }
7450   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7451   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7452 
7453   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7454       // make an exception for id<P>
7455       !LHSType->isObjCQualifiedIdType())
7456     return Sema::CompatiblePointerDiscardsQualifiers;
7457 
7458   if (S.Context.typesAreCompatible(LHSType, RHSType))
7459     return Sema::Compatible;
7460   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7461     return Sema::IncompatibleObjCQualifiedId;
7462   return Sema::IncompatiblePointer;
7463 }
7464 
7465 Sema::AssignConvertType
7466 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7467                                  QualType LHSType, QualType RHSType) {
7468   // Fake up an opaque expression.  We don't actually care about what
7469   // cast operations are required, so if CheckAssignmentConstraints
7470   // adds casts to this they'll be wasted, but fortunately that doesn't
7471   // usually happen on valid code.
7472   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7473   ExprResult RHSPtr = &RHSExpr;
7474   CastKind K = CK_Invalid;
7475 
7476   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7477 }
7478 
7479 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7480 /// has code to accommodate several GCC extensions when type checking
7481 /// pointers. Here are some objectionable examples that GCC considers warnings:
7482 ///
7483 ///  int a, *pint;
7484 ///  short *pshort;
7485 ///  struct foo *pfoo;
7486 ///
7487 ///  pint = pshort; // warning: assignment from incompatible pointer type
7488 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7489 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7490 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7491 ///
7492 /// As a result, the code for dealing with pointers is more complex than the
7493 /// C99 spec dictates.
7494 ///
7495 /// Sets 'Kind' for any result kind except Incompatible.
7496 Sema::AssignConvertType
7497 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7498                                  CastKind &Kind, bool ConvertRHS) {
7499   QualType RHSType = RHS.get()->getType();
7500   QualType OrigLHSType = LHSType;
7501 
7502   // Get canonical types.  We're not formatting these types, just comparing
7503   // them.
7504   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7505   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7506 
7507   // Common case: no conversion required.
7508   if (LHSType == RHSType) {
7509     Kind = CK_NoOp;
7510     return Compatible;
7511   }
7512 
7513   // If we have an atomic type, try a non-atomic assignment, then just add an
7514   // atomic qualification step.
7515   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7516     Sema::AssignConvertType result =
7517       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7518     if (result != Compatible)
7519       return result;
7520     if (Kind != CK_NoOp && ConvertRHS)
7521       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7522     Kind = CK_NonAtomicToAtomic;
7523     return Compatible;
7524   }
7525 
7526   // If the left-hand side is a reference type, then we are in a
7527   // (rare!) case where we've allowed the use of references in C,
7528   // e.g., as a parameter type in a built-in function. In this case,
7529   // just make sure that the type referenced is compatible with the
7530   // right-hand side type. The caller is responsible for adjusting
7531   // LHSType so that the resulting expression does not have reference
7532   // type.
7533   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7534     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7535       Kind = CK_LValueBitCast;
7536       return Compatible;
7537     }
7538     return Incompatible;
7539   }
7540 
7541   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7542   // to the same ExtVector type.
7543   if (LHSType->isExtVectorType()) {
7544     if (RHSType->isExtVectorType())
7545       return Incompatible;
7546     if (RHSType->isArithmeticType()) {
7547       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7548       if (ConvertRHS)
7549         RHS = prepareVectorSplat(LHSType, RHS.get());
7550       Kind = CK_VectorSplat;
7551       return Compatible;
7552     }
7553   }
7554 
7555   // Conversions to or from vector type.
7556   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7557     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7558       // Allow assignments of an AltiVec vector type to an equivalent GCC
7559       // vector type and vice versa
7560       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7561         Kind = CK_BitCast;
7562         return Compatible;
7563       }
7564 
7565       // If we are allowing lax vector conversions, and LHS and RHS are both
7566       // vectors, the total size only needs to be the same. This is a bitcast;
7567       // no bits are changed but the result type is different.
7568       if (isLaxVectorConversion(RHSType, LHSType)) {
7569         Kind = CK_BitCast;
7570         return IncompatibleVectors;
7571       }
7572     }
7573 
7574     // When the RHS comes from another lax conversion (e.g. binops between
7575     // scalars and vectors) the result is canonicalized as a vector. When the
7576     // LHS is also a vector, the lax is allowed by the condition above. Handle
7577     // the case where LHS is a scalar.
7578     if (LHSType->isScalarType()) {
7579       const VectorType *VecType = RHSType->getAs<VectorType>();
7580       if (VecType && VecType->getNumElements() == 1 &&
7581           isLaxVectorConversion(RHSType, LHSType)) {
7582         ExprResult *VecExpr = &RHS;
7583         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7584         Kind = CK_BitCast;
7585         return Compatible;
7586       }
7587     }
7588 
7589     return Incompatible;
7590   }
7591 
7592   // Diagnose attempts to convert between __float128 and long double where
7593   // such conversions currently can't be handled.
7594   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7595     return Incompatible;
7596 
7597   // Arithmetic conversions.
7598   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7599       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7600     if (ConvertRHS)
7601       Kind = PrepareScalarCast(RHS, LHSType);
7602     return Compatible;
7603   }
7604 
7605   // Conversions to normal pointers.
7606   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7607     // U* -> T*
7608     if (isa<PointerType>(RHSType)) {
7609       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7610       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7611       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7612       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7613     }
7614 
7615     // int -> T*
7616     if (RHSType->isIntegerType()) {
7617       Kind = CK_IntegralToPointer; // FIXME: null?
7618       return IntToPointer;
7619     }
7620 
7621     // C pointers are not compatible with ObjC object pointers,
7622     // with two exceptions:
7623     if (isa<ObjCObjectPointerType>(RHSType)) {
7624       //  - conversions to void*
7625       if (LHSPointer->getPointeeType()->isVoidType()) {
7626         Kind = CK_BitCast;
7627         return Compatible;
7628       }
7629 
7630       //  - conversions from 'Class' to the redefinition type
7631       if (RHSType->isObjCClassType() &&
7632           Context.hasSameType(LHSType,
7633                               Context.getObjCClassRedefinitionType())) {
7634         Kind = CK_BitCast;
7635         return Compatible;
7636       }
7637 
7638       Kind = CK_BitCast;
7639       return IncompatiblePointer;
7640     }
7641 
7642     // U^ -> void*
7643     if (RHSType->getAs<BlockPointerType>()) {
7644       if (LHSPointer->getPointeeType()->isVoidType()) {
7645         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7646         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7647                                   ->getPointeeType()
7648                                   .getAddressSpace();
7649         Kind =
7650             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7651         return Compatible;
7652       }
7653     }
7654 
7655     return Incompatible;
7656   }
7657 
7658   // Conversions to block pointers.
7659   if (isa<BlockPointerType>(LHSType)) {
7660     // U^ -> T^
7661     if (RHSType->isBlockPointerType()) {
7662       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7663                                 ->getPointeeType()
7664                                 .getAddressSpace();
7665       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7666                                 ->getPointeeType()
7667                                 .getAddressSpace();
7668       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7669       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7670     }
7671 
7672     // int or null -> T^
7673     if (RHSType->isIntegerType()) {
7674       Kind = CK_IntegralToPointer; // FIXME: null
7675       return IntToBlockPointer;
7676     }
7677 
7678     // id -> T^
7679     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7680       Kind = CK_AnyPointerToBlockPointerCast;
7681       return Compatible;
7682     }
7683 
7684     // void* -> T^
7685     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7686       if (RHSPT->getPointeeType()->isVoidType()) {
7687         Kind = CK_AnyPointerToBlockPointerCast;
7688         return Compatible;
7689       }
7690 
7691     return Incompatible;
7692   }
7693 
7694   // Conversions to Objective-C pointers.
7695   if (isa<ObjCObjectPointerType>(LHSType)) {
7696     // A* -> B*
7697     if (RHSType->isObjCObjectPointerType()) {
7698       Kind = CK_BitCast;
7699       Sema::AssignConvertType result =
7700         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7701       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7702           result == Compatible &&
7703           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7704         result = IncompatibleObjCWeakRef;
7705       return result;
7706     }
7707 
7708     // int or null -> A*
7709     if (RHSType->isIntegerType()) {
7710       Kind = CK_IntegralToPointer; // FIXME: null
7711       return IntToPointer;
7712     }
7713 
7714     // In general, C pointers are not compatible with ObjC object pointers,
7715     // with two exceptions:
7716     if (isa<PointerType>(RHSType)) {
7717       Kind = CK_CPointerToObjCPointerCast;
7718 
7719       //  - conversions from 'void*'
7720       if (RHSType->isVoidPointerType()) {
7721         return Compatible;
7722       }
7723 
7724       //  - conversions to 'Class' from its redefinition type
7725       if (LHSType->isObjCClassType() &&
7726           Context.hasSameType(RHSType,
7727                               Context.getObjCClassRedefinitionType())) {
7728         return Compatible;
7729       }
7730 
7731       return IncompatiblePointer;
7732     }
7733 
7734     // Only under strict condition T^ is compatible with an Objective-C pointer.
7735     if (RHSType->isBlockPointerType() &&
7736         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7737       if (ConvertRHS)
7738         maybeExtendBlockObject(RHS);
7739       Kind = CK_BlockPointerToObjCPointerCast;
7740       return Compatible;
7741     }
7742 
7743     return Incompatible;
7744   }
7745 
7746   // Conversions from pointers that are not covered by the above.
7747   if (isa<PointerType>(RHSType)) {
7748     // T* -> _Bool
7749     if (LHSType == Context.BoolTy) {
7750       Kind = CK_PointerToBoolean;
7751       return Compatible;
7752     }
7753 
7754     // T* -> int
7755     if (LHSType->isIntegerType()) {
7756       Kind = CK_PointerToIntegral;
7757       return PointerToInt;
7758     }
7759 
7760     return Incompatible;
7761   }
7762 
7763   // Conversions from Objective-C pointers that are not covered by the above.
7764   if (isa<ObjCObjectPointerType>(RHSType)) {
7765     // T* -> _Bool
7766     if (LHSType == Context.BoolTy) {
7767       Kind = CK_PointerToBoolean;
7768       return Compatible;
7769     }
7770 
7771     // T* -> int
7772     if (LHSType->isIntegerType()) {
7773       Kind = CK_PointerToIntegral;
7774       return PointerToInt;
7775     }
7776 
7777     return Incompatible;
7778   }
7779 
7780   // struct A -> struct B
7781   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7782     if (Context.typesAreCompatible(LHSType, RHSType)) {
7783       Kind = CK_NoOp;
7784       return Compatible;
7785     }
7786   }
7787 
7788   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7789     Kind = CK_IntToOCLSampler;
7790     return Compatible;
7791   }
7792 
7793   return Incompatible;
7794 }
7795 
7796 /// \brief Constructs a transparent union from an expression that is
7797 /// used to initialize the transparent union.
7798 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7799                                       ExprResult &EResult, QualType UnionType,
7800                                       FieldDecl *Field) {
7801   // Build an initializer list that designates the appropriate member
7802   // of the transparent union.
7803   Expr *E = EResult.get();
7804   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7805                                                    E, SourceLocation());
7806   Initializer->setType(UnionType);
7807   Initializer->setInitializedFieldInUnion(Field);
7808 
7809   // Build a compound literal constructing a value of the transparent
7810   // union type from this initializer list.
7811   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7812   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7813                                         VK_RValue, Initializer, false);
7814 }
7815 
7816 Sema::AssignConvertType
7817 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7818                                                ExprResult &RHS) {
7819   QualType RHSType = RHS.get()->getType();
7820 
7821   // If the ArgType is a Union type, we want to handle a potential
7822   // transparent_union GCC extension.
7823   const RecordType *UT = ArgType->getAsUnionType();
7824   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7825     return Incompatible;
7826 
7827   // The field to initialize within the transparent union.
7828   RecordDecl *UD = UT->getDecl();
7829   FieldDecl *InitField = nullptr;
7830   // It's compatible if the expression matches any of the fields.
7831   for (auto *it : UD->fields()) {
7832     if (it->getType()->isPointerType()) {
7833       // If the transparent union contains a pointer type, we allow:
7834       // 1) void pointer
7835       // 2) null pointer constant
7836       if (RHSType->isPointerType())
7837         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7838           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7839           InitField = it;
7840           break;
7841         }
7842 
7843       if (RHS.get()->isNullPointerConstant(Context,
7844                                            Expr::NPC_ValueDependentIsNull)) {
7845         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7846                                 CK_NullToPointer);
7847         InitField = it;
7848         break;
7849       }
7850     }
7851 
7852     CastKind Kind = CK_Invalid;
7853     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7854           == Compatible) {
7855       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7856       InitField = it;
7857       break;
7858     }
7859   }
7860 
7861   if (!InitField)
7862     return Incompatible;
7863 
7864   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7865   return Compatible;
7866 }
7867 
7868 Sema::AssignConvertType
7869 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7870                                        bool Diagnose,
7871                                        bool DiagnoseCFAudited,
7872                                        bool ConvertRHS) {
7873   // We need to be able to tell the caller whether we diagnosed a problem, if
7874   // they ask us to issue diagnostics.
7875   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7876 
7877   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7878   // we can't avoid *all* modifications at the moment, so we need some somewhere
7879   // to put the updated value.
7880   ExprResult LocalRHS = CallerRHS;
7881   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7882 
7883   if (getLangOpts().CPlusPlus) {
7884     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7885       // C++ 5.17p3: If the left operand is not of class type, the
7886       // expression is implicitly converted (C++ 4) to the
7887       // cv-unqualified type of the left operand.
7888       QualType RHSType = RHS.get()->getType();
7889       if (Diagnose) {
7890         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7891                                         AA_Assigning);
7892       } else {
7893         ImplicitConversionSequence ICS =
7894             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7895                                   /*SuppressUserConversions=*/false,
7896                                   /*AllowExplicit=*/false,
7897                                   /*InOverloadResolution=*/false,
7898                                   /*CStyle=*/false,
7899                                   /*AllowObjCWritebackConversion=*/false);
7900         if (ICS.isFailure())
7901           return Incompatible;
7902         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7903                                         ICS, AA_Assigning);
7904       }
7905       if (RHS.isInvalid())
7906         return Incompatible;
7907       Sema::AssignConvertType result = Compatible;
7908       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7909           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7910         result = IncompatibleObjCWeakRef;
7911       return result;
7912     }
7913 
7914     // FIXME: Currently, we fall through and treat C++ classes like C
7915     // structures.
7916     // FIXME: We also fall through for atomics; not sure what should
7917     // happen there, though.
7918   } else if (RHS.get()->getType() == Context.OverloadTy) {
7919     // As a set of extensions to C, we support overloading on functions. These
7920     // functions need to be resolved here.
7921     DeclAccessPair DAP;
7922     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7923             RHS.get(), LHSType, /*Complain=*/false, DAP))
7924       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7925     else
7926       return Incompatible;
7927   }
7928 
7929   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7930   // a null pointer constant.
7931   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7932        LHSType->isBlockPointerType()) &&
7933       RHS.get()->isNullPointerConstant(Context,
7934                                        Expr::NPC_ValueDependentIsNull)) {
7935     if (Diagnose || ConvertRHS) {
7936       CastKind Kind;
7937       CXXCastPath Path;
7938       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7939                              /*IgnoreBaseAccess=*/false, Diagnose);
7940       if (ConvertRHS)
7941         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7942     }
7943     return Compatible;
7944   }
7945 
7946   // This check seems unnatural, however it is necessary to ensure the proper
7947   // conversion of functions/arrays. If the conversion were done for all
7948   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7949   // expressions that suppress this implicit conversion (&, sizeof).
7950   //
7951   // Suppress this for references: C++ 8.5.3p5.
7952   if (!LHSType->isReferenceType()) {
7953     // FIXME: We potentially allocate here even if ConvertRHS is false.
7954     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7955     if (RHS.isInvalid())
7956       return Incompatible;
7957   }
7958 
7959   Expr *PRE = RHS.get()->IgnoreParenCasts();
7960   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7961     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7962     if (PDecl && !PDecl->hasDefinition()) {
7963       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7964       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7965     }
7966   }
7967 
7968   CastKind Kind = CK_Invalid;
7969   Sema::AssignConvertType result =
7970     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7971 
7972   // C99 6.5.16.1p2: The value of the right operand is converted to the
7973   // type of the assignment expression.
7974   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7975   // so that we can use references in built-in functions even in C.
7976   // The getNonReferenceType() call makes sure that the resulting expression
7977   // does not have reference type.
7978   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7979     QualType Ty = LHSType.getNonLValueExprType(Context);
7980     Expr *E = RHS.get();
7981 
7982     // Check for various Objective-C errors. If we are not reporting
7983     // diagnostics and just checking for errors, e.g., during overload
7984     // resolution, return Incompatible to indicate the failure.
7985     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7986         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7987                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
7988       if (!Diagnose)
7989         return Incompatible;
7990     }
7991     if (getLangOpts().ObjC1 &&
7992         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7993                                            E->getType(), E, Diagnose) ||
7994          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7995       if (!Diagnose)
7996         return Incompatible;
7997       // Replace the expression with a corrected version and continue so we
7998       // can find further errors.
7999       RHS = E;
8000       return Compatible;
8001     }
8002 
8003     if (ConvertRHS)
8004       RHS = ImpCastExprToType(E, Ty, Kind);
8005   }
8006   return result;
8007 }
8008 
8009 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8010                                ExprResult &RHS) {
8011   Diag(Loc, diag::err_typecheck_invalid_operands)
8012     << LHS.get()->getType() << RHS.get()->getType()
8013     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8014   return QualType();
8015 }
8016 
8017 /// Try to convert a value of non-vector type to a vector type by converting
8018 /// the type to the element type of the vector and then performing a splat.
8019 /// If the language is OpenCL, we only use conversions that promote scalar
8020 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8021 /// for float->int.
8022 ///
8023 /// \param scalar - if non-null, actually perform the conversions
8024 /// \return true if the operation fails (but without diagnosing the failure)
8025 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8026                                      QualType scalarTy,
8027                                      QualType vectorEltTy,
8028                                      QualType vectorTy) {
8029   // The conversion to apply to the scalar before splatting it,
8030   // if necessary.
8031   CastKind scalarCast = CK_Invalid;
8032 
8033   if (vectorEltTy->isIntegralType(S.Context)) {
8034     if (!scalarTy->isIntegralType(S.Context))
8035       return true;
8036     if (S.getLangOpts().OpenCL &&
8037         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8038       return true;
8039     scalarCast = CK_IntegralCast;
8040   } else if (vectorEltTy->isRealFloatingType()) {
8041     if (scalarTy->isRealFloatingType()) {
8042       if (S.getLangOpts().OpenCL &&
8043           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8044         return true;
8045       scalarCast = CK_FloatingCast;
8046     }
8047     else if (scalarTy->isIntegralType(S.Context))
8048       scalarCast = CK_IntegralToFloating;
8049     else
8050       return true;
8051   } else {
8052     return true;
8053   }
8054 
8055   // Adjust scalar if desired.
8056   if (scalar) {
8057     if (scalarCast != CK_Invalid)
8058       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8059     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8060   }
8061   return false;
8062 }
8063 
8064 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8065                                    SourceLocation Loc, bool IsCompAssign,
8066                                    bool AllowBothBool,
8067                                    bool AllowBoolConversions) {
8068   if (!IsCompAssign) {
8069     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8070     if (LHS.isInvalid())
8071       return QualType();
8072   }
8073   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8074   if (RHS.isInvalid())
8075     return QualType();
8076 
8077   // For conversion purposes, we ignore any qualifiers.
8078   // For example, "const float" and "float" are equivalent.
8079   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8080   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8081 
8082   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8083   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8084   assert(LHSVecType || RHSVecType);
8085 
8086   // AltiVec-style "vector bool op vector bool" combinations are allowed
8087   // for some operators but not others.
8088   if (!AllowBothBool &&
8089       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8090       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8091     return InvalidOperands(Loc, LHS, RHS);
8092 
8093   // If the vector types are identical, return.
8094   if (Context.hasSameType(LHSType, RHSType))
8095     return LHSType;
8096 
8097   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8098   if (LHSVecType && RHSVecType &&
8099       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8100     if (isa<ExtVectorType>(LHSVecType)) {
8101       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8102       return LHSType;
8103     }
8104 
8105     if (!IsCompAssign)
8106       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8107     return RHSType;
8108   }
8109 
8110   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8111   // can be mixed, with the result being the non-bool type.  The non-bool
8112   // operand must have integer element type.
8113   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8114       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8115       (Context.getTypeSize(LHSVecType->getElementType()) ==
8116        Context.getTypeSize(RHSVecType->getElementType()))) {
8117     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8118         LHSVecType->getElementType()->isIntegerType() &&
8119         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8120       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8121       return LHSType;
8122     }
8123     if (!IsCompAssign &&
8124         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8125         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8126         RHSVecType->getElementType()->isIntegerType()) {
8127       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8128       return RHSType;
8129     }
8130   }
8131 
8132   // If there's an ext-vector type and a scalar, try to convert the scalar to
8133   // the vector element type and splat.
8134   // FIXME: this should also work for regular vector types as supported in GCC.
8135   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8136     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8137                                   LHSVecType->getElementType(), LHSType))
8138       return LHSType;
8139   }
8140   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8141     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8142                                   LHSType, RHSVecType->getElementType(),
8143                                   RHSType))
8144       return RHSType;
8145   }
8146 
8147   // FIXME: The code below also handles conversion between vectors and
8148   // non-scalars, we should break this down into fine grained specific checks
8149   // and emit proper diagnostics.
8150   QualType VecType = LHSVecType ? LHSType : RHSType;
8151   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8152   QualType OtherType = LHSVecType ? RHSType : LHSType;
8153   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8154   if (isLaxVectorConversion(OtherType, VecType)) {
8155     // If we're allowing lax vector conversions, only the total (data) size
8156     // needs to be the same. For non compound assignment, if one of the types is
8157     // scalar, the result is always the vector type.
8158     if (!IsCompAssign) {
8159       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8160       return VecType;
8161     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8162     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8163     // type. Note that this is already done by non-compound assignments in
8164     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8165     // <1 x T> -> T. The result is also a vector type.
8166     } else if (OtherType->isExtVectorType() ||
8167                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8168       ExprResult *RHSExpr = &RHS;
8169       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8170       return VecType;
8171     }
8172   }
8173 
8174   // Okay, the expression is invalid.
8175 
8176   // If there's a non-vector, non-real operand, diagnose that.
8177   if ((!RHSVecType && !RHSType->isRealType()) ||
8178       (!LHSVecType && !LHSType->isRealType())) {
8179     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8180       << LHSType << RHSType
8181       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8182     return QualType();
8183   }
8184 
8185   // OpenCL V1.1 6.2.6.p1:
8186   // If the operands are of more than one vector type, then an error shall
8187   // occur. Implicit conversions between vector types are not permitted, per
8188   // section 6.2.1.
8189   if (getLangOpts().OpenCL &&
8190       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8191       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8192     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8193                                                            << RHSType;
8194     return QualType();
8195   }
8196 
8197   // Otherwise, use the generic diagnostic.
8198   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8199     << LHSType << RHSType
8200     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8201   return QualType();
8202 }
8203 
8204 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8205 // expression.  These are mainly cases where the null pointer is used as an
8206 // integer instead of a pointer.
8207 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8208                                 SourceLocation Loc, bool IsCompare) {
8209   // The canonical way to check for a GNU null is with isNullPointerConstant,
8210   // but we use a bit of a hack here for speed; this is a relatively
8211   // hot path, and isNullPointerConstant is slow.
8212   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8213   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8214 
8215   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8216 
8217   // Avoid analyzing cases where the result will either be invalid (and
8218   // diagnosed as such) or entirely valid and not something to warn about.
8219   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8220       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8221     return;
8222 
8223   // Comparison operations would not make sense with a null pointer no matter
8224   // what the other expression is.
8225   if (!IsCompare) {
8226     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8227         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8228         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8229     return;
8230   }
8231 
8232   // The rest of the operations only make sense with a null pointer
8233   // if the other expression is a pointer.
8234   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8235       NonNullType->canDecayToPointerType())
8236     return;
8237 
8238   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8239       << LHSNull /* LHS is NULL */ << NonNullType
8240       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8241 }
8242 
8243 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8244                                                ExprResult &RHS,
8245                                                SourceLocation Loc, bool IsDiv) {
8246   // Check for division/remainder by zero.
8247   llvm::APSInt RHSValue;
8248   if (!RHS.get()->isValueDependent() &&
8249       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8250     S.DiagRuntimeBehavior(Loc, RHS.get(),
8251                           S.PDiag(diag::warn_remainder_division_by_zero)
8252                             << IsDiv << RHS.get()->getSourceRange());
8253 }
8254 
8255 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8256                                            SourceLocation Loc,
8257                                            bool IsCompAssign, bool IsDiv) {
8258   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8259 
8260   if (LHS.get()->getType()->isVectorType() ||
8261       RHS.get()->getType()->isVectorType())
8262     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8263                                /*AllowBothBool*/getLangOpts().AltiVec,
8264                                /*AllowBoolConversions*/false);
8265 
8266   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8267   if (LHS.isInvalid() || RHS.isInvalid())
8268     return QualType();
8269 
8270 
8271   if (compType.isNull() || !compType->isArithmeticType())
8272     return InvalidOperands(Loc, LHS, RHS);
8273   if (IsDiv)
8274     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8275   return compType;
8276 }
8277 
8278 QualType Sema::CheckRemainderOperands(
8279   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8280   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8281 
8282   if (LHS.get()->getType()->isVectorType() ||
8283       RHS.get()->getType()->isVectorType()) {
8284     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8285         RHS.get()->getType()->hasIntegerRepresentation())
8286       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8287                                  /*AllowBothBool*/getLangOpts().AltiVec,
8288                                  /*AllowBoolConversions*/false);
8289     return InvalidOperands(Loc, LHS, RHS);
8290   }
8291 
8292   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8293   if (LHS.isInvalid() || RHS.isInvalid())
8294     return QualType();
8295 
8296   if (compType.isNull() || !compType->isIntegerType())
8297     return InvalidOperands(Loc, LHS, RHS);
8298   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8299   return compType;
8300 }
8301 
8302 /// \brief Diagnose invalid arithmetic on two void pointers.
8303 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8304                                                 Expr *LHSExpr, Expr *RHSExpr) {
8305   S.Diag(Loc, S.getLangOpts().CPlusPlus
8306                 ? diag::err_typecheck_pointer_arith_void_type
8307                 : diag::ext_gnu_void_ptr)
8308     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8309                             << RHSExpr->getSourceRange();
8310 }
8311 
8312 /// \brief Diagnose invalid arithmetic on a void pointer.
8313 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8314                                             Expr *Pointer) {
8315   S.Diag(Loc, S.getLangOpts().CPlusPlus
8316                 ? diag::err_typecheck_pointer_arith_void_type
8317                 : diag::ext_gnu_void_ptr)
8318     << 0 /* one pointer */ << Pointer->getSourceRange();
8319 }
8320 
8321 /// \brief Diagnose invalid arithmetic on two function pointers.
8322 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8323                                                     Expr *LHS, Expr *RHS) {
8324   assert(LHS->getType()->isAnyPointerType());
8325   assert(RHS->getType()->isAnyPointerType());
8326   S.Diag(Loc, S.getLangOpts().CPlusPlus
8327                 ? diag::err_typecheck_pointer_arith_function_type
8328                 : diag::ext_gnu_ptr_func_arith)
8329     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8330     // We only show the second type if it differs from the first.
8331     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8332                                                    RHS->getType())
8333     << RHS->getType()->getPointeeType()
8334     << LHS->getSourceRange() << RHS->getSourceRange();
8335 }
8336 
8337 /// \brief Diagnose invalid arithmetic on a function pointer.
8338 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8339                                                 Expr *Pointer) {
8340   assert(Pointer->getType()->isAnyPointerType());
8341   S.Diag(Loc, S.getLangOpts().CPlusPlus
8342                 ? diag::err_typecheck_pointer_arith_function_type
8343                 : diag::ext_gnu_ptr_func_arith)
8344     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8345     << 0 /* one pointer, so only one type */
8346     << Pointer->getSourceRange();
8347 }
8348 
8349 /// \brief Emit error if Operand is incomplete pointer type
8350 ///
8351 /// \returns True if pointer has incomplete type
8352 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8353                                                  Expr *Operand) {
8354   QualType ResType = Operand->getType();
8355   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8356     ResType = ResAtomicType->getValueType();
8357 
8358   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8359   QualType PointeeTy = ResType->getPointeeType();
8360   return S.RequireCompleteType(Loc, PointeeTy,
8361                                diag::err_typecheck_arithmetic_incomplete_type,
8362                                PointeeTy, Operand->getSourceRange());
8363 }
8364 
8365 /// \brief Check the validity of an arithmetic pointer operand.
8366 ///
8367 /// If the operand has pointer type, this code will check for pointer types
8368 /// which are invalid in arithmetic operations. These will be diagnosed
8369 /// appropriately, including whether or not the use is supported as an
8370 /// extension.
8371 ///
8372 /// \returns True when the operand is valid to use (even if as an extension).
8373 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8374                                             Expr *Operand) {
8375   QualType ResType = Operand->getType();
8376   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8377     ResType = ResAtomicType->getValueType();
8378 
8379   if (!ResType->isAnyPointerType()) return true;
8380 
8381   QualType PointeeTy = ResType->getPointeeType();
8382   if (PointeeTy->isVoidType()) {
8383     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8384     return !S.getLangOpts().CPlusPlus;
8385   }
8386   if (PointeeTy->isFunctionType()) {
8387     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8388     return !S.getLangOpts().CPlusPlus;
8389   }
8390 
8391   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8392 
8393   return true;
8394 }
8395 
8396 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8397 /// operands.
8398 ///
8399 /// This routine will diagnose any invalid arithmetic on pointer operands much
8400 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8401 /// for emitting a single diagnostic even for operations where both LHS and RHS
8402 /// are (potentially problematic) pointers.
8403 ///
8404 /// \returns True when the operand is valid to use (even if as an extension).
8405 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8406                                                 Expr *LHSExpr, Expr *RHSExpr) {
8407   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8408   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8409   if (!isLHSPointer && !isRHSPointer) return true;
8410 
8411   QualType LHSPointeeTy, RHSPointeeTy;
8412   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8413   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8414 
8415   // if both are pointers check if operation is valid wrt address spaces
8416   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8417     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8418     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8419     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8420       S.Diag(Loc,
8421              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8422           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8423           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8424       return false;
8425     }
8426   }
8427 
8428   // Check for arithmetic on pointers to incomplete types.
8429   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8430   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8431   if (isLHSVoidPtr || isRHSVoidPtr) {
8432     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8433     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8434     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8435 
8436     return !S.getLangOpts().CPlusPlus;
8437   }
8438 
8439   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8440   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8441   if (isLHSFuncPtr || isRHSFuncPtr) {
8442     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8443     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8444                                                                 RHSExpr);
8445     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8446 
8447     return !S.getLangOpts().CPlusPlus;
8448   }
8449 
8450   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8451     return false;
8452   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8453     return false;
8454 
8455   return true;
8456 }
8457 
8458 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8459 /// literal.
8460 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8461                                   Expr *LHSExpr, Expr *RHSExpr) {
8462   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8463   Expr* IndexExpr = RHSExpr;
8464   if (!StrExpr) {
8465     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8466     IndexExpr = LHSExpr;
8467   }
8468 
8469   bool IsStringPlusInt = StrExpr &&
8470       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8471   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8472     return;
8473 
8474   llvm::APSInt index;
8475   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8476     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8477     if (index.isNonNegative() &&
8478         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8479                               index.isUnsigned()))
8480       return;
8481   }
8482 
8483   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8484   Self.Diag(OpLoc, diag::warn_string_plus_int)
8485       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8486 
8487   // Only print a fixit for "str" + int, not for int + "str".
8488   if (IndexExpr == RHSExpr) {
8489     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8490     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8491         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8492         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8493         << FixItHint::CreateInsertion(EndLoc, "]");
8494   } else
8495     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8496 }
8497 
8498 /// \brief Emit a warning when adding a char literal to a string.
8499 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8500                                    Expr *LHSExpr, Expr *RHSExpr) {
8501   const Expr *StringRefExpr = LHSExpr;
8502   const CharacterLiteral *CharExpr =
8503       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8504 
8505   if (!CharExpr) {
8506     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8507     StringRefExpr = RHSExpr;
8508   }
8509 
8510   if (!CharExpr || !StringRefExpr)
8511     return;
8512 
8513   const QualType StringType = StringRefExpr->getType();
8514 
8515   // Return if not a PointerType.
8516   if (!StringType->isAnyPointerType())
8517     return;
8518 
8519   // Return if not a CharacterType.
8520   if (!StringType->getPointeeType()->isAnyCharacterType())
8521     return;
8522 
8523   ASTContext &Ctx = Self.getASTContext();
8524   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8525 
8526   const QualType CharType = CharExpr->getType();
8527   if (!CharType->isAnyCharacterType() &&
8528       CharType->isIntegerType() &&
8529       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8530     Self.Diag(OpLoc, diag::warn_string_plus_char)
8531         << DiagRange << Ctx.CharTy;
8532   } else {
8533     Self.Diag(OpLoc, diag::warn_string_plus_char)
8534         << DiagRange << CharExpr->getType();
8535   }
8536 
8537   // Only print a fixit for str + char, not for char + str.
8538   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8539     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8540     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8541         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8542         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8543         << FixItHint::CreateInsertion(EndLoc, "]");
8544   } else {
8545     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8546   }
8547 }
8548 
8549 /// \brief Emit error when two pointers are incompatible.
8550 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8551                                            Expr *LHSExpr, Expr *RHSExpr) {
8552   assert(LHSExpr->getType()->isAnyPointerType());
8553   assert(RHSExpr->getType()->isAnyPointerType());
8554   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8555     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8556     << RHSExpr->getSourceRange();
8557 }
8558 
8559 // C99 6.5.6
8560 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8561                                      SourceLocation Loc, BinaryOperatorKind Opc,
8562                                      QualType* CompLHSTy) {
8563   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8564 
8565   if (LHS.get()->getType()->isVectorType() ||
8566       RHS.get()->getType()->isVectorType()) {
8567     QualType compType = CheckVectorOperands(
8568         LHS, RHS, Loc, CompLHSTy,
8569         /*AllowBothBool*/getLangOpts().AltiVec,
8570         /*AllowBoolConversions*/getLangOpts().ZVector);
8571     if (CompLHSTy) *CompLHSTy = compType;
8572     return compType;
8573   }
8574 
8575   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8576   if (LHS.isInvalid() || RHS.isInvalid())
8577     return QualType();
8578 
8579   // Diagnose "string literal" '+' int and string '+' "char literal".
8580   if (Opc == BO_Add) {
8581     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8582     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8583   }
8584 
8585   // handle the common case first (both operands are arithmetic).
8586   if (!compType.isNull() && compType->isArithmeticType()) {
8587     if (CompLHSTy) *CompLHSTy = compType;
8588     return compType;
8589   }
8590 
8591   // Type-checking.  Ultimately the pointer's going to be in PExp;
8592   // note that we bias towards the LHS being the pointer.
8593   Expr *PExp = LHS.get(), *IExp = RHS.get();
8594 
8595   bool isObjCPointer;
8596   if (PExp->getType()->isPointerType()) {
8597     isObjCPointer = false;
8598   } else if (PExp->getType()->isObjCObjectPointerType()) {
8599     isObjCPointer = true;
8600   } else {
8601     std::swap(PExp, IExp);
8602     if (PExp->getType()->isPointerType()) {
8603       isObjCPointer = false;
8604     } else if (PExp->getType()->isObjCObjectPointerType()) {
8605       isObjCPointer = true;
8606     } else {
8607       return InvalidOperands(Loc, LHS, RHS);
8608     }
8609   }
8610   assert(PExp->getType()->isAnyPointerType());
8611 
8612   if (!IExp->getType()->isIntegerType())
8613     return InvalidOperands(Loc, LHS, RHS);
8614 
8615   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8616     return QualType();
8617 
8618   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8619     return QualType();
8620 
8621   // Check array bounds for pointer arithemtic
8622   CheckArrayAccess(PExp, IExp);
8623 
8624   if (CompLHSTy) {
8625     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8626     if (LHSTy.isNull()) {
8627       LHSTy = LHS.get()->getType();
8628       if (LHSTy->isPromotableIntegerType())
8629         LHSTy = Context.getPromotedIntegerType(LHSTy);
8630     }
8631     *CompLHSTy = LHSTy;
8632   }
8633 
8634   return PExp->getType();
8635 }
8636 
8637 // C99 6.5.6
8638 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8639                                         SourceLocation Loc,
8640                                         QualType* CompLHSTy) {
8641   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8642 
8643   if (LHS.get()->getType()->isVectorType() ||
8644       RHS.get()->getType()->isVectorType()) {
8645     QualType compType = CheckVectorOperands(
8646         LHS, RHS, Loc, CompLHSTy,
8647         /*AllowBothBool*/getLangOpts().AltiVec,
8648         /*AllowBoolConversions*/getLangOpts().ZVector);
8649     if (CompLHSTy) *CompLHSTy = compType;
8650     return compType;
8651   }
8652 
8653   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8654   if (LHS.isInvalid() || RHS.isInvalid())
8655     return QualType();
8656 
8657   // Enforce type constraints: C99 6.5.6p3.
8658 
8659   // Handle the common case first (both operands are arithmetic).
8660   if (!compType.isNull() && compType->isArithmeticType()) {
8661     if (CompLHSTy) *CompLHSTy = compType;
8662     return compType;
8663   }
8664 
8665   // Either ptr - int   or   ptr - ptr.
8666   if (LHS.get()->getType()->isAnyPointerType()) {
8667     QualType lpointee = LHS.get()->getType()->getPointeeType();
8668 
8669     // Diagnose bad cases where we step over interface counts.
8670     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8671         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8672       return QualType();
8673 
8674     // The result type of a pointer-int computation is the pointer type.
8675     if (RHS.get()->getType()->isIntegerType()) {
8676       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8677         return QualType();
8678 
8679       // Check array bounds for pointer arithemtic
8680       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8681                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8682 
8683       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8684       return LHS.get()->getType();
8685     }
8686 
8687     // Handle pointer-pointer subtractions.
8688     if (const PointerType *RHSPTy
8689           = RHS.get()->getType()->getAs<PointerType>()) {
8690       QualType rpointee = RHSPTy->getPointeeType();
8691 
8692       if (getLangOpts().CPlusPlus) {
8693         // Pointee types must be the same: C++ [expr.add]
8694         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8695           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8696         }
8697       } else {
8698         // Pointee types must be compatible C99 6.5.6p3
8699         if (!Context.typesAreCompatible(
8700                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8701                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8702           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8703           return QualType();
8704         }
8705       }
8706 
8707       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8708                                                LHS.get(), RHS.get()))
8709         return QualType();
8710 
8711       // The pointee type may have zero size.  As an extension, a structure or
8712       // union may have zero size or an array may have zero length.  In this
8713       // case subtraction does not make sense.
8714       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8715         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8716         if (ElementSize.isZero()) {
8717           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8718             << rpointee.getUnqualifiedType()
8719             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8720         }
8721       }
8722 
8723       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8724       return Context.getPointerDiffType();
8725     }
8726   }
8727 
8728   return InvalidOperands(Loc, LHS, RHS);
8729 }
8730 
8731 static bool isScopedEnumerationType(QualType T) {
8732   if (const EnumType *ET = T->getAs<EnumType>())
8733     return ET->getDecl()->isScoped();
8734   return false;
8735 }
8736 
8737 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8738                                    SourceLocation Loc, BinaryOperatorKind Opc,
8739                                    QualType LHSType) {
8740   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8741   // so skip remaining warnings as we don't want to modify values within Sema.
8742   if (S.getLangOpts().OpenCL)
8743     return;
8744 
8745   llvm::APSInt Right;
8746   // Check right/shifter operand
8747   if (RHS.get()->isValueDependent() ||
8748       !RHS.get()->EvaluateAsInt(Right, S.Context))
8749     return;
8750 
8751   if (Right.isNegative()) {
8752     S.DiagRuntimeBehavior(Loc, RHS.get(),
8753                           S.PDiag(diag::warn_shift_negative)
8754                             << RHS.get()->getSourceRange());
8755     return;
8756   }
8757   llvm::APInt LeftBits(Right.getBitWidth(),
8758                        S.Context.getTypeSize(LHS.get()->getType()));
8759   if (Right.uge(LeftBits)) {
8760     S.DiagRuntimeBehavior(Loc, RHS.get(),
8761                           S.PDiag(diag::warn_shift_gt_typewidth)
8762                             << RHS.get()->getSourceRange());
8763     return;
8764   }
8765   if (Opc != BO_Shl)
8766     return;
8767 
8768   // When left shifting an ICE which is signed, we can check for overflow which
8769   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8770   // integers have defined behavior modulo one more than the maximum value
8771   // representable in the result type, so never warn for those.
8772   llvm::APSInt Left;
8773   if (LHS.get()->isValueDependent() ||
8774       LHSType->hasUnsignedIntegerRepresentation() ||
8775       !LHS.get()->EvaluateAsInt(Left, S.Context))
8776     return;
8777 
8778   // If LHS does not have a signed type and non-negative value
8779   // then, the behavior is undefined. Warn about it.
8780   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8781     S.DiagRuntimeBehavior(Loc, LHS.get(),
8782                           S.PDiag(diag::warn_shift_lhs_negative)
8783                             << LHS.get()->getSourceRange());
8784     return;
8785   }
8786 
8787   llvm::APInt ResultBits =
8788       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8789   if (LeftBits.uge(ResultBits))
8790     return;
8791   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8792   Result = Result.shl(Right);
8793 
8794   // Print the bit representation of the signed integer as an unsigned
8795   // hexadecimal number.
8796   SmallString<40> HexResult;
8797   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8798 
8799   // If we are only missing a sign bit, this is less likely to result in actual
8800   // bugs -- if the result is cast back to an unsigned type, it will have the
8801   // expected value. Thus we place this behind a different warning that can be
8802   // turned off separately if needed.
8803   if (LeftBits == ResultBits - 1) {
8804     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8805         << HexResult << LHSType
8806         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8807     return;
8808   }
8809 
8810   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8811     << HexResult.str() << Result.getMinSignedBits() << LHSType
8812     << Left.getBitWidth() << LHS.get()->getSourceRange()
8813     << RHS.get()->getSourceRange();
8814 }
8815 
8816 /// \brief Return the resulting type when a vector is shifted
8817 ///        by a scalar or vector shift amount.
8818 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8819                                  SourceLocation Loc, bool IsCompAssign) {
8820   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8821   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8822       !LHS.get()->getType()->isVectorType()) {
8823     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8824       << RHS.get()->getType() << LHS.get()->getType()
8825       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8826     return QualType();
8827   }
8828 
8829   if (!IsCompAssign) {
8830     LHS = S.UsualUnaryConversions(LHS.get());
8831     if (LHS.isInvalid()) return QualType();
8832   }
8833 
8834   RHS = S.UsualUnaryConversions(RHS.get());
8835   if (RHS.isInvalid()) return QualType();
8836 
8837   QualType LHSType = LHS.get()->getType();
8838   // Note that LHS might be a scalar because the routine calls not only in
8839   // OpenCL case.
8840   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8841   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8842 
8843   // Note that RHS might not be a vector.
8844   QualType RHSType = RHS.get()->getType();
8845   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8846   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8847 
8848   // The operands need to be integers.
8849   if (!LHSEleType->isIntegerType()) {
8850     S.Diag(Loc, diag::err_typecheck_expect_int)
8851       << LHS.get()->getType() << LHS.get()->getSourceRange();
8852     return QualType();
8853   }
8854 
8855   if (!RHSEleType->isIntegerType()) {
8856     S.Diag(Loc, diag::err_typecheck_expect_int)
8857       << RHS.get()->getType() << RHS.get()->getSourceRange();
8858     return QualType();
8859   }
8860 
8861   if (!LHSVecTy) {
8862     assert(RHSVecTy);
8863     if (IsCompAssign)
8864       return RHSType;
8865     if (LHSEleType != RHSEleType) {
8866       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8867       LHSEleType = RHSEleType;
8868     }
8869     QualType VecTy =
8870         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8871     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8872     LHSType = VecTy;
8873   } else if (RHSVecTy) {
8874     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8875     // are applied component-wise. So if RHS is a vector, then ensure
8876     // that the number of elements is the same as LHS...
8877     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8878       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8879         << LHS.get()->getType() << RHS.get()->getType()
8880         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8881       return QualType();
8882     }
8883     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8884       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8885       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8886       if (LHSBT != RHSBT &&
8887           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8888         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8889             << LHS.get()->getType() << RHS.get()->getType()
8890             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8891       }
8892     }
8893   } else {
8894     // ...else expand RHS to match the number of elements in LHS.
8895     QualType VecTy =
8896       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8897     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8898   }
8899 
8900   return LHSType;
8901 }
8902 
8903 // C99 6.5.7
8904 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8905                                   SourceLocation Loc, BinaryOperatorKind Opc,
8906                                   bool IsCompAssign) {
8907   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8908 
8909   // Vector shifts promote their scalar inputs to vector type.
8910   if (LHS.get()->getType()->isVectorType() ||
8911       RHS.get()->getType()->isVectorType()) {
8912     if (LangOpts.ZVector) {
8913       // The shift operators for the z vector extensions work basically
8914       // like general shifts, except that neither the LHS nor the RHS is
8915       // allowed to be a "vector bool".
8916       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8917         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8918           return InvalidOperands(Loc, LHS, RHS);
8919       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8920         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8921           return InvalidOperands(Loc, LHS, RHS);
8922     }
8923     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8924   }
8925 
8926   // Shifts don't perform usual arithmetic conversions, they just do integer
8927   // promotions on each operand. C99 6.5.7p3
8928 
8929   // For the LHS, do usual unary conversions, but then reset them away
8930   // if this is a compound assignment.
8931   ExprResult OldLHS = LHS;
8932   LHS = UsualUnaryConversions(LHS.get());
8933   if (LHS.isInvalid())
8934     return QualType();
8935   QualType LHSType = LHS.get()->getType();
8936   if (IsCompAssign) LHS = OldLHS;
8937 
8938   // The RHS is simpler.
8939   RHS = UsualUnaryConversions(RHS.get());
8940   if (RHS.isInvalid())
8941     return QualType();
8942   QualType RHSType = RHS.get()->getType();
8943 
8944   // C99 6.5.7p2: Each of the operands shall have integer type.
8945   if (!LHSType->hasIntegerRepresentation() ||
8946       !RHSType->hasIntegerRepresentation())
8947     return InvalidOperands(Loc, LHS, RHS);
8948 
8949   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8950   // hasIntegerRepresentation() above instead of this.
8951   if (isScopedEnumerationType(LHSType) ||
8952       isScopedEnumerationType(RHSType)) {
8953     return InvalidOperands(Loc, LHS, RHS);
8954   }
8955   // Sanity-check shift operands
8956   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8957 
8958   // "The type of the result is that of the promoted left operand."
8959   return LHSType;
8960 }
8961 
8962 static bool IsWithinTemplateSpecialization(Decl *D) {
8963   if (DeclContext *DC = D->getDeclContext()) {
8964     if (isa<ClassTemplateSpecializationDecl>(DC))
8965       return true;
8966     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8967       return FD->isFunctionTemplateSpecialization();
8968   }
8969   return false;
8970 }
8971 
8972 /// If two different enums are compared, raise a warning.
8973 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8974                                 Expr *RHS) {
8975   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8976   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8977 
8978   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8979   if (!LHSEnumType)
8980     return;
8981   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8982   if (!RHSEnumType)
8983     return;
8984 
8985   // Ignore anonymous enums.
8986   if (!LHSEnumType->getDecl()->getIdentifier())
8987     return;
8988   if (!RHSEnumType->getDecl()->getIdentifier())
8989     return;
8990 
8991   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8992     return;
8993 
8994   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8995       << LHSStrippedType << RHSStrippedType
8996       << LHS->getSourceRange() << RHS->getSourceRange();
8997 }
8998 
8999 /// \brief Diagnose bad pointer comparisons.
9000 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9001                                               ExprResult &LHS, ExprResult &RHS,
9002                                               bool IsError) {
9003   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9004                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9005     << LHS.get()->getType() << RHS.get()->getType()
9006     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9007 }
9008 
9009 /// \brief Returns false if the pointers are converted to a composite type,
9010 /// true otherwise.
9011 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9012                                            ExprResult &LHS, ExprResult &RHS) {
9013   // C++ [expr.rel]p2:
9014   //   [...] Pointer conversions (4.10) and qualification
9015   //   conversions (4.4) are performed on pointer operands (or on
9016   //   a pointer operand and a null pointer constant) to bring
9017   //   them to their composite pointer type. [...]
9018   //
9019   // C++ [expr.eq]p1 uses the same notion for (in)equality
9020   // comparisons of pointers.
9021 
9022   QualType LHSType = LHS.get()->getType();
9023   QualType RHSType = RHS.get()->getType();
9024   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9025          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9026 
9027   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9028   if (T.isNull()) {
9029     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9030         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9031       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9032     else
9033       S.InvalidOperands(Loc, LHS, RHS);
9034     return true;
9035   }
9036 
9037   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9038   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9039   return false;
9040 }
9041 
9042 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9043                                                     ExprResult &LHS,
9044                                                     ExprResult &RHS,
9045                                                     bool IsError) {
9046   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9047                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9048     << LHS.get()->getType() << RHS.get()->getType()
9049     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9050 }
9051 
9052 static bool isObjCObjectLiteral(ExprResult &E) {
9053   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9054   case Stmt::ObjCArrayLiteralClass:
9055   case Stmt::ObjCDictionaryLiteralClass:
9056   case Stmt::ObjCStringLiteralClass:
9057   case Stmt::ObjCBoxedExprClass:
9058     return true;
9059   default:
9060     // Note that ObjCBoolLiteral is NOT an object literal!
9061     return false;
9062   }
9063 }
9064 
9065 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9066   const ObjCObjectPointerType *Type =
9067     LHS->getType()->getAs<ObjCObjectPointerType>();
9068 
9069   // If this is not actually an Objective-C object, bail out.
9070   if (!Type)
9071     return false;
9072 
9073   // Get the LHS object's interface type.
9074   QualType InterfaceType = Type->getPointeeType();
9075 
9076   // If the RHS isn't an Objective-C object, bail out.
9077   if (!RHS->getType()->isObjCObjectPointerType())
9078     return false;
9079 
9080   // Try to find the -isEqual: method.
9081   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9082   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9083                                                       InterfaceType,
9084                                                       /*instance=*/true);
9085   if (!Method) {
9086     if (Type->isObjCIdType()) {
9087       // For 'id', just check the global pool.
9088       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9089                                                   /*receiverId=*/true);
9090     } else {
9091       // Check protocols.
9092       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9093                                              /*instance=*/true);
9094     }
9095   }
9096 
9097   if (!Method)
9098     return false;
9099 
9100   QualType T = Method->parameters()[0]->getType();
9101   if (!T->isObjCObjectPointerType())
9102     return false;
9103 
9104   QualType R = Method->getReturnType();
9105   if (!R->isScalarType())
9106     return false;
9107 
9108   return true;
9109 }
9110 
9111 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9112   FromE = FromE->IgnoreParenImpCasts();
9113   switch (FromE->getStmtClass()) {
9114     default:
9115       break;
9116     case Stmt::ObjCStringLiteralClass:
9117       // "string literal"
9118       return LK_String;
9119     case Stmt::ObjCArrayLiteralClass:
9120       // "array literal"
9121       return LK_Array;
9122     case Stmt::ObjCDictionaryLiteralClass:
9123       // "dictionary literal"
9124       return LK_Dictionary;
9125     case Stmt::BlockExprClass:
9126       return LK_Block;
9127     case Stmt::ObjCBoxedExprClass: {
9128       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9129       switch (Inner->getStmtClass()) {
9130         case Stmt::IntegerLiteralClass:
9131         case Stmt::FloatingLiteralClass:
9132         case Stmt::CharacterLiteralClass:
9133         case Stmt::ObjCBoolLiteralExprClass:
9134         case Stmt::CXXBoolLiteralExprClass:
9135           // "numeric literal"
9136           return LK_Numeric;
9137         case Stmt::ImplicitCastExprClass: {
9138           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9139           // Boolean literals can be represented by implicit casts.
9140           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9141             return LK_Numeric;
9142           break;
9143         }
9144         default:
9145           break;
9146       }
9147       return LK_Boxed;
9148     }
9149   }
9150   return LK_None;
9151 }
9152 
9153 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9154                                           ExprResult &LHS, ExprResult &RHS,
9155                                           BinaryOperator::Opcode Opc){
9156   Expr *Literal;
9157   Expr *Other;
9158   if (isObjCObjectLiteral(LHS)) {
9159     Literal = LHS.get();
9160     Other = RHS.get();
9161   } else {
9162     Literal = RHS.get();
9163     Other = LHS.get();
9164   }
9165 
9166   // Don't warn on comparisons against nil.
9167   Other = Other->IgnoreParenCasts();
9168   if (Other->isNullPointerConstant(S.getASTContext(),
9169                                    Expr::NPC_ValueDependentIsNotNull))
9170     return;
9171 
9172   // This should be kept in sync with warn_objc_literal_comparison.
9173   // LK_String should always be after the other literals, since it has its own
9174   // warning flag.
9175   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9176   assert(LiteralKind != Sema::LK_Block);
9177   if (LiteralKind == Sema::LK_None) {
9178     llvm_unreachable("Unknown Objective-C object literal kind");
9179   }
9180 
9181   if (LiteralKind == Sema::LK_String)
9182     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9183       << Literal->getSourceRange();
9184   else
9185     S.Diag(Loc, diag::warn_objc_literal_comparison)
9186       << LiteralKind << Literal->getSourceRange();
9187 
9188   if (BinaryOperator::isEqualityOp(Opc) &&
9189       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9190     SourceLocation Start = LHS.get()->getLocStart();
9191     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9192     CharSourceRange OpRange =
9193       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9194 
9195     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9196       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9197       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9198       << FixItHint::CreateInsertion(End, "]");
9199   }
9200 }
9201 
9202 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9203 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9204                                            ExprResult &RHS, SourceLocation Loc,
9205                                            BinaryOperatorKind Opc) {
9206   // Check that left hand side is !something.
9207   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9208   if (!UO || UO->getOpcode() != UO_LNot) return;
9209 
9210   // Only check if the right hand side is non-bool arithmetic type.
9211   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9212 
9213   // Make sure that the something in !something is not bool.
9214   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9215   if (SubExpr->isKnownToHaveBooleanValue()) return;
9216 
9217   // Emit warning.
9218   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9219   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9220       << Loc << IsBitwiseOp;
9221 
9222   // First note suggest !(x < y)
9223   SourceLocation FirstOpen = SubExpr->getLocStart();
9224   SourceLocation FirstClose = RHS.get()->getLocEnd();
9225   FirstClose = S.getLocForEndOfToken(FirstClose);
9226   if (FirstClose.isInvalid())
9227     FirstOpen = SourceLocation();
9228   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9229       << IsBitwiseOp
9230       << FixItHint::CreateInsertion(FirstOpen, "(")
9231       << FixItHint::CreateInsertion(FirstClose, ")");
9232 
9233   // Second note suggests (!x) < y
9234   SourceLocation SecondOpen = LHS.get()->getLocStart();
9235   SourceLocation SecondClose = LHS.get()->getLocEnd();
9236   SecondClose = S.getLocForEndOfToken(SecondClose);
9237   if (SecondClose.isInvalid())
9238     SecondOpen = SourceLocation();
9239   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9240       << FixItHint::CreateInsertion(SecondOpen, "(")
9241       << FixItHint::CreateInsertion(SecondClose, ")");
9242 }
9243 
9244 // Get the decl for a simple expression: a reference to a variable,
9245 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9246 static ValueDecl *getCompareDecl(Expr *E) {
9247   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9248     return DR->getDecl();
9249   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9250     if (Ivar->isFreeIvar())
9251       return Ivar->getDecl();
9252   }
9253   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9254     if (Mem->isImplicitAccess())
9255       return Mem->getMemberDecl();
9256   }
9257   return nullptr;
9258 }
9259 
9260 // C99 6.5.8, C++ [expr.rel]
9261 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9262                                     SourceLocation Loc, BinaryOperatorKind Opc,
9263                                     bool IsRelational) {
9264   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9265 
9266   // Handle vector comparisons separately.
9267   if (LHS.get()->getType()->isVectorType() ||
9268       RHS.get()->getType()->isVectorType())
9269     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9270 
9271   QualType LHSType = LHS.get()->getType();
9272   QualType RHSType = RHS.get()->getType();
9273 
9274   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9275   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9276 
9277   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9278   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9279 
9280   if (!LHSType->hasFloatingRepresentation() &&
9281       !(LHSType->isBlockPointerType() && IsRelational) &&
9282       !LHS.get()->getLocStart().isMacroID() &&
9283       !RHS.get()->getLocStart().isMacroID() &&
9284       !inTemplateInstantiation()) {
9285     // For non-floating point types, check for self-comparisons of the form
9286     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9287     // often indicate logic errors in the program.
9288     //
9289     // NOTE: Don't warn about comparison expressions resulting from macro
9290     // expansion. Also don't warn about comparisons which are only self
9291     // comparisons within a template specialization. The warnings should catch
9292     // obvious cases in the definition of the template anyways. The idea is to
9293     // warn when the typed comparison operator will always evaluate to the same
9294     // result.
9295     ValueDecl *DL = getCompareDecl(LHSStripped);
9296     ValueDecl *DR = getCompareDecl(RHSStripped);
9297     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9298       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9299                           << 0 // self-
9300                           << (Opc == BO_EQ
9301                               || Opc == BO_LE
9302                               || Opc == BO_GE));
9303     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9304                !DL->getType()->isReferenceType() &&
9305                !DR->getType()->isReferenceType()) {
9306         // what is it always going to eval to?
9307         char always_evals_to;
9308         switch(Opc) {
9309         case BO_EQ: // e.g. array1 == array2
9310           always_evals_to = 0; // false
9311           break;
9312         case BO_NE: // e.g. array1 != array2
9313           always_evals_to = 1; // true
9314           break;
9315         default:
9316           // best we can say is 'a constant'
9317           always_evals_to = 2; // e.g. array1 <= array2
9318           break;
9319         }
9320         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9321                             << 1 // array
9322                             << always_evals_to);
9323     }
9324 
9325     if (isa<CastExpr>(LHSStripped))
9326       LHSStripped = LHSStripped->IgnoreParenCasts();
9327     if (isa<CastExpr>(RHSStripped))
9328       RHSStripped = RHSStripped->IgnoreParenCasts();
9329 
9330     // Warn about comparisons against a string constant (unless the other
9331     // operand is null), the user probably wants strcmp.
9332     Expr *literalString = nullptr;
9333     Expr *literalStringStripped = nullptr;
9334     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9335         !RHSStripped->isNullPointerConstant(Context,
9336                                             Expr::NPC_ValueDependentIsNull)) {
9337       literalString = LHS.get();
9338       literalStringStripped = LHSStripped;
9339     } else if ((isa<StringLiteral>(RHSStripped) ||
9340                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9341                !LHSStripped->isNullPointerConstant(Context,
9342                                             Expr::NPC_ValueDependentIsNull)) {
9343       literalString = RHS.get();
9344       literalStringStripped = RHSStripped;
9345     }
9346 
9347     if (literalString) {
9348       DiagRuntimeBehavior(Loc, nullptr,
9349         PDiag(diag::warn_stringcompare)
9350           << isa<ObjCEncodeExpr>(literalStringStripped)
9351           << literalString->getSourceRange());
9352     }
9353   }
9354 
9355   // C99 6.5.8p3 / C99 6.5.9p4
9356   UsualArithmeticConversions(LHS, RHS);
9357   if (LHS.isInvalid() || RHS.isInvalid())
9358     return QualType();
9359 
9360   LHSType = LHS.get()->getType();
9361   RHSType = RHS.get()->getType();
9362 
9363   // The result of comparisons is 'bool' in C++, 'int' in C.
9364   QualType ResultTy = Context.getLogicalOperationType();
9365 
9366   if (IsRelational) {
9367     if (LHSType->isRealType() && RHSType->isRealType())
9368       return ResultTy;
9369   } else {
9370     // Check for comparisons of floating point operands using != and ==.
9371     if (LHSType->hasFloatingRepresentation())
9372       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9373 
9374     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9375       return ResultTy;
9376   }
9377 
9378   const Expr::NullPointerConstantKind LHSNullKind =
9379       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9380   const Expr::NullPointerConstantKind RHSNullKind =
9381       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9382   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9383   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9384 
9385   if (!IsRelational && LHSIsNull != RHSIsNull) {
9386     bool IsEquality = Opc == BO_EQ;
9387     if (RHSIsNull)
9388       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9389                                    RHS.get()->getSourceRange());
9390     else
9391       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9392                                    LHS.get()->getSourceRange());
9393   }
9394 
9395   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9396       (RHSType->isIntegerType() && !RHSIsNull)) {
9397     // Skip normal pointer conversion checks in this case; we have better
9398     // diagnostics for this below.
9399   } else if (getLangOpts().CPlusPlus) {
9400     // Equality comparison of a function pointer to a void pointer is invalid,
9401     // but we allow it as an extension.
9402     // FIXME: If we really want to allow this, should it be part of composite
9403     // pointer type computation so it works in conditionals too?
9404     if (!IsRelational &&
9405         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9406          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9407       // This is a gcc extension compatibility comparison.
9408       // In a SFINAE context, we treat this as a hard error to maintain
9409       // conformance with the C++ standard.
9410       diagnoseFunctionPointerToVoidComparison(
9411           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9412 
9413       if (isSFINAEContext())
9414         return QualType();
9415 
9416       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9417       return ResultTy;
9418     }
9419 
9420     // C++ [expr.eq]p2:
9421     //   If at least one operand is a pointer [...] bring them to their
9422     //   composite pointer type.
9423     // C++ [expr.rel]p2:
9424     //   If both operands are pointers, [...] bring them to their composite
9425     //   pointer type.
9426     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9427             (IsRelational ? 2 : 1) &&
9428         (!LangOpts.ObjCAutoRefCount ||
9429          !(LHSType->isObjCObjectPointerType() ||
9430            RHSType->isObjCObjectPointerType()))) {
9431       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9432         return QualType();
9433       else
9434         return ResultTy;
9435     }
9436   } else if (LHSType->isPointerType() &&
9437              RHSType->isPointerType()) { // C99 6.5.8p2
9438     // All of the following pointer-related warnings are GCC extensions, except
9439     // when handling null pointer constants.
9440     QualType LCanPointeeTy =
9441       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9442     QualType RCanPointeeTy =
9443       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9444 
9445     // C99 6.5.9p2 and C99 6.5.8p2
9446     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9447                                    RCanPointeeTy.getUnqualifiedType())) {
9448       // Valid unless a relational comparison of function pointers
9449       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9450         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9451           << LHSType << RHSType << LHS.get()->getSourceRange()
9452           << RHS.get()->getSourceRange();
9453       }
9454     } else if (!IsRelational &&
9455                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9456       // Valid unless comparison between non-null pointer and function pointer
9457       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9458           && !LHSIsNull && !RHSIsNull)
9459         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9460                                                 /*isError*/false);
9461     } else {
9462       // Invalid
9463       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9464     }
9465     if (LCanPointeeTy != RCanPointeeTy) {
9466       // Treat NULL constant as a special case in OpenCL.
9467       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9468         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9469         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9470           Diag(Loc,
9471                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9472               << LHSType << RHSType << 0 /* comparison */
9473               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9474         }
9475       }
9476       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9477       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9478       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9479                                                : CK_BitCast;
9480       if (LHSIsNull && !RHSIsNull)
9481         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9482       else
9483         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9484     }
9485     return ResultTy;
9486   }
9487 
9488   if (getLangOpts().CPlusPlus) {
9489     // C++ [expr.eq]p4:
9490     //   Two operands of type std::nullptr_t or one operand of type
9491     //   std::nullptr_t and the other a null pointer constant compare equal.
9492     if (!IsRelational && LHSIsNull && RHSIsNull) {
9493       if (LHSType->isNullPtrType()) {
9494         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9495         return ResultTy;
9496       }
9497       if (RHSType->isNullPtrType()) {
9498         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9499         return ResultTy;
9500       }
9501     }
9502 
9503     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9504     // These aren't covered by the composite pointer type rules.
9505     if (!IsRelational && RHSType->isNullPtrType() &&
9506         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9507       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9508       return ResultTy;
9509     }
9510     if (!IsRelational && LHSType->isNullPtrType() &&
9511         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9512       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9513       return ResultTy;
9514     }
9515 
9516     if (IsRelational &&
9517         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9518          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9519       // HACK: Relational comparison of nullptr_t against a pointer type is
9520       // invalid per DR583, but we allow it within std::less<> and friends,
9521       // since otherwise common uses of it break.
9522       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9523       // friends to have std::nullptr_t overload candidates.
9524       DeclContext *DC = CurContext;
9525       if (isa<FunctionDecl>(DC))
9526         DC = DC->getParent();
9527       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9528         if (CTSD->isInStdNamespace() &&
9529             llvm::StringSwitch<bool>(CTSD->getName())
9530                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9531                 .Default(false)) {
9532           if (RHSType->isNullPtrType())
9533             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9534           else
9535             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9536           return ResultTy;
9537         }
9538       }
9539     }
9540 
9541     // C++ [expr.eq]p2:
9542     //   If at least one operand is a pointer to member, [...] bring them to
9543     //   their composite pointer type.
9544     if (!IsRelational &&
9545         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9546       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9547         return QualType();
9548       else
9549         return ResultTy;
9550     }
9551 
9552     // Handle scoped enumeration types specifically, since they don't promote
9553     // to integers.
9554     if (LHS.get()->getType()->isEnumeralType() &&
9555         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9556                                        RHS.get()->getType()))
9557       return ResultTy;
9558   }
9559 
9560   // Handle block pointer types.
9561   if (!IsRelational && LHSType->isBlockPointerType() &&
9562       RHSType->isBlockPointerType()) {
9563     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9564     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9565 
9566     if (!LHSIsNull && !RHSIsNull &&
9567         !Context.typesAreCompatible(lpointee, rpointee)) {
9568       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9569         << LHSType << RHSType << LHS.get()->getSourceRange()
9570         << RHS.get()->getSourceRange();
9571     }
9572     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9573     return ResultTy;
9574   }
9575 
9576   // Allow block pointers to be compared with null pointer constants.
9577   if (!IsRelational
9578       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9579           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9580     if (!LHSIsNull && !RHSIsNull) {
9581       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9582              ->getPointeeType()->isVoidType())
9583             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9584                 ->getPointeeType()->isVoidType())))
9585         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9586           << LHSType << RHSType << LHS.get()->getSourceRange()
9587           << RHS.get()->getSourceRange();
9588     }
9589     if (LHSIsNull && !RHSIsNull)
9590       LHS = ImpCastExprToType(LHS.get(), RHSType,
9591                               RHSType->isPointerType() ? CK_BitCast
9592                                 : CK_AnyPointerToBlockPointerCast);
9593     else
9594       RHS = ImpCastExprToType(RHS.get(), LHSType,
9595                               LHSType->isPointerType() ? CK_BitCast
9596                                 : CK_AnyPointerToBlockPointerCast);
9597     return ResultTy;
9598   }
9599 
9600   if (LHSType->isObjCObjectPointerType() ||
9601       RHSType->isObjCObjectPointerType()) {
9602     const PointerType *LPT = LHSType->getAs<PointerType>();
9603     const PointerType *RPT = RHSType->getAs<PointerType>();
9604     if (LPT || RPT) {
9605       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9606       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9607 
9608       if (!LPtrToVoid && !RPtrToVoid &&
9609           !Context.typesAreCompatible(LHSType, RHSType)) {
9610         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9611                                           /*isError*/false);
9612       }
9613       if (LHSIsNull && !RHSIsNull) {
9614         Expr *E = LHS.get();
9615         if (getLangOpts().ObjCAutoRefCount)
9616           CheckObjCConversion(SourceRange(), RHSType, E,
9617                               CCK_ImplicitConversion);
9618         LHS = ImpCastExprToType(E, RHSType,
9619                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9620       }
9621       else {
9622         Expr *E = RHS.get();
9623         if (getLangOpts().ObjCAutoRefCount)
9624           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9625                               /*Diagnose=*/true,
9626                               /*DiagnoseCFAudited=*/false, Opc);
9627         RHS = ImpCastExprToType(E, LHSType,
9628                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9629       }
9630       return ResultTy;
9631     }
9632     if (LHSType->isObjCObjectPointerType() &&
9633         RHSType->isObjCObjectPointerType()) {
9634       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9635         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9636                                           /*isError*/false);
9637       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9638         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9639 
9640       if (LHSIsNull && !RHSIsNull)
9641         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9642       else
9643         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9644       return ResultTy;
9645     }
9646   }
9647   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9648       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9649     unsigned DiagID = 0;
9650     bool isError = false;
9651     if (LangOpts.DebuggerSupport) {
9652       // Under a debugger, allow the comparison of pointers to integers,
9653       // since users tend to want to compare addresses.
9654     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9655                (RHSIsNull && RHSType->isIntegerType())) {
9656       if (IsRelational) {
9657         isError = getLangOpts().CPlusPlus;
9658         DiagID =
9659           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9660                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9661       }
9662     } else if (getLangOpts().CPlusPlus) {
9663       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9664       isError = true;
9665     } else if (IsRelational)
9666       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9667     else
9668       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9669 
9670     if (DiagID) {
9671       Diag(Loc, DiagID)
9672         << LHSType << RHSType << LHS.get()->getSourceRange()
9673         << RHS.get()->getSourceRange();
9674       if (isError)
9675         return QualType();
9676     }
9677 
9678     if (LHSType->isIntegerType())
9679       LHS = ImpCastExprToType(LHS.get(), RHSType,
9680                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9681     else
9682       RHS = ImpCastExprToType(RHS.get(), LHSType,
9683                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9684     return ResultTy;
9685   }
9686 
9687   // Handle block pointers.
9688   if (!IsRelational && RHSIsNull
9689       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9690     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9691     return ResultTy;
9692   }
9693   if (!IsRelational && LHSIsNull
9694       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9695     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9696     return ResultTy;
9697   }
9698 
9699   if (getLangOpts().OpenCLVersion >= 200) {
9700     if (LHSIsNull && RHSType->isQueueT()) {
9701       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9702       return ResultTy;
9703     }
9704 
9705     if (LHSType->isQueueT() && RHSIsNull) {
9706       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9707       return ResultTy;
9708     }
9709   }
9710 
9711   return InvalidOperands(Loc, LHS, RHS);
9712 }
9713 
9714 
9715 // Return a signed type that is of identical size and number of elements.
9716 // For floating point vectors, return an integer type of identical size
9717 // and number of elements.
9718 QualType Sema::GetSignedVectorType(QualType V) {
9719   const VectorType *VTy = V->getAs<VectorType>();
9720   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9721   if (TypeSize == Context.getTypeSize(Context.CharTy))
9722     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9723   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9724     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9725   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9726     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9727   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9728     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9729   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9730          "Unhandled vector element size in vector compare");
9731   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9732 }
9733 
9734 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9735 /// operates on extended vector types.  Instead of producing an IntTy result,
9736 /// like a scalar comparison, a vector comparison produces a vector of integer
9737 /// types.
9738 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9739                                           SourceLocation Loc,
9740                                           bool IsRelational) {
9741   // Check to make sure we're operating on vectors of the same type and width,
9742   // Allowing one side to be a scalar of element type.
9743   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9744                               /*AllowBothBool*/true,
9745                               /*AllowBoolConversions*/getLangOpts().ZVector);
9746   if (vType.isNull())
9747     return vType;
9748 
9749   QualType LHSType = LHS.get()->getType();
9750 
9751   // If AltiVec, the comparison results in a numeric type, i.e.
9752   // bool for C++, int for C
9753   if (getLangOpts().AltiVec &&
9754       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9755     return Context.getLogicalOperationType();
9756 
9757   // For non-floating point types, check for self-comparisons of the form
9758   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9759   // often indicate logic errors in the program.
9760   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9761     if (DeclRefExpr* DRL
9762           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9763       if (DeclRefExpr* DRR
9764             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9765         if (DRL->getDecl() == DRR->getDecl())
9766           DiagRuntimeBehavior(Loc, nullptr,
9767                               PDiag(diag::warn_comparison_always)
9768                                 << 0 // self-
9769                                 << 2 // "a constant"
9770                               );
9771   }
9772 
9773   // Check for comparisons of floating point operands using != and ==.
9774   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9775     assert (RHS.get()->getType()->hasFloatingRepresentation());
9776     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9777   }
9778 
9779   // Return a signed type for the vector.
9780   return GetSignedVectorType(vType);
9781 }
9782 
9783 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9784                                           SourceLocation Loc) {
9785   // Ensure that either both operands are of the same vector type, or
9786   // one operand is of a vector type and the other is of its element type.
9787   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9788                                        /*AllowBothBool*/true,
9789                                        /*AllowBoolConversions*/false);
9790   if (vType.isNull())
9791     return InvalidOperands(Loc, LHS, RHS);
9792   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9793       vType->hasFloatingRepresentation())
9794     return InvalidOperands(Loc, LHS, RHS);
9795 
9796   return GetSignedVectorType(LHS.get()->getType());
9797 }
9798 
9799 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9800                                            SourceLocation Loc,
9801                                            BinaryOperatorKind Opc) {
9802   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9803 
9804   bool IsCompAssign =
9805       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9806 
9807   if (LHS.get()->getType()->isVectorType() ||
9808       RHS.get()->getType()->isVectorType()) {
9809     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9810         RHS.get()->getType()->hasIntegerRepresentation())
9811       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9812                         /*AllowBothBool*/true,
9813                         /*AllowBoolConversions*/getLangOpts().ZVector);
9814     return InvalidOperands(Loc, LHS, RHS);
9815   }
9816 
9817   if (Opc == BO_And)
9818     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9819 
9820   ExprResult LHSResult = LHS, RHSResult = RHS;
9821   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9822                                                  IsCompAssign);
9823   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9824     return QualType();
9825   LHS = LHSResult.get();
9826   RHS = RHSResult.get();
9827 
9828   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9829     return compType;
9830   return InvalidOperands(Loc, LHS, RHS);
9831 }
9832 
9833 // C99 6.5.[13,14]
9834 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9835                                            SourceLocation Loc,
9836                                            BinaryOperatorKind Opc) {
9837   // Check vector operands differently.
9838   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9839     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9840 
9841   // Diagnose cases where the user write a logical and/or but probably meant a
9842   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9843   // is a constant.
9844   if (LHS.get()->getType()->isIntegerType() &&
9845       !LHS.get()->getType()->isBooleanType() &&
9846       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9847       // Don't warn in macros or template instantiations.
9848       !Loc.isMacroID() && !inTemplateInstantiation()) {
9849     // If the RHS can be constant folded, and if it constant folds to something
9850     // that isn't 0 or 1 (which indicate a potential logical operation that
9851     // happened to fold to true/false) then warn.
9852     // Parens on the RHS are ignored.
9853     llvm::APSInt Result;
9854     if (RHS.get()->EvaluateAsInt(Result, Context))
9855       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9856            !RHS.get()->getExprLoc().isMacroID()) ||
9857           (Result != 0 && Result != 1)) {
9858         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9859           << RHS.get()->getSourceRange()
9860           << (Opc == BO_LAnd ? "&&" : "||");
9861         // Suggest replacing the logical operator with the bitwise version
9862         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9863             << (Opc == BO_LAnd ? "&" : "|")
9864             << FixItHint::CreateReplacement(SourceRange(
9865                                                  Loc, getLocForEndOfToken(Loc)),
9866                                             Opc == BO_LAnd ? "&" : "|");
9867         if (Opc == BO_LAnd)
9868           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9869           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9870               << FixItHint::CreateRemoval(
9871                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9872                               RHS.get()->getLocEnd()));
9873       }
9874   }
9875 
9876   if (!Context.getLangOpts().CPlusPlus) {
9877     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9878     // not operate on the built-in scalar and vector float types.
9879     if (Context.getLangOpts().OpenCL &&
9880         Context.getLangOpts().OpenCLVersion < 120) {
9881       if (LHS.get()->getType()->isFloatingType() ||
9882           RHS.get()->getType()->isFloatingType())
9883         return InvalidOperands(Loc, LHS, RHS);
9884     }
9885 
9886     LHS = UsualUnaryConversions(LHS.get());
9887     if (LHS.isInvalid())
9888       return QualType();
9889 
9890     RHS = UsualUnaryConversions(RHS.get());
9891     if (RHS.isInvalid())
9892       return QualType();
9893 
9894     if (!LHS.get()->getType()->isScalarType() ||
9895         !RHS.get()->getType()->isScalarType())
9896       return InvalidOperands(Loc, LHS, RHS);
9897 
9898     return Context.IntTy;
9899   }
9900 
9901   // The following is safe because we only use this method for
9902   // non-overloadable operands.
9903 
9904   // C++ [expr.log.and]p1
9905   // C++ [expr.log.or]p1
9906   // The operands are both contextually converted to type bool.
9907   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9908   if (LHSRes.isInvalid())
9909     return InvalidOperands(Loc, LHS, RHS);
9910   LHS = LHSRes;
9911 
9912   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9913   if (RHSRes.isInvalid())
9914     return InvalidOperands(Loc, LHS, RHS);
9915   RHS = RHSRes;
9916 
9917   // C++ [expr.log.and]p2
9918   // C++ [expr.log.or]p2
9919   // The result is a bool.
9920   return Context.BoolTy;
9921 }
9922 
9923 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9924   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9925   if (!ME) return false;
9926   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9927   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9928       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9929   if (!Base) return false;
9930   return Base->getMethodDecl() != nullptr;
9931 }
9932 
9933 /// Is the given expression (which must be 'const') a reference to a
9934 /// variable which was originally non-const, but which has become
9935 /// 'const' due to being captured within a block?
9936 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9937 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9938   assert(E->isLValue() && E->getType().isConstQualified());
9939   E = E->IgnoreParens();
9940 
9941   // Must be a reference to a declaration from an enclosing scope.
9942   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9943   if (!DRE) return NCCK_None;
9944   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9945 
9946   // The declaration must be a variable which is not declared 'const'.
9947   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9948   if (!var) return NCCK_None;
9949   if (var->getType().isConstQualified()) return NCCK_None;
9950   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9951 
9952   // Decide whether the first capture was for a block or a lambda.
9953   DeclContext *DC = S.CurContext, *Prev = nullptr;
9954   // Decide whether the first capture was for a block or a lambda.
9955   while (DC) {
9956     // For init-capture, it is possible that the variable belongs to the
9957     // template pattern of the current context.
9958     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9959       if (var->isInitCapture() &&
9960           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9961         break;
9962     if (DC == var->getDeclContext())
9963       break;
9964     Prev = DC;
9965     DC = DC->getParent();
9966   }
9967   // Unless we have an init-capture, we've gone one step too far.
9968   if (!var->isInitCapture())
9969     DC = Prev;
9970   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9971 }
9972 
9973 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9974   Ty = Ty.getNonReferenceType();
9975   if (IsDereference && Ty->isPointerType())
9976     Ty = Ty->getPointeeType();
9977   return !Ty.isConstQualified();
9978 }
9979 
9980 /// Emit the "read-only variable not assignable" error and print notes to give
9981 /// more information about why the variable is not assignable, such as pointing
9982 /// to the declaration of a const variable, showing that a method is const, or
9983 /// that the function is returning a const reference.
9984 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9985                                     SourceLocation Loc) {
9986   // Update err_typecheck_assign_const and note_typecheck_assign_const
9987   // when this enum is changed.
9988   enum {
9989     ConstFunction,
9990     ConstVariable,
9991     ConstMember,
9992     ConstMethod,
9993     ConstUnknown,  // Keep as last element
9994   };
9995 
9996   SourceRange ExprRange = E->getSourceRange();
9997 
9998   // Only emit one error on the first const found.  All other consts will emit
9999   // a note to the error.
10000   bool DiagnosticEmitted = false;
10001 
10002   // Track if the current expression is the result of a dereference, and if the
10003   // next checked expression is the result of a dereference.
10004   bool IsDereference = false;
10005   bool NextIsDereference = false;
10006 
10007   // Loop to process MemberExpr chains.
10008   while (true) {
10009     IsDereference = NextIsDereference;
10010 
10011     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10012     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10013       NextIsDereference = ME->isArrow();
10014       const ValueDecl *VD = ME->getMemberDecl();
10015       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10016         // Mutable fields can be modified even if the class is const.
10017         if (Field->isMutable()) {
10018           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10019           break;
10020         }
10021 
10022         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10023           if (!DiagnosticEmitted) {
10024             S.Diag(Loc, diag::err_typecheck_assign_const)
10025                 << ExprRange << ConstMember << false /*static*/ << Field
10026                 << Field->getType();
10027             DiagnosticEmitted = true;
10028           }
10029           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10030               << ConstMember << false /*static*/ << Field << Field->getType()
10031               << Field->getSourceRange();
10032         }
10033         E = ME->getBase();
10034         continue;
10035       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10036         if (VDecl->getType().isConstQualified()) {
10037           if (!DiagnosticEmitted) {
10038             S.Diag(Loc, diag::err_typecheck_assign_const)
10039                 << ExprRange << ConstMember << true /*static*/ << VDecl
10040                 << VDecl->getType();
10041             DiagnosticEmitted = true;
10042           }
10043           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10044               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10045               << VDecl->getSourceRange();
10046         }
10047         // Static fields do not inherit constness from parents.
10048         break;
10049       }
10050       break;
10051     } // End MemberExpr
10052     break;
10053   }
10054 
10055   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10056     // Function calls
10057     const FunctionDecl *FD = CE->getDirectCallee();
10058     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10059       if (!DiagnosticEmitted) {
10060         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10061                                                       << ConstFunction << FD;
10062         DiagnosticEmitted = true;
10063       }
10064       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10065              diag::note_typecheck_assign_const)
10066           << ConstFunction << FD << FD->getReturnType()
10067           << FD->getReturnTypeSourceRange();
10068     }
10069   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10070     // Point to variable declaration.
10071     if (const ValueDecl *VD = DRE->getDecl()) {
10072       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10073         if (!DiagnosticEmitted) {
10074           S.Diag(Loc, diag::err_typecheck_assign_const)
10075               << ExprRange << ConstVariable << VD << VD->getType();
10076           DiagnosticEmitted = true;
10077         }
10078         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10079             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10080       }
10081     }
10082   } else if (isa<CXXThisExpr>(E)) {
10083     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10084       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10085         if (MD->isConst()) {
10086           if (!DiagnosticEmitted) {
10087             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10088                                                           << ConstMethod << MD;
10089             DiagnosticEmitted = true;
10090           }
10091           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10092               << ConstMethod << MD << MD->getSourceRange();
10093         }
10094       }
10095     }
10096   }
10097 
10098   if (DiagnosticEmitted)
10099     return;
10100 
10101   // Can't determine a more specific message, so display the generic error.
10102   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10103 }
10104 
10105 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10106 /// emit an error and return true.  If so, return false.
10107 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10108   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10109 
10110   S.CheckShadowingDeclModification(E, Loc);
10111 
10112   SourceLocation OrigLoc = Loc;
10113   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10114                                                               &Loc);
10115   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10116     IsLV = Expr::MLV_InvalidMessageExpression;
10117   if (IsLV == Expr::MLV_Valid)
10118     return false;
10119 
10120   unsigned DiagID = 0;
10121   bool NeedType = false;
10122   switch (IsLV) { // C99 6.5.16p2
10123   case Expr::MLV_ConstQualified:
10124     // Use a specialized diagnostic when we're assigning to an object
10125     // from an enclosing function or block.
10126     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10127       if (NCCK == NCCK_Block)
10128         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10129       else
10130         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10131       break;
10132     }
10133 
10134     // In ARC, use some specialized diagnostics for occasions where we
10135     // infer 'const'.  These are always pseudo-strong variables.
10136     if (S.getLangOpts().ObjCAutoRefCount) {
10137       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10138       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10139         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10140 
10141         // Use the normal diagnostic if it's pseudo-__strong but the
10142         // user actually wrote 'const'.
10143         if (var->isARCPseudoStrong() &&
10144             (!var->getTypeSourceInfo() ||
10145              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10146           // There are two pseudo-strong cases:
10147           //  - self
10148           ObjCMethodDecl *method = S.getCurMethodDecl();
10149           if (method && var == method->getSelfDecl())
10150             DiagID = method->isClassMethod()
10151               ? diag::err_typecheck_arc_assign_self_class_method
10152               : diag::err_typecheck_arc_assign_self;
10153 
10154           //  - fast enumeration variables
10155           else
10156             DiagID = diag::err_typecheck_arr_assign_enumeration;
10157 
10158           SourceRange Assign;
10159           if (Loc != OrigLoc)
10160             Assign = SourceRange(OrigLoc, OrigLoc);
10161           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10162           // We need to preserve the AST regardless, so migration tool
10163           // can do its job.
10164           return false;
10165         }
10166       }
10167     }
10168 
10169     // If none of the special cases above are triggered, then this is a
10170     // simple const assignment.
10171     if (DiagID == 0) {
10172       DiagnoseConstAssignment(S, E, Loc);
10173       return true;
10174     }
10175 
10176     break;
10177   case Expr::MLV_ConstAddrSpace:
10178     DiagnoseConstAssignment(S, E, Loc);
10179     return true;
10180   case Expr::MLV_ArrayType:
10181   case Expr::MLV_ArrayTemporary:
10182     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10183     NeedType = true;
10184     break;
10185   case Expr::MLV_NotObjectType:
10186     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10187     NeedType = true;
10188     break;
10189   case Expr::MLV_LValueCast:
10190     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10191     break;
10192   case Expr::MLV_Valid:
10193     llvm_unreachable("did not take early return for MLV_Valid");
10194   case Expr::MLV_InvalidExpression:
10195   case Expr::MLV_MemberFunction:
10196   case Expr::MLV_ClassTemporary:
10197     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10198     break;
10199   case Expr::MLV_IncompleteType:
10200   case Expr::MLV_IncompleteVoidType:
10201     return S.RequireCompleteType(Loc, E->getType(),
10202              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10203   case Expr::MLV_DuplicateVectorComponents:
10204     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10205     break;
10206   case Expr::MLV_NoSetterProperty:
10207     llvm_unreachable("readonly properties should be processed differently");
10208   case Expr::MLV_InvalidMessageExpression:
10209     DiagID = diag::err_readonly_message_assignment;
10210     break;
10211   case Expr::MLV_SubObjCPropertySetting:
10212     DiagID = diag::err_no_subobject_property_setting;
10213     break;
10214   }
10215 
10216   SourceRange Assign;
10217   if (Loc != OrigLoc)
10218     Assign = SourceRange(OrigLoc, OrigLoc);
10219   if (NeedType)
10220     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10221   else
10222     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10223   return true;
10224 }
10225 
10226 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10227                                          SourceLocation Loc,
10228                                          Sema &Sema) {
10229   // C / C++ fields
10230   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10231   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10232   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10233     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10234       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10235   }
10236 
10237   // Objective-C instance variables
10238   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10239   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10240   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10241     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10242     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10243     if (RL && RR && RL->getDecl() == RR->getDecl())
10244       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10245   }
10246 }
10247 
10248 // C99 6.5.16.1
10249 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10250                                        SourceLocation Loc,
10251                                        QualType CompoundType) {
10252   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10253 
10254   // Verify that LHS is a modifiable lvalue, and emit error if not.
10255   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10256     return QualType();
10257 
10258   QualType LHSType = LHSExpr->getType();
10259   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10260                                              CompoundType;
10261   // OpenCL v1.2 s6.1.1.1 p2:
10262   // The half data type can only be used to declare a pointer to a buffer that
10263   // contains half values
10264   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10265     LHSType->isHalfType()) {
10266     Diag(Loc, diag::err_opencl_half_load_store) << 1
10267         << LHSType.getUnqualifiedType();
10268     return QualType();
10269   }
10270 
10271   AssignConvertType ConvTy;
10272   if (CompoundType.isNull()) {
10273     Expr *RHSCheck = RHS.get();
10274 
10275     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10276 
10277     QualType LHSTy(LHSType);
10278     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10279     if (RHS.isInvalid())
10280       return QualType();
10281     // Special case of NSObject attributes on c-style pointer types.
10282     if (ConvTy == IncompatiblePointer &&
10283         ((Context.isObjCNSObjectType(LHSType) &&
10284           RHSType->isObjCObjectPointerType()) ||
10285          (Context.isObjCNSObjectType(RHSType) &&
10286           LHSType->isObjCObjectPointerType())))
10287       ConvTy = Compatible;
10288 
10289     if (ConvTy == Compatible &&
10290         LHSType->isObjCObjectType())
10291         Diag(Loc, diag::err_objc_object_assignment)
10292           << LHSType;
10293 
10294     // If the RHS is a unary plus or minus, check to see if they = and + are
10295     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10296     // instead of "x += 4".
10297     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10298       RHSCheck = ICE->getSubExpr();
10299     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10300       if ((UO->getOpcode() == UO_Plus ||
10301            UO->getOpcode() == UO_Minus) &&
10302           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10303           // Only if the two operators are exactly adjacent.
10304           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10305           // And there is a space or other character before the subexpr of the
10306           // unary +/-.  We don't want to warn on "x=-1".
10307           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10308           UO->getSubExpr()->getLocStart().isFileID()) {
10309         Diag(Loc, diag::warn_not_compound_assign)
10310           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10311           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10312       }
10313     }
10314 
10315     if (ConvTy == Compatible) {
10316       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10317         // Warn about retain cycles where a block captures the LHS, but
10318         // not if the LHS is a simple variable into which the block is
10319         // being stored...unless that variable can be captured by reference!
10320         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10321         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10322         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10323           checkRetainCycles(LHSExpr, RHS.get());
10324       }
10325 
10326       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10327           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10328         // It is safe to assign a weak reference into a strong variable.
10329         // Although this code can still have problems:
10330         //   id x = self.weakProp;
10331         //   id y = self.weakProp;
10332         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10333         // paths through the function. This should be revisited if
10334         // -Wrepeated-use-of-weak is made flow-sensitive.
10335         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10336         // variable, which will be valid for the current autorelease scope.
10337         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10338                              RHS.get()->getLocStart()))
10339           getCurFunction()->markSafeWeakUse(RHS.get());
10340 
10341       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10342         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10343       }
10344     }
10345   } else {
10346     // Compound assignment "x += y"
10347     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10348   }
10349 
10350   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10351                                RHS.get(), AA_Assigning))
10352     return QualType();
10353 
10354   CheckForNullPointerDereference(*this, LHSExpr);
10355 
10356   // C99 6.5.16p3: The type of an assignment expression is the type of the
10357   // left operand unless the left operand has qualified type, in which case
10358   // it is the unqualified version of the type of the left operand.
10359   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10360   // is converted to the type of the assignment expression (above).
10361   // C++ 5.17p1: the type of the assignment expression is that of its left
10362   // operand.
10363   return (getLangOpts().CPlusPlus
10364           ? LHSType : LHSType.getUnqualifiedType());
10365 }
10366 
10367 // Only ignore explicit casts to void.
10368 static bool IgnoreCommaOperand(const Expr *E) {
10369   E = E->IgnoreParens();
10370 
10371   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10372     if (CE->getCastKind() == CK_ToVoid) {
10373       return true;
10374     }
10375   }
10376 
10377   return false;
10378 }
10379 
10380 // Look for instances where it is likely the comma operator is confused with
10381 // another operator.  There is a whitelist of acceptable expressions for the
10382 // left hand side of the comma operator, otherwise emit a warning.
10383 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10384   // No warnings in macros
10385   if (Loc.isMacroID())
10386     return;
10387 
10388   // Don't warn in template instantiations.
10389   if (inTemplateInstantiation())
10390     return;
10391 
10392   // Scope isn't fine-grained enough to whitelist the specific cases, so
10393   // instead, skip more than needed, then call back into here with the
10394   // CommaVisitor in SemaStmt.cpp.
10395   // The whitelisted locations are the initialization and increment portions
10396   // of a for loop.  The additional checks are on the condition of
10397   // if statements, do/while loops, and for loops.
10398   const unsigned ForIncrementFlags =
10399       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10400   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10401   const unsigned ScopeFlags = getCurScope()->getFlags();
10402   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10403       (ScopeFlags & ForInitFlags) == ForInitFlags)
10404     return;
10405 
10406   // If there are multiple comma operators used together, get the RHS of the
10407   // of the comma operator as the LHS.
10408   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10409     if (BO->getOpcode() != BO_Comma)
10410       break;
10411     LHS = BO->getRHS();
10412   }
10413 
10414   // Only allow some expressions on LHS to not warn.
10415   if (IgnoreCommaOperand(LHS))
10416     return;
10417 
10418   Diag(Loc, diag::warn_comma_operator);
10419   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10420       << LHS->getSourceRange()
10421       << FixItHint::CreateInsertion(LHS->getLocStart(),
10422                                     LangOpts.CPlusPlus ? "static_cast<void>("
10423                                                        : "(void)(")
10424       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10425                                     ")");
10426 }
10427 
10428 // C99 6.5.17
10429 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10430                                    SourceLocation Loc) {
10431   LHS = S.CheckPlaceholderExpr(LHS.get());
10432   RHS = S.CheckPlaceholderExpr(RHS.get());
10433   if (LHS.isInvalid() || RHS.isInvalid())
10434     return QualType();
10435 
10436   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10437   // operands, but not unary promotions.
10438   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10439 
10440   // So we treat the LHS as a ignored value, and in C++ we allow the
10441   // containing site to determine what should be done with the RHS.
10442   LHS = S.IgnoredValueConversions(LHS.get());
10443   if (LHS.isInvalid())
10444     return QualType();
10445 
10446   S.DiagnoseUnusedExprResult(LHS.get());
10447 
10448   if (!S.getLangOpts().CPlusPlus) {
10449     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10450     if (RHS.isInvalid())
10451       return QualType();
10452     if (!RHS.get()->getType()->isVoidType())
10453       S.RequireCompleteType(Loc, RHS.get()->getType(),
10454                             diag::err_incomplete_type);
10455   }
10456 
10457   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10458     S.DiagnoseCommaOperator(LHS.get(), Loc);
10459 
10460   return RHS.get()->getType();
10461 }
10462 
10463 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10464 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10465 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10466                                                ExprValueKind &VK,
10467                                                ExprObjectKind &OK,
10468                                                SourceLocation OpLoc,
10469                                                bool IsInc, bool IsPrefix) {
10470   if (Op->isTypeDependent())
10471     return S.Context.DependentTy;
10472 
10473   QualType ResType = Op->getType();
10474   // Atomic types can be used for increment / decrement where the non-atomic
10475   // versions can, so ignore the _Atomic() specifier for the purpose of
10476   // checking.
10477   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10478     ResType = ResAtomicType->getValueType();
10479 
10480   assert(!ResType.isNull() && "no type for increment/decrement expression");
10481 
10482   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10483     // Decrement of bool is not allowed.
10484     if (!IsInc) {
10485       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10486       return QualType();
10487     }
10488     // Increment of bool sets it to true, but is deprecated.
10489     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10490                                               : diag::warn_increment_bool)
10491       << Op->getSourceRange();
10492   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10493     // Error on enum increments and decrements in C++ mode
10494     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10495     return QualType();
10496   } else if (ResType->isRealType()) {
10497     // OK!
10498   } else if (ResType->isPointerType()) {
10499     // C99 6.5.2.4p2, 6.5.6p2
10500     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10501       return QualType();
10502   } else if (ResType->isObjCObjectPointerType()) {
10503     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10504     // Otherwise, we just need a complete type.
10505     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10506         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10507       return QualType();
10508   } else if (ResType->isAnyComplexType()) {
10509     // C99 does not support ++/-- on complex types, we allow as an extension.
10510     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10511       << ResType << Op->getSourceRange();
10512   } else if (ResType->isPlaceholderType()) {
10513     ExprResult PR = S.CheckPlaceholderExpr(Op);
10514     if (PR.isInvalid()) return QualType();
10515     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10516                                           IsInc, IsPrefix);
10517   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10518     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10519   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10520              (ResType->getAs<VectorType>()->getVectorKind() !=
10521               VectorType::AltiVecBool)) {
10522     // The z vector extensions allow ++ and -- for non-bool vectors.
10523   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10524             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10525     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10526   } else {
10527     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10528       << ResType << int(IsInc) << Op->getSourceRange();
10529     return QualType();
10530   }
10531   // At this point, we know we have a real, complex or pointer type.
10532   // Now make sure the operand is a modifiable lvalue.
10533   if (CheckForModifiableLvalue(Op, OpLoc, S))
10534     return QualType();
10535   // In C++, a prefix increment is the same type as the operand. Otherwise
10536   // (in C or with postfix), the increment is the unqualified type of the
10537   // operand.
10538   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10539     VK = VK_LValue;
10540     OK = Op->getObjectKind();
10541     return ResType;
10542   } else {
10543     VK = VK_RValue;
10544     return ResType.getUnqualifiedType();
10545   }
10546 }
10547 
10548 
10549 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10550 /// This routine allows us to typecheck complex/recursive expressions
10551 /// where the declaration is needed for type checking. We only need to
10552 /// handle cases when the expression references a function designator
10553 /// or is an lvalue. Here are some examples:
10554 ///  - &(x) => x
10555 ///  - &*****f => f for f a function designator.
10556 ///  - &s.xx => s
10557 ///  - &s.zz[1].yy -> s, if zz is an array
10558 ///  - *(x + 1) -> x, if x is an array
10559 ///  - &"123"[2] -> 0
10560 ///  - & __real__ x -> x
10561 static ValueDecl *getPrimaryDecl(Expr *E) {
10562   switch (E->getStmtClass()) {
10563   case Stmt::DeclRefExprClass:
10564     return cast<DeclRefExpr>(E)->getDecl();
10565   case Stmt::MemberExprClass:
10566     // If this is an arrow operator, the address is an offset from
10567     // the base's value, so the object the base refers to is
10568     // irrelevant.
10569     if (cast<MemberExpr>(E)->isArrow())
10570       return nullptr;
10571     // Otherwise, the expression refers to a part of the base
10572     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10573   case Stmt::ArraySubscriptExprClass: {
10574     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10575     // promotion of register arrays earlier.
10576     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10577     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10578       if (ICE->getSubExpr()->getType()->isArrayType())
10579         return getPrimaryDecl(ICE->getSubExpr());
10580     }
10581     return nullptr;
10582   }
10583   case Stmt::UnaryOperatorClass: {
10584     UnaryOperator *UO = cast<UnaryOperator>(E);
10585 
10586     switch(UO->getOpcode()) {
10587     case UO_Real:
10588     case UO_Imag:
10589     case UO_Extension:
10590       return getPrimaryDecl(UO->getSubExpr());
10591     default:
10592       return nullptr;
10593     }
10594   }
10595   case Stmt::ParenExprClass:
10596     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10597   case Stmt::ImplicitCastExprClass:
10598     // If the result of an implicit cast is an l-value, we care about
10599     // the sub-expression; otherwise, the result here doesn't matter.
10600     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10601   default:
10602     return nullptr;
10603   }
10604 }
10605 
10606 namespace {
10607   enum {
10608     AO_Bit_Field = 0,
10609     AO_Vector_Element = 1,
10610     AO_Property_Expansion = 2,
10611     AO_Register_Variable = 3,
10612     AO_No_Error = 4
10613   };
10614 }
10615 /// \brief Diagnose invalid operand for address of operations.
10616 ///
10617 /// \param Type The type of operand which cannot have its address taken.
10618 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10619                                          Expr *E, unsigned Type) {
10620   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10621 }
10622 
10623 /// CheckAddressOfOperand - The operand of & must be either a function
10624 /// designator or an lvalue designating an object. If it is an lvalue, the
10625 /// object cannot be declared with storage class register or be a bit field.
10626 /// Note: The usual conversions are *not* applied to the operand of the &
10627 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10628 /// In C++, the operand might be an overloaded function name, in which case
10629 /// we allow the '&' but retain the overloaded-function type.
10630 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10631   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10632     if (PTy->getKind() == BuiltinType::Overload) {
10633       Expr *E = OrigOp.get()->IgnoreParens();
10634       if (!isa<OverloadExpr>(E)) {
10635         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10636         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10637           << OrigOp.get()->getSourceRange();
10638         return QualType();
10639       }
10640 
10641       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10642       if (isa<UnresolvedMemberExpr>(Ovl))
10643         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10644           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10645             << OrigOp.get()->getSourceRange();
10646           return QualType();
10647         }
10648 
10649       return Context.OverloadTy;
10650     }
10651 
10652     if (PTy->getKind() == BuiltinType::UnknownAny)
10653       return Context.UnknownAnyTy;
10654 
10655     if (PTy->getKind() == BuiltinType::BoundMember) {
10656       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10657         << OrigOp.get()->getSourceRange();
10658       return QualType();
10659     }
10660 
10661     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10662     if (OrigOp.isInvalid()) return QualType();
10663   }
10664 
10665   if (OrigOp.get()->isTypeDependent())
10666     return Context.DependentTy;
10667 
10668   assert(!OrigOp.get()->getType()->isPlaceholderType());
10669 
10670   // Make sure to ignore parentheses in subsequent checks
10671   Expr *op = OrigOp.get()->IgnoreParens();
10672 
10673   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10674   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10675     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10676     return QualType();
10677   }
10678 
10679   if (getLangOpts().C99) {
10680     // Implement C99-only parts of addressof rules.
10681     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10682       if (uOp->getOpcode() == UO_Deref)
10683         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10684         // (assuming the deref expression is valid).
10685         return uOp->getSubExpr()->getType();
10686     }
10687     // Technically, there should be a check for array subscript
10688     // expressions here, but the result of one is always an lvalue anyway.
10689   }
10690   ValueDecl *dcl = getPrimaryDecl(op);
10691 
10692   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10693     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10694                                            op->getLocStart()))
10695       return QualType();
10696 
10697   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10698   unsigned AddressOfError = AO_No_Error;
10699 
10700   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10701     bool sfinae = (bool)isSFINAEContext();
10702     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10703                                   : diag::ext_typecheck_addrof_temporary)
10704       << op->getType() << op->getSourceRange();
10705     if (sfinae)
10706       return QualType();
10707     // Materialize the temporary as an lvalue so that we can take its address.
10708     OrigOp = op =
10709         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10710   } else if (isa<ObjCSelectorExpr>(op)) {
10711     return Context.getPointerType(op->getType());
10712   } else if (lval == Expr::LV_MemberFunction) {
10713     // If it's an instance method, make a member pointer.
10714     // The expression must have exactly the form &A::foo.
10715 
10716     // If the underlying expression isn't a decl ref, give up.
10717     if (!isa<DeclRefExpr>(op)) {
10718       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10719         << OrigOp.get()->getSourceRange();
10720       return QualType();
10721     }
10722     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10723     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10724 
10725     // The id-expression was parenthesized.
10726     if (OrigOp.get() != DRE) {
10727       Diag(OpLoc, diag::err_parens_pointer_member_function)
10728         << OrigOp.get()->getSourceRange();
10729 
10730     // The method was named without a qualifier.
10731     } else if (!DRE->getQualifier()) {
10732       if (MD->getParent()->getName().empty())
10733         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10734           << op->getSourceRange();
10735       else {
10736         SmallString<32> Str;
10737         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10738         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10739           << op->getSourceRange()
10740           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10741       }
10742     }
10743 
10744     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10745     if (isa<CXXDestructorDecl>(MD))
10746       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10747 
10748     QualType MPTy = Context.getMemberPointerType(
10749         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10750     // Under the MS ABI, lock down the inheritance model now.
10751     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10752       (void)isCompleteType(OpLoc, MPTy);
10753     return MPTy;
10754   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10755     // C99 6.5.3.2p1
10756     // The operand must be either an l-value or a function designator
10757     if (!op->getType()->isFunctionType()) {
10758       // Use a special diagnostic for loads from property references.
10759       if (isa<PseudoObjectExpr>(op)) {
10760         AddressOfError = AO_Property_Expansion;
10761       } else {
10762         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10763           << op->getType() << op->getSourceRange();
10764         return QualType();
10765       }
10766     }
10767   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10768     // The operand cannot be a bit-field
10769     AddressOfError = AO_Bit_Field;
10770   } else if (op->getObjectKind() == OK_VectorComponent) {
10771     // The operand cannot be an element of a vector
10772     AddressOfError = AO_Vector_Element;
10773   } else if (dcl) { // C99 6.5.3.2p1
10774     // We have an lvalue with a decl. Make sure the decl is not declared
10775     // with the register storage-class specifier.
10776     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10777       // in C++ it is not error to take address of a register
10778       // variable (c++03 7.1.1P3)
10779       if (vd->getStorageClass() == SC_Register &&
10780           !getLangOpts().CPlusPlus) {
10781         AddressOfError = AO_Register_Variable;
10782       }
10783     } else if (isa<MSPropertyDecl>(dcl)) {
10784       AddressOfError = AO_Property_Expansion;
10785     } else if (isa<FunctionTemplateDecl>(dcl)) {
10786       return Context.OverloadTy;
10787     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10788       // Okay: we can take the address of a field.
10789       // Could be a pointer to member, though, if there is an explicit
10790       // scope qualifier for the class.
10791       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10792         DeclContext *Ctx = dcl->getDeclContext();
10793         if (Ctx && Ctx->isRecord()) {
10794           if (dcl->getType()->isReferenceType()) {
10795             Diag(OpLoc,
10796                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10797               << dcl->getDeclName() << dcl->getType();
10798             return QualType();
10799           }
10800 
10801           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10802             Ctx = Ctx->getParent();
10803 
10804           QualType MPTy = Context.getMemberPointerType(
10805               op->getType(),
10806               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10807           // Under the MS ABI, lock down the inheritance model now.
10808           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10809             (void)isCompleteType(OpLoc, MPTy);
10810           return MPTy;
10811         }
10812       }
10813     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10814                !isa<BindingDecl>(dcl))
10815       llvm_unreachable("Unknown/unexpected decl type");
10816   }
10817 
10818   if (AddressOfError != AO_No_Error) {
10819     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10820     return QualType();
10821   }
10822 
10823   if (lval == Expr::LV_IncompleteVoidType) {
10824     // Taking the address of a void variable is technically illegal, but we
10825     // allow it in cases which are otherwise valid.
10826     // Example: "extern void x; void* y = &x;".
10827     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10828   }
10829 
10830   // If the operand has type "type", the result has type "pointer to type".
10831   if (op->getType()->isObjCObjectType())
10832     return Context.getObjCObjectPointerType(op->getType());
10833 
10834   CheckAddressOfPackedMember(op);
10835 
10836   return Context.getPointerType(op->getType());
10837 }
10838 
10839 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10840   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10841   if (!DRE)
10842     return;
10843   const Decl *D = DRE->getDecl();
10844   if (!D)
10845     return;
10846   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10847   if (!Param)
10848     return;
10849   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10850     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10851       return;
10852   if (FunctionScopeInfo *FD = S.getCurFunction())
10853     if (!FD->ModifiedNonNullParams.count(Param))
10854       FD->ModifiedNonNullParams.insert(Param);
10855 }
10856 
10857 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10858 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10859                                         SourceLocation OpLoc) {
10860   if (Op->isTypeDependent())
10861     return S.Context.DependentTy;
10862 
10863   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10864   if (ConvResult.isInvalid())
10865     return QualType();
10866   Op = ConvResult.get();
10867   QualType OpTy = Op->getType();
10868   QualType Result;
10869 
10870   if (isa<CXXReinterpretCastExpr>(Op)) {
10871     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10872     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10873                                      Op->getSourceRange());
10874   }
10875 
10876   if (const PointerType *PT = OpTy->getAs<PointerType>())
10877   {
10878     Result = PT->getPointeeType();
10879   }
10880   else if (const ObjCObjectPointerType *OPT =
10881              OpTy->getAs<ObjCObjectPointerType>())
10882     Result = OPT->getPointeeType();
10883   else {
10884     ExprResult PR = S.CheckPlaceholderExpr(Op);
10885     if (PR.isInvalid()) return QualType();
10886     if (PR.get() != Op)
10887       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10888   }
10889 
10890   if (Result.isNull()) {
10891     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10892       << OpTy << Op->getSourceRange();
10893     return QualType();
10894   }
10895 
10896   // Note that per both C89 and C99, indirection is always legal, even if Result
10897   // is an incomplete type or void.  It would be possible to warn about
10898   // dereferencing a void pointer, but it's completely well-defined, and such a
10899   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10900   // for pointers to 'void' but is fine for any other pointer type:
10901   //
10902   // C++ [expr.unary.op]p1:
10903   //   [...] the expression to which [the unary * operator] is applied shall
10904   //   be a pointer to an object type, or a pointer to a function type
10905   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10906     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10907       << OpTy << Op->getSourceRange();
10908 
10909   // Dereferences are usually l-values...
10910   VK = VK_LValue;
10911 
10912   // ...except that certain expressions are never l-values in C.
10913   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10914     VK = VK_RValue;
10915 
10916   return Result;
10917 }
10918 
10919 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10920   BinaryOperatorKind Opc;
10921   switch (Kind) {
10922   default: llvm_unreachable("Unknown binop!");
10923   case tok::periodstar:           Opc = BO_PtrMemD; break;
10924   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10925   case tok::star:                 Opc = BO_Mul; break;
10926   case tok::slash:                Opc = BO_Div; break;
10927   case tok::percent:              Opc = BO_Rem; break;
10928   case tok::plus:                 Opc = BO_Add; break;
10929   case tok::minus:                Opc = BO_Sub; break;
10930   case tok::lessless:             Opc = BO_Shl; break;
10931   case tok::greatergreater:       Opc = BO_Shr; break;
10932   case tok::lessequal:            Opc = BO_LE; break;
10933   case tok::less:                 Opc = BO_LT; break;
10934   case tok::greaterequal:         Opc = BO_GE; break;
10935   case tok::greater:              Opc = BO_GT; break;
10936   case tok::exclaimequal:         Opc = BO_NE; break;
10937   case tok::equalequal:           Opc = BO_EQ; break;
10938   case tok::amp:                  Opc = BO_And; break;
10939   case tok::caret:                Opc = BO_Xor; break;
10940   case tok::pipe:                 Opc = BO_Or; break;
10941   case tok::ampamp:               Opc = BO_LAnd; break;
10942   case tok::pipepipe:             Opc = BO_LOr; break;
10943   case tok::equal:                Opc = BO_Assign; break;
10944   case tok::starequal:            Opc = BO_MulAssign; break;
10945   case tok::slashequal:           Opc = BO_DivAssign; break;
10946   case tok::percentequal:         Opc = BO_RemAssign; break;
10947   case tok::plusequal:            Opc = BO_AddAssign; break;
10948   case tok::minusequal:           Opc = BO_SubAssign; break;
10949   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10950   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10951   case tok::ampequal:             Opc = BO_AndAssign; break;
10952   case tok::caretequal:           Opc = BO_XorAssign; break;
10953   case tok::pipeequal:            Opc = BO_OrAssign; break;
10954   case tok::comma:                Opc = BO_Comma; break;
10955   }
10956   return Opc;
10957 }
10958 
10959 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10960   tok::TokenKind Kind) {
10961   UnaryOperatorKind Opc;
10962   switch (Kind) {
10963   default: llvm_unreachable("Unknown unary op!");
10964   case tok::plusplus:     Opc = UO_PreInc; break;
10965   case tok::minusminus:   Opc = UO_PreDec; break;
10966   case tok::amp:          Opc = UO_AddrOf; break;
10967   case tok::star:         Opc = UO_Deref; break;
10968   case tok::plus:         Opc = UO_Plus; break;
10969   case tok::minus:        Opc = UO_Minus; break;
10970   case tok::tilde:        Opc = UO_Not; break;
10971   case tok::exclaim:      Opc = UO_LNot; break;
10972   case tok::kw___real:    Opc = UO_Real; break;
10973   case tok::kw___imag:    Opc = UO_Imag; break;
10974   case tok::kw___extension__: Opc = UO_Extension; break;
10975   }
10976   return Opc;
10977 }
10978 
10979 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10980 /// This warning is only emitted for builtin assignment operations. It is also
10981 /// suppressed in the event of macro expansions.
10982 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10983                                    SourceLocation OpLoc) {
10984   if (S.inTemplateInstantiation())
10985     return;
10986   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10987     return;
10988   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10989   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10990   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10991   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10992   if (!LHSDeclRef || !RHSDeclRef ||
10993       LHSDeclRef->getLocation().isMacroID() ||
10994       RHSDeclRef->getLocation().isMacroID())
10995     return;
10996   const ValueDecl *LHSDecl =
10997     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10998   const ValueDecl *RHSDecl =
10999     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11000   if (LHSDecl != RHSDecl)
11001     return;
11002   if (LHSDecl->getType().isVolatileQualified())
11003     return;
11004   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11005     if (RefTy->getPointeeType().isVolatileQualified())
11006       return;
11007 
11008   S.Diag(OpLoc, diag::warn_self_assignment)
11009       << LHSDeclRef->getType()
11010       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11011 }
11012 
11013 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11014 /// is usually indicative of introspection within the Objective-C pointer.
11015 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11016                                           SourceLocation OpLoc) {
11017   if (!S.getLangOpts().ObjC1)
11018     return;
11019 
11020   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11021   const Expr *LHS = L.get();
11022   const Expr *RHS = R.get();
11023 
11024   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11025     ObjCPointerExpr = LHS;
11026     OtherExpr = RHS;
11027   }
11028   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11029     ObjCPointerExpr = RHS;
11030     OtherExpr = LHS;
11031   }
11032 
11033   // This warning is deliberately made very specific to reduce false
11034   // positives with logic that uses '&' for hashing.  This logic mainly
11035   // looks for code trying to introspect into tagged pointers, which
11036   // code should generally never do.
11037   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11038     unsigned Diag = diag::warn_objc_pointer_masking;
11039     // Determine if we are introspecting the result of performSelectorXXX.
11040     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11041     // Special case messages to -performSelector and friends, which
11042     // can return non-pointer values boxed in a pointer value.
11043     // Some clients may wish to silence warnings in this subcase.
11044     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11045       Selector S = ME->getSelector();
11046       StringRef SelArg0 = S.getNameForSlot(0);
11047       if (SelArg0.startswith("performSelector"))
11048         Diag = diag::warn_objc_pointer_masking_performSelector;
11049     }
11050 
11051     S.Diag(OpLoc, Diag)
11052       << ObjCPointerExpr->getSourceRange();
11053   }
11054 }
11055 
11056 static NamedDecl *getDeclFromExpr(Expr *E) {
11057   if (!E)
11058     return nullptr;
11059   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11060     return DRE->getDecl();
11061   if (auto *ME = dyn_cast<MemberExpr>(E))
11062     return ME->getMemberDecl();
11063   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11064     return IRE->getDecl();
11065   return nullptr;
11066 }
11067 
11068 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11069 /// operator @p Opc at location @c TokLoc. This routine only supports
11070 /// built-in operations; ActOnBinOp handles overloaded operators.
11071 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11072                                     BinaryOperatorKind Opc,
11073                                     Expr *LHSExpr, Expr *RHSExpr) {
11074   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11075     // The syntax only allows initializer lists on the RHS of assignment,
11076     // so we don't need to worry about accepting invalid code for
11077     // non-assignment operators.
11078     // C++11 5.17p9:
11079     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11080     //   of x = {} is x = T().
11081     InitializationKind Kind =
11082         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11083     InitializedEntity Entity =
11084         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11085     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11086     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11087     if (Init.isInvalid())
11088       return Init;
11089     RHSExpr = Init.get();
11090   }
11091 
11092   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11093   QualType ResultTy;     // Result type of the binary operator.
11094   // The following two variables are used for compound assignment operators
11095   QualType CompLHSTy;    // Type of LHS after promotions for computation
11096   QualType CompResultTy; // Type of computation result
11097   ExprValueKind VK = VK_RValue;
11098   ExprObjectKind OK = OK_Ordinary;
11099 
11100   if (!getLangOpts().CPlusPlus) {
11101     // C cannot handle TypoExpr nodes on either side of a binop because it
11102     // doesn't handle dependent types properly, so make sure any TypoExprs have
11103     // been dealt with before checking the operands.
11104     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11105     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11106       if (Opc != BO_Assign)
11107         return ExprResult(E);
11108       // Avoid correcting the RHS to the same Expr as the LHS.
11109       Decl *D = getDeclFromExpr(E);
11110       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11111     });
11112     if (!LHS.isUsable() || !RHS.isUsable())
11113       return ExprError();
11114   }
11115 
11116   if (getLangOpts().OpenCL) {
11117     QualType LHSTy = LHSExpr->getType();
11118     QualType RHSTy = RHSExpr->getType();
11119     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11120     // the ATOMIC_VAR_INIT macro.
11121     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11122       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11123       if (BO_Assign == Opc)
11124         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11125       else
11126         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11127       return ExprError();
11128     }
11129 
11130     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11131     // only with a builtin functions and therefore should be disallowed here.
11132     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11133         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11134         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11135         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11136       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11137       return ExprError();
11138     }
11139   }
11140 
11141   switch (Opc) {
11142   case BO_Assign:
11143     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11144     if (getLangOpts().CPlusPlus &&
11145         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11146       VK = LHS.get()->getValueKind();
11147       OK = LHS.get()->getObjectKind();
11148     }
11149     if (!ResultTy.isNull()) {
11150       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11151       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11152     }
11153     RecordModifiableNonNullParam(*this, LHS.get());
11154     break;
11155   case BO_PtrMemD:
11156   case BO_PtrMemI:
11157     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11158                                             Opc == BO_PtrMemI);
11159     break;
11160   case BO_Mul:
11161   case BO_Div:
11162     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11163                                            Opc == BO_Div);
11164     break;
11165   case BO_Rem:
11166     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11167     break;
11168   case BO_Add:
11169     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11170     break;
11171   case BO_Sub:
11172     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11173     break;
11174   case BO_Shl:
11175   case BO_Shr:
11176     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11177     break;
11178   case BO_LE:
11179   case BO_LT:
11180   case BO_GE:
11181   case BO_GT:
11182     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11183     break;
11184   case BO_EQ:
11185   case BO_NE:
11186     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11187     break;
11188   case BO_And:
11189     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11190   case BO_Xor:
11191   case BO_Or:
11192     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11193     break;
11194   case BO_LAnd:
11195   case BO_LOr:
11196     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11197     break;
11198   case BO_MulAssign:
11199   case BO_DivAssign:
11200     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11201                                                Opc == BO_DivAssign);
11202     CompLHSTy = CompResultTy;
11203     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11204       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11205     break;
11206   case BO_RemAssign:
11207     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11208     CompLHSTy = CompResultTy;
11209     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11210       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11211     break;
11212   case BO_AddAssign:
11213     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11214     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11215       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11216     break;
11217   case BO_SubAssign:
11218     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11219     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11220       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11221     break;
11222   case BO_ShlAssign:
11223   case BO_ShrAssign:
11224     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11225     CompLHSTy = CompResultTy;
11226     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11227       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11228     break;
11229   case BO_AndAssign:
11230   case BO_OrAssign: // fallthrough
11231     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11232   case BO_XorAssign:
11233     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11234     CompLHSTy = CompResultTy;
11235     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11236       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11237     break;
11238   case BO_Comma:
11239     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11240     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11241       VK = RHS.get()->getValueKind();
11242       OK = RHS.get()->getObjectKind();
11243     }
11244     break;
11245   }
11246   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11247     return ExprError();
11248 
11249   // Check for array bounds violations for both sides of the BinaryOperator
11250   CheckArrayAccess(LHS.get());
11251   CheckArrayAccess(RHS.get());
11252 
11253   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11254     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11255                                                  &Context.Idents.get("object_setClass"),
11256                                                  SourceLocation(), LookupOrdinaryName);
11257     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11258       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11259       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11260       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11261       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11262       FixItHint::CreateInsertion(RHSLocEnd, ")");
11263     }
11264     else
11265       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11266   }
11267   else if (const ObjCIvarRefExpr *OIRE =
11268            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11269     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11270 
11271   if (CompResultTy.isNull())
11272     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11273                                         OK, OpLoc, FPFeatures);
11274   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11275       OK_ObjCProperty) {
11276     VK = VK_LValue;
11277     OK = LHS.get()->getObjectKind();
11278   }
11279   return new (Context) CompoundAssignOperator(
11280       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11281       OpLoc, FPFeatures);
11282 }
11283 
11284 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11285 /// operators are mixed in a way that suggests that the programmer forgot that
11286 /// comparison operators have higher precedence. The most typical example of
11287 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11288 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11289                                       SourceLocation OpLoc, Expr *LHSExpr,
11290                                       Expr *RHSExpr) {
11291   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11292   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11293 
11294   // Check that one of the sides is a comparison operator and the other isn't.
11295   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11296   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11297   if (isLeftComp == isRightComp)
11298     return;
11299 
11300   // Bitwise operations are sometimes used as eager logical ops.
11301   // Don't diagnose this.
11302   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11303   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11304   if (isLeftBitwise || isRightBitwise)
11305     return;
11306 
11307   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11308                                                    OpLoc)
11309                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11310   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11311   SourceRange ParensRange = isLeftComp ?
11312       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11313     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11314 
11315   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11316     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11317   SuggestParentheses(Self, OpLoc,
11318     Self.PDiag(diag::note_precedence_silence) << OpStr,
11319     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11320   SuggestParentheses(Self, OpLoc,
11321     Self.PDiag(diag::note_precedence_bitwise_first)
11322       << BinaryOperator::getOpcodeStr(Opc),
11323     ParensRange);
11324 }
11325 
11326 /// \brief It accepts a '&&' expr that is inside a '||' one.
11327 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11328 /// in parentheses.
11329 static void
11330 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11331                                        BinaryOperator *Bop) {
11332   assert(Bop->getOpcode() == BO_LAnd);
11333   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11334       << Bop->getSourceRange() << OpLoc;
11335   SuggestParentheses(Self, Bop->getOperatorLoc(),
11336     Self.PDiag(diag::note_precedence_silence)
11337       << Bop->getOpcodeStr(),
11338     Bop->getSourceRange());
11339 }
11340 
11341 /// \brief Returns true if the given expression can be evaluated as a constant
11342 /// 'true'.
11343 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11344   bool Res;
11345   return !E->isValueDependent() &&
11346          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11347 }
11348 
11349 /// \brief Returns true if the given expression can be evaluated as a constant
11350 /// 'false'.
11351 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11352   bool Res;
11353   return !E->isValueDependent() &&
11354          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11355 }
11356 
11357 /// \brief Look for '&&' in the left hand of a '||' expr.
11358 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11359                                              Expr *LHSExpr, Expr *RHSExpr) {
11360   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11361     if (Bop->getOpcode() == BO_LAnd) {
11362       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11363       if (EvaluatesAsFalse(S, RHSExpr))
11364         return;
11365       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11366       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11367         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11368     } else if (Bop->getOpcode() == BO_LOr) {
11369       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11370         // If it's "a || b && 1 || c" we didn't warn earlier for
11371         // "a || b && 1", but warn now.
11372         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11373           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11374       }
11375     }
11376   }
11377 }
11378 
11379 /// \brief Look for '&&' in the right hand of a '||' expr.
11380 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11381                                              Expr *LHSExpr, Expr *RHSExpr) {
11382   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11383     if (Bop->getOpcode() == BO_LAnd) {
11384       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11385       if (EvaluatesAsFalse(S, LHSExpr))
11386         return;
11387       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11388       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11389         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11390     }
11391   }
11392 }
11393 
11394 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11395 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11396 /// the '&' expression in parentheses.
11397 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11398                                          SourceLocation OpLoc, Expr *SubExpr) {
11399   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11400     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11401       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11402         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11403         << Bop->getSourceRange() << OpLoc;
11404       SuggestParentheses(S, Bop->getOperatorLoc(),
11405         S.PDiag(diag::note_precedence_silence)
11406           << Bop->getOpcodeStr(),
11407         Bop->getSourceRange());
11408     }
11409   }
11410 }
11411 
11412 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11413                                     Expr *SubExpr, StringRef Shift) {
11414   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11415     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11416       StringRef Op = Bop->getOpcodeStr();
11417       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11418           << Bop->getSourceRange() << OpLoc << Shift << Op;
11419       SuggestParentheses(S, Bop->getOperatorLoc(),
11420           S.PDiag(diag::note_precedence_silence) << Op,
11421           Bop->getSourceRange());
11422     }
11423   }
11424 }
11425 
11426 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11427                                  Expr *LHSExpr, Expr *RHSExpr) {
11428   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11429   if (!OCE)
11430     return;
11431 
11432   FunctionDecl *FD = OCE->getDirectCallee();
11433   if (!FD || !FD->isOverloadedOperator())
11434     return;
11435 
11436   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11437   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11438     return;
11439 
11440   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11441       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11442       << (Kind == OO_LessLess);
11443   SuggestParentheses(S, OCE->getOperatorLoc(),
11444                      S.PDiag(diag::note_precedence_silence)
11445                          << (Kind == OO_LessLess ? "<<" : ">>"),
11446                      OCE->getSourceRange());
11447   SuggestParentheses(S, OpLoc,
11448                      S.PDiag(diag::note_evaluate_comparison_first),
11449                      SourceRange(OCE->getArg(1)->getLocStart(),
11450                                  RHSExpr->getLocEnd()));
11451 }
11452 
11453 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11454 /// precedence.
11455 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11456                                     SourceLocation OpLoc, Expr *LHSExpr,
11457                                     Expr *RHSExpr){
11458   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11459   if (BinaryOperator::isBitwiseOp(Opc))
11460     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11461 
11462   // Diagnose "arg1 & arg2 | arg3"
11463   if ((Opc == BO_Or || Opc == BO_Xor) &&
11464       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11465     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11466     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11467   }
11468 
11469   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11470   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11471   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11472     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11473     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11474   }
11475 
11476   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11477       || Opc == BO_Shr) {
11478     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11479     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11480     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11481   }
11482 
11483   // Warn on overloaded shift operators and comparisons, such as:
11484   // cout << 5 == 4;
11485   if (BinaryOperator::isComparisonOp(Opc))
11486     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11487 }
11488 
11489 // Binary Operators.  'Tok' is the token for the operator.
11490 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11491                             tok::TokenKind Kind,
11492                             Expr *LHSExpr, Expr *RHSExpr) {
11493   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11494   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11495   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11496 
11497   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11498   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11499 
11500   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11501 }
11502 
11503 /// Build an overloaded binary operator expression in the given scope.
11504 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11505                                        BinaryOperatorKind Opc,
11506                                        Expr *LHS, Expr *RHS) {
11507   // Find all of the overloaded operators visible from this
11508   // point. We perform both an operator-name lookup from the local
11509   // scope and an argument-dependent lookup based on the types of
11510   // the arguments.
11511   UnresolvedSet<16> Functions;
11512   OverloadedOperatorKind OverOp
11513     = BinaryOperator::getOverloadedOperator(Opc);
11514   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11515     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11516                                    RHS->getType(), Functions);
11517 
11518   // Build the (potentially-overloaded, potentially-dependent)
11519   // binary operation.
11520   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11521 }
11522 
11523 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11524                             BinaryOperatorKind Opc,
11525                             Expr *LHSExpr, Expr *RHSExpr) {
11526   // We want to end up calling one of checkPseudoObjectAssignment
11527   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11528   // both expressions are overloadable or either is type-dependent),
11529   // or CreateBuiltinBinOp (in any other case).  We also want to get
11530   // any placeholder types out of the way.
11531 
11532   // Handle pseudo-objects in the LHS.
11533   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11534     // Assignments with a pseudo-object l-value need special analysis.
11535     if (pty->getKind() == BuiltinType::PseudoObject &&
11536         BinaryOperator::isAssignmentOp(Opc))
11537       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11538 
11539     // Don't resolve overloads if the other type is overloadable.
11540     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11541       // We can't actually test that if we still have a placeholder,
11542       // though.  Fortunately, none of the exceptions we see in that
11543       // code below are valid when the LHS is an overload set.  Note
11544       // that an overload set can be dependently-typed, but it never
11545       // instantiates to having an overloadable type.
11546       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11547       if (resolvedRHS.isInvalid()) return ExprError();
11548       RHSExpr = resolvedRHS.get();
11549 
11550       if (RHSExpr->isTypeDependent() ||
11551           RHSExpr->getType()->isOverloadableType())
11552         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11553     }
11554 
11555     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11556     if (LHS.isInvalid()) return ExprError();
11557     LHSExpr = LHS.get();
11558   }
11559 
11560   // Handle pseudo-objects in the RHS.
11561   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11562     // An overload in the RHS can potentially be resolved by the type
11563     // being assigned to.
11564     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11565       if (getLangOpts().CPlusPlus &&
11566           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11567            LHSExpr->getType()->isOverloadableType()))
11568         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11569 
11570       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11571     }
11572 
11573     // Don't resolve overloads if the other type is overloadable.
11574     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11575         LHSExpr->getType()->isOverloadableType())
11576       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11577 
11578     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11579     if (!resolvedRHS.isUsable()) return ExprError();
11580     RHSExpr = resolvedRHS.get();
11581   }
11582 
11583   if (getLangOpts().CPlusPlus) {
11584     // If either expression is type-dependent, always build an
11585     // overloaded op.
11586     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11587       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11588 
11589     // Otherwise, build an overloaded op if either expression has an
11590     // overloadable type.
11591     if (LHSExpr->getType()->isOverloadableType() ||
11592         RHSExpr->getType()->isOverloadableType())
11593       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11594   }
11595 
11596   // Build a built-in binary operation.
11597   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11598 }
11599 
11600 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11601                                       UnaryOperatorKind Opc,
11602                                       Expr *InputExpr) {
11603   ExprResult Input = InputExpr;
11604   ExprValueKind VK = VK_RValue;
11605   ExprObjectKind OK = OK_Ordinary;
11606   QualType resultType;
11607   if (getLangOpts().OpenCL) {
11608     QualType Ty = InputExpr->getType();
11609     // The only legal unary operation for atomics is '&'.
11610     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11611     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11612     // only with a builtin functions and therefore should be disallowed here.
11613         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11614         || Ty->isBlockPointerType())) {
11615       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11616                        << InputExpr->getType()
11617                        << Input.get()->getSourceRange());
11618     }
11619   }
11620   switch (Opc) {
11621   case UO_PreInc:
11622   case UO_PreDec:
11623   case UO_PostInc:
11624   case UO_PostDec:
11625     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11626                                                 OpLoc,
11627                                                 Opc == UO_PreInc ||
11628                                                 Opc == UO_PostInc,
11629                                                 Opc == UO_PreInc ||
11630                                                 Opc == UO_PreDec);
11631     break;
11632   case UO_AddrOf:
11633     resultType = CheckAddressOfOperand(Input, OpLoc);
11634     RecordModifiableNonNullParam(*this, InputExpr);
11635     break;
11636   case UO_Deref: {
11637     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11638     if (Input.isInvalid()) return ExprError();
11639     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11640     break;
11641   }
11642   case UO_Plus:
11643   case UO_Minus:
11644     Input = UsualUnaryConversions(Input.get());
11645     if (Input.isInvalid()) return ExprError();
11646     resultType = Input.get()->getType();
11647     if (resultType->isDependentType())
11648       break;
11649     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11650       break;
11651     else if (resultType->isVectorType() &&
11652              // The z vector extensions don't allow + or - with bool vectors.
11653              (!Context.getLangOpts().ZVector ||
11654               resultType->getAs<VectorType>()->getVectorKind() !=
11655               VectorType::AltiVecBool))
11656       break;
11657     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11658              Opc == UO_Plus &&
11659              resultType->isPointerType())
11660       break;
11661 
11662     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11663       << resultType << Input.get()->getSourceRange());
11664 
11665   case UO_Not: // bitwise complement
11666     Input = UsualUnaryConversions(Input.get());
11667     if (Input.isInvalid())
11668       return ExprError();
11669     resultType = Input.get()->getType();
11670     if (resultType->isDependentType())
11671       break;
11672     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11673     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11674       // C99 does not support '~' for complex conjugation.
11675       Diag(OpLoc, diag::ext_integer_complement_complex)
11676           << resultType << Input.get()->getSourceRange();
11677     else if (resultType->hasIntegerRepresentation())
11678       break;
11679     else if (resultType->isExtVectorType()) {
11680       if (Context.getLangOpts().OpenCL) {
11681         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11682         // on vector float types.
11683         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11684         if (!T->isIntegerType())
11685           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11686                            << resultType << Input.get()->getSourceRange());
11687       }
11688       break;
11689     } else {
11690       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11691                        << resultType << Input.get()->getSourceRange());
11692     }
11693     break;
11694 
11695   case UO_LNot: // logical negation
11696     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11697     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11698     if (Input.isInvalid()) return ExprError();
11699     resultType = Input.get()->getType();
11700 
11701     // Though we still have to promote half FP to float...
11702     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11703       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11704       resultType = Context.FloatTy;
11705     }
11706 
11707     if (resultType->isDependentType())
11708       break;
11709     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11710       // C99 6.5.3.3p1: ok, fallthrough;
11711       if (Context.getLangOpts().CPlusPlus) {
11712         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11713         // operand contextually converted to bool.
11714         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11715                                   ScalarTypeToBooleanCastKind(resultType));
11716       } else if (Context.getLangOpts().OpenCL &&
11717                  Context.getLangOpts().OpenCLVersion < 120) {
11718         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11719         // operate on scalar float types.
11720         if (!resultType->isIntegerType() && !resultType->isPointerType())
11721           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11722                            << resultType << Input.get()->getSourceRange());
11723       }
11724     } else if (resultType->isExtVectorType()) {
11725       if (Context.getLangOpts().OpenCL &&
11726           Context.getLangOpts().OpenCLVersion < 120) {
11727         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11728         // operate on vector float types.
11729         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11730         if (!T->isIntegerType())
11731           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11732                            << resultType << Input.get()->getSourceRange());
11733       }
11734       // Vector logical not returns the signed variant of the operand type.
11735       resultType = GetSignedVectorType(resultType);
11736       break;
11737     } else {
11738       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11739         << resultType << Input.get()->getSourceRange());
11740     }
11741 
11742     // LNot always has type int. C99 6.5.3.3p5.
11743     // In C++, it's bool. C++ 5.3.1p8
11744     resultType = Context.getLogicalOperationType();
11745     break;
11746   case UO_Real:
11747   case UO_Imag:
11748     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11749     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11750     // complex l-values to ordinary l-values and all other values to r-values.
11751     if (Input.isInvalid()) return ExprError();
11752     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11753       if (Input.get()->getValueKind() != VK_RValue &&
11754           Input.get()->getObjectKind() == OK_Ordinary)
11755         VK = Input.get()->getValueKind();
11756     } else if (!getLangOpts().CPlusPlus) {
11757       // In C, a volatile scalar is read by __imag. In C++, it is not.
11758       Input = DefaultLvalueConversion(Input.get());
11759     }
11760     break;
11761   case UO_Extension:
11762   case UO_Coawait:
11763     resultType = Input.get()->getType();
11764     VK = Input.get()->getValueKind();
11765     OK = Input.get()->getObjectKind();
11766     break;
11767   }
11768   if (resultType.isNull() || Input.isInvalid())
11769     return ExprError();
11770 
11771   // Check for array bounds violations in the operand of the UnaryOperator,
11772   // except for the '*' and '&' operators that have to be handled specially
11773   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11774   // that are explicitly defined as valid by the standard).
11775   if (Opc != UO_AddrOf && Opc != UO_Deref)
11776     CheckArrayAccess(Input.get());
11777 
11778   return new (Context)
11779       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11780 }
11781 
11782 /// \brief Determine whether the given expression is a qualified member
11783 /// access expression, of a form that could be turned into a pointer to member
11784 /// with the address-of operator.
11785 static bool isQualifiedMemberAccess(Expr *E) {
11786   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11787     if (!DRE->getQualifier())
11788       return false;
11789 
11790     ValueDecl *VD = DRE->getDecl();
11791     if (!VD->isCXXClassMember())
11792       return false;
11793 
11794     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11795       return true;
11796     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11797       return Method->isInstance();
11798 
11799     return false;
11800   }
11801 
11802   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11803     if (!ULE->getQualifier())
11804       return false;
11805 
11806     for (NamedDecl *D : ULE->decls()) {
11807       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11808         if (Method->isInstance())
11809           return true;
11810       } else {
11811         // Overload set does not contain methods.
11812         break;
11813       }
11814     }
11815 
11816     return false;
11817   }
11818 
11819   return false;
11820 }
11821 
11822 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11823                               UnaryOperatorKind Opc, Expr *Input) {
11824   // First things first: handle placeholders so that the
11825   // overloaded-operator check considers the right type.
11826   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11827     // Increment and decrement of pseudo-object references.
11828     if (pty->getKind() == BuiltinType::PseudoObject &&
11829         UnaryOperator::isIncrementDecrementOp(Opc))
11830       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11831 
11832     // extension is always a builtin operator.
11833     if (Opc == UO_Extension)
11834       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11835 
11836     // & gets special logic for several kinds of placeholder.
11837     // The builtin code knows what to do.
11838     if (Opc == UO_AddrOf &&
11839         (pty->getKind() == BuiltinType::Overload ||
11840          pty->getKind() == BuiltinType::UnknownAny ||
11841          pty->getKind() == BuiltinType::BoundMember))
11842       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11843 
11844     // Anything else needs to be handled now.
11845     ExprResult Result = CheckPlaceholderExpr(Input);
11846     if (Result.isInvalid()) return ExprError();
11847     Input = Result.get();
11848   }
11849 
11850   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11851       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11852       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11853     // Find all of the overloaded operators visible from this
11854     // point. We perform both an operator-name lookup from the local
11855     // scope and an argument-dependent lookup based on the types of
11856     // the arguments.
11857     UnresolvedSet<16> Functions;
11858     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11859     if (S && OverOp != OO_None)
11860       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11861                                    Functions);
11862 
11863     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11864   }
11865 
11866   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11867 }
11868 
11869 // Unary Operators.  'Tok' is the token for the operator.
11870 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11871                               tok::TokenKind Op, Expr *Input) {
11872   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11873 }
11874 
11875 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11876 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11877                                 LabelDecl *TheDecl) {
11878   TheDecl->markUsed(Context);
11879   // Create the AST node.  The address of a label always has type 'void*'.
11880   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11881                                      Context.getPointerType(Context.VoidTy));
11882 }
11883 
11884 /// Given the last statement in a statement-expression, check whether
11885 /// the result is a producing expression (like a call to an
11886 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11887 /// release out of the full-expression.  Otherwise, return null.
11888 /// Cannot fail.
11889 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11890   // Should always be wrapped with one of these.
11891   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11892   if (!cleanups) return nullptr;
11893 
11894   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11895   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11896     return nullptr;
11897 
11898   // Splice out the cast.  This shouldn't modify any interesting
11899   // features of the statement.
11900   Expr *producer = cast->getSubExpr();
11901   assert(producer->getType() == cast->getType());
11902   assert(producer->getValueKind() == cast->getValueKind());
11903   cleanups->setSubExpr(producer);
11904   return cleanups;
11905 }
11906 
11907 void Sema::ActOnStartStmtExpr() {
11908   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11909 }
11910 
11911 void Sema::ActOnStmtExprError() {
11912   // Note that function is also called by TreeTransform when leaving a
11913   // StmtExpr scope without rebuilding anything.
11914 
11915   DiscardCleanupsInEvaluationContext();
11916   PopExpressionEvaluationContext();
11917 }
11918 
11919 ExprResult
11920 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11921                     SourceLocation RPLoc) { // "({..})"
11922   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11923   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11924 
11925   if (hasAnyUnrecoverableErrorsInThisFunction())
11926     DiscardCleanupsInEvaluationContext();
11927   assert(!Cleanup.exprNeedsCleanups() &&
11928          "cleanups within StmtExpr not correctly bound!");
11929   PopExpressionEvaluationContext();
11930 
11931   // FIXME: there are a variety of strange constraints to enforce here, for
11932   // example, it is not possible to goto into a stmt expression apparently.
11933   // More semantic analysis is needed.
11934 
11935   // If there are sub-stmts in the compound stmt, take the type of the last one
11936   // as the type of the stmtexpr.
11937   QualType Ty = Context.VoidTy;
11938   bool StmtExprMayBindToTemp = false;
11939   if (!Compound->body_empty()) {
11940     Stmt *LastStmt = Compound->body_back();
11941     LabelStmt *LastLabelStmt = nullptr;
11942     // If LastStmt is a label, skip down through into the body.
11943     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11944       LastLabelStmt = Label;
11945       LastStmt = Label->getSubStmt();
11946     }
11947 
11948     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11949       // Do function/array conversion on the last expression, but not
11950       // lvalue-to-rvalue.  However, initialize an unqualified type.
11951       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11952       if (LastExpr.isInvalid())
11953         return ExprError();
11954       Ty = LastExpr.get()->getType().getUnqualifiedType();
11955 
11956       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11957         // In ARC, if the final expression ends in a consume, splice
11958         // the consume out and bind it later.  In the alternate case
11959         // (when dealing with a retainable type), the result
11960         // initialization will create a produce.  In both cases the
11961         // result will be +1, and we'll need to balance that out with
11962         // a bind.
11963         if (Expr *rebuiltLastStmt
11964               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11965           LastExpr = rebuiltLastStmt;
11966         } else {
11967           LastExpr = PerformCopyInitialization(
11968                             InitializedEntity::InitializeResult(LPLoc,
11969                                                                 Ty,
11970                                                                 false),
11971                                                    SourceLocation(),
11972                                                LastExpr);
11973         }
11974 
11975         if (LastExpr.isInvalid())
11976           return ExprError();
11977         if (LastExpr.get() != nullptr) {
11978           if (!LastLabelStmt)
11979             Compound->setLastStmt(LastExpr.get());
11980           else
11981             LastLabelStmt->setSubStmt(LastExpr.get());
11982           StmtExprMayBindToTemp = true;
11983         }
11984       }
11985     }
11986   }
11987 
11988   // FIXME: Check that expression type is complete/non-abstract; statement
11989   // expressions are not lvalues.
11990   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11991   if (StmtExprMayBindToTemp)
11992     return MaybeBindToTemporary(ResStmtExpr);
11993   return ResStmtExpr;
11994 }
11995 
11996 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11997                                       TypeSourceInfo *TInfo,
11998                                       ArrayRef<OffsetOfComponent> Components,
11999                                       SourceLocation RParenLoc) {
12000   QualType ArgTy = TInfo->getType();
12001   bool Dependent = ArgTy->isDependentType();
12002   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12003 
12004   // We must have at least one component that refers to the type, and the first
12005   // one is known to be a field designator.  Verify that the ArgTy represents
12006   // a struct/union/class.
12007   if (!Dependent && !ArgTy->isRecordType())
12008     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12009                        << ArgTy << TypeRange);
12010 
12011   // Type must be complete per C99 7.17p3 because a declaring a variable
12012   // with an incomplete type would be ill-formed.
12013   if (!Dependent
12014       && RequireCompleteType(BuiltinLoc, ArgTy,
12015                              diag::err_offsetof_incomplete_type, TypeRange))
12016     return ExprError();
12017 
12018   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12019   // GCC extension, diagnose them.
12020   // FIXME: This diagnostic isn't actually visible because the location is in
12021   // a system header!
12022   if (Components.size() != 1)
12023     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12024       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12025 
12026   bool DidWarnAboutNonPOD = false;
12027   QualType CurrentType = ArgTy;
12028   SmallVector<OffsetOfNode, 4> Comps;
12029   SmallVector<Expr*, 4> Exprs;
12030   for (const OffsetOfComponent &OC : Components) {
12031     if (OC.isBrackets) {
12032       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12033       if (!CurrentType->isDependentType()) {
12034         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12035         if(!AT)
12036           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12037                            << CurrentType);
12038         CurrentType = AT->getElementType();
12039       } else
12040         CurrentType = Context.DependentTy;
12041 
12042       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12043       if (IdxRval.isInvalid())
12044         return ExprError();
12045       Expr *Idx = IdxRval.get();
12046 
12047       // The expression must be an integral expression.
12048       // FIXME: An integral constant expression?
12049       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12050           !Idx->getType()->isIntegerType())
12051         return ExprError(Diag(Idx->getLocStart(),
12052                               diag::err_typecheck_subscript_not_integer)
12053                          << Idx->getSourceRange());
12054 
12055       // Record this array index.
12056       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12057       Exprs.push_back(Idx);
12058       continue;
12059     }
12060 
12061     // Offset of a field.
12062     if (CurrentType->isDependentType()) {
12063       // We have the offset of a field, but we can't look into the dependent
12064       // type. Just record the identifier of the field.
12065       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12066       CurrentType = Context.DependentTy;
12067       continue;
12068     }
12069 
12070     // We need to have a complete type to look into.
12071     if (RequireCompleteType(OC.LocStart, CurrentType,
12072                             diag::err_offsetof_incomplete_type))
12073       return ExprError();
12074 
12075     // Look for the designated field.
12076     const RecordType *RC = CurrentType->getAs<RecordType>();
12077     if (!RC)
12078       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12079                        << CurrentType);
12080     RecordDecl *RD = RC->getDecl();
12081 
12082     // C++ [lib.support.types]p5:
12083     //   The macro offsetof accepts a restricted set of type arguments in this
12084     //   International Standard. type shall be a POD structure or a POD union
12085     //   (clause 9).
12086     // C++11 [support.types]p4:
12087     //   If type is not a standard-layout class (Clause 9), the results are
12088     //   undefined.
12089     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12090       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12091       unsigned DiagID =
12092         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12093                             : diag::ext_offsetof_non_pod_type;
12094 
12095       if (!IsSafe && !DidWarnAboutNonPOD &&
12096           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12097                               PDiag(DiagID)
12098                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12099                               << CurrentType))
12100         DidWarnAboutNonPOD = true;
12101     }
12102 
12103     // Look for the field.
12104     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12105     LookupQualifiedName(R, RD);
12106     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12107     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12108     if (!MemberDecl) {
12109       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12110         MemberDecl = IndirectMemberDecl->getAnonField();
12111     }
12112 
12113     if (!MemberDecl)
12114       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12115                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12116                                                               OC.LocEnd));
12117 
12118     // C99 7.17p3:
12119     //   (If the specified member is a bit-field, the behavior is undefined.)
12120     //
12121     // We diagnose this as an error.
12122     if (MemberDecl->isBitField()) {
12123       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12124         << MemberDecl->getDeclName()
12125         << SourceRange(BuiltinLoc, RParenLoc);
12126       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12127       return ExprError();
12128     }
12129 
12130     RecordDecl *Parent = MemberDecl->getParent();
12131     if (IndirectMemberDecl)
12132       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12133 
12134     // If the member was found in a base class, introduce OffsetOfNodes for
12135     // the base class indirections.
12136     CXXBasePaths Paths;
12137     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12138                       Paths)) {
12139       if (Paths.getDetectedVirtual()) {
12140         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12141           << MemberDecl->getDeclName()
12142           << SourceRange(BuiltinLoc, RParenLoc);
12143         return ExprError();
12144       }
12145 
12146       CXXBasePath &Path = Paths.front();
12147       for (const CXXBasePathElement &B : Path)
12148         Comps.push_back(OffsetOfNode(B.Base));
12149     }
12150 
12151     if (IndirectMemberDecl) {
12152       for (auto *FI : IndirectMemberDecl->chain()) {
12153         assert(isa<FieldDecl>(FI));
12154         Comps.push_back(OffsetOfNode(OC.LocStart,
12155                                      cast<FieldDecl>(FI), OC.LocEnd));
12156       }
12157     } else
12158       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12159 
12160     CurrentType = MemberDecl->getType().getNonReferenceType();
12161   }
12162 
12163   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12164                               Comps, Exprs, RParenLoc);
12165 }
12166 
12167 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12168                                       SourceLocation BuiltinLoc,
12169                                       SourceLocation TypeLoc,
12170                                       ParsedType ParsedArgTy,
12171                                       ArrayRef<OffsetOfComponent> Components,
12172                                       SourceLocation RParenLoc) {
12173 
12174   TypeSourceInfo *ArgTInfo;
12175   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12176   if (ArgTy.isNull())
12177     return ExprError();
12178 
12179   if (!ArgTInfo)
12180     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12181 
12182   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12183 }
12184 
12185 
12186 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12187                                  Expr *CondExpr,
12188                                  Expr *LHSExpr, Expr *RHSExpr,
12189                                  SourceLocation RPLoc) {
12190   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12191 
12192   ExprValueKind VK = VK_RValue;
12193   ExprObjectKind OK = OK_Ordinary;
12194   QualType resType;
12195   bool ValueDependent = false;
12196   bool CondIsTrue = false;
12197   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12198     resType = Context.DependentTy;
12199     ValueDependent = true;
12200   } else {
12201     // The conditional expression is required to be a constant expression.
12202     llvm::APSInt condEval(32);
12203     ExprResult CondICE
12204       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12205           diag::err_typecheck_choose_expr_requires_constant, false);
12206     if (CondICE.isInvalid())
12207       return ExprError();
12208     CondExpr = CondICE.get();
12209     CondIsTrue = condEval.getZExtValue();
12210 
12211     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12212     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12213 
12214     resType = ActiveExpr->getType();
12215     ValueDependent = ActiveExpr->isValueDependent();
12216     VK = ActiveExpr->getValueKind();
12217     OK = ActiveExpr->getObjectKind();
12218   }
12219 
12220   return new (Context)
12221       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12222                  CondIsTrue, resType->isDependentType(), ValueDependent);
12223 }
12224 
12225 //===----------------------------------------------------------------------===//
12226 // Clang Extensions.
12227 //===----------------------------------------------------------------------===//
12228 
12229 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12230 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12231   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12232 
12233   if (LangOpts.CPlusPlus) {
12234     Decl *ManglingContextDecl;
12235     if (MangleNumberingContext *MCtx =
12236             getCurrentMangleNumberContext(Block->getDeclContext(),
12237                                           ManglingContextDecl)) {
12238       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12239       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12240     }
12241   }
12242 
12243   PushBlockScope(CurScope, Block);
12244   CurContext->addDecl(Block);
12245   if (CurScope)
12246     PushDeclContext(CurScope, Block);
12247   else
12248     CurContext = Block;
12249 
12250   getCurBlock()->HasImplicitReturnType = true;
12251 
12252   // Enter a new evaluation context to insulate the block from any
12253   // cleanups from the enclosing full-expression.
12254   PushExpressionEvaluationContext(
12255       ExpressionEvaluationContext::PotentiallyEvaluated);
12256 }
12257 
12258 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12259                                Scope *CurScope) {
12260   assert(ParamInfo.getIdentifier() == nullptr &&
12261          "block-id should have no identifier!");
12262   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12263   BlockScopeInfo *CurBlock = getCurBlock();
12264 
12265   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12266   QualType T = Sig->getType();
12267 
12268   // FIXME: We should allow unexpanded parameter packs here, but that would,
12269   // in turn, make the block expression contain unexpanded parameter packs.
12270   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12271     // Drop the parameters.
12272     FunctionProtoType::ExtProtoInfo EPI;
12273     EPI.HasTrailingReturn = false;
12274     EPI.TypeQuals |= DeclSpec::TQ_const;
12275     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12276     Sig = Context.getTrivialTypeSourceInfo(T);
12277   }
12278 
12279   // GetTypeForDeclarator always produces a function type for a block
12280   // literal signature.  Furthermore, it is always a FunctionProtoType
12281   // unless the function was written with a typedef.
12282   assert(T->isFunctionType() &&
12283          "GetTypeForDeclarator made a non-function block signature");
12284 
12285   // Look for an explicit signature in that function type.
12286   FunctionProtoTypeLoc ExplicitSignature;
12287 
12288   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12289   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12290 
12291     // Check whether that explicit signature was synthesized by
12292     // GetTypeForDeclarator.  If so, don't save that as part of the
12293     // written signature.
12294     if (ExplicitSignature.getLocalRangeBegin() ==
12295         ExplicitSignature.getLocalRangeEnd()) {
12296       // This would be much cheaper if we stored TypeLocs instead of
12297       // TypeSourceInfos.
12298       TypeLoc Result = ExplicitSignature.getReturnLoc();
12299       unsigned Size = Result.getFullDataSize();
12300       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12301       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12302 
12303       ExplicitSignature = FunctionProtoTypeLoc();
12304     }
12305   }
12306 
12307   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12308   CurBlock->FunctionType = T;
12309 
12310   const FunctionType *Fn = T->getAs<FunctionType>();
12311   QualType RetTy = Fn->getReturnType();
12312   bool isVariadic =
12313     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12314 
12315   CurBlock->TheDecl->setIsVariadic(isVariadic);
12316 
12317   // Context.DependentTy is used as a placeholder for a missing block
12318   // return type.  TODO:  what should we do with declarators like:
12319   //   ^ * { ... }
12320   // If the answer is "apply template argument deduction"....
12321   if (RetTy != Context.DependentTy) {
12322     CurBlock->ReturnType = RetTy;
12323     CurBlock->TheDecl->setBlockMissingReturnType(false);
12324     CurBlock->HasImplicitReturnType = false;
12325   }
12326 
12327   // Push block parameters from the declarator if we had them.
12328   SmallVector<ParmVarDecl*, 8> Params;
12329   if (ExplicitSignature) {
12330     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12331       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12332       if (Param->getIdentifier() == nullptr &&
12333           !Param->isImplicit() &&
12334           !Param->isInvalidDecl() &&
12335           !getLangOpts().CPlusPlus)
12336         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12337       Params.push_back(Param);
12338     }
12339 
12340   // Fake up parameter variables if we have a typedef, like
12341   //   ^ fntype { ... }
12342   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12343     for (const auto &I : Fn->param_types()) {
12344       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12345           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12346       Params.push_back(Param);
12347     }
12348   }
12349 
12350   // Set the parameters on the block decl.
12351   if (!Params.empty()) {
12352     CurBlock->TheDecl->setParams(Params);
12353     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12354                              /*CheckParameterNames=*/false);
12355   }
12356 
12357   // Finally we can process decl attributes.
12358   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12359 
12360   // Put the parameter variables in scope.
12361   for (auto AI : CurBlock->TheDecl->parameters()) {
12362     AI->setOwningFunction(CurBlock->TheDecl);
12363 
12364     // If this has an identifier, add it to the scope stack.
12365     if (AI->getIdentifier()) {
12366       CheckShadow(CurBlock->TheScope, AI);
12367 
12368       PushOnScopeChains(AI, CurBlock->TheScope);
12369     }
12370   }
12371 }
12372 
12373 /// ActOnBlockError - If there is an error parsing a block, this callback
12374 /// is invoked to pop the information about the block from the action impl.
12375 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12376   // Leave the expression-evaluation context.
12377   DiscardCleanupsInEvaluationContext();
12378   PopExpressionEvaluationContext();
12379 
12380   // Pop off CurBlock, handle nested blocks.
12381   PopDeclContext();
12382   PopFunctionScopeInfo();
12383 }
12384 
12385 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12386 /// literal was successfully completed.  ^(int x){...}
12387 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12388                                     Stmt *Body, Scope *CurScope) {
12389   // If blocks are disabled, emit an error.
12390   if (!LangOpts.Blocks)
12391     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12392 
12393   // Leave the expression-evaluation context.
12394   if (hasAnyUnrecoverableErrorsInThisFunction())
12395     DiscardCleanupsInEvaluationContext();
12396   assert(!Cleanup.exprNeedsCleanups() &&
12397          "cleanups within block not correctly bound!");
12398   PopExpressionEvaluationContext();
12399 
12400   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12401 
12402   if (BSI->HasImplicitReturnType)
12403     deduceClosureReturnType(*BSI);
12404 
12405   PopDeclContext();
12406 
12407   QualType RetTy = Context.VoidTy;
12408   if (!BSI->ReturnType.isNull())
12409     RetTy = BSI->ReturnType;
12410 
12411   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12412   QualType BlockTy;
12413 
12414   // Set the captured variables on the block.
12415   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12416   SmallVector<BlockDecl::Capture, 4> Captures;
12417   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12418     if (Cap.isThisCapture())
12419       continue;
12420     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12421                               Cap.isNested(), Cap.getInitExpr());
12422     Captures.push_back(NewCap);
12423   }
12424   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12425 
12426   // If the user wrote a function type in some form, try to use that.
12427   if (!BSI->FunctionType.isNull()) {
12428     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12429 
12430     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12431     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12432 
12433     // Turn protoless block types into nullary block types.
12434     if (isa<FunctionNoProtoType>(FTy)) {
12435       FunctionProtoType::ExtProtoInfo EPI;
12436       EPI.ExtInfo = Ext;
12437       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12438 
12439     // Otherwise, if we don't need to change anything about the function type,
12440     // preserve its sugar structure.
12441     } else if (FTy->getReturnType() == RetTy &&
12442                (!NoReturn || FTy->getNoReturnAttr())) {
12443       BlockTy = BSI->FunctionType;
12444 
12445     // Otherwise, make the minimal modifications to the function type.
12446     } else {
12447       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12448       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12449       EPI.TypeQuals = 0; // FIXME: silently?
12450       EPI.ExtInfo = Ext;
12451       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12452     }
12453 
12454   // If we don't have a function type, just build one from nothing.
12455   } else {
12456     FunctionProtoType::ExtProtoInfo EPI;
12457     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12458     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12459   }
12460 
12461   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12462   BlockTy = Context.getBlockPointerType(BlockTy);
12463 
12464   // If needed, diagnose invalid gotos and switches in the block.
12465   if (getCurFunction()->NeedsScopeChecking() &&
12466       !PP.isCodeCompletionEnabled())
12467     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12468 
12469   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12470 
12471   // Try to apply the named return value optimization. We have to check again
12472   // if we can do this, though, because blocks keep return statements around
12473   // to deduce an implicit return type.
12474   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12475       !BSI->TheDecl->isDependentContext())
12476     computeNRVO(Body, BSI);
12477 
12478   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12479   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12480   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12481 
12482   // If the block isn't obviously global, i.e. it captures anything at
12483   // all, then we need to do a few things in the surrounding context:
12484   if (Result->getBlockDecl()->hasCaptures()) {
12485     // First, this expression has a new cleanup object.
12486     ExprCleanupObjects.push_back(Result->getBlockDecl());
12487     Cleanup.setExprNeedsCleanups(true);
12488 
12489     // It also gets a branch-protected scope if any of the captured
12490     // variables needs destruction.
12491     for (const auto &CI : Result->getBlockDecl()->captures()) {
12492       const VarDecl *var = CI.getVariable();
12493       if (var->getType().isDestructedType() != QualType::DK_none) {
12494         getCurFunction()->setHasBranchProtectedScope();
12495         break;
12496       }
12497     }
12498   }
12499 
12500   return Result;
12501 }
12502 
12503 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12504                             SourceLocation RPLoc) {
12505   TypeSourceInfo *TInfo;
12506   GetTypeFromParser(Ty, &TInfo);
12507   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12508 }
12509 
12510 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12511                                 Expr *E, TypeSourceInfo *TInfo,
12512                                 SourceLocation RPLoc) {
12513   Expr *OrigExpr = E;
12514   bool IsMS = false;
12515 
12516   // CUDA device code does not support varargs.
12517   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12518     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12519       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12520       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12521         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12522     }
12523   }
12524 
12525   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12526   // as Microsoft ABI on an actual Microsoft platform, where
12527   // __builtin_ms_va_list and __builtin_va_list are the same.)
12528   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12529       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12530     QualType MSVaListType = Context.getBuiltinMSVaListType();
12531     if (Context.hasSameType(MSVaListType, E->getType())) {
12532       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12533         return ExprError();
12534       IsMS = true;
12535     }
12536   }
12537 
12538   // Get the va_list type
12539   QualType VaListType = Context.getBuiltinVaListType();
12540   if (!IsMS) {
12541     if (VaListType->isArrayType()) {
12542       // Deal with implicit array decay; for example, on x86-64,
12543       // va_list is an array, but it's supposed to decay to
12544       // a pointer for va_arg.
12545       VaListType = Context.getArrayDecayedType(VaListType);
12546       // Make sure the input expression also decays appropriately.
12547       ExprResult Result = UsualUnaryConversions(E);
12548       if (Result.isInvalid())
12549         return ExprError();
12550       E = Result.get();
12551     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12552       // If va_list is a record type and we are compiling in C++ mode,
12553       // check the argument using reference binding.
12554       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12555           Context, Context.getLValueReferenceType(VaListType), false);
12556       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12557       if (Init.isInvalid())
12558         return ExprError();
12559       E = Init.getAs<Expr>();
12560     } else {
12561       // Otherwise, the va_list argument must be an l-value because
12562       // it is modified by va_arg.
12563       if (!E->isTypeDependent() &&
12564           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12565         return ExprError();
12566     }
12567   }
12568 
12569   if (!IsMS && !E->isTypeDependent() &&
12570       !Context.hasSameType(VaListType, E->getType()))
12571     return ExprError(Diag(E->getLocStart(),
12572                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12573       << OrigExpr->getType() << E->getSourceRange());
12574 
12575   if (!TInfo->getType()->isDependentType()) {
12576     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12577                             diag::err_second_parameter_to_va_arg_incomplete,
12578                             TInfo->getTypeLoc()))
12579       return ExprError();
12580 
12581     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12582                                TInfo->getType(),
12583                                diag::err_second_parameter_to_va_arg_abstract,
12584                                TInfo->getTypeLoc()))
12585       return ExprError();
12586 
12587     if (!TInfo->getType().isPODType(Context)) {
12588       Diag(TInfo->getTypeLoc().getBeginLoc(),
12589            TInfo->getType()->isObjCLifetimeType()
12590              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12591              : diag::warn_second_parameter_to_va_arg_not_pod)
12592         << TInfo->getType()
12593         << TInfo->getTypeLoc().getSourceRange();
12594     }
12595 
12596     // Check for va_arg where arguments of the given type will be promoted
12597     // (i.e. this va_arg is guaranteed to have undefined behavior).
12598     QualType PromoteType;
12599     if (TInfo->getType()->isPromotableIntegerType()) {
12600       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12601       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12602         PromoteType = QualType();
12603     }
12604     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12605       PromoteType = Context.DoubleTy;
12606     if (!PromoteType.isNull())
12607       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12608                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12609                           << TInfo->getType()
12610                           << PromoteType
12611                           << TInfo->getTypeLoc().getSourceRange());
12612   }
12613 
12614   QualType T = TInfo->getType().getNonLValueExprType(Context);
12615   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12616 }
12617 
12618 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12619   // The type of __null will be int or long, depending on the size of
12620   // pointers on the target.
12621   QualType Ty;
12622   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12623   if (pw == Context.getTargetInfo().getIntWidth())
12624     Ty = Context.IntTy;
12625   else if (pw == Context.getTargetInfo().getLongWidth())
12626     Ty = Context.LongTy;
12627   else if (pw == Context.getTargetInfo().getLongLongWidth())
12628     Ty = Context.LongLongTy;
12629   else {
12630     llvm_unreachable("I don't know size of pointer!");
12631   }
12632 
12633   return new (Context) GNUNullExpr(Ty, TokenLoc);
12634 }
12635 
12636 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12637                                               bool Diagnose) {
12638   if (!getLangOpts().ObjC1)
12639     return false;
12640 
12641   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12642   if (!PT)
12643     return false;
12644 
12645   if (!PT->isObjCIdType()) {
12646     // Check if the destination is the 'NSString' interface.
12647     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12648     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12649       return false;
12650   }
12651 
12652   // Ignore any parens, implicit casts (should only be
12653   // array-to-pointer decays), and not-so-opaque values.  The last is
12654   // important for making this trigger for property assignments.
12655   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12656   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12657     if (OV->getSourceExpr())
12658       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12659 
12660   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12661   if (!SL || !SL->isAscii())
12662     return false;
12663   if (Diagnose) {
12664     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12665       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12666     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12667   }
12668   return true;
12669 }
12670 
12671 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12672                                               const Expr *SrcExpr) {
12673   if (!DstType->isFunctionPointerType() ||
12674       !SrcExpr->getType()->isFunctionType())
12675     return false;
12676 
12677   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12678   if (!DRE)
12679     return false;
12680 
12681   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12682   if (!FD)
12683     return false;
12684 
12685   return !S.checkAddressOfFunctionIsAvailable(FD,
12686                                               /*Complain=*/true,
12687                                               SrcExpr->getLocStart());
12688 }
12689 
12690 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12691                                     SourceLocation Loc,
12692                                     QualType DstType, QualType SrcType,
12693                                     Expr *SrcExpr, AssignmentAction Action,
12694                                     bool *Complained) {
12695   if (Complained)
12696     *Complained = false;
12697 
12698   // Decode the result (notice that AST's are still created for extensions).
12699   bool CheckInferredResultType = false;
12700   bool isInvalid = false;
12701   unsigned DiagKind = 0;
12702   FixItHint Hint;
12703   ConversionFixItGenerator ConvHints;
12704   bool MayHaveConvFixit = false;
12705   bool MayHaveFunctionDiff = false;
12706   const ObjCInterfaceDecl *IFace = nullptr;
12707   const ObjCProtocolDecl *PDecl = nullptr;
12708 
12709   switch (ConvTy) {
12710   case Compatible:
12711       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12712       return false;
12713 
12714   case PointerToInt:
12715     DiagKind = diag::ext_typecheck_convert_pointer_int;
12716     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12717     MayHaveConvFixit = true;
12718     break;
12719   case IntToPointer:
12720     DiagKind = diag::ext_typecheck_convert_int_pointer;
12721     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12722     MayHaveConvFixit = true;
12723     break;
12724   case IncompatiblePointer:
12725     if (Action == AA_Passing_CFAudited)
12726       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12727     else if (SrcType->isFunctionPointerType() &&
12728              DstType->isFunctionPointerType())
12729       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12730     else
12731       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12732 
12733     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12734       SrcType->isObjCObjectPointerType();
12735     if (Hint.isNull() && !CheckInferredResultType) {
12736       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12737     }
12738     else if (CheckInferredResultType) {
12739       SrcType = SrcType.getUnqualifiedType();
12740       DstType = DstType.getUnqualifiedType();
12741     }
12742     MayHaveConvFixit = true;
12743     break;
12744   case IncompatiblePointerSign:
12745     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12746     break;
12747   case FunctionVoidPointer:
12748     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12749     break;
12750   case IncompatiblePointerDiscardsQualifiers: {
12751     // Perform array-to-pointer decay if necessary.
12752     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12753 
12754     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12755     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12756     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12757       DiagKind = diag::err_typecheck_incompatible_address_space;
12758       break;
12759 
12760 
12761     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12762       DiagKind = diag::err_typecheck_incompatible_ownership;
12763       break;
12764     }
12765 
12766     llvm_unreachable("unknown error case for discarding qualifiers!");
12767     // fallthrough
12768   }
12769   case CompatiblePointerDiscardsQualifiers:
12770     // If the qualifiers lost were because we were applying the
12771     // (deprecated) C++ conversion from a string literal to a char*
12772     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12773     // Ideally, this check would be performed in
12774     // checkPointerTypesForAssignment. However, that would require a
12775     // bit of refactoring (so that the second argument is an
12776     // expression, rather than a type), which should be done as part
12777     // of a larger effort to fix checkPointerTypesForAssignment for
12778     // C++ semantics.
12779     if (getLangOpts().CPlusPlus &&
12780         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12781       return false;
12782     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12783     break;
12784   case IncompatibleNestedPointerQualifiers:
12785     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12786     break;
12787   case IntToBlockPointer:
12788     DiagKind = diag::err_int_to_block_pointer;
12789     break;
12790   case IncompatibleBlockPointer:
12791     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12792     break;
12793   case IncompatibleObjCQualifiedId: {
12794     if (SrcType->isObjCQualifiedIdType()) {
12795       const ObjCObjectPointerType *srcOPT =
12796                 SrcType->getAs<ObjCObjectPointerType>();
12797       for (auto *srcProto : srcOPT->quals()) {
12798         PDecl = srcProto;
12799         break;
12800       }
12801       if (const ObjCInterfaceType *IFaceT =
12802             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12803         IFace = IFaceT->getDecl();
12804     }
12805     else if (DstType->isObjCQualifiedIdType()) {
12806       const ObjCObjectPointerType *dstOPT =
12807         DstType->getAs<ObjCObjectPointerType>();
12808       for (auto *dstProto : dstOPT->quals()) {
12809         PDecl = dstProto;
12810         break;
12811       }
12812       if (const ObjCInterfaceType *IFaceT =
12813             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12814         IFace = IFaceT->getDecl();
12815     }
12816     DiagKind = diag::warn_incompatible_qualified_id;
12817     break;
12818   }
12819   case IncompatibleVectors:
12820     DiagKind = diag::warn_incompatible_vectors;
12821     break;
12822   case IncompatibleObjCWeakRef:
12823     DiagKind = diag::err_arc_weak_unavailable_assign;
12824     break;
12825   case Incompatible:
12826     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12827       if (Complained)
12828         *Complained = true;
12829       return true;
12830     }
12831 
12832     DiagKind = diag::err_typecheck_convert_incompatible;
12833     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12834     MayHaveConvFixit = true;
12835     isInvalid = true;
12836     MayHaveFunctionDiff = true;
12837     break;
12838   }
12839 
12840   QualType FirstType, SecondType;
12841   switch (Action) {
12842   case AA_Assigning:
12843   case AA_Initializing:
12844     // The destination type comes first.
12845     FirstType = DstType;
12846     SecondType = SrcType;
12847     break;
12848 
12849   case AA_Returning:
12850   case AA_Passing:
12851   case AA_Passing_CFAudited:
12852   case AA_Converting:
12853   case AA_Sending:
12854   case AA_Casting:
12855     // The source type comes first.
12856     FirstType = SrcType;
12857     SecondType = DstType;
12858     break;
12859   }
12860 
12861   PartialDiagnostic FDiag = PDiag(DiagKind);
12862   if (Action == AA_Passing_CFAudited)
12863     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12864   else
12865     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12866 
12867   // If we can fix the conversion, suggest the FixIts.
12868   assert(ConvHints.isNull() || Hint.isNull());
12869   if (!ConvHints.isNull()) {
12870     for (FixItHint &H : ConvHints.Hints)
12871       FDiag << H;
12872   } else {
12873     FDiag << Hint;
12874   }
12875   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12876 
12877   if (MayHaveFunctionDiff)
12878     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12879 
12880   Diag(Loc, FDiag);
12881   if (DiagKind == diag::warn_incompatible_qualified_id &&
12882       PDecl && IFace && !IFace->hasDefinition())
12883       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12884         << IFace->getName() << PDecl->getName();
12885 
12886   if (SecondType == Context.OverloadTy)
12887     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12888                               FirstType, /*TakingAddress=*/true);
12889 
12890   if (CheckInferredResultType)
12891     EmitRelatedResultTypeNote(SrcExpr);
12892 
12893   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12894     EmitRelatedResultTypeNoteForReturn(DstType);
12895 
12896   if (Complained)
12897     *Complained = true;
12898   return isInvalid;
12899 }
12900 
12901 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12902                                                  llvm::APSInt *Result) {
12903   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12904   public:
12905     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12906       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12907     }
12908   } Diagnoser;
12909 
12910   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12911 }
12912 
12913 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12914                                                  llvm::APSInt *Result,
12915                                                  unsigned DiagID,
12916                                                  bool AllowFold) {
12917   class IDDiagnoser : public VerifyICEDiagnoser {
12918     unsigned DiagID;
12919 
12920   public:
12921     IDDiagnoser(unsigned DiagID)
12922       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12923 
12924     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12925       S.Diag(Loc, DiagID) << SR;
12926     }
12927   } Diagnoser(DiagID);
12928 
12929   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12930 }
12931 
12932 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12933                                             SourceRange SR) {
12934   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12935 }
12936 
12937 ExprResult
12938 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12939                                       VerifyICEDiagnoser &Diagnoser,
12940                                       bool AllowFold) {
12941   SourceLocation DiagLoc = E->getLocStart();
12942 
12943   if (getLangOpts().CPlusPlus11) {
12944     // C++11 [expr.const]p5:
12945     //   If an expression of literal class type is used in a context where an
12946     //   integral constant expression is required, then that class type shall
12947     //   have a single non-explicit conversion function to an integral or
12948     //   unscoped enumeration type
12949     ExprResult Converted;
12950     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12951     public:
12952       CXX11ConvertDiagnoser(bool Silent)
12953           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12954                                 Silent, true) {}
12955 
12956       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12957                                            QualType T) override {
12958         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12959       }
12960 
12961       SemaDiagnosticBuilder diagnoseIncomplete(
12962           Sema &S, SourceLocation Loc, QualType T) override {
12963         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12964       }
12965 
12966       SemaDiagnosticBuilder diagnoseExplicitConv(
12967           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12968         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12969       }
12970 
12971       SemaDiagnosticBuilder noteExplicitConv(
12972           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12973         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12974                  << ConvTy->isEnumeralType() << ConvTy;
12975       }
12976 
12977       SemaDiagnosticBuilder diagnoseAmbiguous(
12978           Sema &S, SourceLocation Loc, QualType T) override {
12979         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12980       }
12981 
12982       SemaDiagnosticBuilder noteAmbiguous(
12983           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12984         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12985                  << ConvTy->isEnumeralType() << ConvTy;
12986       }
12987 
12988       SemaDiagnosticBuilder diagnoseConversion(
12989           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12990         llvm_unreachable("conversion functions are permitted");
12991       }
12992     } ConvertDiagnoser(Diagnoser.Suppress);
12993 
12994     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12995                                                     ConvertDiagnoser);
12996     if (Converted.isInvalid())
12997       return Converted;
12998     E = Converted.get();
12999     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13000       return ExprError();
13001   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13002     // An ICE must be of integral or unscoped enumeration type.
13003     if (!Diagnoser.Suppress)
13004       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13005     return ExprError();
13006   }
13007 
13008   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13009   // in the non-ICE case.
13010   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13011     if (Result)
13012       *Result = E->EvaluateKnownConstInt(Context);
13013     return E;
13014   }
13015 
13016   Expr::EvalResult EvalResult;
13017   SmallVector<PartialDiagnosticAt, 8> Notes;
13018   EvalResult.Diag = &Notes;
13019 
13020   // Try to evaluate the expression, and produce diagnostics explaining why it's
13021   // not a constant expression as a side-effect.
13022   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13023                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13024 
13025   // In C++11, we can rely on diagnostics being produced for any expression
13026   // which is not a constant expression. If no diagnostics were produced, then
13027   // this is a constant expression.
13028   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13029     if (Result)
13030       *Result = EvalResult.Val.getInt();
13031     return E;
13032   }
13033 
13034   // If our only note is the usual "invalid subexpression" note, just point
13035   // the caret at its location rather than producing an essentially
13036   // redundant note.
13037   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13038         diag::note_invalid_subexpr_in_const_expr) {
13039     DiagLoc = Notes[0].first;
13040     Notes.clear();
13041   }
13042 
13043   if (!Folded || !AllowFold) {
13044     if (!Diagnoser.Suppress) {
13045       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13046       for (const PartialDiagnosticAt &Note : Notes)
13047         Diag(Note.first, Note.second);
13048     }
13049 
13050     return ExprError();
13051   }
13052 
13053   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13054   for (const PartialDiagnosticAt &Note : Notes)
13055     Diag(Note.first, Note.second);
13056 
13057   if (Result)
13058     *Result = EvalResult.Val.getInt();
13059   return E;
13060 }
13061 
13062 namespace {
13063   // Handle the case where we conclude a expression which we speculatively
13064   // considered to be unevaluated is actually evaluated.
13065   class TransformToPE : public TreeTransform<TransformToPE> {
13066     typedef TreeTransform<TransformToPE> BaseTransform;
13067 
13068   public:
13069     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13070 
13071     // Make sure we redo semantic analysis
13072     bool AlwaysRebuild() { return true; }
13073 
13074     // Make sure we handle LabelStmts correctly.
13075     // FIXME: This does the right thing, but maybe we need a more general
13076     // fix to TreeTransform?
13077     StmtResult TransformLabelStmt(LabelStmt *S) {
13078       S->getDecl()->setStmt(nullptr);
13079       return BaseTransform::TransformLabelStmt(S);
13080     }
13081 
13082     // We need to special-case DeclRefExprs referring to FieldDecls which
13083     // are not part of a member pointer formation; normal TreeTransforming
13084     // doesn't catch this case because of the way we represent them in the AST.
13085     // FIXME: This is a bit ugly; is it really the best way to handle this
13086     // case?
13087     //
13088     // Error on DeclRefExprs referring to FieldDecls.
13089     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13090       if (isa<FieldDecl>(E->getDecl()) &&
13091           !SemaRef.isUnevaluatedContext())
13092         return SemaRef.Diag(E->getLocation(),
13093                             diag::err_invalid_non_static_member_use)
13094             << E->getDecl() << E->getSourceRange();
13095 
13096       return BaseTransform::TransformDeclRefExpr(E);
13097     }
13098 
13099     // Exception: filter out member pointer formation
13100     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13101       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13102         return E;
13103 
13104       return BaseTransform::TransformUnaryOperator(E);
13105     }
13106 
13107     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13108       // Lambdas never need to be transformed.
13109       return E;
13110     }
13111   };
13112 }
13113 
13114 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13115   assert(isUnevaluatedContext() &&
13116          "Should only transform unevaluated expressions");
13117   ExprEvalContexts.back().Context =
13118       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13119   if (isUnevaluatedContext())
13120     return E;
13121   return TransformToPE(*this).TransformExpr(E);
13122 }
13123 
13124 void
13125 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13126                                       Decl *LambdaContextDecl,
13127                                       bool IsDecltype) {
13128   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13129                                 LambdaContextDecl, IsDecltype);
13130   Cleanup.reset();
13131   if (!MaybeODRUseExprs.empty())
13132     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13133 }
13134 
13135 void
13136 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13137                                       ReuseLambdaContextDecl_t,
13138                                       bool IsDecltype) {
13139   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13140   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13141 }
13142 
13143 void Sema::PopExpressionEvaluationContext() {
13144   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13145   unsigned NumTypos = Rec.NumTypos;
13146 
13147   if (!Rec.Lambdas.empty()) {
13148     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13149       unsigned D;
13150       if (Rec.isUnevaluated()) {
13151         // C++11 [expr.prim.lambda]p2:
13152         //   A lambda-expression shall not appear in an unevaluated operand
13153         //   (Clause 5).
13154         D = diag::err_lambda_unevaluated_operand;
13155       } else {
13156         // C++1y [expr.const]p2:
13157         //   A conditional-expression e is a core constant expression unless the
13158         //   evaluation of e, following the rules of the abstract machine, would
13159         //   evaluate [...] a lambda-expression.
13160         D = diag::err_lambda_in_constant_expression;
13161       }
13162 
13163       // C++1z allows lambda expressions as core constant expressions.
13164       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13165       // 1607) from appearing within template-arguments and array-bounds that
13166       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13167       // unevaluated contexts) might lift some of these restrictions in a
13168       // future version.
13169       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13170         for (const auto *L : Rec.Lambdas)
13171           Diag(L->getLocStart(), D);
13172     } else {
13173       // Mark the capture expressions odr-used. This was deferred
13174       // during lambda expression creation.
13175       for (auto *Lambda : Rec.Lambdas) {
13176         for (auto *C : Lambda->capture_inits())
13177           MarkDeclarationsReferencedInExpr(C);
13178       }
13179     }
13180   }
13181 
13182   // When are coming out of an unevaluated context, clear out any
13183   // temporaries that we may have created as part of the evaluation of
13184   // the expression in that context: they aren't relevant because they
13185   // will never be constructed.
13186   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13187     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13188                              ExprCleanupObjects.end());
13189     Cleanup = Rec.ParentCleanup;
13190     CleanupVarDeclMarking();
13191     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13192   // Otherwise, merge the contexts together.
13193   } else {
13194     Cleanup.mergeFrom(Rec.ParentCleanup);
13195     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13196                             Rec.SavedMaybeODRUseExprs.end());
13197   }
13198 
13199   // Pop the current expression evaluation context off the stack.
13200   ExprEvalContexts.pop_back();
13201 
13202   if (!ExprEvalContexts.empty())
13203     ExprEvalContexts.back().NumTypos += NumTypos;
13204   else
13205     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13206                             "last ExpressionEvaluationContextRecord");
13207 }
13208 
13209 void Sema::DiscardCleanupsInEvaluationContext() {
13210   ExprCleanupObjects.erase(
13211          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13212          ExprCleanupObjects.end());
13213   Cleanup.reset();
13214   MaybeODRUseExprs.clear();
13215 }
13216 
13217 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13218   if (!E->getType()->isVariablyModifiedType())
13219     return E;
13220   return TransformToPotentiallyEvaluated(E);
13221 }
13222 
13223 /// Are we within a context in which some evaluation could be performed (be it
13224 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13225 /// captured by C++'s idea of an "unevaluated context".
13226 static bool isEvaluatableContext(Sema &SemaRef) {
13227   switch (SemaRef.ExprEvalContexts.back().Context) {
13228     case Sema::ExpressionEvaluationContext::Unevaluated:
13229     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13230     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13231       // Expressions in this context are never evaluated.
13232       return false;
13233 
13234     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13235     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13236     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13237       // Expressions in this context could be evaluated.
13238       return true;
13239 
13240     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13241       // Referenced declarations will only be used if the construct in the
13242       // containing expression is used, at which point we'll be given another
13243       // turn to mark them.
13244       return false;
13245   }
13246   llvm_unreachable("Invalid context");
13247 }
13248 
13249 /// Are we within a context in which references to resolved functions or to
13250 /// variables result in odr-use?
13251 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13252   // An expression in a template is not really an expression until it's been
13253   // instantiated, so it doesn't trigger odr-use.
13254   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13255     return false;
13256 
13257   switch (SemaRef.ExprEvalContexts.back().Context) {
13258     case Sema::ExpressionEvaluationContext::Unevaluated:
13259     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13260     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13261     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13262       return false;
13263 
13264     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13265     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13266       return true;
13267 
13268     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13269       return false;
13270   }
13271   llvm_unreachable("Invalid context");
13272 }
13273 
13274 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13275   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13276   return Func->isConstexpr() &&
13277          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13278 }
13279 
13280 /// \brief Mark a function referenced, and check whether it is odr-used
13281 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13282 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13283                                   bool MightBeOdrUse) {
13284   assert(Func && "No function?");
13285 
13286   Func->setReferenced();
13287 
13288   // C++11 [basic.def.odr]p3:
13289   //   A function whose name appears as a potentially-evaluated expression is
13290   //   odr-used if it is the unique lookup result or the selected member of a
13291   //   set of overloaded functions [...].
13292   //
13293   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13294   // can just check that here.
13295   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13296 
13297   // Determine whether we require a function definition to exist, per
13298   // C++11 [temp.inst]p3:
13299   //   Unless a function template specialization has been explicitly
13300   //   instantiated or explicitly specialized, the function template
13301   //   specialization is implicitly instantiated when the specialization is
13302   //   referenced in a context that requires a function definition to exist.
13303   //
13304   // That is either when this is an odr-use, or when a usage of a constexpr
13305   // function occurs within an evaluatable context.
13306   bool NeedDefinition =
13307       OdrUse || (isEvaluatableContext(*this) &&
13308                  isImplicitlyDefinableConstexprFunction(Func));
13309 
13310   // C++14 [temp.expl.spec]p6:
13311   //   If a template [...] is explicitly specialized then that specialization
13312   //   shall be declared before the first use of that specialization that would
13313   //   cause an implicit instantiation to take place, in every translation unit
13314   //   in which such a use occurs
13315   if (NeedDefinition &&
13316       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13317        Func->getMemberSpecializationInfo()))
13318     checkSpecializationVisibility(Loc, Func);
13319 
13320   // C++14 [except.spec]p17:
13321   //   An exception-specification is considered to be needed when:
13322   //   - the function is odr-used or, if it appears in an unevaluated operand,
13323   //     would be odr-used if the expression were potentially-evaluated;
13324   //
13325   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13326   // function is a pure virtual function we're calling, and in that case the
13327   // function was selected by overload resolution and we need to resolve its
13328   // exception specification for a different reason.
13329   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13330   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13331     ResolveExceptionSpec(Loc, FPT);
13332 
13333   // If we don't need to mark the function as used, and we don't need to
13334   // try to provide a definition, there's nothing more to do.
13335   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13336       (!NeedDefinition || Func->getBody()))
13337     return;
13338 
13339   // Note that this declaration has been used.
13340   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13341     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13342     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13343       if (Constructor->isDefaultConstructor()) {
13344         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13345           return;
13346         DefineImplicitDefaultConstructor(Loc, Constructor);
13347       } else if (Constructor->isCopyConstructor()) {
13348         DefineImplicitCopyConstructor(Loc, Constructor);
13349       } else if (Constructor->isMoveConstructor()) {
13350         DefineImplicitMoveConstructor(Loc, Constructor);
13351       }
13352     } else if (Constructor->getInheritedConstructor()) {
13353       DefineInheritingConstructor(Loc, Constructor);
13354     }
13355   } else if (CXXDestructorDecl *Destructor =
13356                  dyn_cast<CXXDestructorDecl>(Func)) {
13357     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13358     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13359       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13360         return;
13361       DefineImplicitDestructor(Loc, Destructor);
13362     }
13363     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13364       MarkVTableUsed(Loc, Destructor->getParent());
13365   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13366     if (MethodDecl->isOverloadedOperator() &&
13367         MethodDecl->getOverloadedOperator() == OO_Equal) {
13368       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13369       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13370         if (MethodDecl->isCopyAssignmentOperator())
13371           DefineImplicitCopyAssignment(Loc, MethodDecl);
13372         else if (MethodDecl->isMoveAssignmentOperator())
13373           DefineImplicitMoveAssignment(Loc, MethodDecl);
13374       }
13375     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13376                MethodDecl->getParent()->isLambda()) {
13377       CXXConversionDecl *Conversion =
13378           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13379       if (Conversion->isLambdaToBlockPointerConversion())
13380         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13381       else
13382         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13383     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13384       MarkVTableUsed(Loc, MethodDecl->getParent());
13385   }
13386 
13387   // Recursive functions should be marked when used from another function.
13388   // FIXME: Is this really right?
13389   if (CurContext == Func) return;
13390 
13391   // Implicit instantiation of function templates and member functions of
13392   // class templates.
13393   if (Func->isImplicitlyInstantiable()) {
13394     bool AlreadyInstantiated = false;
13395     SourceLocation PointOfInstantiation = Loc;
13396     if (FunctionTemplateSpecializationInfo *SpecInfo
13397                               = Func->getTemplateSpecializationInfo()) {
13398       if (SpecInfo->getPointOfInstantiation().isInvalid())
13399         SpecInfo->setPointOfInstantiation(Loc);
13400       else if (SpecInfo->getTemplateSpecializationKind()
13401                  == TSK_ImplicitInstantiation) {
13402         AlreadyInstantiated = true;
13403         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13404       }
13405     } else if (MemberSpecializationInfo *MSInfo
13406                                 = Func->getMemberSpecializationInfo()) {
13407       if (MSInfo->getPointOfInstantiation().isInvalid())
13408         MSInfo->setPointOfInstantiation(Loc);
13409       else if (MSInfo->getTemplateSpecializationKind()
13410                  == TSK_ImplicitInstantiation) {
13411         AlreadyInstantiated = true;
13412         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13413       }
13414     }
13415 
13416     if (!AlreadyInstantiated || Func->isConstexpr()) {
13417       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13418           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13419           CodeSynthesisContexts.size())
13420         PendingLocalImplicitInstantiations.push_back(
13421             std::make_pair(Func, PointOfInstantiation));
13422       else if (Func->isConstexpr())
13423         // Do not defer instantiations of constexpr functions, to avoid the
13424         // expression evaluator needing to call back into Sema if it sees a
13425         // call to such a function.
13426         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13427       else {
13428         PendingInstantiations.push_back(std::make_pair(Func,
13429                                                        PointOfInstantiation));
13430         // Notify the consumer that a function was implicitly instantiated.
13431         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13432       }
13433     }
13434   } else {
13435     // Walk redefinitions, as some of them may be instantiable.
13436     for (auto i : Func->redecls()) {
13437       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13438         MarkFunctionReferenced(Loc, i, OdrUse);
13439     }
13440   }
13441 
13442   if (!OdrUse) return;
13443 
13444   // Keep track of used but undefined functions.
13445   if (!Func->isDefined()) {
13446     if (mightHaveNonExternalLinkage(Func))
13447       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13448     else if (Func->getMostRecentDecl()->isInlined() &&
13449              !LangOpts.GNUInline &&
13450              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13451       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13452   }
13453 
13454   Func->markUsed(Context);
13455 }
13456 
13457 static void
13458 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13459                                    ValueDecl *var, DeclContext *DC) {
13460   DeclContext *VarDC = var->getDeclContext();
13461 
13462   //  If the parameter still belongs to the translation unit, then
13463   //  we're actually just using one parameter in the declaration of
13464   //  the next.
13465   if (isa<ParmVarDecl>(var) &&
13466       isa<TranslationUnitDecl>(VarDC))
13467     return;
13468 
13469   // For C code, don't diagnose about capture if we're not actually in code
13470   // right now; it's impossible to write a non-constant expression outside of
13471   // function context, so we'll get other (more useful) diagnostics later.
13472   //
13473   // For C++, things get a bit more nasty... it would be nice to suppress this
13474   // diagnostic for certain cases like using a local variable in an array bound
13475   // for a member of a local class, but the correct predicate is not obvious.
13476   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13477     return;
13478 
13479   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13480   unsigned ContextKind = 3; // unknown
13481   if (isa<CXXMethodDecl>(VarDC) &&
13482       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13483     ContextKind = 2;
13484   } else if (isa<FunctionDecl>(VarDC)) {
13485     ContextKind = 0;
13486   } else if (isa<BlockDecl>(VarDC)) {
13487     ContextKind = 1;
13488   }
13489 
13490   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13491     << var << ValueKind << ContextKind << VarDC;
13492   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13493       << var;
13494 
13495   // FIXME: Add additional diagnostic info about class etc. which prevents
13496   // capture.
13497 }
13498 
13499 
13500 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13501                                       bool &SubCapturesAreNested,
13502                                       QualType &CaptureType,
13503                                       QualType &DeclRefType) {
13504    // Check whether we've already captured it.
13505   if (CSI->CaptureMap.count(Var)) {
13506     // If we found a capture, any subcaptures are nested.
13507     SubCapturesAreNested = true;
13508 
13509     // Retrieve the capture type for this variable.
13510     CaptureType = CSI->getCapture(Var).getCaptureType();
13511 
13512     // Compute the type of an expression that refers to this variable.
13513     DeclRefType = CaptureType.getNonReferenceType();
13514 
13515     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13516     // are mutable in the sense that user can change their value - they are
13517     // private instances of the captured declarations.
13518     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13519     if (Cap.isCopyCapture() &&
13520         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13521         !(isa<CapturedRegionScopeInfo>(CSI) &&
13522           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13523       DeclRefType.addConst();
13524     return true;
13525   }
13526   return false;
13527 }
13528 
13529 // Only block literals, captured statements, and lambda expressions can
13530 // capture; other scopes don't work.
13531 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13532                                  SourceLocation Loc,
13533                                  const bool Diagnose, Sema &S) {
13534   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13535     return getLambdaAwareParentOfDeclContext(DC);
13536   else if (Var->hasLocalStorage()) {
13537     if (Diagnose)
13538        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13539   }
13540   return nullptr;
13541 }
13542 
13543 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13544 // certain types of variables (unnamed, variably modified types etc.)
13545 // so check for eligibility.
13546 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13547                                  SourceLocation Loc,
13548                                  const bool Diagnose, Sema &S) {
13549 
13550   bool IsBlock = isa<BlockScopeInfo>(CSI);
13551   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13552 
13553   // Lambdas are not allowed to capture unnamed variables
13554   // (e.g. anonymous unions).
13555   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13556   // assuming that's the intent.
13557   if (IsLambda && !Var->getDeclName()) {
13558     if (Diagnose) {
13559       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13560       S.Diag(Var->getLocation(), diag::note_declared_at);
13561     }
13562     return false;
13563   }
13564 
13565   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13566   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13567     if (Diagnose) {
13568       S.Diag(Loc, diag::err_ref_vm_type);
13569       S.Diag(Var->getLocation(), diag::note_previous_decl)
13570         << Var->getDeclName();
13571     }
13572     return false;
13573   }
13574   // Prohibit structs with flexible array members too.
13575   // We cannot capture what is in the tail end of the struct.
13576   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13577     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13578       if (Diagnose) {
13579         if (IsBlock)
13580           S.Diag(Loc, diag::err_ref_flexarray_type);
13581         else
13582           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13583             << Var->getDeclName();
13584         S.Diag(Var->getLocation(), diag::note_previous_decl)
13585           << Var->getDeclName();
13586       }
13587       return false;
13588     }
13589   }
13590   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13591   // Lambdas and captured statements are not allowed to capture __block
13592   // variables; they don't support the expected semantics.
13593   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13594     if (Diagnose) {
13595       S.Diag(Loc, diag::err_capture_block_variable)
13596         << Var->getDeclName() << !IsLambda;
13597       S.Diag(Var->getLocation(), diag::note_previous_decl)
13598         << Var->getDeclName();
13599     }
13600     return false;
13601   }
13602   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13603   if (S.getLangOpts().OpenCL && IsBlock &&
13604       Var->getType()->isBlockPointerType()) {
13605     if (Diagnose)
13606       S.Diag(Loc, diag::err_opencl_block_ref_block);
13607     return false;
13608   }
13609 
13610   return true;
13611 }
13612 
13613 // Returns true if the capture by block was successful.
13614 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13615                                  SourceLocation Loc,
13616                                  const bool BuildAndDiagnose,
13617                                  QualType &CaptureType,
13618                                  QualType &DeclRefType,
13619                                  const bool Nested,
13620                                  Sema &S) {
13621   Expr *CopyExpr = nullptr;
13622   bool ByRef = false;
13623 
13624   // Blocks are not allowed to capture arrays.
13625   if (CaptureType->isArrayType()) {
13626     if (BuildAndDiagnose) {
13627       S.Diag(Loc, diag::err_ref_array_type);
13628       S.Diag(Var->getLocation(), diag::note_previous_decl)
13629       << Var->getDeclName();
13630     }
13631     return false;
13632   }
13633 
13634   // Forbid the block-capture of autoreleasing variables.
13635   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13636     if (BuildAndDiagnose) {
13637       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13638         << /*block*/ 0;
13639       S.Diag(Var->getLocation(), diag::note_previous_decl)
13640         << Var->getDeclName();
13641     }
13642     return false;
13643   }
13644 
13645   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13646   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13647     // This function finds out whether there is an AttributedType of kind
13648     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13649     // attr_objc_ownership implies __autoreleasing was explicitly specified
13650     // rather than being added implicitly by the compiler.
13651     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13652       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13653         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13654           return true;
13655 
13656         // Peel off AttributedTypes that are not of kind objc_ownership.
13657         Ty = AttrTy->getModifiedType();
13658       }
13659 
13660       return false;
13661     };
13662 
13663     QualType PointeeTy = PT->getPointeeType();
13664 
13665     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13666         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13667         !IsObjCOwnershipAttributedType(PointeeTy)) {
13668       if (BuildAndDiagnose) {
13669         SourceLocation VarLoc = Var->getLocation();
13670         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13671         {
13672           auto AddAutoreleaseNote =
13673               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13674           // Provide a fix-it for the '__autoreleasing' keyword at the
13675           // appropriate location in the variable's type.
13676           if (const auto *TSI = Var->getTypeSourceInfo()) {
13677             PointerTypeLoc PTL =
13678                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13679             if (PTL) {
13680               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13681               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13682                                                S.getLangOpts());
13683               if (Loc.isValid()) {
13684                 StringRef CharAtLoc = Lexer::getSourceText(
13685                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13686                     S.getSourceManager(), S.getLangOpts());
13687                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13688                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13689                              ? " __autoreleasing "
13690                              : " __autoreleasing");
13691               }
13692             }
13693           }
13694         }
13695         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13696       }
13697     }
13698   }
13699 
13700   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13701   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13702       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13703     // Block capture by reference does not change the capture or
13704     // declaration reference types.
13705     ByRef = true;
13706   } else {
13707     // Block capture by copy introduces 'const'.
13708     CaptureType = CaptureType.getNonReferenceType().withConst();
13709     DeclRefType = CaptureType;
13710 
13711     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13712       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13713         // The capture logic needs the destructor, so make sure we mark it.
13714         // Usually this is unnecessary because most local variables have
13715         // their destructors marked at declaration time, but parameters are
13716         // an exception because it's technically only the call site that
13717         // actually requires the destructor.
13718         if (isa<ParmVarDecl>(Var))
13719           S.FinalizeVarWithDestructor(Var, Record);
13720 
13721         // Enter a new evaluation context to insulate the copy
13722         // full-expression.
13723         EnterExpressionEvaluationContext scope(
13724             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13725 
13726         // According to the blocks spec, the capture of a variable from
13727         // the stack requires a const copy constructor.  This is not true
13728         // of the copy/move done to move a __block variable to the heap.
13729         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13730                                                   DeclRefType.withConst(),
13731                                                   VK_LValue, Loc);
13732 
13733         ExprResult Result
13734           = S.PerformCopyInitialization(
13735               InitializedEntity::InitializeBlock(Var->getLocation(),
13736                                                   CaptureType, false),
13737               Loc, DeclRef);
13738 
13739         // Build a full-expression copy expression if initialization
13740         // succeeded and used a non-trivial constructor.  Recover from
13741         // errors by pretending that the copy isn't necessary.
13742         if (!Result.isInvalid() &&
13743             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13744                 ->isTrivial()) {
13745           Result = S.MaybeCreateExprWithCleanups(Result);
13746           CopyExpr = Result.get();
13747         }
13748       }
13749     }
13750   }
13751 
13752   // Actually capture the variable.
13753   if (BuildAndDiagnose)
13754     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13755                     SourceLocation(), CaptureType, CopyExpr);
13756 
13757   return true;
13758 
13759 }
13760 
13761 
13762 /// \brief Capture the given variable in the captured region.
13763 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13764                                     VarDecl *Var,
13765                                     SourceLocation Loc,
13766                                     const bool BuildAndDiagnose,
13767                                     QualType &CaptureType,
13768                                     QualType &DeclRefType,
13769                                     const bool RefersToCapturedVariable,
13770                                     Sema &S) {
13771   // By default, capture variables by reference.
13772   bool ByRef = true;
13773   // Using an LValue reference type is consistent with Lambdas (see below).
13774   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13775     if (S.IsOpenMPCapturedDecl(Var))
13776       DeclRefType = DeclRefType.getUnqualifiedType();
13777     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13778   }
13779 
13780   if (ByRef)
13781     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13782   else
13783     CaptureType = DeclRefType;
13784 
13785   Expr *CopyExpr = nullptr;
13786   if (BuildAndDiagnose) {
13787     // The current implementation assumes that all variables are captured
13788     // by references. Since there is no capture by copy, no expression
13789     // evaluation will be needed.
13790     RecordDecl *RD = RSI->TheRecordDecl;
13791 
13792     FieldDecl *Field
13793       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13794                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13795                           nullptr, false, ICIS_NoInit);
13796     Field->setImplicit(true);
13797     Field->setAccess(AS_private);
13798     RD->addDecl(Field);
13799 
13800     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13801                                             DeclRefType, VK_LValue, Loc);
13802     Var->setReferenced(true);
13803     Var->markUsed(S.Context);
13804   }
13805 
13806   // Actually capture the variable.
13807   if (BuildAndDiagnose)
13808     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13809                     SourceLocation(), CaptureType, CopyExpr);
13810 
13811 
13812   return true;
13813 }
13814 
13815 /// \brief Create a field within the lambda class for the variable
13816 /// being captured.
13817 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13818                                     QualType FieldType, QualType DeclRefType,
13819                                     SourceLocation Loc,
13820                                     bool RefersToCapturedVariable) {
13821   CXXRecordDecl *Lambda = LSI->Lambda;
13822 
13823   // Build the non-static data member.
13824   FieldDecl *Field
13825     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13826                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13827                         nullptr, false, ICIS_NoInit);
13828   Field->setImplicit(true);
13829   Field->setAccess(AS_private);
13830   Lambda->addDecl(Field);
13831 }
13832 
13833 /// \brief Capture the given variable in the lambda.
13834 static bool captureInLambda(LambdaScopeInfo *LSI,
13835                             VarDecl *Var,
13836                             SourceLocation Loc,
13837                             const bool BuildAndDiagnose,
13838                             QualType &CaptureType,
13839                             QualType &DeclRefType,
13840                             const bool RefersToCapturedVariable,
13841                             const Sema::TryCaptureKind Kind,
13842                             SourceLocation EllipsisLoc,
13843                             const bool IsTopScope,
13844                             Sema &S) {
13845 
13846   // Determine whether we are capturing by reference or by value.
13847   bool ByRef = false;
13848   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13849     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13850   } else {
13851     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13852   }
13853 
13854   // Compute the type of the field that will capture this variable.
13855   if (ByRef) {
13856     // C++11 [expr.prim.lambda]p15:
13857     //   An entity is captured by reference if it is implicitly or
13858     //   explicitly captured but not captured by copy. It is
13859     //   unspecified whether additional unnamed non-static data
13860     //   members are declared in the closure type for entities
13861     //   captured by reference.
13862     //
13863     // FIXME: It is not clear whether we want to build an lvalue reference
13864     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13865     // to do the former, while EDG does the latter. Core issue 1249 will
13866     // clarify, but for now we follow GCC because it's a more permissive and
13867     // easily defensible position.
13868     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13869   } else {
13870     // C++11 [expr.prim.lambda]p14:
13871     //   For each entity captured by copy, an unnamed non-static
13872     //   data member is declared in the closure type. The
13873     //   declaration order of these members is unspecified. The type
13874     //   of such a data member is the type of the corresponding
13875     //   captured entity if the entity is not a reference to an
13876     //   object, or the referenced type otherwise. [Note: If the
13877     //   captured entity is a reference to a function, the
13878     //   corresponding data member is also a reference to a
13879     //   function. - end note ]
13880     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13881       if (!RefType->getPointeeType()->isFunctionType())
13882         CaptureType = RefType->getPointeeType();
13883     }
13884 
13885     // Forbid the lambda copy-capture of autoreleasing variables.
13886     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13887       if (BuildAndDiagnose) {
13888         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13889         S.Diag(Var->getLocation(), diag::note_previous_decl)
13890           << Var->getDeclName();
13891       }
13892       return false;
13893     }
13894 
13895     // Make sure that by-copy captures are of a complete and non-abstract type.
13896     if (BuildAndDiagnose) {
13897       if (!CaptureType->isDependentType() &&
13898           S.RequireCompleteType(Loc, CaptureType,
13899                                 diag::err_capture_of_incomplete_type,
13900                                 Var->getDeclName()))
13901         return false;
13902 
13903       if (S.RequireNonAbstractType(Loc, CaptureType,
13904                                    diag::err_capture_of_abstract_type))
13905         return false;
13906     }
13907   }
13908 
13909   // Capture this variable in the lambda.
13910   if (BuildAndDiagnose)
13911     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13912                             RefersToCapturedVariable);
13913 
13914   // Compute the type of a reference to this captured variable.
13915   if (ByRef)
13916     DeclRefType = CaptureType.getNonReferenceType();
13917   else {
13918     // C++ [expr.prim.lambda]p5:
13919     //   The closure type for a lambda-expression has a public inline
13920     //   function call operator [...]. This function call operator is
13921     //   declared const (9.3.1) if and only if the lambda-expression's
13922     //   parameter-declaration-clause is not followed by mutable.
13923     DeclRefType = CaptureType.getNonReferenceType();
13924     if (!LSI->Mutable && !CaptureType->isReferenceType())
13925       DeclRefType.addConst();
13926   }
13927 
13928   // Add the capture.
13929   if (BuildAndDiagnose)
13930     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13931                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13932 
13933   return true;
13934 }
13935 
13936 bool Sema::tryCaptureVariable(
13937     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13938     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13939     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13940   // An init-capture is notionally from the context surrounding its
13941   // declaration, but its parent DC is the lambda class.
13942   DeclContext *VarDC = Var->getDeclContext();
13943   if (Var->isInitCapture())
13944     VarDC = VarDC->getParent();
13945 
13946   DeclContext *DC = CurContext;
13947   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13948       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13949   // We need to sync up the Declaration Context with the
13950   // FunctionScopeIndexToStopAt
13951   if (FunctionScopeIndexToStopAt) {
13952     unsigned FSIndex = FunctionScopes.size() - 1;
13953     while (FSIndex != MaxFunctionScopesIndex) {
13954       DC = getLambdaAwareParentOfDeclContext(DC);
13955       --FSIndex;
13956     }
13957   }
13958 
13959 
13960   // If the variable is declared in the current context, there is no need to
13961   // capture it.
13962   if (VarDC == DC) return true;
13963 
13964   // Capture global variables if it is required to use private copy of this
13965   // variable.
13966   bool IsGlobal = !Var->hasLocalStorage();
13967   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13968     return true;
13969 
13970   // Walk up the stack to determine whether we can capture the variable,
13971   // performing the "simple" checks that don't depend on type. We stop when
13972   // we've either hit the declared scope of the variable or find an existing
13973   // capture of that variable.  We start from the innermost capturing-entity
13974   // (the DC) and ensure that all intervening capturing-entities
13975   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13976   // declcontext can either capture the variable or have already captured
13977   // the variable.
13978   CaptureType = Var->getType();
13979   DeclRefType = CaptureType.getNonReferenceType();
13980   bool Nested = false;
13981   bool Explicit = (Kind != TryCapture_Implicit);
13982   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13983   do {
13984     // Only block literals, captured statements, and lambda expressions can
13985     // capture; other scopes don't work.
13986     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13987                                                               ExprLoc,
13988                                                               BuildAndDiagnose,
13989                                                               *this);
13990     // We need to check for the parent *first* because, if we *have*
13991     // private-captured a global variable, we need to recursively capture it in
13992     // intermediate blocks, lambdas, etc.
13993     if (!ParentDC) {
13994       if (IsGlobal) {
13995         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13996         break;
13997       }
13998       return true;
13999     }
14000 
14001     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14002     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14003 
14004 
14005     // Check whether we've already captured it.
14006     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14007                                              DeclRefType)) {
14008       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14009       break;
14010     }
14011     // If we are instantiating a generic lambda call operator body,
14012     // we do not want to capture new variables.  What was captured
14013     // during either a lambdas transformation or initial parsing
14014     // should be used.
14015     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14016       if (BuildAndDiagnose) {
14017         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14018         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14019           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14020           Diag(Var->getLocation(), diag::note_previous_decl)
14021              << Var->getDeclName();
14022           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14023         } else
14024           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14025       }
14026       return true;
14027     }
14028     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14029     // certain types of variables (unnamed, variably modified types etc.)
14030     // so check for eligibility.
14031     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14032        return true;
14033 
14034     // Try to capture variable-length arrays types.
14035     if (Var->getType()->isVariablyModifiedType()) {
14036       // We're going to walk down into the type and look for VLA
14037       // expressions.
14038       QualType QTy = Var->getType();
14039       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14040         QTy = PVD->getOriginalType();
14041       captureVariablyModifiedType(Context, QTy, CSI);
14042     }
14043 
14044     if (getLangOpts().OpenMP) {
14045       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14046         // OpenMP private variables should not be captured in outer scope, so
14047         // just break here. Similarly, global variables that are captured in a
14048         // target region should not be captured outside the scope of the region.
14049         if (RSI->CapRegionKind == CR_OpenMP) {
14050           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14051           // When we detect target captures we are looking from inside the
14052           // target region, therefore we need to propagate the capture from the
14053           // enclosing region. Therefore, the capture is not initially nested.
14054           if (IsTargetCap)
14055             FunctionScopesIndex--;
14056 
14057           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14058             Nested = !IsTargetCap;
14059             DeclRefType = DeclRefType.getUnqualifiedType();
14060             CaptureType = Context.getLValueReferenceType(DeclRefType);
14061             break;
14062           }
14063         }
14064       }
14065     }
14066     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14067       // No capture-default, and this is not an explicit capture
14068       // so cannot capture this variable.
14069       if (BuildAndDiagnose) {
14070         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14071         Diag(Var->getLocation(), diag::note_previous_decl)
14072           << Var->getDeclName();
14073         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14074           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14075                diag::note_lambda_decl);
14076         // FIXME: If we error out because an outer lambda can not implicitly
14077         // capture a variable that an inner lambda explicitly captures, we
14078         // should have the inner lambda do the explicit capture - because
14079         // it makes for cleaner diagnostics later.  This would purely be done
14080         // so that the diagnostic does not misleadingly claim that a variable
14081         // can not be captured by a lambda implicitly even though it is captured
14082         // explicitly.  Suggestion:
14083         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14084         //    at the function head
14085         //  - cache the StartingDeclContext - this must be a lambda
14086         //  - captureInLambda in the innermost lambda the variable.
14087       }
14088       return true;
14089     }
14090 
14091     FunctionScopesIndex--;
14092     DC = ParentDC;
14093     Explicit = false;
14094   } while (!VarDC->Equals(DC));
14095 
14096   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14097   // computing the type of the capture at each step, checking type-specific
14098   // requirements, and adding captures if requested.
14099   // If the variable had already been captured previously, we start capturing
14100   // at the lambda nested within that one.
14101   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14102        ++I) {
14103     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14104 
14105     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14106       if (!captureInBlock(BSI, Var, ExprLoc,
14107                           BuildAndDiagnose, CaptureType,
14108                           DeclRefType, Nested, *this))
14109         return true;
14110       Nested = true;
14111     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14112       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14113                                    BuildAndDiagnose, CaptureType,
14114                                    DeclRefType, Nested, *this))
14115         return true;
14116       Nested = true;
14117     } else {
14118       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14119       if (!captureInLambda(LSI, Var, ExprLoc,
14120                            BuildAndDiagnose, CaptureType,
14121                            DeclRefType, Nested, Kind, EllipsisLoc,
14122                             /*IsTopScope*/I == N - 1, *this))
14123         return true;
14124       Nested = true;
14125     }
14126   }
14127   return false;
14128 }
14129 
14130 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14131                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14132   QualType CaptureType;
14133   QualType DeclRefType;
14134   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14135                             /*BuildAndDiagnose=*/true, CaptureType,
14136                             DeclRefType, nullptr);
14137 }
14138 
14139 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14140   QualType CaptureType;
14141   QualType DeclRefType;
14142   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14143                              /*BuildAndDiagnose=*/false, CaptureType,
14144                              DeclRefType, nullptr);
14145 }
14146 
14147 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14148   QualType CaptureType;
14149   QualType DeclRefType;
14150 
14151   // Determine whether we can capture this variable.
14152   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14153                          /*BuildAndDiagnose=*/false, CaptureType,
14154                          DeclRefType, nullptr))
14155     return QualType();
14156 
14157   return DeclRefType;
14158 }
14159 
14160 
14161 
14162 // If either the type of the variable or the initializer is dependent,
14163 // return false. Otherwise, determine whether the variable is a constant
14164 // expression. Use this if you need to know if a variable that might or
14165 // might not be dependent is truly a constant expression.
14166 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14167     ASTContext &Context) {
14168 
14169   if (Var->getType()->isDependentType())
14170     return false;
14171   const VarDecl *DefVD = nullptr;
14172   Var->getAnyInitializer(DefVD);
14173   if (!DefVD)
14174     return false;
14175   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14176   Expr *Init = cast<Expr>(Eval->Value);
14177   if (Init->isValueDependent())
14178     return false;
14179   return IsVariableAConstantExpression(Var, Context);
14180 }
14181 
14182 
14183 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14184   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14185   // an object that satisfies the requirements for appearing in a
14186   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14187   // is immediately applied."  This function handles the lvalue-to-rvalue
14188   // conversion part.
14189   MaybeODRUseExprs.erase(E->IgnoreParens());
14190 
14191   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14192   // to a variable that is a constant expression, and if so, identify it as
14193   // a reference to a variable that does not involve an odr-use of that
14194   // variable.
14195   if (LambdaScopeInfo *LSI = getCurLambda()) {
14196     Expr *SansParensExpr = E->IgnoreParens();
14197     VarDecl *Var = nullptr;
14198     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14199       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14200     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14201       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14202 
14203     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14204       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14205   }
14206 }
14207 
14208 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14209   Res = CorrectDelayedTyposInExpr(Res);
14210 
14211   if (!Res.isUsable())
14212     return Res;
14213 
14214   // If a constant-expression is a reference to a variable where we delay
14215   // deciding whether it is an odr-use, just assume we will apply the
14216   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14217   // (a non-type template argument), we have special handling anyway.
14218   UpdateMarkingForLValueToRValue(Res.get());
14219   return Res;
14220 }
14221 
14222 void Sema::CleanupVarDeclMarking() {
14223   for (Expr *E : MaybeODRUseExprs) {
14224     VarDecl *Var;
14225     SourceLocation Loc;
14226     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14227       Var = cast<VarDecl>(DRE->getDecl());
14228       Loc = DRE->getLocation();
14229     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14230       Var = cast<VarDecl>(ME->getMemberDecl());
14231       Loc = ME->getMemberLoc();
14232     } else {
14233       llvm_unreachable("Unexpected expression");
14234     }
14235 
14236     MarkVarDeclODRUsed(Var, Loc, *this,
14237                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14238   }
14239 
14240   MaybeODRUseExprs.clear();
14241 }
14242 
14243 
14244 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14245                                     VarDecl *Var, Expr *E) {
14246   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14247          "Invalid Expr argument to DoMarkVarDeclReferenced");
14248   Var->setReferenced();
14249 
14250   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14251 
14252   bool OdrUseContext = isOdrUseContext(SemaRef);
14253   bool NeedDefinition =
14254       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14255                         Var->isUsableInConstantExpressions(SemaRef.Context));
14256 
14257   VarTemplateSpecializationDecl *VarSpec =
14258       dyn_cast<VarTemplateSpecializationDecl>(Var);
14259   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14260          "Can't instantiate a partial template specialization.");
14261 
14262   // If this might be a member specialization of a static data member, check
14263   // the specialization is visible. We already did the checks for variable
14264   // template specializations when we created them.
14265   if (NeedDefinition && TSK != TSK_Undeclared &&
14266       !isa<VarTemplateSpecializationDecl>(Var))
14267     SemaRef.checkSpecializationVisibility(Loc, Var);
14268 
14269   // Perform implicit instantiation of static data members, static data member
14270   // templates of class templates, and variable template specializations. Delay
14271   // instantiations of variable templates, except for those that could be used
14272   // in a constant expression.
14273   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14274     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14275 
14276     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14277       if (Var->getPointOfInstantiation().isInvalid()) {
14278         // This is a modification of an existing AST node. Notify listeners.
14279         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14280           L->StaticDataMemberInstantiated(Var);
14281       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14282         // Don't bother trying to instantiate it again, unless we might need
14283         // its initializer before we get to the end of the TU.
14284         TryInstantiating = false;
14285     }
14286 
14287     if (Var->getPointOfInstantiation().isInvalid())
14288       Var->setTemplateSpecializationKind(TSK, Loc);
14289 
14290     if (TryInstantiating) {
14291       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14292       bool InstantiationDependent = false;
14293       bool IsNonDependent =
14294           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14295                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14296                   : true;
14297 
14298       // Do not instantiate specializations that are still type-dependent.
14299       if (IsNonDependent) {
14300         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14301           // Do not defer instantiations of variables which could be used in a
14302           // constant expression.
14303           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14304         } else {
14305           SemaRef.PendingInstantiations
14306               .push_back(std::make_pair(Var, PointOfInstantiation));
14307         }
14308       }
14309     }
14310   }
14311 
14312   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14313   // the requirements for appearing in a constant expression (5.19) and, if
14314   // it is an object, the lvalue-to-rvalue conversion (4.1)
14315   // is immediately applied."  We check the first part here, and
14316   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14317   // Note that we use the C++11 definition everywhere because nothing in
14318   // C++03 depends on whether we get the C++03 version correct. The second
14319   // part does not apply to references, since they are not objects.
14320   if (OdrUseContext && E &&
14321       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14322     // A reference initialized by a constant expression can never be
14323     // odr-used, so simply ignore it.
14324     if (!Var->getType()->isReferenceType())
14325       SemaRef.MaybeODRUseExprs.insert(E);
14326   } else if (OdrUseContext) {
14327     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14328                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14329   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14330     // If this is a dependent context, we don't need to mark variables as
14331     // odr-used, but we may still need to track them for lambda capture.
14332     // FIXME: Do we also need to do this inside dependent typeid expressions
14333     // (which are modeled as unevaluated at this point)?
14334     const bool RefersToEnclosingScope =
14335         (SemaRef.CurContext != Var->getDeclContext() &&
14336          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14337     if (RefersToEnclosingScope) {
14338       LambdaScopeInfo *const LSI =
14339           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14340       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14341         // If a variable could potentially be odr-used, defer marking it so
14342         // until we finish analyzing the full expression for any
14343         // lvalue-to-rvalue
14344         // or discarded value conversions that would obviate odr-use.
14345         // Add it to the list of potential captures that will be analyzed
14346         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14347         // unless the variable is a reference that was initialized by a constant
14348         // expression (this will never need to be captured or odr-used).
14349         assert(E && "Capture variable should be used in an expression.");
14350         if (!Var->getType()->isReferenceType() ||
14351             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14352           LSI->addPotentialCapture(E->IgnoreParens());
14353       }
14354     }
14355   }
14356 }
14357 
14358 /// \brief Mark a variable referenced, and check whether it is odr-used
14359 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14360 /// used directly for normal expressions referring to VarDecl.
14361 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14362   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14363 }
14364 
14365 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14366                                Decl *D, Expr *E, bool MightBeOdrUse) {
14367   if (SemaRef.isInOpenMPDeclareTargetContext())
14368     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14369 
14370   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14371     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14372     return;
14373   }
14374 
14375   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14376 
14377   // If this is a call to a method via a cast, also mark the method in the
14378   // derived class used in case codegen can devirtualize the call.
14379   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14380   if (!ME)
14381     return;
14382   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14383   if (!MD)
14384     return;
14385   // Only attempt to devirtualize if this is truly a virtual call.
14386   bool IsVirtualCall = MD->isVirtual() &&
14387                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14388   if (!IsVirtualCall)
14389     return;
14390   const Expr *Base = ME->getBase();
14391   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14392   if (!MostDerivedClassDecl)
14393     return;
14394   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14395   if (!DM || DM->isPure())
14396     return;
14397   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14398 }
14399 
14400 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14401 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14402   // TODO: update this with DR# once a defect report is filed.
14403   // C++11 defect. The address of a pure member should not be an ODR use, even
14404   // if it's a qualified reference.
14405   bool OdrUse = true;
14406   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14407     if (Method->isVirtual())
14408       OdrUse = false;
14409   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14410 }
14411 
14412 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14413 void Sema::MarkMemberReferenced(MemberExpr *E) {
14414   // C++11 [basic.def.odr]p2:
14415   //   A non-overloaded function whose name appears as a potentially-evaluated
14416   //   expression or a member of a set of candidate functions, if selected by
14417   //   overload resolution when referred to from a potentially-evaluated
14418   //   expression, is odr-used, unless it is a pure virtual function and its
14419   //   name is not explicitly qualified.
14420   bool MightBeOdrUse = true;
14421   if (E->performsVirtualDispatch(getLangOpts())) {
14422     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14423       if (Method->isPure())
14424         MightBeOdrUse = false;
14425   }
14426   SourceLocation Loc = E->getMemberLoc().isValid() ?
14427                             E->getMemberLoc() : E->getLocStart();
14428   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14429 }
14430 
14431 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14432 /// marks the declaration referenced, and performs odr-use checking for
14433 /// functions and variables. This method should not be used when building a
14434 /// normal expression which refers to a variable.
14435 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14436                                  bool MightBeOdrUse) {
14437   if (MightBeOdrUse) {
14438     if (auto *VD = dyn_cast<VarDecl>(D)) {
14439       MarkVariableReferenced(Loc, VD);
14440       return;
14441     }
14442   }
14443   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14444     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14445     return;
14446   }
14447   D->setReferenced();
14448 }
14449 
14450 namespace {
14451   // Mark all of the declarations used by a type as referenced.
14452   // FIXME: Not fully implemented yet! We need to have a better understanding
14453   // of when we're entering a context we should not recurse into.
14454   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14455   // TreeTransforms rebuilding the type in a new context. Rather than
14456   // duplicating the TreeTransform logic, we should consider reusing it here.
14457   // Currently that causes problems when rebuilding LambdaExprs.
14458   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14459     Sema &S;
14460     SourceLocation Loc;
14461 
14462   public:
14463     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14464 
14465     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14466 
14467     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14468   };
14469 }
14470 
14471 bool MarkReferencedDecls::TraverseTemplateArgument(
14472     const TemplateArgument &Arg) {
14473   {
14474     // A non-type template argument is a constant-evaluated context.
14475     EnterExpressionEvaluationContext Evaluated(
14476         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14477     if (Arg.getKind() == TemplateArgument::Declaration) {
14478       if (Decl *D = Arg.getAsDecl())
14479         S.MarkAnyDeclReferenced(Loc, D, true);
14480     } else if (Arg.getKind() == TemplateArgument::Expression) {
14481       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14482     }
14483   }
14484 
14485   return Inherited::TraverseTemplateArgument(Arg);
14486 }
14487 
14488 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14489   MarkReferencedDecls Marker(*this, Loc);
14490   Marker.TraverseType(T);
14491 }
14492 
14493 namespace {
14494   /// \brief Helper class that marks all of the declarations referenced by
14495   /// potentially-evaluated subexpressions as "referenced".
14496   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14497     Sema &S;
14498     bool SkipLocalVariables;
14499 
14500   public:
14501     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14502 
14503     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14504       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14505 
14506     void VisitDeclRefExpr(DeclRefExpr *E) {
14507       // If we were asked not to visit local variables, don't.
14508       if (SkipLocalVariables) {
14509         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14510           if (VD->hasLocalStorage())
14511             return;
14512       }
14513 
14514       S.MarkDeclRefReferenced(E);
14515     }
14516 
14517     void VisitMemberExpr(MemberExpr *E) {
14518       S.MarkMemberReferenced(E);
14519       Inherited::VisitMemberExpr(E);
14520     }
14521 
14522     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14523       S.MarkFunctionReferenced(E->getLocStart(),
14524             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14525       Visit(E->getSubExpr());
14526     }
14527 
14528     void VisitCXXNewExpr(CXXNewExpr *E) {
14529       if (E->getOperatorNew())
14530         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14531       if (E->getOperatorDelete())
14532         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14533       Inherited::VisitCXXNewExpr(E);
14534     }
14535 
14536     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14537       if (E->getOperatorDelete())
14538         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14539       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14540       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14541         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14542         S.MarkFunctionReferenced(E->getLocStart(),
14543                                     S.LookupDestructor(Record));
14544       }
14545 
14546       Inherited::VisitCXXDeleteExpr(E);
14547     }
14548 
14549     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14550       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14551       Inherited::VisitCXXConstructExpr(E);
14552     }
14553 
14554     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14555       Visit(E->getExpr());
14556     }
14557 
14558     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14559       Inherited::VisitImplicitCastExpr(E);
14560 
14561       if (E->getCastKind() == CK_LValueToRValue)
14562         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14563     }
14564   };
14565 }
14566 
14567 /// \brief Mark any declarations that appear within this expression or any
14568 /// potentially-evaluated subexpressions as "referenced".
14569 ///
14570 /// \param SkipLocalVariables If true, don't mark local variables as
14571 /// 'referenced'.
14572 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14573                                             bool SkipLocalVariables) {
14574   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14575 }
14576 
14577 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14578 /// of the program being compiled.
14579 ///
14580 /// This routine emits the given diagnostic when the code currently being
14581 /// type-checked is "potentially evaluated", meaning that there is a
14582 /// possibility that the code will actually be executable. Code in sizeof()
14583 /// expressions, code used only during overload resolution, etc., are not
14584 /// potentially evaluated. This routine will suppress such diagnostics or,
14585 /// in the absolutely nutty case of potentially potentially evaluated
14586 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14587 /// later.
14588 ///
14589 /// This routine should be used for all diagnostics that describe the run-time
14590 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14591 /// Failure to do so will likely result in spurious diagnostics or failures
14592 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14593 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14594                                const PartialDiagnostic &PD) {
14595   switch (ExprEvalContexts.back().Context) {
14596   case ExpressionEvaluationContext::Unevaluated:
14597   case ExpressionEvaluationContext::UnevaluatedList:
14598   case ExpressionEvaluationContext::UnevaluatedAbstract:
14599   case ExpressionEvaluationContext::DiscardedStatement:
14600     // The argument will never be evaluated, so don't complain.
14601     break;
14602 
14603   case ExpressionEvaluationContext::ConstantEvaluated:
14604     // Relevant diagnostics should be produced by constant evaluation.
14605     break;
14606 
14607   case ExpressionEvaluationContext::PotentiallyEvaluated:
14608   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14609     if (Statement && getCurFunctionOrMethodDecl()) {
14610       FunctionScopes.back()->PossiblyUnreachableDiags.
14611         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14612     }
14613     else
14614       Diag(Loc, PD);
14615 
14616     return true;
14617   }
14618 
14619   return false;
14620 }
14621 
14622 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14623                                CallExpr *CE, FunctionDecl *FD) {
14624   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14625     return false;
14626 
14627   // If we're inside a decltype's expression, don't check for a valid return
14628   // type or construct temporaries until we know whether this is the last call.
14629   if (ExprEvalContexts.back().IsDecltype) {
14630     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14631     return false;
14632   }
14633 
14634   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14635     FunctionDecl *FD;
14636     CallExpr *CE;
14637 
14638   public:
14639     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14640       : FD(FD), CE(CE) { }
14641 
14642     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14643       if (!FD) {
14644         S.Diag(Loc, diag::err_call_incomplete_return)
14645           << T << CE->getSourceRange();
14646         return;
14647       }
14648 
14649       S.Diag(Loc, diag::err_call_function_incomplete_return)
14650         << CE->getSourceRange() << FD->getDeclName() << T;
14651       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14652           << FD->getDeclName();
14653     }
14654   } Diagnoser(FD, CE);
14655 
14656   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14657     return true;
14658 
14659   return false;
14660 }
14661 
14662 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14663 // will prevent this condition from triggering, which is what we want.
14664 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14665   SourceLocation Loc;
14666 
14667   unsigned diagnostic = diag::warn_condition_is_assignment;
14668   bool IsOrAssign = false;
14669 
14670   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14671     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14672       return;
14673 
14674     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14675 
14676     // Greylist some idioms by putting them into a warning subcategory.
14677     if (ObjCMessageExpr *ME
14678           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14679       Selector Sel = ME->getSelector();
14680 
14681       // self = [<foo> init...]
14682       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14683         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14684 
14685       // <foo> = [<bar> nextObject]
14686       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14687         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14688     }
14689 
14690     Loc = Op->getOperatorLoc();
14691   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14692     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14693       return;
14694 
14695     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14696     Loc = Op->getOperatorLoc();
14697   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14698     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14699   else {
14700     // Not an assignment.
14701     return;
14702   }
14703 
14704   Diag(Loc, diagnostic) << E->getSourceRange();
14705 
14706   SourceLocation Open = E->getLocStart();
14707   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14708   Diag(Loc, diag::note_condition_assign_silence)
14709         << FixItHint::CreateInsertion(Open, "(")
14710         << FixItHint::CreateInsertion(Close, ")");
14711 
14712   if (IsOrAssign)
14713     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14714       << FixItHint::CreateReplacement(Loc, "!=");
14715   else
14716     Diag(Loc, diag::note_condition_assign_to_comparison)
14717       << FixItHint::CreateReplacement(Loc, "==");
14718 }
14719 
14720 /// \brief Redundant parentheses over an equality comparison can indicate
14721 /// that the user intended an assignment used as condition.
14722 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14723   // Don't warn if the parens came from a macro.
14724   SourceLocation parenLoc = ParenE->getLocStart();
14725   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14726     return;
14727   // Don't warn for dependent expressions.
14728   if (ParenE->isTypeDependent())
14729     return;
14730 
14731   Expr *E = ParenE->IgnoreParens();
14732 
14733   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14734     if (opE->getOpcode() == BO_EQ &&
14735         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14736                                                            == Expr::MLV_Valid) {
14737       SourceLocation Loc = opE->getOperatorLoc();
14738 
14739       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14740       SourceRange ParenERange = ParenE->getSourceRange();
14741       Diag(Loc, diag::note_equality_comparison_silence)
14742         << FixItHint::CreateRemoval(ParenERange.getBegin())
14743         << FixItHint::CreateRemoval(ParenERange.getEnd());
14744       Diag(Loc, diag::note_equality_comparison_to_assign)
14745         << FixItHint::CreateReplacement(Loc, "=");
14746     }
14747 }
14748 
14749 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14750                                        bool IsConstexpr) {
14751   DiagnoseAssignmentAsCondition(E);
14752   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14753     DiagnoseEqualityWithExtraParens(parenE);
14754 
14755   ExprResult result = CheckPlaceholderExpr(E);
14756   if (result.isInvalid()) return ExprError();
14757   E = result.get();
14758 
14759   if (!E->isTypeDependent()) {
14760     if (getLangOpts().CPlusPlus)
14761       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14762 
14763     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14764     if (ERes.isInvalid())
14765       return ExprError();
14766     E = ERes.get();
14767 
14768     QualType T = E->getType();
14769     if (!T->isScalarType()) { // C99 6.8.4.1p1
14770       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14771         << T << E->getSourceRange();
14772       return ExprError();
14773     }
14774     CheckBoolLikeConversion(E, Loc);
14775   }
14776 
14777   return E;
14778 }
14779 
14780 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14781                                            Expr *SubExpr, ConditionKind CK) {
14782   // Empty conditions are valid in for-statements.
14783   if (!SubExpr)
14784     return ConditionResult();
14785 
14786   ExprResult Cond;
14787   switch (CK) {
14788   case ConditionKind::Boolean:
14789     Cond = CheckBooleanCondition(Loc, SubExpr);
14790     break;
14791 
14792   case ConditionKind::ConstexprIf:
14793     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14794     break;
14795 
14796   case ConditionKind::Switch:
14797     Cond = CheckSwitchCondition(Loc, SubExpr);
14798     break;
14799   }
14800   if (Cond.isInvalid())
14801     return ConditionError();
14802 
14803   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14804   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14805   if (!FullExpr.get())
14806     return ConditionError();
14807 
14808   return ConditionResult(*this, nullptr, FullExpr,
14809                          CK == ConditionKind::ConstexprIf);
14810 }
14811 
14812 namespace {
14813   /// A visitor for rebuilding a call to an __unknown_any expression
14814   /// to have an appropriate type.
14815   struct RebuildUnknownAnyFunction
14816     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14817 
14818     Sema &S;
14819 
14820     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14821 
14822     ExprResult VisitStmt(Stmt *S) {
14823       llvm_unreachable("unexpected statement!");
14824     }
14825 
14826     ExprResult VisitExpr(Expr *E) {
14827       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14828         << E->getSourceRange();
14829       return ExprError();
14830     }
14831 
14832     /// Rebuild an expression which simply semantically wraps another
14833     /// expression which it shares the type and value kind of.
14834     template <class T> ExprResult rebuildSugarExpr(T *E) {
14835       ExprResult SubResult = Visit(E->getSubExpr());
14836       if (SubResult.isInvalid()) return ExprError();
14837 
14838       Expr *SubExpr = SubResult.get();
14839       E->setSubExpr(SubExpr);
14840       E->setType(SubExpr->getType());
14841       E->setValueKind(SubExpr->getValueKind());
14842       assert(E->getObjectKind() == OK_Ordinary);
14843       return E;
14844     }
14845 
14846     ExprResult VisitParenExpr(ParenExpr *E) {
14847       return rebuildSugarExpr(E);
14848     }
14849 
14850     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14851       return rebuildSugarExpr(E);
14852     }
14853 
14854     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14855       ExprResult SubResult = Visit(E->getSubExpr());
14856       if (SubResult.isInvalid()) return ExprError();
14857 
14858       Expr *SubExpr = SubResult.get();
14859       E->setSubExpr(SubExpr);
14860       E->setType(S.Context.getPointerType(SubExpr->getType()));
14861       assert(E->getValueKind() == VK_RValue);
14862       assert(E->getObjectKind() == OK_Ordinary);
14863       return E;
14864     }
14865 
14866     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14867       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14868 
14869       E->setType(VD->getType());
14870 
14871       assert(E->getValueKind() == VK_RValue);
14872       if (S.getLangOpts().CPlusPlus &&
14873           !(isa<CXXMethodDecl>(VD) &&
14874             cast<CXXMethodDecl>(VD)->isInstance()))
14875         E->setValueKind(VK_LValue);
14876 
14877       return E;
14878     }
14879 
14880     ExprResult VisitMemberExpr(MemberExpr *E) {
14881       return resolveDecl(E, E->getMemberDecl());
14882     }
14883 
14884     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14885       return resolveDecl(E, E->getDecl());
14886     }
14887   };
14888 }
14889 
14890 /// Given a function expression of unknown-any type, try to rebuild it
14891 /// to have a function type.
14892 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14893   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14894   if (Result.isInvalid()) return ExprError();
14895   return S.DefaultFunctionArrayConversion(Result.get());
14896 }
14897 
14898 namespace {
14899   /// A visitor for rebuilding an expression of type __unknown_anytype
14900   /// into one which resolves the type directly on the referring
14901   /// expression.  Strict preservation of the original source
14902   /// structure is not a goal.
14903   struct RebuildUnknownAnyExpr
14904     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14905 
14906     Sema &S;
14907 
14908     /// The current destination type.
14909     QualType DestType;
14910 
14911     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14912       : S(S), DestType(CastType) {}
14913 
14914     ExprResult VisitStmt(Stmt *S) {
14915       llvm_unreachable("unexpected statement!");
14916     }
14917 
14918     ExprResult VisitExpr(Expr *E) {
14919       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14920         << E->getSourceRange();
14921       return ExprError();
14922     }
14923 
14924     ExprResult VisitCallExpr(CallExpr *E);
14925     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14926 
14927     /// Rebuild an expression which simply semantically wraps another
14928     /// expression which it shares the type and value kind of.
14929     template <class T> ExprResult rebuildSugarExpr(T *E) {
14930       ExprResult SubResult = Visit(E->getSubExpr());
14931       if (SubResult.isInvalid()) return ExprError();
14932       Expr *SubExpr = SubResult.get();
14933       E->setSubExpr(SubExpr);
14934       E->setType(SubExpr->getType());
14935       E->setValueKind(SubExpr->getValueKind());
14936       assert(E->getObjectKind() == OK_Ordinary);
14937       return E;
14938     }
14939 
14940     ExprResult VisitParenExpr(ParenExpr *E) {
14941       return rebuildSugarExpr(E);
14942     }
14943 
14944     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14945       return rebuildSugarExpr(E);
14946     }
14947 
14948     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14949       const PointerType *Ptr = DestType->getAs<PointerType>();
14950       if (!Ptr) {
14951         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14952           << E->getSourceRange();
14953         return ExprError();
14954       }
14955 
14956       if (isa<CallExpr>(E->getSubExpr())) {
14957         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14958           << E->getSourceRange();
14959         return ExprError();
14960       }
14961 
14962       assert(E->getValueKind() == VK_RValue);
14963       assert(E->getObjectKind() == OK_Ordinary);
14964       E->setType(DestType);
14965 
14966       // Build the sub-expression as if it were an object of the pointee type.
14967       DestType = Ptr->getPointeeType();
14968       ExprResult SubResult = Visit(E->getSubExpr());
14969       if (SubResult.isInvalid()) return ExprError();
14970       E->setSubExpr(SubResult.get());
14971       return E;
14972     }
14973 
14974     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14975 
14976     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14977 
14978     ExprResult VisitMemberExpr(MemberExpr *E) {
14979       return resolveDecl(E, E->getMemberDecl());
14980     }
14981 
14982     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14983       return resolveDecl(E, E->getDecl());
14984     }
14985   };
14986 }
14987 
14988 /// Rebuilds a call expression which yielded __unknown_anytype.
14989 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14990   Expr *CalleeExpr = E->getCallee();
14991 
14992   enum FnKind {
14993     FK_MemberFunction,
14994     FK_FunctionPointer,
14995     FK_BlockPointer
14996   };
14997 
14998   FnKind Kind;
14999   QualType CalleeType = CalleeExpr->getType();
15000   if (CalleeType == S.Context.BoundMemberTy) {
15001     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15002     Kind = FK_MemberFunction;
15003     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15004   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15005     CalleeType = Ptr->getPointeeType();
15006     Kind = FK_FunctionPointer;
15007   } else {
15008     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15009     Kind = FK_BlockPointer;
15010   }
15011   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15012 
15013   // Verify that this is a legal result type of a function.
15014   if (DestType->isArrayType() || DestType->isFunctionType()) {
15015     unsigned diagID = diag::err_func_returning_array_function;
15016     if (Kind == FK_BlockPointer)
15017       diagID = diag::err_block_returning_array_function;
15018 
15019     S.Diag(E->getExprLoc(), diagID)
15020       << DestType->isFunctionType() << DestType;
15021     return ExprError();
15022   }
15023 
15024   // Otherwise, go ahead and set DestType as the call's result.
15025   E->setType(DestType.getNonLValueExprType(S.Context));
15026   E->setValueKind(Expr::getValueKindForType(DestType));
15027   assert(E->getObjectKind() == OK_Ordinary);
15028 
15029   // Rebuild the function type, replacing the result type with DestType.
15030   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15031   if (Proto) {
15032     // __unknown_anytype(...) is a special case used by the debugger when
15033     // it has no idea what a function's signature is.
15034     //
15035     // We want to build this call essentially under the K&R
15036     // unprototyped rules, but making a FunctionNoProtoType in C++
15037     // would foul up all sorts of assumptions.  However, we cannot
15038     // simply pass all arguments as variadic arguments, nor can we
15039     // portably just call the function under a non-variadic type; see
15040     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15041     // However, it turns out that in practice it is generally safe to
15042     // call a function declared as "A foo(B,C,D);" under the prototype
15043     // "A foo(B,C,D,...);".  The only known exception is with the
15044     // Windows ABI, where any variadic function is implicitly cdecl
15045     // regardless of its normal CC.  Therefore we change the parameter
15046     // types to match the types of the arguments.
15047     //
15048     // This is a hack, but it is far superior to moving the
15049     // corresponding target-specific code from IR-gen to Sema/AST.
15050 
15051     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15052     SmallVector<QualType, 8> ArgTypes;
15053     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15054       ArgTypes.reserve(E->getNumArgs());
15055       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15056         Expr *Arg = E->getArg(i);
15057         QualType ArgType = Arg->getType();
15058         if (E->isLValue()) {
15059           ArgType = S.Context.getLValueReferenceType(ArgType);
15060         } else if (E->isXValue()) {
15061           ArgType = S.Context.getRValueReferenceType(ArgType);
15062         }
15063         ArgTypes.push_back(ArgType);
15064       }
15065       ParamTypes = ArgTypes;
15066     }
15067     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15068                                          Proto->getExtProtoInfo());
15069   } else {
15070     DestType = S.Context.getFunctionNoProtoType(DestType,
15071                                                 FnType->getExtInfo());
15072   }
15073 
15074   // Rebuild the appropriate pointer-to-function type.
15075   switch (Kind) {
15076   case FK_MemberFunction:
15077     // Nothing to do.
15078     break;
15079 
15080   case FK_FunctionPointer:
15081     DestType = S.Context.getPointerType(DestType);
15082     break;
15083 
15084   case FK_BlockPointer:
15085     DestType = S.Context.getBlockPointerType(DestType);
15086     break;
15087   }
15088 
15089   // Finally, we can recurse.
15090   ExprResult CalleeResult = Visit(CalleeExpr);
15091   if (!CalleeResult.isUsable()) return ExprError();
15092   E->setCallee(CalleeResult.get());
15093 
15094   // Bind a temporary if necessary.
15095   return S.MaybeBindToTemporary(E);
15096 }
15097 
15098 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15099   // Verify that this is a legal result type of a call.
15100   if (DestType->isArrayType() || DestType->isFunctionType()) {
15101     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15102       << DestType->isFunctionType() << DestType;
15103     return ExprError();
15104   }
15105 
15106   // Rewrite the method result type if available.
15107   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15108     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15109     Method->setReturnType(DestType);
15110   }
15111 
15112   // Change the type of the message.
15113   E->setType(DestType.getNonReferenceType());
15114   E->setValueKind(Expr::getValueKindForType(DestType));
15115 
15116   return S.MaybeBindToTemporary(E);
15117 }
15118 
15119 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15120   // The only case we should ever see here is a function-to-pointer decay.
15121   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15122     assert(E->getValueKind() == VK_RValue);
15123     assert(E->getObjectKind() == OK_Ordinary);
15124 
15125     E->setType(DestType);
15126 
15127     // Rebuild the sub-expression as the pointee (function) type.
15128     DestType = DestType->castAs<PointerType>()->getPointeeType();
15129 
15130     ExprResult Result = Visit(E->getSubExpr());
15131     if (!Result.isUsable()) return ExprError();
15132 
15133     E->setSubExpr(Result.get());
15134     return E;
15135   } else if (E->getCastKind() == CK_LValueToRValue) {
15136     assert(E->getValueKind() == VK_RValue);
15137     assert(E->getObjectKind() == OK_Ordinary);
15138 
15139     assert(isa<BlockPointerType>(E->getType()));
15140 
15141     E->setType(DestType);
15142 
15143     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15144     DestType = S.Context.getLValueReferenceType(DestType);
15145 
15146     ExprResult Result = Visit(E->getSubExpr());
15147     if (!Result.isUsable()) return ExprError();
15148 
15149     E->setSubExpr(Result.get());
15150     return E;
15151   } else {
15152     llvm_unreachable("Unhandled cast type!");
15153   }
15154 }
15155 
15156 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15157   ExprValueKind ValueKind = VK_LValue;
15158   QualType Type = DestType;
15159 
15160   // We know how to make this work for certain kinds of decls:
15161 
15162   //  - functions
15163   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15164     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15165       DestType = Ptr->getPointeeType();
15166       ExprResult Result = resolveDecl(E, VD);
15167       if (Result.isInvalid()) return ExprError();
15168       return S.ImpCastExprToType(Result.get(), Type,
15169                                  CK_FunctionToPointerDecay, VK_RValue);
15170     }
15171 
15172     if (!Type->isFunctionType()) {
15173       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15174         << VD << E->getSourceRange();
15175       return ExprError();
15176     }
15177     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15178       // We must match the FunctionDecl's type to the hack introduced in
15179       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15180       // type. See the lengthy commentary in that routine.
15181       QualType FDT = FD->getType();
15182       const FunctionType *FnType = FDT->castAs<FunctionType>();
15183       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15184       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15185       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15186         SourceLocation Loc = FD->getLocation();
15187         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15188                                       FD->getDeclContext(),
15189                                       Loc, Loc, FD->getNameInfo().getName(),
15190                                       DestType, FD->getTypeSourceInfo(),
15191                                       SC_None, false/*isInlineSpecified*/,
15192                                       FD->hasPrototype(),
15193                                       false/*isConstexprSpecified*/);
15194 
15195         if (FD->getQualifier())
15196           NewFD->setQualifierInfo(FD->getQualifierLoc());
15197 
15198         SmallVector<ParmVarDecl*, 16> Params;
15199         for (const auto &AI : FT->param_types()) {
15200           ParmVarDecl *Param =
15201             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15202           Param->setScopeInfo(0, Params.size());
15203           Params.push_back(Param);
15204         }
15205         NewFD->setParams(Params);
15206         DRE->setDecl(NewFD);
15207         VD = DRE->getDecl();
15208       }
15209     }
15210 
15211     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15212       if (MD->isInstance()) {
15213         ValueKind = VK_RValue;
15214         Type = S.Context.BoundMemberTy;
15215       }
15216 
15217     // Function references aren't l-values in C.
15218     if (!S.getLangOpts().CPlusPlus)
15219       ValueKind = VK_RValue;
15220 
15221   //  - variables
15222   } else if (isa<VarDecl>(VD)) {
15223     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15224       Type = RefTy->getPointeeType();
15225     } else if (Type->isFunctionType()) {
15226       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15227         << VD << E->getSourceRange();
15228       return ExprError();
15229     }
15230 
15231   //  - nothing else
15232   } else {
15233     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15234       << VD << E->getSourceRange();
15235     return ExprError();
15236   }
15237 
15238   // Modifying the declaration like this is friendly to IR-gen but
15239   // also really dangerous.
15240   VD->setType(DestType);
15241   E->setType(Type);
15242   E->setValueKind(ValueKind);
15243   return E;
15244 }
15245 
15246 /// Check a cast of an unknown-any type.  We intentionally only
15247 /// trigger this for C-style casts.
15248 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15249                                      Expr *CastExpr, CastKind &CastKind,
15250                                      ExprValueKind &VK, CXXCastPath &Path) {
15251   // The type we're casting to must be either void or complete.
15252   if (!CastType->isVoidType() &&
15253       RequireCompleteType(TypeRange.getBegin(), CastType,
15254                           diag::err_typecheck_cast_to_incomplete))
15255     return ExprError();
15256 
15257   // Rewrite the casted expression from scratch.
15258   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15259   if (!result.isUsable()) return ExprError();
15260 
15261   CastExpr = result.get();
15262   VK = CastExpr->getValueKind();
15263   CastKind = CK_NoOp;
15264 
15265   return CastExpr;
15266 }
15267 
15268 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15269   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15270 }
15271 
15272 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15273                                     Expr *arg, QualType &paramType) {
15274   // If the syntactic form of the argument is not an explicit cast of
15275   // any sort, just do default argument promotion.
15276   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15277   if (!castArg) {
15278     ExprResult result = DefaultArgumentPromotion(arg);
15279     if (result.isInvalid()) return ExprError();
15280     paramType = result.get()->getType();
15281     return result;
15282   }
15283 
15284   // Otherwise, use the type that was written in the explicit cast.
15285   assert(!arg->hasPlaceholderType());
15286   paramType = castArg->getTypeAsWritten();
15287 
15288   // Copy-initialize a parameter of that type.
15289   InitializedEntity entity =
15290     InitializedEntity::InitializeParameter(Context, paramType,
15291                                            /*consumed*/ false);
15292   return PerformCopyInitialization(entity, callLoc, arg);
15293 }
15294 
15295 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15296   Expr *orig = E;
15297   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15298   while (true) {
15299     E = E->IgnoreParenImpCasts();
15300     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15301       E = call->getCallee();
15302       diagID = diag::err_uncasted_call_of_unknown_any;
15303     } else {
15304       break;
15305     }
15306   }
15307 
15308   SourceLocation loc;
15309   NamedDecl *d;
15310   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15311     loc = ref->getLocation();
15312     d = ref->getDecl();
15313   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15314     loc = mem->getMemberLoc();
15315     d = mem->getMemberDecl();
15316   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15317     diagID = diag::err_uncasted_call_of_unknown_any;
15318     loc = msg->getSelectorStartLoc();
15319     d = msg->getMethodDecl();
15320     if (!d) {
15321       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15322         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15323         << orig->getSourceRange();
15324       return ExprError();
15325     }
15326   } else {
15327     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15328       << E->getSourceRange();
15329     return ExprError();
15330   }
15331 
15332   S.Diag(loc, diagID) << d << orig->getSourceRange();
15333 
15334   // Never recoverable.
15335   return ExprError();
15336 }
15337 
15338 /// Check for operands with placeholder types and complain if found.
15339 /// Returns true if there was an error and no recovery was possible.
15340 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15341   if (!getLangOpts().CPlusPlus) {
15342     // C cannot handle TypoExpr nodes on either side of a binop because it
15343     // doesn't handle dependent types properly, so make sure any TypoExprs have
15344     // been dealt with before checking the operands.
15345     ExprResult Result = CorrectDelayedTyposInExpr(E);
15346     if (!Result.isUsable()) return ExprError();
15347     E = Result.get();
15348   }
15349 
15350   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15351   if (!placeholderType) return E;
15352 
15353   switch (placeholderType->getKind()) {
15354 
15355   // Overloaded expressions.
15356   case BuiltinType::Overload: {
15357     // Try to resolve a single function template specialization.
15358     // This is obligatory.
15359     ExprResult Result = E;
15360     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15361       return Result;
15362 
15363     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15364     // leaves Result unchanged on failure.
15365     Result = E;
15366     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15367       return Result;
15368 
15369     // If that failed, try to recover with a call.
15370     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15371                          /*complain*/ true);
15372     return Result;
15373   }
15374 
15375   // Bound member functions.
15376   case BuiltinType::BoundMember: {
15377     ExprResult result = E;
15378     const Expr *BME = E->IgnoreParens();
15379     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15380     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15381     if (isa<CXXPseudoDestructorExpr>(BME)) {
15382       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15383     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15384       if (ME->getMemberNameInfo().getName().getNameKind() ==
15385           DeclarationName::CXXDestructorName)
15386         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15387     }
15388     tryToRecoverWithCall(result, PD,
15389                          /*complain*/ true);
15390     return result;
15391   }
15392 
15393   // ARC unbridged casts.
15394   case BuiltinType::ARCUnbridgedCast: {
15395     Expr *realCast = stripARCUnbridgedCast(E);
15396     diagnoseARCUnbridgedCast(realCast);
15397     return realCast;
15398   }
15399 
15400   // Expressions of unknown type.
15401   case BuiltinType::UnknownAny:
15402     return diagnoseUnknownAnyExpr(*this, E);
15403 
15404   // Pseudo-objects.
15405   case BuiltinType::PseudoObject:
15406     return checkPseudoObjectRValue(E);
15407 
15408   case BuiltinType::BuiltinFn: {
15409     // Accept __noop without parens by implicitly converting it to a call expr.
15410     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15411     if (DRE) {
15412       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15413       if (FD->getBuiltinID() == Builtin::BI__noop) {
15414         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15415                               CK_BuiltinFnToFnPtr).get();
15416         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15417                                       VK_RValue, SourceLocation());
15418       }
15419     }
15420 
15421     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15422     return ExprError();
15423   }
15424 
15425   // Expressions of unknown type.
15426   case BuiltinType::OMPArraySection:
15427     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15428     return ExprError();
15429 
15430   // Everything else should be impossible.
15431 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15432   case BuiltinType::Id:
15433 #include "clang/Basic/OpenCLImageTypes.def"
15434 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15435 #define PLACEHOLDER_TYPE(Id, SingletonId)
15436 #include "clang/AST/BuiltinTypes.def"
15437     break;
15438   }
15439 
15440   llvm_unreachable("invalid placeholder type!");
15441 }
15442 
15443 bool Sema::CheckCaseExpression(Expr *E) {
15444   if (E->isTypeDependent())
15445     return true;
15446   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15447     return E->getType()->isIntegralOrEnumerationType();
15448   return false;
15449 }
15450 
15451 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15452 ExprResult
15453 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15454   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15455          "Unknown Objective-C Boolean value!");
15456   QualType BoolT = Context.ObjCBuiltinBoolTy;
15457   if (!Context.getBOOLDecl()) {
15458     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15459                         Sema::LookupOrdinaryName);
15460     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15461       NamedDecl *ND = Result.getFoundDecl();
15462       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15463         Context.setBOOLDecl(TD);
15464     }
15465   }
15466   if (Context.getBOOLDecl())
15467     BoolT = Context.getBOOLType();
15468   return new (Context)
15469       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15470 }
15471 
15472 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15473     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15474     SourceLocation RParen) {
15475 
15476   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15477 
15478   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15479                            [&](const AvailabilitySpec &Spec) {
15480                              return Spec.getPlatform() == Platform;
15481                            });
15482 
15483   VersionTuple Version;
15484   if (Spec != AvailSpecs.end())
15485     Version = Spec->getVersion();
15486 
15487   return new (Context)
15488       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15489 }
15490