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       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
337 
338       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339         << D->getDeclName() << (unsigned)AT->getKeyword();
340     }
341     return true;
342   }
343 
344   // See if this is a deleted function.
345   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346     if (FD->isDeleted()) {
347       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
348       if (Ctor && Ctor->isInheritingConstructor())
349         Diag(Loc, diag::err_deleted_inherited_ctor_use)
350             << Ctor->getParent()
351             << Ctor->getInheritedConstructor().getConstructor()->getParent();
352       else
353         Diag(Loc, diag::err_deleted_function_use);
354       NoteDeletedFunction(FD);
355       return true;
356     }
357 
358     // If the function has a deduced return type, and we can't deduce it,
359     // then we can't use it either.
360     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
361         DeduceReturnType(FD, Loc))
362       return true;
363 
364     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
365       return true;
366   }
367 
368   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
369   // Only the variables omp_in and omp_out are allowed in the combiner.
370   // Only the variables omp_priv and omp_orig are allowed in the
371   // initializer-clause.
372   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
373   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
374       isa<VarDecl>(D)) {
375     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
376         << getCurFunction()->HasOMPDeclareReductionCombiner;
377     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
378     return true;
379   }
380   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
381                              ObjCPropertyAccess);
382 
383   DiagnoseUnusedOfDecl(*this, D, Loc);
384 
385   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
386 
387   return false;
388 }
389 
390 /// \brief Retrieve the message suffix that should be added to a
391 /// diagnostic complaining about the given function being deleted or
392 /// unavailable.
393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
394   std::string Message;
395   if (FD->getAvailability(&Message))
396     return ": " + Message;
397 
398   return std::string();
399 }
400 
401 /// DiagnoseSentinelCalls - This routine checks whether a call or
402 /// message-send is to a declaration with the sentinel attribute, and
403 /// if so, it checks that the requirements of the sentinel are
404 /// satisfied.
405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
406                                  ArrayRef<Expr *> Args) {
407   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
408   if (!attr)
409     return;
410 
411   // The number of formal parameters of the declaration.
412   unsigned numFormalParams;
413 
414   // The kind of declaration.  This is also an index into a %select in
415   // the diagnostic.
416   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417 
418   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
419     numFormalParams = MD->param_size();
420     calleeType = CT_Method;
421   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422     numFormalParams = FD->param_size();
423     calleeType = CT_Function;
424   } else if (isa<VarDecl>(D)) {
425     QualType type = cast<ValueDecl>(D)->getType();
426     const FunctionType *fn = nullptr;
427     if (const PointerType *ptr = type->getAs<PointerType>()) {
428       fn = ptr->getPointeeType()->getAs<FunctionType>();
429       if (!fn) return;
430       calleeType = CT_Function;
431     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432       fn = ptr->getPointeeType()->castAs<FunctionType>();
433       calleeType = CT_Block;
434     } else {
435       return;
436     }
437 
438     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
439       numFormalParams = proto->getNumParams();
440     } else {
441       numFormalParams = 0;
442     }
443   } else {
444     return;
445   }
446 
447   // "nullPos" is the number of formal parameters at the end which
448   // effectively count as part of the variadic arguments.  This is
449   // useful if you would prefer to not have *any* formal parameters,
450   // but the language forces you to have at least one.
451   unsigned nullPos = attr->getNullPos();
452   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
453   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454 
455   // The number of arguments which should follow the sentinel.
456   unsigned numArgsAfterSentinel = attr->getSentinel();
457 
458   // If there aren't enough arguments for all the formal parameters,
459   // the sentinel, and the args after the sentinel, complain.
460   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
461     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
463     return;
464   }
465 
466   // Otherwise, find the sentinel expression.
467   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
468   if (!sentinelExpr) return;
469   if (sentinelExpr->isValueDependent()) return;
470   if (Context.isSentinelNullExpr(sentinelExpr)) return;
471 
472   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
473   // or 'NULL' if those are actually defined in the context.  Only use
474   // 'nil' for ObjC methods, where it's much more likely that the
475   // variadic arguments form a list of object pointers.
476   SourceLocation MissingNilLoc
477     = getLocForEndOfToken(sentinelExpr->getLocEnd());
478   std::string NullValue;
479   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
480     NullValue = "nil";
481   else if (getLangOpts().CPlusPlus11)
482     NullValue = "nullptr";
483   else if (PP.isMacroDefined("NULL"))
484     NullValue = "NULL";
485   else
486     NullValue = "(void*) 0";
487 
488   if (MissingNilLoc.isInvalid())
489     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
490   else
491     Diag(MissingNilLoc, diag::warn_missing_sentinel)
492       << int(calleeType)
493       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
494   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
495 }
496 
497 SourceRange Sema::getExprRange(Expr *E) const {
498   return E ? E->getSourceRange() : SourceRange();
499 }
500 
501 //===----------------------------------------------------------------------===//
502 //  Standard Promotions and Conversions
503 //===----------------------------------------------------------------------===//
504 
505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
507   // Handle any placeholder expressions which made it here.
508   if (E->getType()->isPlaceholderType()) {
509     ExprResult result = CheckPlaceholderExpr(E);
510     if (result.isInvalid()) return ExprError();
511     E = result.get();
512   }
513 
514   QualType Ty = E->getType();
515   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
516 
517   if (Ty->isFunctionType()) {
518     // If we are here, we are not calling a function but taking
519     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
520     if (getLangOpts().OpenCL) {
521       if (Diagnose)
522         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
523       return ExprError();
524     }
525 
526     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
527       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
528         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
529           return ExprError();
530 
531     E = ImpCastExprToType(E, Context.getPointerType(Ty),
532                           CK_FunctionToPointerDecay).get();
533   } else if (Ty->isArrayType()) {
534     // In C90 mode, arrays only promote to pointers if the array expression is
535     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
536     // type 'array of type' is converted to an expression that has type 'pointer
537     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
538     // that has type 'array of type' ...".  The relevant change is "an lvalue"
539     // (C90) to "an expression" (C99).
540     //
541     // C++ 4.2p1:
542     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
543     // T" can be converted to an rvalue of type "pointer to T".
544     //
545     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
546       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
547                             CK_ArrayToPointerDecay).get();
548   }
549   return E;
550 }
551 
552 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
553   // Check to see if we are dereferencing a null pointer.  If so,
554   // and if not volatile-qualified, this is undefined behavior that the
555   // optimizer will delete, so warn about it.  People sometimes try to use this
556   // to get a deterministic trap and are surprised by clang's behavior.  This
557   // only handles the pattern "*null", which is a very syntactic check.
558   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
559     if (UO->getOpcode() == UO_Deref &&
560         UO->getSubExpr()->IgnoreParenCasts()->
561           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
562         !UO->getType().isVolatileQualified()) {
563     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564                           S.PDiag(diag::warn_indirection_through_null)
565                             << UO->getSubExpr()->getSourceRange());
566     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567                         S.PDiag(diag::note_indirection_through_null));
568   }
569 }
570 
571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
572                                     SourceLocation AssignLoc,
573                                     const Expr* RHS) {
574   const ObjCIvarDecl *IV = OIRE->getDecl();
575   if (!IV)
576     return;
577 
578   DeclarationName MemberName = IV->getDeclName();
579   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
580   if (!Member || !Member->isStr("isa"))
581     return;
582 
583   const Expr *Base = OIRE->getBase();
584   QualType BaseType = Base->getType();
585   if (OIRE->isArrow())
586     BaseType = BaseType->getPointeeType();
587   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
588     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
589       ObjCInterfaceDecl *ClassDeclared = nullptr;
590       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
591       if (!ClassDeclared->getSuperClass()
592           && (*ClassDeclared->ivar_begin()) == IV) {
593         if (RHS) {
594           NamedDecl *ObjectSetClass =
595             S.LookupSingleName(S.TUScope,
596                                &S.Context.Idents.get("object_setClass"),
597                                SourceLocation(), S.LookupOrdinaryName);
598           if (ObjectSetClass) {
599             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
600             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
601             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
602             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
603                                                      AssignLoc), ",") <<
604             FixItHint::CreateInsertion(RHSLocEnd, ")");
605           }
606           else
607             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
608         } else {
609           NamedDecl *ObjectGetClass =
610             S.LookupSingleName(S.TUScope,
611                                &S.Context.Idents.get("object_getClass"),
612                                SourceLocation(), S.LookupOrdinaryName);
613           if (ObjectGetClass)
614             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
615             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
616             FixItHint::CreateReplacement(
617                                          SourceRange(OIRE->getOpLoc(),
618                                                      OIRE->getLocEnd()), ")");
619           else
620             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
621         }
622         S.Diag(IV->getLocation(), diag::note_ivar_decl);
623       }
624     }
625 }
626 
627 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
628   // Handle any placeholder expressions which made it here.
629   if (E->getType()->isPlaceholderType()) {
630     ExprResult result = CheckPlaceholderExpr(E);
631     if (result.isInvalid()) return ExprError();
632     E = result.get();
633   }
634 
635   // C++ [conv.lval]p1:
636   //   A glvalue of a non-function, non-array type T can be
637   //   converted to a prvalue.
638   if (!E->isGLValue()) return E;
639 
640   QualType T = E->getType();
641   assert(!T.isNull() && "r-value conversion on typeless expression?");
642 
643   // We don't want to throw lvalue-to-rvalue casts on top of
644   // expressions of certain types in C++.
645   if (getLangOpts().CPlusPlus &&
646       (E->getType() == Context.OverloadTy ||
647        T->isDependentType() ||
648        T->isRecordType()))
649     return E;
650 
651   // The C standard is actually really unclear on this point, and
652   // DR106 tells us what the result should be but not why.  It's
653   // generally best to say that void types just doesn't undergo
654   // lvalue-to-rvalue at all.  Note that expressions of unqualified
655   // 'void' type are never l-values, but qualified void can be.
656   if (T->isVoidType())
657     return E;
658 
659   // OpenCL usually rejects direct accesses to values of 'half' type.
660   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
661       T->isHalfType()) {
662     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663       << 0 << T;
664     return ExprError();
665   }
666 
667   CheckForNullPointerDereference(*this, E);
668   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670                                      &Context.Idents.get("object_getClass"),
671                                      SourceLocation(), LookupOrdinaryName);
672     if (ObjectGetClass)
673       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
674         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
675         FixItHint::CreateReplacement(
676                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677     else
678       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679   }
680   else if (const ObjCIvarRefExpr *OIRE =
681             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683 
684   // C++ [conv.lval]p1:
685   //   [...] If T is a non-class type, the type of the prvalue is the
686   //   cv-unqualified version of T. Otherwise, the type of the
687   //   rvalue is T.
688   //
689   // C99 6.3.2.1p2:
690   //   If the lvalue has qualified type, the value has the unqualified
691   //   version of the type of the lvalue; otherwise, the value has the
692   //   type of the lvalue.
693   if (T.hasQualifiers())
694     T = T.getUnqualifiedType();
695 
696   // Under the MS ABI, lock down the inheritance model now.
697   if (T->isMemberPointerType() &&
698       Context.getTargetInfo().getCXXABI().isMicrosoft())
699     (void)isCompleteType(E->getExprLoc(), T);
700 
701   UpdateMarkingForLValueToRValue(E);
702 
703   // Loading a __weak object implicitly retains the value, so we need a cleanup to
704   // balance that.
705   if (getLangOpts().ObjCAutoRefCount &&
706       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
707     Cleanup.setExprNeedsCleanups(true);
708 
709   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
710                                             nullptr, VK_RValue);
711 
712   // C11 6.3.2.1p2:
713   //   ... if the lvalue has atomic type, the value has the non-atomic version
714   //   of the type of the lvalue ...
715   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
716     T = Atomic->getValueType().getUnqualifiedType();
717     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
718                                    nullptr, VK_RValue);
719   }
720 
721   return Res;
722 }
723 
724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
725   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
726   if (Res.isInvalid())
727     return ExprError();
728   Res = DefaultLvalueConversion(Res.get());
729   if (Res.isInvalid())
730     return ExprError();
731   return Res;
732 }
733 
734 /// CallExprUnaryConversions - a special case of an unary conversion
735 /// performed on a function designator of a call expression.
736 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
737   QualType Ty = E->getType();
738   ExprResult Res = E;
739   // Only do implicit cast for a function type, but not for a pointer
740   // to function type.
741   if (Ty->isFunctionType()) {
742     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
743                             CK_FunctionToPointerDecay).get();
744     if (Res.isInvalid())
745       return ExprError();
746   }
747   Res = DefaultLvalueConversion(Res.get());
748   if (Res.isInvalid())
749     return ExprError();
750   return Res.get();
751 }
752 
753 /// UsualUnaryConversions - Performs various conversions that are common to most
754 /// operators (C99 6.3). The conversions of array and function types are
755 /// sometimes suppressed. For example, the array->pointer conversion doesn't
756 /// apply if the array is an argument to the sizeof or address (&) operators.
757 /// In these instances, this routine should *not* be called.
758 ExprResult Sema::UsualUnaryConversions(Expr *E) {
759   // First, convert to an r-value.
760   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
761   if (Res.isInvalid())
762     return ExprError();
763   E = Res.get();
764 
765   QualType Ty = E->getType();
766   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
767 
768   // Half FP have to be promoted to float unless it is natively supported
769   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
770     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
771 
772   // Try to perform integral promotions if the object has a theoretically
773   // promotable type.
774   if (Ty->isIntegralOrUnscopedEnumerationType()) {
775     // C99 6.3.1.1p2:
776     //
777     //   The following may be used in an expression wherever an int or
778     //   unsigned int may be used:
779     //     - an object or expression with an integer type whose integer
780     //       conversion rank is less than or equal to the rank of int
781     //       and unsigned int.
782     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
783     //
784     //   If an int can represent all values of the original type, the
785     //   value is converted to an int; otherwise, it is converted to an
786     //   unsigned int. These are called the integer promotions. All
787     //   other types are unchanged by the integer promotions.
788 
789     QualType PTy = Context.isPromotableBitField(E);
790     if (!PTy.isNull()) {
791       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
792       return E;
793     }
794     if (Ty->isPromotableIntegerType()) {
795       QualType PT = Context.getPromotedIntegerType(Ty);
796       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
797       return E;
798     }
799   }
800   return E;
801 }
802 
803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
804 /// do not have a prototype. Arguments that have type float or __fp16
805 /// are promoted to double. All other argument types are converted by
806 /// UsualUnaryConversions().
807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
808   QualType Ty = E->getType();
809   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
810 
811   ExprResult Res = UsualUnaryConversions(E);
812   if (Res.isInvalid())
813     return ExprError();
814   E = Res.get();
815 
816   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
817   // double.
818   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
819   if (BTy && (BTy->getKind() == BuiltinType::Half ||
820               BTy->getKind() == BuiltinType::Float)) {
821     if (getLangOpts().OpenCL &&
822         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
823         if (BTy->getKind() == BuiltinType::Half) {
824             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
825         }
826     } else {
827       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
828     }
829   }
830 
831   // C++ performs lvalue-to-rvalue conversion as a default argument
832   // promotion, even on class types, but note:
833   //   C++11 [conv.lval]p2:
834   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
835   //     operand or a subexpression thereof the value contained in the
836   //     referenced object is not accessed. Otherwise, if the glvalue
837   //     has a class type, the conversion copy-initializes a temporary
838   //     of type T from the glvalue and the result of the conversion
839   //     is a prvalue for the temporary.
840   // FIXME: add some way to gate this entire thing for correctness in
841   // potentially potentially evaluated contexts.
842   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
843     ExprResult Temp = PerformCopyInitialization(
844                        InitializedEntity::InitializeTemporary(E->getType()),
845                                                 E->getExprLoc(), E);
846     if (Temp.isInvalid())
847       return ExprError();
848     E = Temp.get();
849   }
850 
851   return E;
852 }
853 
854 /// Determine the degree of POD-ness for an expression.
855 /// Incomplete types are considered POD, since this check can be performed
856 /// when we're in an unevaluated context.
857 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
858   if (Ty->isIncompleteType()) {
859     // C++11 [expr.call]p7:
860     //   After these conversions, if the argument does not have arithmetic,
861     //   enumeration, pointer, pointer to member, or class type, the program
862     //   is ill-formed.
863     //
864     // Since we've already performed array-to-pointer and function-to-pointer
865     // decay, the only such type in C++ is cv void. This also handles
866     // initializer lists as variadic arguments.
867     if (Ty->isVoidType())
868       return VAK_Invalid;
869 
870     if (Ty->isObjCObjectType())
871       return VAK_Invalid;
872     return VAK_Valid;
873   }
874 
875   if (Ty.isCXX98PODType(Context))
876     return VAK_Valid;
877 
878   // C++11 [expr.call]p7:
879   //   Passing a potentially-evaluated argument of class type (Clause 9)
880   //   having a non-trivial copy constructor, a non-trivial move constructor,
881   //   or a non-trivial destructor, with no corresponding parameter,
882   //   is conditionally-supported with implementation-defined semantics.
883   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
884     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
885       if (!Record->hasNonTrivialCopyConstructor() &&
886           !Record->hasNonTrivialMoveConstructor() &&
887           !Record->hasNonTrivialDestructor())
888         return VAK_ValidInCXX11;
889 
890   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
891     return VAK_Valid;
892 
893   if (Ty->isObjCObjectType())
894     return VAK_Invalid;
895 
896   if (getLangOpts().MSVCCompat)
897     return VAK_MSVCUndefined;
898 
899   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
900   // permitted to reject them. We should consider doing so.
901   return VAK_Undefined;
902 }
903 
904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
905   // Don't allow one to pass an Objective-C interface to a vararg.
906   const QualType &Ty = E->getType();
907   VarArgKind VAK = isValidVarArgType(Ty);
908 
909   // Complain about passing non-POD types through varargs.
910   switch (VAK) {
911   case VAK_ValidInCXX11:
912     DiagRuntimeBehavior(
913         E->getLocStart(), nullptr,
914         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
915           << Ty << CT);
916     // Fall through.
917   case VAK_Valid:
918     if (Ty->isRecordType()) {
919       // This is unlikely to be what the user intended. If the class has a
920       // 'c_str' member function, the user probably meant to call that.
921       DiagRuntimeBehavior(E->getLocStart(), nullptr,
922                           PDiag(diag::warn_pass_class_arg_to_vararg)
923                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
924     }
925     break;
926 
927   case VAK_Undefined:
928   case VAK_MSVCUndefined:
929     DiagRuntimeBehavior(
930         E->getLocStart(), nullptr,
931         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
932           << getLangOpts().CPlusPlus11 << Ty << CT);
933     break;
934 
935   case VAK_Invalid:
936     if (Ty->isObjCObjectType())
937       DiagRuntimeBehavior(
938           E->getLocStart(), nullptr,
939           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
940             << Ty << CT);
941     else
942       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
943         << isa<InitListExpr>(E) << Ty << CT;
944     break;
945   }
946 }
947 
948 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
949 /// will create a trap if the resulting type is not a POD type.
950 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
951                                                   FunctionDecl *FDecl) {
952   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
953     // Strip the unbridged-cast placeholder expression off, if applicable.
954     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
955         (CT == VariadicMethod ||
956          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
957       E = stripARCUnbridgedCast(E);
958 
959     // Otherwise, do normal placeholder checking.
960     } else {
961       ExprResult ExprRes = CheckPlaceholderExpr(E);
962       if (ExprRes.isInvalid())
963         return ExprError();
964       E = ExprRes.get();
965     }
966   }
967 
968   ExprResult ExprRes = DefaultArgumentPromotion(E);
969   if (ExprRes.isInvalid())
970     return ExprError();
971   E = ExprRes.get();
972 
973   // Diagnostics regarding non-POD argument types are
974   // emitted along with format string checking in Sema::CheckFunctionCall().
975   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
976     // Turn this into a trap.
977     CXXScopeSpec SS;
978     SourceLocation TemplateKWLoc;
979     UnqualifiedId Name;
980     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
981                        E->getLocStart());
982     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
983                                           Name, true, false);
984     if (TrapFn.isInvalid())
985       return ExprError();
986 
987     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
988                                     E->getLocStart(), None,
989                                     E->getLocEnd());
990     if (Call.isInvalid())
991       return ExprError();
992 
993     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
994                                   Call.get(), E);
995     if (Comma.isInvalid())
996       return ExprError();
997     return Comma.get();
998   }
999 
1000   if (!getLangOpts().CPlusPlus &&
1001       RequireCompleteType(E->getExprLoc(), E->getType(),
1002                           diag::err_call_incomplete_argument))
1003     return ExprError();
1004 
1005   return E;
1006 }
1007 
1008 /// \brief Converts an integer to complex float type.  Helper function of
1009 /// UsualArithmeticConversions()
1010 ///
1011 /// \return false if the integer expression is an integer type and is
1012 /// successfully converted to the complex type.
1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1014                                                   ExprResult &ComplexExpr,
1015                                                   QualType IntTy,
1016                                                   QualType ComplexTy,
1017                                                   bool SkipCast) {
1018   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1019   if (SkipCast) return false;
1020   if (IntTy->isIntegerType()) {
1021     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1024                                   CK_FloatingRealToComplex);
1025   } else {
1026     assert(IntTy->isComplexIntegerType());
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_IntegralComplexToFloatingComplex);
1029   }
1030   return false;
1031 }
1032 
1033 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1034 /// UsualArithmeticConversions()
1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1036                                              ExprResult &RHS, QualType LHSType,
1037                                              QualType RHSType,
1038                                              bool IsCompAssign) {
1039   // if we have an integer operand, the result is the complex type.
1040   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1041                                              /*skipCast*/false))
1042     return LHSType;
1043   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1044                                              /*skipCast*/IsCompAssign))
1045     return RHSType;
1046 
1047   // This handles complex/complex, complex/float, or float/complex.
1048   // When both operands are complex, the shorter operand is converted to the
1049   // type of the longer, and that is the type of the result. This corresponds
1050   // to what is done when combining two real floating-point operands.
1051   // The fun begins when size promotion occur across type domains.
1052   // From H&S 6.3.4: When one operand is complex and the other is a real
1053   // floating-point type, the less precise type is converted, within it's
1054   // real or complex domain, to the precision of the other type. For example,
1055   // when combining a "long double" with a "double _Complex", the
1056   // "double _Complex" is promoted to "long double _Complex".
1057 
1058   // Compute the rank of the two types, regardless of whether they are complex.
1059   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1060 
1061   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1062   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1063   QualType LHSElementType =
1064       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1065   QualType RHSElementType =
1066       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1067 
1068   QualType ResultType = S.Context.getComplexType(LHSElementType);
1069   if (Order < 0) {
1070     // Promote the precision of the LHS if not an assignment.
1071     ResultType = S.Context.getComplexType(RHSElementType);
1072     if (!IsCompAssign) {
1073       if (LHSComplexType)
1074         LHS =
1075             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1076       else
1077         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1078     }
1079   } else if (Order > 0) {
1080     // Promote the precision of the RHS.
1081     if (RHSComplexType)
1082       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1083     else
1084       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1085   }
1086   return ResultType;
1087 }
1088 
1089 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1090 /// of UsualArithmeticConversions()
1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1092                                            ExprResult &IntExpr,
1093                                            QualType FloatTy, QualType IntTy,
1094                                            bool ConvertFloat, bool ConvertInt) {
1095   if (IntTy->isIntegerType()) {
1096     if (ConvertInt)
1097       // Convert intExpr to the lhs floating point type.
1098       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1099                                     CK_IntegralToFloating);
1100     return FloatTy;
1101   }
1102 
1103   // Convert both sides to the appropriate complex float.
1104   assert(IntTy->isComplexIntegerType());
1105   QualType result = S.Context.getComplexType(FloatTy);
1106 
1107   // _Complex int -> _Complex float
1108   if (ConvertInt)
1109     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1110                                   CK_IntegralComplexToFloatingComplex);
1111 
1112   // float -> _Complex float
1113   if (ConvertFloat)
1114     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1115                                     CK_FloatingRealToComplex);
1116 
1117   return result;
1118 }
1119 
1120 /// \brief Handle arithmethic conversion with floating point types.  Helper
1121 /// function of UsualArithmeticConversions()
1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1123                                       ExprResult &RHS, QualType LHSType,
1124                                       QualType RHSType, bool IsCompAssign) {
1125   bool LHSFloat = LHSType->isRealFloatingType();
1126   bool RHSFloat = RHSType->isRealFloatingType();
1127 
1128   // If we have two real floating types, convert the smaller operand
1129   // to the bigger result.
1130   if (LHSFloat && RHSFloat) {
1131     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1132     if (order > 0) {
1133       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1134       return LHSType;
1135     }
1136 
1137     assert(order < 0 && "illegal float comparison");
1138     if (!IsCompAssign)
1139       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1140     return RHSType;
1141   }
1142 
1143   if (LHSFloat) {
1144     // Half FP has to be promoted to float unless it is natively supported
1145     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1146       LHSType = S.Context.FloatTy;
1147 
1148     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1149                                       /*convertFloat=*/!IsCompAssign,
1150                                       /*convertInt=*/ true);
1151   }
1152   assert(RHSFloat);
1153   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1154                                     /*convertInt=*/ true,
1155                                     /*convertFloat=*/!IsCompAssign);
1156 }
1157 
1158 /// \brief Diagnose attempts to convert between __float128 and long double if
1159 /// there is no support for such conversion. Helper function of
1160 /// UsualArithmeticConversions().
1161 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1162                                       QualType RHSType) {
1163   /*  No issue converting if at least one of the types is not a floating point
1164       type or the two types have the same rank.
1165   */
1166   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1167       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1168     return false;
1169 
1170   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1171          "The remaining types must be floating point types.");
1172 
1173   auto *LHSComplex = LHSType->getAs<ComplexType>();
1174   auto *RHSComplex = RHSType->getAs<ComplexType>();
1175 
1176   QualType LHSElemType = LHSComplex ?
1177     LHSComplex->getElementType() : LHSType;
1178   QualType RHSElemType = RHSComplex ?
1179     RHSComplex->getElementType() : RHSType;
1180 
1181   // No issue if the two types have the same representation
1182   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1183       &S.Context.getFloatTypeSemantics(RHSElemType))
1184     return false;
1185 
1186   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1187                                 RHSElemType == S.Context.LongDoubleTy);
1188   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1189                             RHSElemType == S.Context.Float128Ty);
1190 
1191   /* We've handled the situation where __float128 and long double have the same
1192      representation. The only other allowable conversion is if long double is
1193      really just double.
1194   */
1195   return Float128AndLongDouble &&
1196     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1197      &llvm::APFloat::IEEEdouble());
1198 }
1199 
1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1201 
1202 namespace {
1203 /// These helper callbacks are placed in an anonymous namespace to
1204 /// permit their use as function template parameters.
1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207 }
1208 
1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211                              CK_IntegralComplexCast);
1212 }
1213 }
1214 
1215 /// \brief Handle integer arithmetic conversions.  Helper function of
1216 /// UsualArithmeticConversions()
1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219                                         ExprResult &RHS, QualType LHSType,
1220                                         QualType RHSType, bool IsCompAssign) {
1221   // The rules for this case are in C99 6.3.1.8
1222   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225   if (LHSSigned == RHSSigned) {
1226     // Same signedness; use the higher-ranked type
1227     if (order >= 0) {
1228       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1229       return LHSType;
1230     } else if (!IsCompAssign)
1231       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1232     return RHSType;
1233   } else if (order != (LHSSigned ? 1 : -1)) {
1234     // The unsigned type has greater than or equal rank to the
1235     // signed type, so use the unsigned type
1236     if (RHSSigned) {
1237       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1238       return LHSType;
1239     } else if (!IsCompAssign)
1240       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1241     return RHSType;
1242   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243     // The two types are different widths; if we are here, that
1244     // means the signed type is larger than the unsigned type, so
1245     // use the signed type.
1246     if (LHSSigned) {
1247       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1248       return LHSType;
1249     } else if (!IsCompAssign)
1250       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1251     return RHSType;
1252   } else {
1253     // The signed type is higher-ranked than the unsigned type,
1254     // but isn't actually any bigger (like unsigned int and long
1255     // on most 32-bit systems).  Use the unsigned type corresponding
1256     // to the signed type.
1257     QualType result =
1258       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259     RHS = (*doRHSCast)(S, RHS.get(), result);
1260     if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), result);
1262     return result;
1263   }
1264 }
1265 
1266 /// \brief Handle conversions with GCC complex int extension.  Helper function
1267 /// of UsualArithmeticConversions()
1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269                                            ExprResult &RHS, QualType LHSType,
1270                                            QualType RHSType,
1271                                            bool IsCompAssign) {
1272   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274 
1275   if (LHSComplexInt && RHSComplexInt) {
1276     QualType LHSEltType = LHSComplexInt->getElementType();
1277     QualType RHSEltType = RHSComplexInt->getElementType();
1278     QualType ScalarType =
1279       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281 
1282     return S.Context.getComplexType(ScalarType);
1283   }
1284 
1285   if (LHSComplexInt) {
1286     QualType LHSEltType = LHSComplexInt->getElementType();
1287     QualType ScalarType =
1288       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290     QualType ComplexType = S.Context.getComplexType(ScalarType);
1291     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292                               CK_IntegralRealToComplex);
1293 
1294     return ComplexType;
1295   }
1296 
1297   assert(RHSComplexInt);
1298 
1299   QualType RHSEltType = RHSComplexInt->getElementType();
1300   QualType ScalarType =
1301     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303   QualType ComplexType = S.Context.getComplexType(ScalarType);
1304 
1305   if (!IsCompAssign)
1306     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307                               CK_IntegralRealToComplex);
1308   return ComplexType;
1309 }
1310 
1311 /// UsualArithmeticConversions - Performs various conversions that are common to
1312 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1313 /// routine returns the first non-arithmetic type found. The client is
1314 /// responsible for emitting appropriate error diagnostics.
1315 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1316                                           bool IsCompAssign) {
1317   if (!IsCompAssign) {
1318     LHS = UsualUnaryConversions(LHS.get());
1319     if (LHS.isInvalid())
1320       return QualType();
1321   }
1322 
1323   RHS = UsualUnaryConversions(RHS.get());
1324   if (RHS.isInvalid())
1325     return QualType();
1326 
1327   // For conversion purposes, we ignore any qualifiers.
1328   // For example, "const float" and "float" are equivalent.
1329   QualType LHSType =
1330     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1331   QualType RHSType =
1332     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1333 
1334   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1335   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1336     LHSType = AtomicLHS->getValueType();
1337 
1338   // If both types are identical, no conversion is needed.
1339   if (LHSType == RHSType)
1340     return LHSType;
1341 
1342   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1343   // The caller can deal with this (e.g. pointer + int).
1344   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1345     return QualType();
1346 
1347   // Apply unary and bitfield promotions to the LHS's type.
1348   QualType LHSUnpromotedType = LHSType;
1349   if (LHSType->isPromotableIntegerType())
1350     LHSType = Context.getPromotedIntegerType(LHSType);
1351   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1352   if (!LHSBitfieldPromoteTy.isNull())
1353     LHSType = LHSBitfieldPromoteTy;
1354   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1355     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1356 
1357   // If both types are identical, no conversion is needed.
1358   if (LHSType == RHSType)
1359     return LHSType;
1360 
1361   // At this point, we have two different arithmetic types.
1362 
1363   // Diagnose attempts to convert between __float128 and long double where
1364   // such conversions currently can't be handled.
1365   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1366     return QualType();
1367 
1368   // Handle complex types first (C99 6.3.1.8p1).
1369   if (LHSType->isComplexType() || RHSType->isComplexType())
1370     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1371                                         IsCompAssign);
1372 
1373   // Now handle "real" floating types (i.e. float, double, long double).
1374   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1375     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1376                                  IsCompAssign);
1377 
1378   // Handle GCC complex int extension.
1379   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1380     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1381                                       IsCompAssign);
1382 
1383   // Finally, we have two differing integer types.
1384   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1385            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1386 }
1387 
1388 
1389 //===----------------------------------------------------------------------===//
1390 //  Semantic Analysis for various Expression Types
1391 //===----------------------------------------------------------------------===//
1392 
1393 
1394 ExprResult
1395 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1396                                 SourceLocation DefaultLoc,
1397                                 SourceLocation RParenLoc,
1398                                 Expr *ControllingExpr,
1399                                 ArrayRef<ParsedType> ArgTypes,
1400                                 ArrayRef<Expr *> ArgExprs) {
1401   unsigned NumAssocs = ArgTypes.size();
1402   assert(NumAssocs == ArgExprs.size());
1403 
1404   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1405   for (unsigned i = 0; i < NumAssocs; ++i) {
1406     if (ArgTypes[i])
1407       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1408     else
1409       Types[i] = nullptr;
1410   }
1411 
1412   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1413                                              ControllingExpr,
1414                                              llvm::makeArrayRef(Types, NumAssocs),
1415                                              ArgExprs);
1416   delete [] Types;
1417   return ER;
1418 }
1419 
1420 ExprResult
1421 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1422                                  SourceLocation DefaultLoc,
1423                                  SourceLocation RParenLoc,
1424                                  Expr *ControllingExpr,
1425                                  ArrayRef<TypeSourceInfo *> Types,
1426                                  ArrayRef<Expr *> Exprs) {
1427   unsigned NumAssocs = Types.size();
1428   assert(NumAssocs == Exprs.size());
1429 
1430   // Decay and strip qualifiers for the controlling expression type, and handle
1431   // placeholder type replacement. See committee discussion from WG14 DR423.
1432   {
1433     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1434     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1435     if (R.isInvalid())
1436       return ExprError();
1437     ControllingExpr = R.get();
1438   }
1439 
1440   // The controlling expression is an unevaluated operand, so side effects are
1441   // likely unintended.
1442   if (ActiveTemplateInstantiations.empty() &&
1443       ControllingExpr->HasSideEffects(Context, false))
1444     Diag(ControllingExpr->getExprLoc(),
1445          diag::warn_side_effects_unevaluated_context);
1446 
1447   bool TypeErrorFound = false,
1448        IsResultDependent = ControllingExpr->isTypeDependent(),
1449        ContainsUnexpandedParameterPack
1450          = ControllingExpr->containsUnexpandedParameterPack();
1451 
1452   for (unsigned i = 0; i < NumAssocs; ++i) {
1453     if (Exprs[i]->containsUnexpandedParameterPack())
1454       ContainsUnexpandedParameterPack = true;
1455 
1456     if (Types[i]) {
1457       if (Types[i]->getType()->containsUnexpandedParameterPack())
1458         ContainsUnexpandedParameterPack = true;
1459 
1460       if (Types[i]->getType()->isDependentType()) {
1461         IsResultDependent = true;
1462       } else {
1463         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1464         // complete object type other than a variably modified type."
1465         unsigned D = 0;
1466         if (Types[i]->getType()->isIncompleteType())
1467           D = diag::err_assoc_type_incomplete;
1468         else if (!Types[i]->getType()->isObjectType())
1469           D = diag::err_assoc_type_nonobject;
1470         else if (Types[i]->getType()->isVariablyModifiedType())
1471           D = diag::err_assoc_type_variably_modified;
1472 
1473         if (D != 0) {
1474           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1475             << Types[i]->getTypeLoc().getSourceRange()
1476             << Types[i]->getType();
1477           TypeErrorFound = true;
1478         }
1479 
1480         // C11 6.5.1.1p2 "No two generic associations in the same generic
1481         // selection shall specify compatible types."
1482         for (unsigned j = i+1; j < NumAssocs; ++j)
1483           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1484               Context.typesAreCompatible(Types[i]->getType(),
1485                                          Types[j]->getType())) {
1486             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1487                  diag::err_assoc_compatible_types)
1488               << Types[j]->getTypeLoc().getSourceRange()
1489               << Types[j]->getType()
1490               << Types[i]->getType();
1491             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1492                  diag::note_compat_assoc)
1493               << Types[i]->getTypeLoc().getSourceRange()
1494               << Types[i]->getType();
1495             TypeErrorFound = true;
1496           }
1497       }
1498     }
1499   }
1500   if (TypeErrorFound)
1501     return ExprError();
1502 
1503   // If we determined that the generic selection is result-dependent, don't
1504   // try to compute the result expression.
1505   if (IsResultDependent)
1506     return new (Context) GenericSelectionExpr(
1507         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1508         ContainsUnexpandedParameterPack);
1509 
1510   SmallVector<unsigned, 1> CompatIndices;
1511   unsigned DefaultIndex = -1U;
1512   for (unsigned i = 0; i < NumAssocs; ++i) {
1513     if (!Types[i])
1514       DefaultIndex = i;
1515     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1516                                         Types[i]->getType()))
1517       CompatIndices.push_back(i);
1518   }
1519 
1520   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1521   // type compatible with at most one of the types named in its generic
1522   // association list."
1523   if (CompatIndices.size() > 1) {
1524     // We strip parens here because the controlling expression is typically
1525     // parenthesized in macro definitions.
1526     ControllingExpr = ControllingExpr->IgnoreParens();
1527     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1528       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1529       << (unsigned) CompatIndices.size();
1530     for (unsigned I : CompatIndices) {
1531       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1532            diag::note_compat_assoc)
1533         << Types[I]->getTypeLoc().getSourceRange()
1534         << Types[I]->getType();
1535     }
1536     return ExprError();
1537   }
1538 
1539   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1540   // its controlling expression shall have type compatible with exactly one of
1541   // the types named in its generic association list."
1542   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1543     // We strip parens here because the controlling expression is typically
1544     // parenthesized in macro definitions.
1545     ControllingExpr = ControllingExpr->IgnoreParens();
1546     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1547       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1548     return ExprError();
1549   }
1550 
1551   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1552   // type name that is compatible with the type of the controlling expression,
1553   // then the result expression of the generic selection is the expression
1554   // in that generic association. Otherwise, the result expression of the
1555   // generic selection is the expression in the default generic association."
1556   unsigned ResultIndex =
1557     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1558 
1559   return new (Context) GenericSelectionExpr(
1560       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1561       ContainsUnexpandedParameterPack, ResultIndex);
1562 }
1563 
1564 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1565 /// location of the token and the offset of the ud-suffix within it.
1566 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1567                                      unsigned Offset) {
1568   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1569                                         S.getLangOpts());
1570 }
1571 
1572 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1573 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1574 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1575                                                  IdentifierInfo *UDSuffix,
1576                                                  SourceLocation UDSuffixLoc,
1577                                                  ArrayRef<Expr*> Args,
1578                                                  SourceLocation LitEndLoc) {
1579   assert(Args.size() <= 2 && "too many arguments for literal operator");
1580 
1581   QualType ArgTy[2];
1582   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1583     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1584     if (ArgTy[ArgIdx]->isArrayType())
1585       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1586   }
1587 
1588   DeclarationName OpName =
1589     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1594   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1595                               /*AllowRaw*/false, /*AllowTemplate*/false,
1596                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1597     return ExprError();
1598 
1599   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1600 }
1601 
1602 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1603 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1604 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1605 /// multiple tokens.  However, the common case is that StringToks points to one
1606 /// string.
1607 ///
1608 ExprResult
1609 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1610   assert(!StringToks.empty() && "Must have at least one string!");
1611 
1612   StringLiteralParser Literal(StringToks, PP);
1613   if (Literal.hadError)
1614     return ExprError();
1615 
1616   SmallVector<SourceLocation, 4> StringTokLocs;
1617   for (const Token &Tok : StringToks)
1618     StringTokLocs.push_back(Tok.getLocation());
1619 
1620   QualType CharTy = Context.CharTy;
1621   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1622   if (Literal.isWide()) {
1623     CharTy = Context.getWideCharType();
1624     Kind = StringLiteral::Wide;
1625   } else if (Literal.isUTF8()) {
1626     Kind = StringLiteral::UTF8;
1627   } else if (Literal.isUTF16()) {
1628     CharTy = Context.Char16Ty;
1629     Kind = StringLiteral::UTF16;
1630   } else if (Literal.isUTF32()) {
1631     CharTy = Context.Char32Ty;
1632     Kind = StringLiteral::UTF32;
1633   } else if (Literal.isPascal()) {
1634     CharTy = Context.UnsignedCharTy;
1635   }
1636 
1637   QualType CharTyConst = CharTy;
1638   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1639   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1640     CharTyConst.addConst();
1641 
1642   // Get an array type for the string, according to C99 6.4.5.  This includes
1643   // the nul terminator character as well as the string length for pascal
1644   // strings.
1645   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1646                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1647                                  ArrayType::Normal, 0);
1648 
1649   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1650   if (getLangOpts().OpenCL) {
1651     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1652   }
1653 
1654   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1655   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1656                                              Kind, Literal.Pascal, StrTy,
1657                                              &StringTokLocs[0],
1658                                              StringTokLocs.size());
1659   if (Literal.getUDSuffix().empty())
1660     return Lit;
1661 
1662   // We're building a user-defined literal.
1663   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1664   SourceLocation UDSuffixLoc =
1665     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1666                    Literal.getUDSuffixOffset());
1667 
1668   // Make sure we're allowed user-defined literals here.
1669   if (!UDLScope)
1670     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1671 
1672   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1673   //   operator "" X (str, len)
1674   QualType SizeType = Context.getSizeType();
1675 
1676   DeclarationName OpName =
1677     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1678   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1679   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1680 
1681   QualType ArgTy[] = {
1682     Context.getArrayDecayedType(StrTy), SizeType
1683   };
1684 
1685   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1686   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1687                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1688                                 /*AllowStringTemplate*/true)) {
1689 
1690   case LOLR_Cooked: {
1691     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1692     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1693                                                     StringTokLocs[0]);
1694     Expr *Args[] = { Lit, LenArg };
1695 
1696     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1697   }
1698 
1699   case LOLR_StringTemplate: {
1700     TemplateArgumentListInfo ExplicitArgs;
1701 
1702     unsigned CharBits = Context.getIntWidth(CharTy);
1703     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1704     llvm::APSInt Value(CharBits, CharIsUnsigned);
1705 
1706     TemplateArgument TypeArg(CharTy);
1707     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1708     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1709 
1710     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1711       Value = Lit->getCodeUnit(I);
1712       TemplateArgument Arg(Context, Value, CharTy);
1713       TemplateArgumentLocInfo ArgInfo;
1714       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1715     }
1716     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1717                                     &ExplicitArgs);
1718   }
1719   case LOLR_Raw:
1720   case LOLR_Template:
1721     llvm_unreachable("unexpected literal operator lookup result");
1722   case LOLR_Error:
1723     return ExprError();
1724   }
1725   llvm_unreachable("unexpected literal operator lookup result");
1726 }
1727 
1728 ExprResult
1729 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1730                        SourceLocation Loc,
1731                        const CXXScopeSpec *SS) {
1732   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1733   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1734 }
1735 
1736 /// BuildDeclRefExpr - Build an expression that references a
1737 /// declaration that does not require a closure capture.
1738 ExprResult
1739 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1740                        const DeclarationNameInfo &NameInfo,
1741                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1742                        const TemplateArgumentListInfo *TemplateArgs) {
1743   bool RefersToCapturedVariable =
1744       isa<VarDecl>(D) &&
1745       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1746 
1747   DeclRefExpr *E;
1748   if (isa<VarTemplateSpecializationDecl>(D)) {
1749     VarTemplateSpecializationDecl *VarSpec =
1750         cast<VarTemplateSpecializationDecl>(D);
1751 
1752     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1753                                         : NestedNameSpecifierLoc(),
1754                             VarSpec->getTemplateKeywordLoc(), D,
1755                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1756                             FoundD, TemplateArgs);
1757   } else {
1758     assert(!TemplateArgs && "No template arguments for non-variable"
1759                             " template specialization references");
1760     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1761                                         : NestedNameSpecifierLoc(),
1762                             SourceLocation(), D, RefersToCapturedVariable,
1763                             NameInfo, Ty, VK, FoundD);
1764   }
1765 
1766   MarkDeclRefReferenced(E);
1767 
1768   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1769       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1770       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1771       recordUseOfEvaluatedWeak(E);
1772 
1773   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1774     UnusedPrivateFields.remove(FD);
1775     // Just in case we're building an illegal pointer-to-member.
1776     if (FD->isBitField())
1777       E->setObjectKind(OK_BitField);
1778   }
1779 
1780   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1781   // designates a bit-field.
1782   if (auto *BD = dyn_cast<BindingDecl>(D))
1783     if (auto *BE = BD->getBinding())
1784       E->setObjectKind(BE->getObjectKind());
1785 
1786   return E;
1787 }
1788 
1789 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1790 /// possibly a list of template arguments.
1791 ///
1792 /// If this produces template arguments, it is permitted to call
1793 /// DecomposeTemplateName.
1794 ///
1795 /// This actually loses a lot of source location information for
1796 /// non-standard name kinds; we should consider preserving that in
1797 /// some way.
1798 void
1799 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1800                              TemplateArgumentListInfo &Buffer,
1801                              DeclarationNameInfo &NameInfo,
1802                              const TemplateArgumentListInfo *&TemplateArgs) {
1803   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1804     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1805     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1806 
1807     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1808                                        Id.TemplateId->NumArgs);
1809     translateTemplateArguments(TemplateArgsPtr, Buffer);
1810 
1811     TemplateName TName = Id.TemplateId->Template.get();
1812     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1813     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1814     TemplateArgs = &Buffer;
1815   } else {
1816     NameInfo = GetNameFromUnqualifiedId(Id);
1817     TemplateArgs = nullptr;
1818   }
1819 }
1820 
1821 static void emitEmptyLookupTypoDiagnostic(
1822     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1823     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1824     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1825   DeclContext *Ctx =
1826       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1827   if (!TC) {
1828     // Emit a special diagnostic for failed member lookups.
1829     // FIXME: computing the declaration context might fail here (?)
1830     if (Ctx)
1831       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1832                                                  << SS.getRange();
1833     else
1834       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1835     return;
1836   }
1837 
1838   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1839   bool DroppedSpecifier =
1840       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1841   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1842                         ? diag::note_implicit_param_decl
1843                         : diag::note_previous_decl;
1844   if (!Ctx)
1845     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1846                          SemaRef.PDiag(NoteID));
1847   else
1848     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1849                                  << Typo << Ctx << DroppedSpecifier
1850                                  << SS.getRange(),
1851                          SemaRef.PDiag(NoteID));
1852 }
1853 
1854 /// Diagnose an empty lookup.
1855 ///
1856 /// \return false if new lookup candidates were found
1857 bool
1858 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1859                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1860                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1861                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1862   DeclarationName Name = R.getLookupName();
1863 
1864   unsigned diagnostic = diag::err_undeclared_var_use;
1865   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1866   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1867       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1868       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1869     diagnostic = diag::err_undeclared_use;
1870     diagnostic_suggest = diag::err_undeclared_use_suggest;
1871   }
1872 
1873   // If the original lookup was an unqualified lookup, fake an
1874   // unqualified lookup.  This is useful when (for example) the
1875   // original lookup would not have found something because it was a
1876   // dependent name.
1877   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1878   while (DC) {
1879     if (isa<CXXRecordDecl>(DC)) {
1880       LookupQualifiedName(R, DC);
1881 
1882       if (!R.empty()) {
1883         // Don't give errors about ambiguities in this lookup.
1884         R.suppressDiagnostics();
1885 
1886         // During a default argument instantiation the CurContext points
1887         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1888         // function parameter list, hence add an explicit check.
1889         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1890                               ActiveTemplateInstantiations.back().Kind ==
1891             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1892         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1893         bool isInstance = CurMethod &&
1894                           CurMethod->isInstance() &&
1895                           DC == CurMethod->getParent() && !isDefaultArgument;
1896 
1897         // Give a code modification hint to insert 'this->'.
1898         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1899         // Actually quite difficult!
1900         if (getLangOpts().MSVCCompat)
1901           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1902         if (isInstance) {
1903           Diag(R.getNameLoc(), diagnostic) << Name
1904             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1905           CheckCXXThisCapture(R.getNameLoc());
1906         } else {
1907           Diag(R.getNameLoc(), diagnostic) << Name;
1908         }
1909 
1910         // Do we really want to note all of these?
1911         for (NamedDecl *D : R)
1912           Diag(D->getLocation(), diag::note_dependent_var_use);
1913 
1914         // Return true if we are inside a default argument instantiation
1915         // and the found name refers to an instance member function, otherwise
1916         // the function calling DiagnoseEmptyLookup will try to create an
1917         // implicit member call and this is wrong for default argument.
1918         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1919           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1920           return true;
1921         }
1922 
1923         // Tell the callee to try to recover.
1924         return false;
1925       }
1926 
1927       R.clear();
1928     }
1929 
1930     // In Microsoft mode, if we are performing lookup from within a friend
1931     // function definition declared at class scope then we must set
1932     // DC to the lexical parent to be able to search into the parent
1933     // class.
1934     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1935         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1936         DC->getLexicalParent()->isRecord())
1937       DC = DC->getLexicalParent();
1938     else
1939       DC = DC->getParent();
1940   }
1941 
1942   // We didn't find anything, so try to correct for a typo.
1943   TypoCorrection Corrected;
1944   if (S && Out) {
1945     SourceLocation TypoLoc = R.getNameLoc();
1946     assert(!ExplicitTemplateArgs &&
1947            "Diagnosing an empty lookup with explicit template args!");
1948     *Out = CorrectTypoDelayed(
1949         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1950         [=](const TypoCorrection &TC) {
1951           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1952                                         diagnostic, diagnostic_suggest);
1953         },
1954         nullptr, CTK_ErrorRecovery);
1955     if (*Out)
1956       return true;
1957   } else if (S && (Corrected =
1958                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1959                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1960     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1961     bool DroppedSpecifier =
1962         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1963     R.setLookupName(Corrected.getCorrection());
1964 
1965     bool AcceptableWithRecovery = false;
1966     bool AcceptableWithoutRecovery = false;
1967     NamedDecl *ND = Corrected.getFoundDecl();
1968     if (ND) {
1969       if (Corrected.isOverloaded()) {
1970         OverloadCandidateSet OCS(R.getNameLoc(),
1971                                  OverloadCandidateSet::CSK_Normal);
1972         OverloadCandidateSet::iterator Best;
1973         for (NamedDecl *CD : Corrected) {
1974           if (FunctionTemplateDecl *FTD =
1975                    dyn_cast<FunctionTemplateDecl>(CD))
1976             AddTemplateOverloadCandidate(
1977                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1978                 Args, OCS);
1979           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1980             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1981               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1982                                    Args, OCS);
1983         }
1984         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1985         case OR_Success:
1986           ND = Best->FoundDecl;
1987           Corrected.setCorrectionDecl(ND);
1988           break;
1989         default:
1990           // FIXME: Arbitrarily pick the first declaration for the note.
1991           Corrected.setCorrectionDecl(ND);
1992           break;
1993         }
1994       }
1995       R.addDecl(ND);
1996       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1997         CXXRecordDecl *Record = nullptr;
1998         if (Corrected.getCorrectionSpecifier()) {
1999           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2000           Record = Ty->getAsCXXRecordDecl();
2001         }
2002         if (!Record)
2003           Record = cast<CXXRecordDecl>(
2004               ND->getDeclContext()->getRedeclContext());
2005         R.setNamingClass(Record);
2006       }
2007 
2008       auto *UnderlyingND = ND->getUnderlyingDecl();
2009       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2010                                isa<FunctionTemplateDecl>(UnderlyingND);
2011       // FIXME: If we ended up with a typo for a type name or
2012       // Objective-C class name, we're in trouble because the parser
2013       // is in the wrong place to recover. Suggest the typo
2014       // correction, but don't make it a fix-it since we're not going
2015       // to recover well anyway.
2016       AcceptableWithoutRecovery =
2017           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2018     } else {
2019       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2020       // because we aren't able to recover.
2021       AcceptableWithoutRecovery = true;
2022     }
2023 
2024     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2025       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2026                             ? diag::note_implicit_param_decl
2027                             : diag::note_previous_decl;
2028       if (SS.isEmpty())
2029         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2030                      PDiag(NoteID), AcceptableWithRecovery);
2031       else
2032         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2033                                   << Name << computeDeclContext(SS, false)
2034                                   << DroppedSpecifier << SS.getRange(),
2035                      PDiag(NoteID), AcceptableWithRecovery);
2036 
2037       // Tell the callee whether to try to recover.
2038       return !AcceptableWithRecovery;
2039     }
2040   }
2041   R.clear();
2042 
2043   // Emit a special diagnostic for failed member lookups.
2044   // FIXME: computing the declaration context might fail here (?)
2045   if (!SS.isEmpty()) {
2046     Diag(R.getNameLoc(), diag::err_no_member)
2047       << Name << computeDeclContext(SS, false)
2048       << SS.getRange();
2049     return true;
2050   }
2051 
2052   // Give up, we can't recover.
2053   Diag(R.getNameLoc(), diagnostic) << Name;
2054   return true;
2055 }
2056 
2057 /// In Microsoft mode, if we are inside a template class whose parent class has
2058 /// dependent base classes, and we can't resolve an unqualified identifier, then
2059 /// assume the identifier is a member of a dependent base class.  We can only
2060 /// recover successfully in static methods, instance methods, and other contexts
2061 /// where 'this' is available.  This doesn't precisely match MSVC's
2062 /// instantiation model, but it's close enough.
2063 static Expr *
2064 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2065                                DeclarationNameInfo &NameInfo,
2066                                SourceLocation TemplateKWLoc,
2067                                const TemplateArgumentListInfo *TemplateArgs) {
2068   // Only try to recover from lookup into dependent bases in static methods or
2069   // contexts where 'this' is available.
2070   QualType ThisType = S.getCurrentThisType();
2071   const CXXRecordDecl *RD = nullptr;
2072   if (!ThisType.isNull())
2073     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2074   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2075     RD = MD->getParent();
2076   if (!RD || !RD->hasAnyDependentBases())
2077     return nullptr;
2078 
2079   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2080   // is available, suggest inserting 'this->' as a fixit.
2081   SourceLocation Loc = NameInfo.getLoc();
2082   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2083   DB << NameInfo.getName() << RD;
2084 
2085   if (!ThisType.isNull()) {
2086     DB << FixItHint::CreateInsertion(Loc, "this->");
2087     return CXXDependentScopeMemberExpr::Create(
2088         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2089         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2090         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2091   }
2092 
2093   // Synthesize a fake NNS that points to the derived class.  This will
2094   // perform name lookup during template instantiation.
2095   CXXScopeSpec SS;
2096   auto *NNS =
2097       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2098   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2099   return DependentScopeDeclRefExpr::Create(
2100       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2101       TemplateArgs);
2102 }
2103 
2104 ExprResult
2105 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2106                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2107                         bool HasTrailingLParen, bool IsAddressOfOperand,
2108                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2109                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2110   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2111          "cannot be direct & operand and have a trailing lparen");
2112   if (SS.isInvalid())
2113     return ExprError();
2114 
2115   TemplateArgumentListInfo TemplateArgsBuffer;
2116 
2117   // Decompose the UnqualifiedId into the following data.
2118   DeclarationNameInfo NameInfo;
2119   const TemplateArgumentListInfo *TemplateArgs;
2120   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2121 
2122   DeclarationName Name = NameInfo.getName();
2123   IdentifierInfo *II = Name.getAsIdentifierInfo();
2124   SourceLocation NameLoc = NameInfo.getLoc();
2125 
2126   // C++ [temp.dep.expr]p3:
2127   //   An id-expression is type-dependent if it contains:
2128   //     -- an identifier that was declared with a dependent type,
2129   //        (note: handled after lookup)
2130   //     -- a template-id that is dependent,
2131   //        (note: handled in BuildTemplateIdExpr)
2132   //     -- a conversion-function-id that specifies a dependent type,
2133   //     -- a nested-name-specifier that contains a class-name that
2134   //        names a dependent type.
2135   // Determine whether this is a member of an unknown specialization;
2136   // we need to handle these differently.
2137   bool DependentID = false;
2138   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2139       Name.getCXXNameType()->isDependentType()) {
2140     DependentID = true;
2141   } else if (SS.isSet()) {
2142     if (DeclContext *DC = computeDeclContext(SS, false)) {
2143       if (RequireCompleteDeclContext(SS, DC))
2144         return ExprError();
2145     } else {
2146       DependentID = true;
2147     }
2148   }
2149 
2150   if (DependentID)
2151     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2152                                       IsAddressOfOperand, TemplateArgs);
2153 
2154   // Perform the required lookup.
2155   LookupResult R(*this, NameInfo,
2156                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2157                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2158   if (TemplateArgs) {
2159     // Lookup the template name again to correctly establish the context in
2160     // which it was found. This is really unfortunate as we already did the
2161     // lookup to determine that it was a template name in the first place. If
2162     // this becomes a performance hit, we can work harder to preserve those
2163     // results until we get here but it's likely not worth it.
2164     bool MemberOfUnknownSpecialization;
2165     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2166                        MemberOfUnknownSpecialization);
2167 
2168     if (MemberOfUnknownSpecialization ||
2169         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2170       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2171                                         IsAddressOfOperand, TemplateArgs);
2172   } else {
2173     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2174     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2175 
2176     // If the result might be in a dependent base class, this is a dependent
2177     // id-expression.
2178     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2179       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2180                                         IsAddressOfOperand, TemplateArgs);
2181 
2182     // If this reference is in an Objective-C method, then we need to do
2183     // some special Objective-C lookup, too.
2184     if (IvarLookupFollowUp) {
2185       ExprResult E(LookupInObjCMethod(R, S, II, true));
2186       if (E.isInvalid())
2187         return ExprError();
2188 
2189       if (Expr *Ex = E.getAs<Expr>())
2190         return Ex;
2191     }
2192   }
2193 
2194   if (R.isAmbiguous())
2195     return ExprError();
2196 
2197   // This could be an implicitly declared function reference (legal in C90,
2198   // extension in C99, forbidden in C++).
2199   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2200     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2201     if (D) R.addDecl(D);
2202   }
2203 
2204   // Determine whether this name might be a candidate for
2205   // argument-dependent lookup.
2206   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2207 
2208   if (R.empty() && !ADL) {
2209     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2210       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2211                                                    TemplateKWLoc, TemplateArgs))
2212         return E;
2213     }
2214 
2215     // Don't diagnose an empty lookup for inline assembly.
2216     if (IsInlineAsmIdentifier)
2217       return ExprError();
2218 
2219     // If this name wasn't predeclared and if this is not a function
2220     // call, diagnose the problem.
2221     TypoExpr *TE = nullptr;
2222     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2223         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2224     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2225     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2226            "Typo correction callback misconfigured");
2227     if (CCC) {
2228       // Make sure the callback knows what the typo being diagnosed is.
2229       CCC->setTypoName(II);
2230       if (SS.isValid())
2231         CCC->setTypoNNS(SS.getScopeRep());
2232     }
2233     if (DiagnoseEmptyLookup(S, SS, R,
2234                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2235                             nullptr, None, &TE)) {
2236       if (TE && KeywordReplacement) {
2237         auto &State = getTypoExprState(TE);
2238         auto BestTC = State.Consumer->getNextCorrection();
2239         if (BestTC.isKeyword()) {
2240           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2241           if (State.DiagHandler)
2242             State.DiagHandler(BestTC);
2243           KeywordReplacement->startToken();
2244           KeywordReplacement->setKind(II->getTokenID());
2245           KeywordReplacement->setIdentifierInfo(II);
2246           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2247           // Clean up the state associated with the TypoExpr, since it has
2248           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2249           clearDelayedTypo(TE);
2250           // Signal that a correction to a keyword was performed by returning a
2251           // valid-but-null ExprResult.
2252           return (Expr*)nullptr;
2253         }
2254         State.Consumer->resetCorrectionStream();
2255       }
2256       return TE ? TE : ExprError();
2257     }
2258 
2259     assert(!R.empty() &&
2260            "DiagnoseEmptyLookup returned false but added no results");
2261 
2262     // If we found an Objective-C instance variable, let
2263     // LookupInObjCMethod build the appropriate expression to
2264     // reference the ivar.
2265     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2266       R.clear();
2267       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2268       // In a hopelessly buggy code, Objective-C instance variable
2269       // lookup fails and no expression will be built to reference it.
2270       if (!E.isInvalid() && !E.get())
2271         return ExprError();
2272       return E;
2273     }
2274   }
2275 
2276   // This is guaranteed from this point on.
2277   assert(!R.empty() || ADL);
2278 
2279   // Check whether this might be a C++ implicit instance member access.
2280   // C++ [class.mfct.non-static]p3:
2281   //   When an id-expression that is not part of a class member access
2282   //   syntax and not used to form a pointer to member is used in the
2283   //   body of a non-static member function of class X, if name lookup
2284   //   resolves the name in the id-expression to a non-static non-type
2285   //   member of some class C, the id-expression is transformed into a
2286   //   class member access expression using (*this) as the
2287   //   postfix-expression to the left of the . operator.
2288   //
2289   // But we don't actually need to do this for '&' operands if R
2290   // resolved to a function or overloaded function set, because the
2291   // expression is ill-formed if it actually works out to be a
2292   // non-static member function:
2293   //
2294   // C++ [expr.ref]p4:
2295   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2296   //   [t]he expression can be used only as the left-hand operand of a
2297   //   member function call.
2298   //
2299   // There are other safeguards against such uses, but it's important
2300   // to get this right here so that we don't end up making a
2301   // spuriously dependent expression if we're inside a dependent
2302   // instance method.
2303   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2304     bool MightBeImplicitMember;
2305     if (!IsAddressOfOperand)
2306       MightBeImplicitMember = true;
2307     else if (!SS.isEmpty())
2308       MightBeImplicitMember = false;
2309     else if (R.isOverloadedResult())
2310       MightBeImplicitMember = false;
2311     else if (R.isUnresolvableResult())
2312       MightBeImplicitMember = true;
2313     else
2314       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2315                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2316                               isa<MSPropertyDecl>(R.getFoundDecl());
2317 
2318     if (MightBeImplicitMember)
2319       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2320                                              R, TemplateArgs, S);
2321   }
2322 
2323   if (TemplateArgs || TemplateKWLoc.isValid()) {
2324 
2325     // In C++1y, if this is a variable template id, then check it
2326     // in BuildTemplateIdExpr().
2327     // The single lookup result must be a variable template declaration.
2328     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2329         Id.TemplateId->Kind == TNK_Var_template) {
2330       assert(R.getAsSingle<VarTemplateDecl>() &&
2331              "There should only be one declaration found.");
2332     }
2333 
2334     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2335   }
2336 
2337   return BuildDeclarationNameExpr(SS, R, ADL);
2338 }
2339 
2340 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2341 /// declaration name, generally during template instantiation.
2342 /// There's a large number of things which don't need to be done along
2343 /// this path.
2344 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2345     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2346     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2347   DeclContext *DC = computeDeclContext(SS, false);
2348   if (!DC)
2349     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2350                                      NameInfo, /*TemplateArgs=*/nullptr);
2351 
2352   if (RequireCompleteDeclContext(SS, DC))
2353     return ExprError();
2354 
2355   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2356   LookupQualifiedName(R, DC);
2357 
2358   if (R.isAmbiguous())
2359     return ExprError();
2360 
2361   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2362     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2363                                      NameInfo, /*TemplateArgs=*/nullptr);
2364 
2365   if (R.empty()) {
2366     Diag(NameInfo.getLoc(), diag::err_no_member)
2367       << NameInfo.getName() << DC << SS.getRange();
2368     return ExprError();
2369   }
2370 
2371   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2372     // Diagnose a missing typename if this resolved unambiguously to a type in
2373     // a dependent context.  If we can recover with a type, downgrade this to
2374     // a warning in Microsoft compatibility mode.
2375     unsigned DiagID = diag::err_typename_missing;
2376     if (RecoveryTSI && getLangOpts().MSVCCompat)
2377       DiagID = diag::ext_typename_missing;
2378     SourceLocation Loc = SS.getBeginLoc();
2379     auto D = Diag(Loc, DiagID);
2380     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2381       << SourceRange(Loc, NameInfo.getEndLoc());
2382 
2383     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2384     // context.
2385     if (!RecoveryTSI)
2386       return ExprError();
2387 
2388     // Only issue the fixit if we're prepared to recover.
2389     D << FixItHint::CreateInsertion(Loc, "typename ");
2390 
2391     // Recover by pretending this was an elaborated type.
2392     QualType Ty = Context.getTypeDeclType(TD);
2393     TypeLocBuilder TLB;
2394     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2395 
2396     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2397     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2398     QTL.setElaboratedKeywordLoc(SourceLocation());
2399     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2400 
2401     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2402 
2403     return ExprEmpty();
2404   }
2405 
2406   // Defend against this resolving to an implicit member access. We usually
2407   // won't get here if this might be a legitimate a class member (we end up in
2408   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2409   // a pointer-to-member or in an unevaluated context in C++11.
2410   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2411     return BuildPossibleImplicitMemberExpr(SS,
2412                                            /*TemplateKWLoc=*/SourceLocation(),
2413                                            R, /*TemplateArgs=*/nullptr, S);
2414 
2415   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2416 }
2417 
2418 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2419 /// detected that we're currently inside an ObjC method.  Perform some
2420 /// additional lookup.
2421 ///
2422 /// Ideally, most of this would be done by lookup, but there's
2423 /// actually quite a lot of extra work involved.
2424 ///
2425 /// Returns a null sentinel to indicate trivial success.
2426 ExprResult
2427 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2428                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2429   SourceLocation Loc = Lookup.getNameLoc();
2430   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2431 
2432   // Check for error condition which is already reported.
2433   if (!CurMethod)
2434     return ExprError();
2435 
2436   // There are two cases to handle here.  1) scoped lookup could have failed,
2437   // in which case we should look for an ivar.  2) scoped lookup could have
2438   // found a decl, but that decl is outside the current instance method (i.e.
2439   // a global variable).  In these two cases, we do a lookup for an ivar with
2440   // this name, if the lookup sucedes, we replace it our current decl.
2441 
2442   // If we're in a class method, we don't normally want to look for
2443   // ivars.  But if we don't find anything else, and there's an
2444   // ivar, that's an error.
2445   bool IsClassMethod = CurMethod->isClassMethod();
2446 
2447   bool LookForIvars;
2448   if (Lookup.empty())
2449     LookForIvars = true;
2450   else if (IsClassMethod)
2451     LookForIvars = false;
2452   else
2453     LookForIvars = (Lookup.isSingleResult() &&
2454                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2455   ObjCInterfaceDecl *IFace = nullptr;
2456   if (LookForIvars) {
2457     IFace = CurMethod->getClassInterface();
2458     ObjCInterfaceDecl *ClassDeclared;
2459     ObjCIvarDecl *IV = nullptr;
2460     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2461       // Diagnose using an ivar in a class method.
2462       if (IsClassMethod)
2463         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2464                          << IV->getDeclName());
2465 
2466       // If we're referencing an invalid decl, just return this as a silent
2467       // error node.  The error diagnostic was already emitted on the decl.
2468       if (IV->isInvalidDecl())
2469         return ExprError();
2470 
2471       // Check if referencing a field with __attribute__((deprecated)).
2472       if (DiagnoseUseOfDecl(IV, Loc))
2473         return ExprError();
2474 
2475       // Diagnose the use of an ivar outside of the declaring class.
2476       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2477           !declaresSameEntity(ClassDeclared, IFace) &&
2478           !getLangOpts().DebuggerSupport)
2479         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2480 
2481       // FIXME: This should use a new expr for a direct reference, don't
2482       // turn this into Self->ivar, just return a BareIVarExpr or something.
2483       IdentifierInfo &II = Context.Idents.get("self");
2484       UnqualifiedId SelfName;
2485       SelfName.setIdentifier(&II, SourceLocation());
2486       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2487       CXXScopeSpec SelfScopeSpec;
2488       SourceLocation TemplateKWLoc;
2489       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2490                                               SelfName, false, false);
2491       if (SelfExpr.isInvalid())
2492         return ExprError();
2493 
2494       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2495       if (SelfExpr.isInvalid())
2496         return ExprError();
2497 
2498       MarkAnyDeclReferenced(Loc, IV, true);
2499 
2500       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2501       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2502           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2503         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2504 
2505       ObjCIvarRefExpr *Result = new (Context)
2506           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2507                           IV->getLocation(), SelfExpr.get(), true, true);
2508 
2509       if (getLangOpts().ObjCAutoRefCount) {
2510         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2511           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2512             recordUseOfEvaluatedWeak(Result);
2513         }
2514         if (CurContext->isClosure())
2515           Diag(Loc, diag::warn_implicitly_retains_self)
2516             << FixItHint::CreateInsertion(Loc, "self->");
2517       }
2518 
2519       return Result;
2520     }
2521   } else if (CurMethod->isInstanceMethod()) {
2522     // We should warn if a local variable hides an ivar.
2523     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2524       ObjCInterfaceDecl *ClassDeclared;
2525       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2526         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2527             declaresSameEntity(IFace, ClassDeclared))
2528           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2529       }
2530     }
2531   } else if (Lookup.isSingleResult() &&
2532              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2533     // If accessing a stand-alone ivar in a class method, this is an error.
2534     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2535       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2536                        << IV->getDeclName());
2537   }
2538 
2539   if (Lookup.empty() && II && AllowBuiltinCreation) {
2540     // FIXME. Consolidate this with similar code in LookupName.
2541     if (unsigned BuiltinID = II->getBuiltinID()) {
2542       if (!(getLangOpts().CPlusPlus &&
2543             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2544         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2545                                            S, Lookup.isForRedeclaration(),
2546                                            Lookup.getNameLoc());
2547         if (D) Lookup.addDecl(D);
2548       }
2549     }
2550   }
2551   // Sentinel value saying that we didn't do anything special.
2552   return ExprResult((Expr *)nullptr);
2553 }
2554 
2555 /// \brief Cast a base object to a member's actual type.
2556 ///
2557 /// Logically this happens in three phases:
2558 ///
2559 /// * First we cast from the base type to the naming class.
2560 ///   The naming class is the class into which we were looking
2561 ///   when we found the member;  it's the qualifier type if a
2562 ///   qualifier was provided, and otherwise it's the base type.
2563 ///
2564 /// * Next we cast from the naming class to the declaring class.
2565 ///   If the member we found was brought into a class's scope by
2566 ///   a using declaration, this is that class;  otherwise it's
2567 ///   the class declaring the member.
2568 ///
2569 /// * Finally we cast from the declaring class to the "true"
2570 ///   declaring class of the member.  This conversion does not
2571 ///   obey access control.
2572 ExprResult
2573 Sema::PerformObjectMemberConversion(Expr *From,
2574                                     NestedNameSpecifier *Qualifier,
2575                                     NamedDecl *FoundDecl,
2576                                     NamedDecl *Member) {
2577   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2578   if (!RD)
2579     return From;
2580 
2581   QualType DestRecordType;
2582   QualType DestType;
2583   QualType FromRecordType;
2584   QualType FromType = From->getType();
2585   bool PointerConversions = false;
2586   if (isa<FieldDecl>(Member)) {
2587     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2588 
2589     if (FromType->getAs<PointerType>()) {
2590       DestType = Context.getPointerType(DestRecordType);
2591       FromRecordType = FromType->getPointeeType();
2592       PointerConversions = true;
2593     } else {
2594       DestType = DestRecordType;
2595       FromRecordType = FromType;
2596     }
2597   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2598     if (Method->isStatic())
2599       return From;
2600 
2601     DestType = Method->getThisType(Context);
2602     DestRecordType = DestType->getPointeeType();
2603 
2604     if (FromType->getAs<PointerType>()) {
2605       FromRecordType = FromType->getPointeeType();
2606       PointerConversions = true;
2607     } else {
2608       FromRecordType = FromType;
2609       DestType = DestRecordType;
2610     }
2611   } else {
2612     // No conversion necessary.
2613     return From;
2614   }
2615 
2616   if (DestType->isDependentType() || FromType->isDependentType())
2617     return From;
2618 
2619   // If the unqualified types are the same, no conversion is necessary.
2620   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2621     return From;
2622 
2623   SourceRange FromRange = From->getSourceRange();
2624   SourceLocation FromLoc = FromRange.getBegin();
2625 
2626   ExprValueKind VK = From->getValueKind();
2627 
2628   // C++ [class.member.lookup]p8:
2629   //   [...] Ambiguities can often be resolved by qualifying a name with its
2630   //   class name.
2631   //
2632   // If the member was a qualified name and the qualified referred to a
2633   // specific base subobject type, we'll cast to that intermediate type
2634   // first and then to the object in which the member is declared. That allows
2635   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2636   //
2637   //   class Base { public: int x; };
2638   //   class Derived1 : public Base { };
2639   //   class Derived2 : public Base { };
2640   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2641   //
2642   //   void VeryDerived::f() {
2643   //     x = 17; // error: ambiguous base subobjects
2644   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2645   //   }
2646   if (Qualifier && Qualifier->getAsType()) {
2647     QualType QType = QualType(Qualifier->getAsType(), 0);
2648     assert(QType->isRecordType() && "lookup done with non-record type");
2649 
2650     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2651 
2652     // In C++98, the qualifier type doesn't actually have to be a base
2653     // type of the object type, in which case we just ignore it.
2654     // Otherwise build the appropriate casts.
2655     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2656       CXXCastPath BasePath;
2657       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2658                                        FromLoc, FromRange, &BasePath))
2659         return ExprError();
2660 
2661       if (PointerConversions)
2662         QType = Context.getPointerType(QType);
2663       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2664                                VK, &BasePath).get();
2665 
2666       FromType = QType;
2667       FromRecordType = QRecordType;
2668 
2669       // If the qualifier type was the same as the destination type,
2670       // we're done.
2671       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2672         return From;
2673     }
2674   }
2675 
2676   bool IgnoreAccess = false;
2677 
2678   // If we actually found the member through a using declaration, cast
2679   // down to the using declaration's type.
2680   //
2681   // Pointer equality is fine here because only one declaration of a
2682   // class ever has member declarations.
2683   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2684     assert(isa<UsingShadowDecl>(FoundDecl));
2685     QualType URecordType = Context.getTypeDeclType(
2686                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2687 
2688     // We only need to do this if the naming-class to declaring-class
2689     // conversion is non-trivial.
2690     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2691       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2692       CXXCastPath BasePath;
2693       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2694                                        FromLoc, FromRange, &BasePath))
2695         return ExprError();
2696 
2697       QualType UType = URecordType;
2698       if (PointerConversions)
2699         UType = Context.getPointerType(UType);
2700       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2701                                VK, &BasePath).get();
2702       FromType = UType;
2703       FromRecordType = URecordType;
2704     }
2705 
2706     // We don't do access control for the conversion from the
2707     // declaring class to the true declaring class.
2708     IgnoreAccess = true;
2709   }
2710 
2711   CXXCastPath BasePath;
2712   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2713                                    FromLoc, FromRange, &BasePath,
2714                                    IgnoreAccess))
2715     return ExprError();
2716 
2717   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2718                            VK, &BasePath);
2719 }
2720 
2721 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2722                                       const LookupResult &R,
2723                                       bool HasTrailingLParen) {
2724   // Only when used directly as the postfix-expression of a call.
2725   if (!HasTrailingLParen)
2726     return false;
2727 
2728   // Never if a scope specifier was provided.
2729   if (SS.isSet())
2730     return false;
2731 
2732   // Only in C++ or ObjC++.
2733   if (!getLangOpts().CPlusPlus)
2734     return false;
2735 
2736   // Turn off ADL when we find certain kinds of declarations during
2737   // normal lookup:
2738   for (NamedDecl *D : R) {
2739     // C++0x [basic.lookup.argdep]p3:
2740     //     -- a declaration of a class member
2741     // Since using decls preserve this property, we check this on the
2742     // original decl.
2743     if (D->isCXXClassMember())
2744       return false;
2745 
2746     // C++0x [basic.lookup.argdep]p3:
2747     //     -- a block-scope function declaration that is not a
2748     //        using-declaration
2749     // NOTE: we also trigger this for function templates (in fact, we
2750     // don't check the decl type at all, since all other decl types
2751     // turn off ADL anyway).
2752     if (isa<UsingShadowDecl>(D))
2753       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2754     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2755       return false;
2756 
2757     // C++0x [basic.lookup.argdep]p3:
2758     //     -- a declaration that is neither a function or a function
2759     //        template
2760     // And also for builtin functions.
2761     if (isa<FunctionDecl>(D)) {
2762       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2763 
2764       // But also builtin functions.
2765       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2766         return false;
2767     } else if (!isa<FunctionTemplateDecl>(D))
2768       return false;
2769   }
2770 
2771   return true;
2772 }
2773 
2774 
2775 /// Diagnoses obvious problems with the use of the given declaration
2776 /// as an expression.  This is only actually called for lookups that
2777 /// were not overloaded, and it doesn't promise that the declaration
2778 /// will in fact be used.
2779 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2780   if (isa<TypedefNameDecl>(D)) {
2781     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2782     return true;
2783   }
2784 
2785   if (isa<ObjCInterfaceDecl>(D)) {
2786     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2787     return true;
2788   }
2789 
2790   if (isa<NamespaceDecl>(D)) {
2791     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2792     return true;
2793   }
2794 
2795   return false;
2796 }
2797 
2798 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2799                                           LookupResult &R, bool NeedsADL,
2800                                           bool AcceptInvalidDecl) {
2801   // If this is a single, fully-resolved result and we don't need ADL,
2802   // just build an ordinary singleton decl ref.
2803   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2804     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2805                                     R.getRepresentativeDecl(), nullptr,
2806                                     AcceptInvalidDecl);
2807 
2808   // We only need to check the declaration if there's exactly one
2809   // result, because in the overloaded case the results can only be
2810   // functions and function templates.
2811   if (R.isSingleResult() &&
2812       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2813     return ExprError();
2814 
2815   // Otherwise, just build an unresolved lookup expression.  Suppress
2816   // any lookup-related diagnostics; we'll hash these out later, when
2817   // we've picked a target.
2818   R.suppressDiagnostics();
2819 
2820   UnresolvedLookupExpr *ULE
2821     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2822                                    SS.getWithLocInContext(Context),
2823                                    R.getLookupNameInfo(),
2824                                    NeedsADL, R.isOverloadedResult(),
2825                                    R.begin(), R.end());
2826 
2827   return ULE;
2828 }
2829 
2830 static void
2831 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2832                                    ValueDecl *var, DeclContext *DC);
2833 
2834 /// \brief Complete semantic analysis for a reference to the given declaration.
2835 ExprResult Sema::BuildDeclarationNameExpr(
2836     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2837     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2838     bool AcceptInvalidDecl) {
2839   assert(D && "Cannot refer to a NULL declaration");
2840   assert(!isa<FunctionTemplateDecl>(D) &&
2841          "Cannot refer unambiguously to a function template");
2842 
2843   SourceLocation Loc = NameInfo.getLoc();
2844   if (CheckDeclInExpr(*this, Loc, D))
2845     return ExprError();
2846 
2847   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2848     // Specifically diagnose references to class templates that are missing
2849     // a template argument list.
2850     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2851                                            << Template << SS.getRange();
2852     Diag(Template->getLocation(), diag::note_template_decl_here);
2853     return ExprError();
2854   }
2855 
2856   // Make sure that we're referring to a value.
2857   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2858   if (!VD) {
2859     Diag(Loc, diag::err_ref_non_value)
2860       << D << SS.getRange();
2861     Diag(D->getLocation(), diag::note_declared_at);
2862     return ExprError();
2863   }
2864 
2865   // Check whether this declaration can be used. Note that we suppress
2866   // this check when we're going to perform argument-dependent lookup
2867   // on this function name, because this might not be the function
2868   // that overload resolution actually selects.
2869   if (DiagnoseUseOfDecl(VD, Loc))
2870     return ExprError();
2871 
2872   // Only create DeclRefExpr's for valid Decl's.
2873   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2874     return ExprError();
2875 
2876   // Handle members of anonymous structs and unions.  If we got here,
2877   // and the reference is to a class member indirect field, then this
2878   // must be the subject of a pointer-to-member expression.
2879   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2880     if (!indirectField->isCXXClassMember())
2881       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2882                                                       indirectField);
2883 
2884   {
2885     QualType type = VD->getType();
2886     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2887       // C++ [except.spec]p17:
2888       //   An exception-specification is considered to be needed when:
2889       //   - in an expression, the function is the unique lookup result or
2890       //     the selected member of a set of overloaded functions.
2891       ResolveExceptionSpec(Loc, FPT);
2892       type = VD->getType();
2893     }
2894     ExprValueKind valueKind = VK_RValue;
2895 
2896     switch (D->getKind()) {
2897     // Ignore all the non-ValueDecl kinds.
2898 #define ABSTRACT_DECL(kind)
2899 #define VALUE(type, base)
2900 #define DECL(type, base) \
2901     case Decl::type:
2902 #include "clang/AST/DeclNodes.inc"
2903       llvm_unreachable("invalid value decl kind");
2904 
2905     // These shouldn't make it here.
2906     case Decl::ObjCAtDefsField:
2907     case Decl::ObjCIvar:
2908       llvm_unreachable("forming non-member reference to ivar?");
2909 
2910     // Enum constants are always r-values and never references.
2911     // Unresolved using declarations are dependent.
2912     case Decl::EnumConstant:
2913     case Decl::UnresolvedUsingValue:
2914     case Decl::OMPDeclareReduction:
2915       valueKind = VK_RValue;
2916       break;
2917 
2918     // Fields and indirect fields that got here must be for
2919     // pointer-to-member expressions; we just call them l-values for
2920     // internal consistency, because this subexpression doesn't really
2921     // exist in the high-level semantics.
2922     case Decl::Field:
2923     case Decl::IndirectField:
2924       assert(getLangOpts().CPlusPlus &&
2925              "building reference to field in C?");
2926 
2927       // These can't have reference type in well-formed programs, but
2928       // for internal consistency we do this anyway.
2929       type = type.getNonReferenceType();
2930       valueKind = VK_LValue;
2931       break;
2932 
2933     // Non-type template parameters are either l-values or r-values
2934     // depending on the type.
2935     case Decl::NonTypeTemplateParm: {
2936       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2937         type = reftype->getPointeeType();
2938         valueKind = VK_LValue; // even if the parameter is an r-value reference
2939         break;
2940       }
2941 
2942       // For non-references, we need to strip qualifiers just in case
2943       // the template parameter was declared as 'const int' or whatever.
2944       valueKind = VK_RValue;
2945       type = type.getUnqualifiedType();
2946       break;
2947     }
2948 
2949     case Decl::Var:
2950     case Decl::VarTemplateSpecialization:
2951     case Decl::VarTemplatePartialSpecialization:
2952     case Decl::Decomposition:
2953     case Decl::OMPCapturedExpr:
2954       // In C, "extern void blah;" is valid and is an r-value.
2955       if (!getLangOpts().CPlusPlus &&
2956           !type.hasQualifiers() &&
2957           type->isVoidType()) {
2958         valueKind = VK_RValue;
2959         break;
2960       }
2961       // fallthrough
2962 
2963     case Decl::ImplicitParam:
2964     case Decl::ParmVar: {
2965       // These are always l-values.
2966       valueKind = VK_LValue;
2967       type = type.getNonReferenceType();
2968 
2969       // FIXME: Does the addition of const really only apply in
2970       // potentially-evaluated contexts? Since the variable isn't actually
2971       // captured in an unevaluated context, it seems that the answer is no.
2972       if (!isUnevaluatedContext()) {
2973         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2974         if (!CapturedType.isNull())
2975           type = CapturedType;
2976       }
2977 
2978       break;
2979     }
2980 
2981     case Decl::Binding: {
2982       // These are always lvalues.
2983       valueKind = VK_LValue;
2984       type = type.getNonReferenceType();
2985       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2986       // decides how that's supposed to work.
2987       auto *BD = cast<BindingDecl>(VD);
2988       if (BD->getDeclContext()->isFunctionOrMethod() &&
2989           BD->getDeclContext() != CurContext)
2990         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2991       break;
2992     }
2993 
2994     case Decl::Function: {
2995       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2996         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2997           type = Context.BuiltinFnTy;
2998           valueKind = VK_RValue;
2999           break;
3000         }
3001       }
3002 
3003       const FunctionType *fty = type->castAs<FunctionType>();
3004 
3005       // If we're referring to a function with an __unknown_anytype
3006       // result type, make the entire expression __unknown_anytype.
3007       if (fty->getReturnType() == Context.UnknownAnyTy) {
3008         type = Context.UnknownAnyTy;
3009         valueKind = VK_RValue;
3010         break;
3011       }
3012 
3013       // Functions are l-values in C++.
3014       if (getLangOpts().CPlusPlus) {
3015         valueKind = VK_LValue;
3016         break;
3017       }
3018 
3019       // C99 DR 316 says that, if a function type comes from a
3020       // function definition (without a prototype), that type is only
3021       // used for checking compatibility. Therefore, when referencing
3022       // the function, we pretend that we don't have the full function
3023       // type.
3024       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3025           isa<FunctionProtoType>(fty))
3026         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3027                                               fty->getExtInfo());
3028 
3029       // Functions are r-values in C.
3030       valueKind = VK_RValue;
3031       break;
3032     }
3033 
3034     case Decl::MSProperty:
3035       valueKind = VK_LValue;
3036       break;
3037 
3038     case Decl::CXXMethod:
3039       // If we're referring to a method with an __unknown_anytype
3040       // result type, make the entire expression __unknown_anytype.
3041       // This should only be possible with a type written directly.
3042       if (const FunctionProtoType *proto
3043             = dyn_cast<FunctionProtoType>(VD->getType()))
3044         if (proto->getReturnType() == Context.UnknownAnyTy) {
3045           type = Context.UnknownAnyTy;
3046           valueKind = VK_RValue;
3047           break;
3048         }
3049 
3050       // C++ methods are l-values if static, r-values if non-static.
3051       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3052         valueKind = VK_LValue;
3053         break;
3054       }
3055       // fallthrough
3056 
3057     case Decl::CXXConversion:
3058     case Decl::CXXDestructor:
3059     case Decl::CXXConstructor:
3060       valueKind = VK_RValue;
3061       break;
3062     }
3063 
3064     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3065                             TemplateArgs);
3066   }
3067 }
3068 
3069 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3070                                     SmallString<32> &Target) {
3071   Target.resize(CharByteWidth * (Source.size() + 1));
3072   char *ResultPtr = &Target[0];
3073   const llvm::UTF8 *ErrorPtr;
3074   bool success =
3075       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3076   (void)success;
3077   assert(success);
3078   Target.resize(ResultPtr - &Target[0]);
3079 }
3080 
3081 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3082                                      PredefinedExpr::IdentType IT) {
3083   // Pick the current block, lambda, captured statement or function.
3084   Decl *currentDecl = nullptr;
3085   if (const BlockScopeInfo *BSI = getCurBlock())
3086     currentDecl = BSI->TheDecl;
3087   else if (const LambdaScopeInfo *LSI = getCurLambda())
3088     currentDecl = LSI->CallOperator;
3089   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3090     currentDecl = CSI->TheCapturedDecl;
3091   else
3092     currentDecl = getCurFunctionOrMethodDecl();
3093 
3094   if (!currentDecl) {
3095     Diag(Loc, diag::ext_predef_outside_function);
3096     currentDecl = Context.getTranslationUnitDecl();
3097   }
3098 
3099   QualType ResTy;
3100   StringLiteral *SL = nullptr;
3101   if (cast<DeclContext>(currentDecl)->isDependentContext())
3102     ResTy = Context.DependentTy;
3103   else {
3104     // Pre-defined identifiers are of type char[x], where x is the length of
3105     // the string.
3106     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3107     unsigned Length = Str.length();
3108 
3109     llvm::APInt LengthI(32, Length + 1);
3110     if (IT == PredefinedExpr::LFunction) {
3111       ResTy = Context.WideCharTy.withConst();
3112       SmallString<32> RawChars;
3113       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3114                               Str, RawChars);
3115       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3116                                            /*IndexTypeQuals*/ 0);
3117       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3118                                  /*Pascal*/ false, ResTy, Loc);
3119     } else {
3120       ResTy = Context.CharTy.withConst();
3121       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3122                                            /*IndexTypeQuals*/ 0);
3123       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3124                                  /*Pascal*/ false, ResTy, Loc);
3125     }
3126   }
3127 
3128   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3129 }
3130 
3131 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3132   PredefinedExpr::IdentType IT;
3133 
3134   switch (Kind) {
3135   default: llvm_unreachable("Unknown simple primary expr!");
3136   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3137   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3138   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3139   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3140   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3141   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3142   }
3143 
3144   return BuildPredefinedExpr(Loc, IT);
3145 }
3146 
3147 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3148   SmallString<16> CharBuffer;
3149   bool Invalid = false;
3150   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3151   if (Invalid)
3152     return ExprError();
3153 
3154   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3155                             PP, Tok.getKind());
3156   if (Literal.hadError())
3157     return ExprError();
3158 
3159   QualType Ty;
3160   if (Literal.isWide())
3161     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3162   else if (Literal.isUTF16())
3163     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3164   else if (Literal.isUTF32())
3165     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3166   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3167     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3168   else
3169     Ty = Context.CharTy;  // 'x' -> char in C++
3170 
3171   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3172   if (Literal.isWide())
3173     Kind = CharacterLiteral::Wide;
3174   else if (Literal.isUTF16())
3175     Kind = CharacterLiteral::UTF16;
3176   else if (Literal.isUTF32())
3177     Kind = CharacterLiteral::UTF32;
3178   else if (Literal.isUTF8())
3179     Kind = CharacterLiteral::UTF8;
3180 
3181   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3182                                              Tok.getLocation());
3183 
3184   if (Literal.getUDSuffix().empty())
3185     return Lit;
3186 
3187   // We're building a user-defined literal.
3188   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3189   SourceLocation UDSuffixLoc =
3190     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3191 
3192   // Make sure we're allowed user-defined literals here.
3193   if (!UDLScope)
3194     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3195 
3196   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3197   //   operator "" X (ch)
3198   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3199                                         Lit, Tok.getLocation());
3200 }
3201 
3202 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3203   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3204   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3205                                 Context.IntTy, Loc);
3206 }
3207 
3208 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3209                                   QualType Ty, SourceLocation Loc) {
3210   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3211 
3212   using llvm::APFloat;
3213   APFloat Val(Format);
3214 
3215   APFloat::opStatus result = Literal.GetFloatValue(Val);
3216 
3217   // Overflow is always an error, but underflow is only an error if
3218   // we underflowed to zero (APFloat reports denormals as underflow).
3219   if ((result & APFloat::opOverflow) ||
3220       ((result & APFloat::opUnderflow) && Val.isZero())) {
3221     unsigned diagnostic;
3222     SmallString<20> buffer;
3223     if (result & APFloat::opOverflow) {
3224       diagnostic = diag::warn_float_overflow;
3225       APFloat::getLargest(Format).toString(buffer);
3226     } else {
3227       diagnostic = diag::warn_float_underflow;
3228       APFloat::getSmallest(Format).toString(buffer);
3229     }
3230 
3231     S.Diag(Loc, diagnostic)
3232       << Ty
3233       << StringRef(buffer.data(), buffer.size());
3234   }
3235 
3236   bool isExact = (result == APFloat::opOK);
3237   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3238 }
3239 
3240 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3241   assert(E && "Invalid expression");
3242 
3243   if (E->isValueDependent())
3244     return false;
3245 
3246   QualType QT = E->getType();
3247   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3248     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3249     return true;
3250   }
3251 
3252   llvm::APSInt ValueAPS;
3253   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3254 
3255   if (R.isInvalid())
3256     return true;
3257 
3258   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3259   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3260     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3261         << ValueAPS.toString(10) << ValueIsPositive;
3262     return true;
3263   }
3264 
3265   return false;
3266 }
3267 
3268 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3269   // Fast path for a single digit (which is quite common).  A single digit
3270   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3271   if (Tok.getLength() == 1) {
3272     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3273     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3274   }
3275 
3276   SmallString<128> SpellingBuffer;
3277   // NumericLiteralParser wants to overread by one character.  Add padding to
3278   // the buffer in case the token is copied to the buffer.  If getSpelling()
3279   // returns a StringRef to the memory buffer, it should have a null char at
3280   // the EOF, so it is also safe.
3281   SpellingBuffer.resize(Tok.getLength() + 1);
3282 
3283   // Get the spelling of the token, which eliminates trigraphs, etc.
3284   bool Invalid = false;
3285   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3286   if (Invalid)
3287     return ExprError();
3288 
3289   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3290   if (Literal.hadError)
3291     return ExprError();
3292 
3293   if (Literal.hasUDSuffix()) {
3294     // We're building a user-defined literal.
3295     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3296     SourceLocation UDSuffixLoc =
3297       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3298 
3299     // Make sure we're allowed user-defined literals here.
3300     if (!UDLScope)
3301       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3302 
3303     QualType CookedTy;
3304     if (Literal.isFloatingLiteral()) {
3305       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3306       // long double, the literal is treated as a call of the form
3307       //   operator "" X (f L)
3308       CookedTy = Context.LongDoubleTy;
3309     } else {
3310       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3311       // unsigned long long, the literal is treated as a call of the form
3312       //   operator "" X (n ULL)
3313       CookedTy = Context.UnsignedLongLongTy;
3314     }
3315 
3316     DeclarationName OpName =
3317       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3318     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3319     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3320 
3321     SourceLocation TokLoc = Tok.getLocation();
3322 
3323     // Perform literal operator lookup to determine if we're building a raw
3324     // literal or a cooked one.
3325     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3326     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3327                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3328                                   /*AllowStringTemplate*/false)) {
3329     case LOLR_Error:
3330       return ExprError();
3331 
3332     case LOLR_Cooked: {
3333       Expr *Lit;
3334       if (Literal.isFloatingLiteral()) {
3335         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3336       } else {
3337         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3338         if (Literal.GetIntegerValue(ResultVal))
3339           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3340               << /* Unsigned */ 1;
3341         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3342                                      Tok.getLocation());
3343       }
3344       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3345     }
3346 
3347     case LOLR_Raw: {
3348       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3349       // literal is treated as a call of the form
3350       //   operator "" X ("n")
3351       unsigned Length = Literal.getUDSuffixOffset();
3352       QualType StrTy = Context.getConstantArrayType(
3353           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3354           ArrayType::Normal, 0);
3355       Expr *Lit = StringLiteral::Create(
3356           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3357           /*Pascal*/false, StrTy, &TokLoc, 1);
3358       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3359     }
3360 
3361     case LOLR_Template: {
3362       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3363       // template), L is treated as a call fo the form
3364       //   operator "" X <'c1', 'c2', ... 'ck'>()
3365       // where n is the source character sequence c1 c2 ... ck.
3366       TemplateArgumentListInfo ExplicitArgs;
3367       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3368       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3369       llvm::APSInt Value(CharBits, CharIsUnsigned);
3370       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3371         Value = TokSpelling[I];
3372         TemplateArgument Arg(Context, Value, Context.CharTy);
3373         TemplateArgumentLocInfo ArgInfo;
3374         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3375       }
3376       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3377                                       &ExplicitArgs);
3378     }
3379     case LOLR_StringTemplate:
3380       llvm_unreachable("unexpected literal operator lookup result");
3381     }
3382   }
3383 
3384   Expr *Res;
3385 
3386   if (Literal.isFloatingLiteral()) {
3387     QualType Ty;
3388     if (Literal.isHalf){
3389       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3390         Ty = Context.HalfTy;
3391       else {
3392         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3393         return ExprError();
3394       }
3395     } else if (Literal.isFloat)
3396       Ty = Context.FloatTy;
3397     else if (Literal.isLong)
3398       Ty = Context.LongDoubleTy;
3399     else if (Literal.isFloat128)
3400       Ty = Context.Float128Ty;
3401     else
3402       Ty = Context.DoubleTy;
3403 
3404     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3405 
3406     if (Ty == Context.DoubleTy) {
3407       if (getLangOpts().SinglePrecisionConstants) {
3408         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3409         if (BTy->getKind() != BuiltinType::Float) {
3410           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3411         }
3412       } else if (getLangOpts().OpenCL &&
3413                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3414         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3415         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3416         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3417       }
3418     }
3419   } else if (!Literal.isIntegerLiteral()) {
3420     return ExprError();
3421   } else {
3422     QualType Ty;
3423 
3424     // 'long long' is a C99 or C++11 feature.
3425     if (!getLangOpts().C99 && Literal.isLongLong) {
3426       if (getLangOpts().CPlusPlus)
3427         Diag(Tok.getLocation(),
3428              getLangOpts().CPlusPlus11 ?
3429              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3430       else
3431         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3432     }
3433 
3434     // Get the value in the widest-possible width.
3435     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3436     llvm::APInt ResultVal(MaxWidth, 0);
3437 
3438     if (Literal.GetIntegerValue(ResultVal)) {
3439       // If this value didn't fit into uintmax_t, error and force to ull.
3440       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3441           << /* Unsigned */ 1;
3442       Ty = Context.UnsignedLongLongTy;
3443       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3444              "long long is not intmax_t?");
3445     } else {
3446       // If this value fits into a ULL, try to figure out what else it fits into
3447       // according to the rules of C99 6.4.4.1p5.
3448 
3449       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3450       // be an unsigned int.
3451       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3452 
3453       // Check from smallest to largest, picking the smallest type we can.
3454       unsigned Width = 0;
3455 
3456       // Microsoft specific integer suffixes are explicitly sized.
3457       if (Literal.MicrosoftInteger) {
3458         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3459           Width = 8;
3460           Ty = Context.CharTy;
3461         } else {
3462           Width = Literal.MicrosoftInteger;
3463           Ty = Context.getIntTypeForBitwidth(Width,
3464                                              /*Signed=*/!Literal.isUnsigned);
3465         }
3466       }
3467 
3468       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3469         // Are int/unsigned possibilities?
3470         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3471 
3472         // Does it fit in a unsigned int?
3473         if (ResultVal.isIntN(IntSize)) {
3474           // Does it fit in a signed int?
3475           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3476             Ty = Context.IntTy;
3477           else if (AllowUnsigned)
3478             Ty = Context.UnsignedIntTy;
3479           Width = IntSize;
3480         }
3481       }
3482 
3483       // Are long/unsigned long possibilities?
3484       if (Ty.isNull() && !Literal.isLongLong) {
3485         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3486 
3487         // Does it fit in a unsigned long?
3488         if (ResultVal.isIntN(LongSize)) {
3489           // Does it fit in a signed long?
3490           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3491             Ty = Context.LongTy;
3492           else if (AllowUnsigned)
3493             Ty = Context.UnsignedLongTy;
3494           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3495           // is compatible.
3496           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3497             const unsigned LongLongSize =
3498                 Context.getTargetInfo().getLongLongWidth();
3499             Diag(Tok.getLocation(),
3500                  getLangOpts().CPlusPlus
3501                      ? Literal.isLong
3502                            ? diag::warn_old_implicitly_unsigned_long_cxx
3503                            : /*C++98 UB*/ diag::
3504                                  ext_old_implicitly_unsigned_long_cxx
3505                      : diag::warn_old_implicitly_unsigned_long)
3506                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3507                                             : /*will be ill-formed*/ 1);
3508             Ty = Context.UnsignedLongTy;
3509           }
3510           Width = LongSize;
3511         }
3512       }
3513 
3514       // Check long long if needed.
3515       if (Ty.isNull()) {
3516         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3517 
3518         // Does it fit in a unsigned long long?
3519         if (ResultVal.isIntN(LongLongSize)) {
3520           // Does it fit in a signed long long?
3521           // To be compatible with MSVC, hex integer literals ending with the
3522           // LL or i64 suffix are always signed in Microsoft mode.
3523           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3524               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3525             Ty = Context.LongLongTy;
3526           else if (AllowUnsigned)
3527             Ty = Context.UnsignedLongLongTy;
3528           Width = LongLongSize;
3529         }
3530       }
3531 
3532       // If we still couldn't decide a type, we probably have something that
3533       // does not fit in a signed long long, but has no U suffix.
3534       if (Ty.isNull()) {
3535         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3536         Ty = Context.UnsignedLongLongTy;
3537         Width = Context.getTargetInfo().getLongLongWidth();
3538       }
3539 
3540       if (ResultVal.getBitWidth() != Width)
3541         ResultVal = ResultVal.trunc(Width);
3542     }
3543     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3544   }
3545 
3546   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3547   if (Literal.isImaginary)
3548     Res = new (Context) ImaginaryLiteral(Res,
3549                                         Context.getComplexType(Res->getType()));
3550 
3551   return Res;
3552 }
3553 
3554 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3555   assert(E && "ActOnParenExpr() missing expr");
3556   return new (Context) ParenExpr(L, R, E);
3557 }
3558 
3559 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3560                                          SourceLocation Loc,
3561                                          SourceRange ArgRange) {
3562   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3563   // scalar or vector data type argument..."
3564   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3565   // type (C99 6.2.5p18) or void.
3566   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3567     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3568       << T << ArgRange;
3569     return true;
3570   }
3571 
3572   assert((T->isVoidType() || !T->isIncompleteType()) &&
3573          "Scalar types should always be complete");
3574   return false;
3575 }
3576 
3577 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3578                                            SourceLocation Loc,
3579                                            SourceRange ArgRange,
3580                                            UnaryExprOrTypeTrait TraitKind) {
3581   // Invalid types must be hard errors for SFINAE in C++.
3582   if (S.LangOpts.CPlusPlus)
3583     return true;
3584 
3585   // C99 6.5.3.4p1:
3586   if (T->isFunctionType() &&
3587       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3588     // sizeof(function)/alignof(function) is allowed as an extension.
3589     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3590       << TraitKind << ArgRange;
3591     return false;
3592   }
3593 
3594   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3595   // this is an error (OpenCL v1.1 s6.3.k)
3596   if (T->isVoidType()) {
3597     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3598                                         : diag::ext_sizeof_alignof_void_type;
3599     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3600     return false;
3601   }
3602 
3603   return true;
3604 }
3605 
3606 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3607                                              SourceLocation Loc,
3608                                              SourceRange ArgRange,
3609                                              UnaryExprOrTypeTrait TraitKind) {
3610   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3611   // runtime doesn't allow it.
3612   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3613     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3614       << T << (TraitKind == UETT_SizeOf)
3615       << ArgRange;
3616     return true;
3617   }
3618 
3619   return false;
3620 }
3621 
3622 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3623 /// pointer type is equal to T) and emit a warning if it is.
3624 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3625                                      Expr *E) {
3626   // Don't warn if the operation changed the type.
3627   if (T != E->getType())
3628     return;
3629 
3630   // Now look for array decays.
3631   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3632   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3633     return;
3634 
3635   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3636                                              << ICE->getType()
3637                                              << ICE->getSubExpr()->getType();
3638 }
3639 
3640 /// \brief Check the constraints on expression operands to unary type expression
3641 /// and type traits.
3642 ///
3643 /// Completes any types necessary and validates the constraints on the operand
3644 /// expression. The logic mostly mirrors the type-based overload, but may modify
3645 /// the expression as it completes the type for that expression through template
3646 /// instantiation, etc.
3647 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3648                                             UnaryExprOrTypeTrait ExprKind) {
3649   QualType ExprTy = E->getType();
3650   assert(!ExprTy->isReferenceType());
3651 
3652   if (ExprKind == UETT_VecStep)
3653     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3654                                         E->getSourceRange());
3655 
3656   // Whitelist some types as extensions
3657   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3658                                       E->getSourceRange(), ExprKind))
3659     return false;
3660 
3661   // 'alignof' applied to an expression only requires the base element type of
3662   // the expression to be complete. 'sizeof' requires the expression's type to
3663   // be complete (and will attempt to complete it if it's an array of unknown
3664   // bound).
3665   if (ExprKind == UETT_AlignOf) {
3666     if (RequireCompleteType(E->getExprLoc(),
3667                             Context.getBaseElementType(E->getType()),
3668                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3669                             E->getSourceRange()))
3670       return true;
3671   } else {
3672     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3673                                 ExprKind, E->getSourceRange()))
3674       return true;
3675   }
3676 
3677   // Completing the expression's type may have changed it.
3678   ExprTy = E->getType();
3679   assert(!ExprTy->isReferenceType());
3680 
3681   if (ExprTy->isFunctionType()) {
3682     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3683       << ExprKind << E->getSourceRange();
3684     return true;
3685   }
3686 
3687   // The operand for sizeof and alignof is in an unevaluated expression context,
3688   // so side effects could result in unintended consequences.
3689   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3690       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3691     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3692 
3693   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3694                                        E->getSourceRange(), ExprKind))
3695     return true;
3696 
3697   if (ExprKind == UETT_SizeOf) {
3698     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3699       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3700         QualType OType = PVD->getOriginalType();
3701         QualType Type = PVD->getType();
3702         if (Type->isPointerType() && OType->isArrayType()) {
3703           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3704             << Type << OType;
3705           Diag(PVD->getLocation(), diag::note_declared_at);
3706         }
3707       }
3708     }
3709 
3710     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3711     // decays into a pointer and returns an unintended result. This is most
3712     // likely a typo for "sizeof(array) op x".
3713     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3714       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3715                                BO->getLHS());
3716       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3717                                BO->getRHS());
3718     }
3719   }
3720 
3721   return false;
3722 }
3723 
3724 /// \brief Check the constraints on operands to unary expression and type
3725 /// traits.
3726 ///
3727 /// This will complete any types necessary, and validate the various constraints
3728 /// on those operands.
3729 ///
3730 /// The UsualUnaryConversions() function is *not* called by this routine.
3731 /// C99 6.3.2.1p[2-4] all state:
3732 ///   Except when it is the operand of the sizeof operator ...
3733 ///
3734 /// C++ [expr.sizeof]p4
3735 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3736 ///   standard conversions are not applied to the operand of sizeof.
3737 ///
3738 /// This policy is followed for all of the unary trait expressions.
3739 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3740                                             SourceLocation OpLoc,
3741                                             SourceRange ExprRange,
3742                                             UnaryExprOrTypeTrait ExprKind) {
3743   if (ExprType->isDependentType())
3744     return false;
3745 
3746   // C++ [expr.sizeof]p2:
3747   //     When applied to a reference or a reference type, the result
3748   //     is the size of the referenced type.
3749   // C++11 [expr.alignof]p3:
3750   //     When alignof is applied to a reference type, the result
3751   //     shall be the alignment of the referenced type.
3752   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3753     ExprType = Ref->getPointeeType();
3754 
3755   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3756   //   When alignof or _Alignof is applied to an array type, the result
3757   //   is the alignment of the element type.
3758   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3759     ExprType = Context.getBaseElementType(ExprType);
3760 
3761   if (ExprKind == UETT_VecStep)
3762     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3763 
3764   // Whitelist some types as extensions
3765   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3766                                       ExprKind))
3767     return false;
3768 
3769   if (RequireCompleteType(OpLoc, ExprType,
3770                           diag::err_sizeof_alignof_incomplete_type,
3771                           ExprKind, ExprRange))
3772     return true;
3773 
3774   if (ExprType->isFunctionType()) {
3775     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3776       << ExprKind << ExprRange;
3777     return true;
3778   }
3779 
3780   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3781                                        ExprKind))
3782     return true;
3783 
3784   return false;
3785 }
3786 
3787 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3788   E = E->IgnoreParens();
3789 
3790   // Cannot know anything else if the expression is dependent.
3791   if (E->isTypeDependent())
3792     return false;
3793 
3794   if (E->getObjectKind() == OK_BitField) {
3795     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3796        << 1 << E->getSourceRange();
3797     return true;
3798   }
3799 
3800   ValueDecl *D = nullptr;
3801   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3802     D = DRE->getDecl();
3803   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3804     D = ME->getMemberDecl();
3805   }
3806 
3807   // If it's a field, require the containing struct to have a
3808   // complete definition so that we can compute the layout.
3809   //
3810   // This can happen in C++11 onwards, either by naming the member
3811   // in a way that is not transformed into a member access expression
3812   // (in an unevaluated operand, for instance), or by naming the member
3813   // in a trailing-return-type.
3814   //
3815   // For the record, since __alignof__ on expressions is a GCC
3816   // extension, GCC seems to permit this but always gives the
3817   // nonsensical answer 0.
3818   //
3819   // We don't really need the layout here --- we could instead just
3820   // directly check for all the appropriate alignment-lowing
3821   // attributes --- but that would require duplicating a lot of
3822   // logic that just isn't worth duplicating for such a marginal
3823   // use-case.
3824   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3825     // Fast path this check, since we at least know the record has a
3826     // definition if we can find a member of it.
3827     if (!FD->getParent()->isCompleteDefinition()) {
3828       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3829         << E->getSourceRange();
3830       return true;
3831     }
3832 
3833     // Otherwise, if it's a field, and the field doesn't have
3834     // reference type, then it must have a complete type (or be a
3835     // flexible array member, which we explicitly want to
3836     // white-list anyway), which makes the following checks trivial.
3837     if (!FD->getType()->isReferenceType())
3838       return false;
3839   }
3840 
3841   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3842 }
3843 
3844 bool Sema::CheckVecStepExpr(Expr *E) {
3845   E = E->IgnoreParens();
3846 
3847   // Cannot know anything else if the expression is dependent.
3848   if (E->isTypeDependent())
3849     return false;
3850 
3851   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3852 }
3853 
3854 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3855                                         CapturingScopeInfo *CSI) {
3856   assert(T->isVariablyModifiedType());
3857   assert(CSI != nullptr);
3858 
3859   // We're going to walk down into the type and look for VLA expressions.
3860   do {
3861     const Type *Ty = T.getTypePtr();
3862     switch (Ty->getTypeClass()) {
3863 #define TYPE(Class, Base)
3864 #define ABSTRACT_TYPE(Class, Base)
3865 #define NON_CANONICAL_TYPE(Class, Base)
3866 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3867 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3868 #include "clang/AST/TypeNodes.def"
3869       T = QualType();
3870       break;
3871     // These types are never variably-modified.
3872     case Type::Builtin:
3873     case Type::Complex:
3874     case Type::Vector:
3875     case Type::ExtVector:
3876     case Type::Record:
3877     case Type::Enum:
3878     case Type::Elaborated:
3879     case Type::TemplateSpecialization:
3880     case Type::ObjCObject:
3881     case Type::ObjCInterface:
3882     case Type::ObjCObjectPointer:
3883     case Type::ObjCTypeParam:
3884     case Type::Pipe:
3885       llvm_unreachable("type class is never variably-modified!");
3886     case Type::Adjusted:
3887       T = cast<AdjustedType>(Ty)->getOriginalType();
3888       break;
3889     case Type::Decayed:
3890       T = cast<DecayedType>(Ty)->getPointeeType();
3891       break;
3892     case Type::Pointer:
3893       T = cast<PointerType>(Ty)->getPointeeType();
3894       break;
3895     case Type::BlockPointer:
3896       T = cast<BlockPointerType>(Ty)->getPointeeType();
3897       break;
3898     case Type::LValueReference:
3899     case Type::RValueReference:
3900       T = cast<ReferenceType>(Ty)->getPointeeType();
3901       break;
3902     case Type::MemberPointer:
3903       T = cast<MemberPointerType>(Ty)->getPointeeType();
3904       break;
3905     case Type::ConstantArray:
3906     case Type::IncompleteArray:
3907       // Losing element qualification here is fine.
3908       T = cast<ArrayType>(Ty)->getElementType();
3909       break;
3910     case Type::VariableArray: {
3911       // Losing element qualification here is fine.
3912       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3913 
3914       // Unknown size indication requires no size computation.
3915       // Otherwise, evaluate and record it.
3916       if (auto Size = VAT->getSizeExpr()) {
3917         if (!CSI->isVLATypeCaptured(VAT)) {
3918           RecordDecl *CapRecord = nullptr;
3919           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3920             CapRecord = LSI->Lambda;
3921           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3922             CapRecord = CRSI->TheRecordDecl;
3923           }
3924           if (CapRecord) {
3925             auto ExprLoc = Size->getExprLoc();
3926             auto SizeType = Context.getSizeType();
3927             // Build the non-static data member.
3928             auto Field =
3929                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3930                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3931                                   /*BW*/ nullptr, /*Mutable*/ false,
3932                                   /*InitStyle*/ ICIS_NoInit);
3933             Field->setImplicit(true);
3934             Field->setAccess(AS_private);
3935             Field->setCapturedVLAType(VAT);
3936             CapRecord->addDecl(Field);
3937 
3938             CSI->addVLATypeCapture(ExprLoc, SizeType);
3939           }
3940         }
3941       }
3942       T = VAT->getElementType();
3943       break;
3944     }
3945     case Type::FunctionProto:
3946     case Type::FunctionNoProto:
3947       T = cast<FunctionType>(Ty)->getReturnType();
3948       break;
3949     case Type::Paren:
3950     case Type::TypeOf:
3951     case Type::UnaryTransform:
3952     case Type::Attributed:
3953     case Type::SubstTemplateTypeParm:
3954     case Type::PackExpansion:
3955       // Keep walking after single level desugaring.
3956       T = T.getSingleStepDesugaredType(Context);
3957       break;
3958     case Type::Typedef:
3959       T = cast<TypedefType>(Ty)->desugar();
3960       break;
3961     case Type::Decltype:
3962       T = cast<DecltypeType>(Ty)->desugar();
3963       break;
3964     case Type::Auto:
3965       T = cast<AutoType>(Ty)->getDeducedType();
3966       break;
3967     case Type::TypeOfExpr:
3968       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3969       break;
3970     case Type::Atomic:
3971       T = cast<AtomicType>(Ty)->getValueType();
3972       break;
3973     }
3974   } while (!T.isNull() && T->isVariablyModifiedType());
3975 }
3976 
3977 /// \brief Build a sizeof or alignof expression given a type operand.
3978 ExprResult
3979 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3980                                      SourceLocation OpLoc,
3981                                      UnaryExprOrTypeTrait ExprKind,
3982                                      SourceRange R) {
3983   if (!TInfo)
3984     return ExprError();
3985 
3986   QualType T = TInfo->getType();
3987 
3988   if (!T->isDependentType() &&
3989       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3990     return ExprError();
3991 
3992   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3993     if (auto *TT = T->getAs<TypedefType>()) {
3994       for (auto I = FunctionScopes.rbegin(),
3995                 E = std::prev(FunctionScopes.rend());
3996            I != E; ++I) {
3997         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3998         if (CSI == nullptr)
3999           break;
4000         DeclContext *DC = nullptr;
4001         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4002           DC = LSI->CallOperator;
4003         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4004           DC = CRSI->TheCapturedDecl;
4005         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4006           DC = BSI->TheDecl;
4007         if (DC) {
4008           if (DC->containsDecl(TT->getDecl()))
4009             break;
4010           captureVariablyModifiedType(Context, T, CSI);
4011         }
4012       }
4013     }
4014   }
4015 
4016   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4017   return new (Context) UnaryExprOrTypeTraitExpr(
4018       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4019 }
4020 
4021 /// \brief Build a sizeof or alignof expression given an expression
4022 /// operand.
4023 ExprResult
4024 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4025                                      UnaryExprOrTypeTrait ExprKind) {
4026   ExprResult PE = CheckPlaceholderExpr(E);
4027   if (PE.isInvalid())
4028     return ExprError();
4029 
4030   E = PE.get();
4031 
4032   // Verify that the operand is valid.
4033   bool isInvalid = false;
4034   if (E->isTypeDependent()) {
4035     // Delay type-checking for type-dependent expressions.
4036   } else if (ExprKind == UETT_AlignOf) {
4037     isInvalid = CheckAlignOfExpr(*this, E);
4038   } else if (ExprKind == UETT_VecStep) {
4039     isInvalid = CheckVecStepExpr(E);
4040   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4041       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4042       isInvalid = true;
4043   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4044     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4045     isInvalid = true;
4046   } else {
4047     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4048   }
4049 
4050   if (isInvalid)
4051     return ExprError();
4052 
4053   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4054     PE = TransformToPotentiallyEvaluated(E);
4055     if (PE.isInvalid()) return ExprError();
4056     E = PE.get();
4057   }
4058 
4059   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4060   return new (Context) UnaryExprOrTypeTraitExpr(
4061       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4062 }
4063 
4064 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4065 /// expr and the same for @c alignof and @c __alignof
4066 /// Note that the ArgRange is invalid if isType is false.
4067 ExprResult
4068 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4069                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4070                                     void *TyOrEx, SourceRange ArgRange) {
4071   // If error parsing type, ignore.
4072   if (!TyOrEx) return ExprError();
4073 
4074   if (IsType) {
4075     TypeSourceInfo *TInfo;
4076     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4077     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4078   }
4079 
4080   Expr *ArgEx = (Expr *)TyOrEx;
4081   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4082   return Result;
4083 }
4084 
4085 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4086                                      bool IsReal) {
4087   if (V.get()->isTypeDependent())
4088     return S.Context.DependentTy;
4089 
4090   // _Real and _Imag are only l-values for normal l-values.
4091   if (V.get()->getObjectKind() != OK_Ordinary) {
4092     V = S.DefaultLvalueConversion(V.get());
4093     if (V.isInvalid())
4094       return QualType();
4095   }
4096 
4097   // These operators return the element type of a complex type.
4098   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4099     return CT->getElementType();
4100 
4101   // Otherwise they pass through real integer and floating point types here.
4102   if (V.get()->getType()->isArithmeticType())
4103     return V.get()->getType();
4104 
4105   // Test for placeholders.
4106   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4107   if (PR.isInvalid()) return QualType();
4108   if (PR.get() != V.get()) {
4109     V = PR;
4110     return CheckRealImagOperand(S, V, Loc, IsReal);
4111   }
4112 
4113   // Reject anything else.
4114   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4115     << (IsReal ? "__real" : "__imag");
4116   return QualType();
4117 }
4118 
4119 
4120 
4121 ExprResult
4122 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4123                           tok::TokenKind Kind, Expr *Input) {
4124   UnaryOperatorKind Opc;
4125   switch (Kind) {
4126   default: llvm_unreachable("Unknown unary op!");
4127   case tok::plusplus:   Opc = UO_PostInc; break;
4128   case tok::minusminus: Opc = UO_PostDec; break;
4129   }
4130 
4131   // Since this might is a postfix expression, get rid of ParenListExprs.
4132   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4133   if (Result.isInvalid()) return ExprError();
4134   Input = Result.get();
4135 
4136   return BuildUnaryOp(S, OpLoc, Opc, Input);
4137 }
4138 
4139 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4140 ///
4141 /// \return true on error
4142 static bool checkArithmeticOnObjCPointer(Sema &S,
4143                                          SourceLocation opLoc,
4144                                          Expr *op) {
4145   assert(op->getType()->isObjCObjectPointerType());
4146   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4147       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4148     return false;
4149 
4150   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4151     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4152     << op->getSourceRange();
4153   return true;
4154 }
4155 
4156 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4157   auto *BaseNoParens = Base->IgnoreParens();
4158   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4159     return MSProp->getPropertyDecl()->getType()->isArrayType();
4160   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4161 }
4162 
4163 ExprResult
4164 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4165                               Expr *idx, SourceLocation rbLoc) {
4166   if (base && !base->getType().isNull() &&
4167       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4168     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4169                                     /*Length=*/nullptr, rbLoc);
4170 
4171   // Since this might be a postfix expression, get rid of ParenListExprs.
4172   if (isa<ParenListExpr>(base)) {
4173     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4174     if (result.isInvalid()) return ExprError();
4175     base = result.get();
4176   }
4177 
4178   // Handle any non-overload placeholder types in the base and index
4179   // expressions.  We can't handle overloads here because the other
4180   // operand might be an overloadable type, in which case the overload
4181   // resolution for the operator overload should get the first crack
4182   // at the overload.
4183   bool IsMSPropertySubscript = false;
4184   if (base->getType()->isNonOverloadPlaceholderType()) {
4185     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4186     if (!IsMSPropertySubscript) {
4187       ExprResult result = CheckPlaceholderExpr(base);
4188       if (result.isInvalid())
4189         return ExprError();
4190       base = result.get();
4191     }
4192   }
4193   if (idx->getType()->isNonOverloadPlaceholderType()) {
4194     ExprResult result = CheckPlaceholderExpr(idx);
4195     if (result.isInvalid()) return ExprError();
4196     idx = result.get();
4197   }
4198 
4199   // Build an unanalyzed expression if either operand is type-dependent.
4200   if (getLangOpts().CPlusPlus &&
4201       (base->isTypeDependent() || idx->isTypeDependent())) {
4202     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4203                                             VK_LValue, OK_Ordinary, rbLoc);
4204   }
4205 
4206   // MSDN, property (C++)
4207   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4208   // This attribute can also be used in the declaration of an empty array in a
4209   // class or structure definition. For example:
4210   // __declspec(property(get=GetX, put=PutX)) int x[];
4211   // The above statement indicates that x[] can be used with one or more array
4212   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4213   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4214   if (IsMSPropertySubscript) {
4215     // Build MS property subscript expression if base is MS property reference
4216     // or MS property subscript.
4217     return new (Context) MSPropertySubscriptExpr(
4218         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4219   }
4220 
4221   // Use C++ overloaded-operator rules if either operand has record
4222   // type.  The spec says to do this if either type is *overloadable*,
4223   // but enum types can't declare subscript operators or conversion
4224   // operators, so there's nothing interesting for overload resolution
4225   // to do if there aren't any record types involved.
4226   //
4227   // ObjC pointers have their own subscripting logic that is not tied
4228   // to overload resolution and so should not take this path.
4229   if (getLangOpts().CPlusPlus &&
4230       (base->getType()->isRecordType() ||
4231        (!base->getType()->isObjCObjectPointerType() &&
4232         idx->getType()->isRecordType()))) {
4233     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4234   }
4235 
4236   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4237 }
4238 
4239 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4240                                           Expr *LowerBound,
4241                                           SourceLocation ColonLoc, Expr *Length,
4242                                           SourceLocation RBLoc) {
4243   if (Base->getType()->isPlaceholderType() &&
4244       !Base->getType()->isSpecificPlaceholderType(
4245           BuiltinType::OMPArraySection)) {
4246     ExprResult Result = CheckPlaceholderExpr(Base);
4247     if (Result.isInvalid())
4248       return ExprError();
4249     Base = Result.get();
4250   }
4251   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4252     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4253     if (Result.isInvalid())
4254       return ExprError();
4255     Result = DefaultLvalueConversion(Result.get());
4256     if (Result.isInvalid())
4257       return ExprError();
4258     LowerBound = Result.get();
4259   }
4260   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4261     ExprResult Result = CheckPlaceholderExpr(Length);
4262     if (Result.isInvalid())
4263       return ExprError();
4264     Result = DefaultLvalueConversion(Result.get());
4265     if (Result.isInvalid())
4266       return ExprError();
4267     Length = Result.get();
4268   }
4269 
4270   // Build an unanalyzed expression if either operand is type-dependent.
4271   if (Base->isTypeDependent() ||
4272       (LowerBound &&
4273        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4274       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4275     return new (Context)
4276         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4277                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4278   }
4279 
4280   // Perform default conversions.
4281   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4282   QualType ResultTy;
4283   if (OriginalTy->isAnyPointerType()) {
4284     ResultTy = OriginalTy->getPointeeType();
4285   } else if (OriginalTy->isArrayType()) {
4286     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4287   } else {
4288     return ExprError(
4289         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4290         << Base->getSourceRange());
4291   }
4292   // C99 6.5.2.1p1
4293   if (LowerBound) {
4294     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4295                                                       LowerBound);
4296     if (Res.isInvalid())
4297       return ExprError(Diag(LowerBound->getExprLoc(),
4298                             diag::err_omp_typecheck_section_not_integer)
4299                        << 0 << LowerBound->getSourceRange());
4300     LowerBound = Res.get();
4301 
4302     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4303         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4304       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4305           << 0 << LowerBound->getSourceRange();
4306   }
4307   if (Length) {
4308     auto Res =
4309         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4310     if (Res.isInvalid())
4311       return ExprError(Diag(Length->getExprLoc(),
4312                             diag::err_omp_typecheck_section_not_integer)
4313                        << 1 << Length->getSourceRange());
4314     Length = Res.get();
4315 
4316     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4317         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4318       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4319           << 1 << Length->getSourceRange();
4320   }
4321 
4322   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4323   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4324   // type. Note that functions are not objects, and that (in C99 parlance)
4325   // incomplete types are not object types.
4326   if (ResultTy->isFunctionType()) {
4327     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4328         << ResultTy << Base->getSourceRange();
4329     return ExprError();
4330   }
4331 
4332   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4333                           diag::err_omp_section_incomplete_type, Base))
4334     return ExprError();
4335 
4336   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4337     llvm::APSInt LowerBoundValue;
4338     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4339       // OpenMP 4.5, [2.4 Array Sections]
4340       // The array section must be a subset of the original array.
4341       if (LowerBoundValue.isNegative()) {
4342         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4343             << LowerBound->getSourceRange();
4344         return ExprError();
4345       }
4346     }
4347   }
4348 
4349   if (Length) {
4350     llvm::APSInt LengthValue;
4351     if (Length->EvaluateAsInt(LengthValue, Context)) {
4352       // OpenMP 4.5, [2.4 Array Sections]
4353       // The length must evaluate to non-negative integers.
4354       if (LengthValue.isNegative()) {
4355         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4356             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4357             << Length->getSourceRange();
4358         return ExprError();
4359       }
4360     }
4361   } else if (ColonLoc.isValid() &&
4362              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4363                                       !OriginalTy->isVariableArrayType()))) {
4364     // OpenMP 4.5, [2.4 Array Sections]
4365     // When the size of the array dimension is not known, the length must be
4366     // specified explicitly.
4367     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4368         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4369     return ExprError();
4370   }
4371 
4372   if (!Base->getType()->isSpecificPlaceholderType(
4373           BuiltinType::OMPArraySection)) {
4374     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4375     if (Result.isInvalid())
4376       return ExprError();
4377     Base = Result.get();
4378   }
4379   return new (Context)
4380       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4381                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4382 }
4383 
4384 ExprResult
4385 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4386                                       Expr *Idx, SourceLocation RLoc) {
4387   Expr *LHSExp = Base;
4388   Expr *RHSExp = Idx;
4389 
4390   ExprValueKind VK = VK_LValue;
4391   ExprObjectKind OK = OK_Ordinary;
4392 
4393   // Per C++ core issue 1213, the result is an xvalue if either operand is
4394   // a non-lvalue array, and an lvalue otherwise.
4395   if (getLangOpts().CPlusPlus11 &&
4396       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4397        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4398     VK = VK_XValue;
4399 
4400   // Perform default conversions.
4401   if (!LHSExp->getType()->getAs<VectorType>()) {
4402     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4403     if (Result.isInvalid())
4404       return ExprError();
4405     LHSExp = Result.get();
4406   }
4407   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4408   if (Result.isInvalid())
4409     return ExprError();
4410   RHSExp = Result.get();
4411 
4412   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4413 
4414   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4415   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4416   // in the subscript position. As a result, we need to derive the array base
4417   // and index from the expression types.
4418   Expr *BaseExpr, *IndexExpr;
4419   QualType ResultType;
4420   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4421     BaseExpr = LHSExp;
4422     IndexExpr = RHSExp;
4423     ResultType = Context.DependentTy;
4424   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4425     BaseExpr = LHSExp;
4426     IndexExpr = RHSExp;
4427     ResultType = PTy->getPointeeType();
4428   } else if (const ObjCObjectPointerType *PTy =
4429                LHSTy->getAs<ObjCObjectPointerType>()) {
4430     BaseExpr = LHSExp;
4431     IndexExpr = RHSExp;
4432 
4433     // Use custom logic if this should be the pseudo-object subscript
4434     // expression.
4435     if (!LangOpts.isSubscriptPointerArithmetic())
4436       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4437                                           nullptr);
4438 
4439     ResultType = PTy->getPointeeType();
4440   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4441      // Handle the uncommon case of "123[Ptr]".
4442     BaseExpr = RHSExp;
4443     IndexExpr = LHSExp;
4444     ResultType = PTy->getPointeeType();
4445   } else if (const ObjCObjectPointerType *PTy =
4446                RHSTy->getAs<ObjCObjectPointerType>()) {
4447      // Handle the uncommon case of "123[Ptr]".
4448     BaseExpr = RHSExp;
4449     IndexExpr = LHSExp;
4450     ResultType = PTy->getPointeeType();
4451     if (!LangOpts.isSubscriptPointerArithmetic()) {
4452       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4453         << ResultType << BaseExpr->getSourceRange();
4454       return ExprError();
4455     }
4456   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4457     BaseExpr = LHSExp;    // vectors: V[123]
4458     IndexExpr = RHSExp;
4459     VK = LHSExp->getValueKind();
4460     if (VK != VK_RValue)
4461       OK = OK_VectorComponent;
4462 
4463     // FIXME: need to deal with const...
4464     ResultType = VTy->getElementType();
4465   } else if (LHSTy->isArrayType()) {
4466     // If we see an array that wasn't promoted by
4467     // DefaultFunctionArrayLvalueConversion, it must be an array that
4468     // wasn't promoted because of the C90 rule that doesn't
4469     // allow promoting non-lvalue arrays.  Warn, then
4470     // force the promotion here.
4471     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4472         LHSExp->getSourceRange();
4473     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4474                                CK_ArrayToPointerDecay).get();
4475     LHSTy = LHSExp->getType();
4476 
4477     BaseExpr = LHSExp;
4478     IndexExpr = RHSExp;
4479     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4480   } else if (RHSTy->isArrayType()) {
4481     // Same as previous, except for 123[f().a] case
4482     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4483         RHSExp->getSourceRange();
4484     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4485                                CK_ArrayToPointerDecay).get();
4486     RHSTy = RHSExp->getType();
4487 
4488     BaseExpr = RHSExp;
4489     IndexExpr = LHSExp;
4490     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4491   } else {
4492     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4493        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4494   }
4495   // C99 6.5.2.1p1
4496   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4497     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4498                      << IndexExpr->getSourceRange());
4499 
4500   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4501        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4502          && !IndexExpr->isTypeDependent())
4503     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4504 
4505   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4506   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4507   // type. Note that Functions are not objects, and that (in C99 parlance)
4508   // incomplete types are not object types.
4509   if (ResultType->isFunctionType()) {
4510     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4511       << ResultType << BaseExpr->getSourceRange();
4512     return ExprError();
4513   }
4514 
4515   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4516     // GNU extension: subscripting on pointer to void
4517     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4518       << BaseExpr->getSourceRange();
4519 
4520     // C forbids expressions of unqualified void type from being l-values.
4521     // See IsCForbiddenLValueType.
4522     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4523   } else if (!ResultType->isDependentType() &&
4524       RequireCompleteType(LLoc, ResultType,
4525                           diag::err_subscript_incomplete_type, BaseExpr))
4526     return ExprError();
4527 
4528   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4529          !ResultType.isCForbiddenLValueType());
4530 
4531   return new (Context)
4532       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4533 }
4534 
4535 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4536                                   ParmVarDecl *Param) {
4537   if (Param->hasUnparsedDefaultArg()) {
4538     Diag(CallLoc,
4539          diag::err_use_of_default_argument_to_function_declared_later) <<
4540       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4541     Diag(UnparsedDefaultArgLocs[Param],
4542          diag::note_default_argument_declared_here);
4543     return true;
4544   }
4545 
4546   if (Param->hasUninstantiatedDefaultArg()) {
4547     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4548 
4549     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4550                                                  Param);
4551 
4552     // Instantiate the expression.
4553     MultiLevelTemplateArgumentList MutiLevelArgList
4554       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4555 
4556     InstantiatingTemplate Inst(*this, CallLoc, Param,
4557                                MutiLevelArgList.getInnermost());
4558     if (Inst.isInvalid())
4559       return true;
4560     if (Inst.isAlreadyInstantiating()) {
4561       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4562       Param->setInvalidDecl();
4563       return true;
4564     }
4565 
4566     ExprResult Result;
4567     {
4568       // C++ [dcl.fct.default]p5:
4569       //   The names in the [default argument] expression are bound, and
4570       //   the semantic constraints are checked, at the point where the
4571       //   default argument expression appears.
4572       ContextRAII SavedContext(*this, FD);
4573       LocalInstantiationScope Local(*this);
4574       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4575                                 /*DirectInit*/false);
4576     }
4577     if (Result.isInvalid())
4578       return true;
4579 
4580     // Check the expression as an initializer for the parameter.
4581     InitializedEntity Entity
4582       = InitializedEntity::InitializeParameter(Context, Param);
4583     InitializationKind Kind
4584       = InitializationKind::CreateCopy(Param->getLocation(),
4585              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4586     Expr *ResultE = Result.getAs<Expr>();
4587 
4588     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4589     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4590     if (Result.isInvalid())
4591       return true;
4592 
4593     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4594                                  Param->getOuterLocStart());
4595     if (Result.isInvalid())
4596       return true;
4597 
4598     // Remember the instantiated default argument.
4599     Param->setDefaultArg(Result.getAs<Expr>());
4600     if (ASTMutationListener *L = getASTMutationListener()) {
4601       L->DefaultArgumentInstantiated(Param);
4602     }
4603   }
4604 
4605   // If the default argument expression is not set yet, we are building it now.
4606   if (!Param->hasInit()) {
4607     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4608     Param->setInvalidDecl();
4609     return true;
4610   }
4611 
4612   // If the default expression creates temporaries, we need to
4613   // push them to the current stack of expression temporaries so they'll
4614   // be properly destroyed.
4615   // FIXME: We should really be rebuilding the default argument with new
4616   // bound temporaries; see the comment in PR5810.
4617   // We don't need to do that with block decls, though, because
4618   // blocks in default argument expression can never capture anything.
4619   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4620     // Set the "needs cleanups" bit regardless of whether there are
4621     // any explicit objects.
4622     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4623 
4624     // Append all the objects to the cleanup list.  Right now, this
4625     // should always be a no-op, because blocks in default argument
4626     // expressions should never be able to capture anything.
4627     assert(!Init->getNumObjects() &&
4628            "default argument expression has capturing blocks?");
4629   }
4630 
4631   // We already type-checked the argument, so we know it works.
4632   // Just mark all of the declarations in this potentially-evaluated expression
4633   // as being "referenced".
4634   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4635                                    /*SkipLocalVariables=*/true);
4636   return false;
4637 }
4638 
4639 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4640                                         FunctionDecl *FD, ParmVarDecl *Param) {
4641   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4642     return ExprError();
4643   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4644 }
4645 
4646 Sema::VariadicCallType
4647 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4648                           Expr *Fn) {
4649   if (Proto && Proto->isVariadic()) {
4650     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4651       return VariadicConstructor;
4652     else if (Fn && Fn->getType()->isBlockPointerType())
4653       return VariadicBlock;
4654     else if (FDecl) {
4655       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4656         if (Method->isInstance())
4657           return VariadicMethod;
4658     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4659       return VariadicMethod;
4660     return VariadicFunction;
4661   }
4662   return VariadicDoesNotApply;
4663 }
4664 
4665 namespace {
4666 class FunctionCallCCC : public FunctionCallFilterCCC {
4667 public:
4668   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4669                   unsigned NumArgs, MemberExpr *ME)
4670       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4671         FunctionName(FuncName) {}
4672 
4673   bool ValidateCandidate(const TypoCorrection &candidate) override {
4674     if (!candidate.getCorrectionSpecifier() ||
4675         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4676       return false;
4677     }
4678 
4679     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4680   }
4681 
4682 private:
4683   const IdentifierInfo *const FunctionName;
4684 };
4685 }
4686 
4687 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4688                                                FunctionDecl *FDecl,
4689                                                ArrayRef<Expr *> Args) {
4690   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4691   DeclarationName FuncName = FDecl->getDeclName();
4692   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4693 
4694   if (TypoCorrection Corrected = S.CorrectTypo(
4695           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4696           S.getScopeForContext(S.CurContext), nullptr,
4697           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4698                                              Args.size(), ME),
4699           Sema::CTK_ErrorRecovery)) {
4700     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4701       if (Corrected.isOverloaded()) {
4702         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4703         OverloadCandidateSet::iterator Best;
4704         for (NamedDecl *CD : Corrected) {
4705           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4706             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4707                                    OCS);
4708         }
4709         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4710         case OR_Success:
4711           ND = Best->FoundDecl;
4712           Corrected.setCorrectionDecl(ND);
4713           break;
4714         default:
4715           break;
4716         }
4717       }
4718       ND = ND->getUnderlyingDecl();
4719       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4720         return Corrected;
4721     }
4722   }
4723   return TypoCorrection();
4724 }
4725 
4726 /// ConvertArgumentsForCall - Converts the arguments specified in
4727 /// Args/NumArgs to the parameter types of the function FDecl with
4728 /// function prototype Proto. Call is the call expression itself, and
4729 /// Fn is the function expression. For a C++ member function, this
4730 /// routine does not attempt to convert the object argument. Returns
4731 /// true if the call is ill-formed.
4732 bool
4733 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4734                               FunctionDecl *FDecl,
4735                               const FunctionProtoType *Proto,
4736                               ArrayRef<Expr *> Args,
4737                               SourceLocation RParenLoc,
4738                               bool IsExecConfig) {
4739   // Bail out early if calling a builtin with custom typechecking.
4740   if (FDecl)
4741     if (unsigned ID = FDecl->getBuiltinID())
4742       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4743         return false;
4744 
4745   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4746   // assignment, to the types of the corresponding parameter, ...
4747   unsigned NumParams = Proto->getNumParams();
4748   bool Invalid = false;
4749   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4750   unsigned FnKind = Fn->getType()->isBlockPointerType()
4751                        ? 1 /* block */
4752                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4753                                        : 0 /* function */);
4754 
4755   // If too few arguments are available (and we don't have default
4756   // arguments for the remaining parameters), don't make the call.
4757   if (Args.size() < NumParams) {
4758     if (Args.size() < MinArgs) {
4759       TypoCorrection TC;
4760       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4761         unsigned diag_id =
4762             MinArgs == NumParams && !Proto->isVariadic()
4763                 ? diag::err_typecheck_call_too_few_args_suggest
4764                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4765         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4766                                         << static_cast<unsigned>(Args.size())
4767                                         << TC.getCorrectionRange());
4768       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4769         Diag(RParenLoc,
4770              MinArgs == NumParams && !Proto->isVariadic()
4771                  ? diag::err_typecheck_call_too_few_args_one
4772                  : diag::err_typecheck_call_too_few_args_at_least_one)
4773             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4774       else
4775         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4776                             ? diag::err_typecheck_call_too_few_args
4777                             : diag::err_typecheck_call_too_few_args_at_least)
4778             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4779             << Fn->getSourceRange();
4780 
4781       // Emit the location of the prototype.
4782       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4783         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4784           << FDecl;
4785 
4786       return true;
4787     }
4788     Call->setNumArgs(Context, NumParams);
4789   }
4790 
4791   // If too many are passed and not variadic, error on the extras and drop
4792   // them.
4793   if (Args.size() > NumParams) {
4794     if (!Proto->isVariadic()) {
4795       TypoCorrection TC;
4796       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4797         unsigned diag_id =
4798             MinArgs == NumParams && !Proto->isVariadic()
4799                 ? diag::err_typecheck_call_too_many_args_suggest
4800                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4801         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4802                                         << static_cast<unsigned>(Args.size())
4803                                         << TC.getCorrectionRange());
4804       } else if (NumParams == 1 && FDecl &&
4805                  FDecl->getParamDecl(0)->getDeclName())
4806         Diag(Args[NumParams]->getLocStart(),
4807              MinArgs == NumParams
4808                  ? diag::err_typecheck_call_too_many_args_one
4809                  : diag::err_typecheck_call_too_many_args_at_most_one)
4810             << FnKind << FDecl->getParamDecl(0)
4811             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4812             << SourceRange(Args[NumParams]->getLocStart(),
4813                            Args.back()->getLocEnd());
4814       else
4815         Diag(Args[NumParams]->getLocStart(),
4816              MinArgs == NumParams
4817                  ? diag::err_typecheck_call_too_many_args
4818                  : diag::err_typecheck_call_too_many_args_at_most)
4819             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4820             << Fn->getSourceRange()
4821             << SourceRange(Args[NumParams]->getLocStart(),
4822                            Args.back()->getLocEnd());
4823 
4824       // Emit the location of the prototype.
4825       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4826         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4827           << FDecl;
4828 
4829       // This deletes the extra arguments.
4830       Call->setNumArgs(Context, NumParams);
4831       return true;
4832     }
4833   }
4834   SmallVector<Expr *, 8> AllArgs;
4835   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4836 
4837   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4838                                    Proto, 0, Args, AllArgs, CallType);
4839   if (Invalid)
4840     return true;
4841   unsigned TotalNumArgs = AllArgs.size();
4842   for (unsigned i = 0; i < TotalNumArgs; ++i)
4843     Call->setArg(i, AllArgs[i]);
4844 
4845   return false;
4846 }
4847 
4848 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4849                                   const FunctionProtoType *Proto,
4850                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4851                                   SmallVectorImpl<Expr *> &AllArgs,
4852                                   VariadicCallType CallType, bool AllowExplicit,
4853                                   bool IsListInitialization) {
4854   unsigned NumParams = Proto->getNumParams();
4855   bool Invalid = false;
4856   size_t ArgIx = 0;
4857   // Continue to check argument types (even if we have too few/many args).
4858   for (unsigned i = FirstParam; i < NumParams; i++) {
4859     QualType ProtoArgType = Proto->getParamType(i);
4860 
4861     Expr *Arg;
4862     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4863     if (ArgIx < Args.size()) {
4864       Arg = Args[ArgIx++];
4865 
4866       if (RequireCompleteType(Arg->getLocStart(),
4867                               ProtoArgType,
4868                               diag::err_call_incomplete_argument, Arg))
4869         return true;
4870 
4871       // Strip the unbridged-cast placeholder expression off, if applicable.
4872       bool CFAudited = false;
4873       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4874           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4875           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4876         Arg = stripARCUnbridgedCast(Arg);
4877       else if (getLangOpts().ObjCAutoRefCount &&
4878                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4879                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4880         CFAudited = true;
4881 
4882       InitializedEntity Entity =
4883           Param ? InitializedEntity::InitializeParameter(Context, Param,
4884                                                          ProtoArgType)
4885                 : InitializedEntity::InitializeParameter(
4886                       Context, ProtoArgType, Proto->isParamConsumed(i));
4887 
4888       // Remember that parameter belongs to a CF audited API.
4889       if (CFAudited)
4890         Entity.setParameterCFAudited();
4891 
4892       ExprResult ArgE = PerformCopyInitialization(
4893           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4894       if (ArgE.isInvalid())
4895         return true;
4896 
4897       Arg = ArgE.getAs<Expr>();
4898     } else {
4899       assert(Param && "can't use default arguments without a known callee");
4900 
4901       ExprResult ArgExpr =
4902         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4903       if (ArgExpr.isInvalid())
4904         return true;
4905 
4906       Arg = ArgExpr.getAs<Expr>();
4907     }
4908 
4909     // Check for array bounds violations for each argument to the call. This
4910     // check only triggers warnings when the argument isn't a more complex Expr
4911     // with its own checking, such as a BinaryOperator.
4912     CheckArrayAccess(Arg);
4913 
4914     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4915     CheckStaticArrayArgument(CallLoc, Param, Arg);
4916 
4917     AllArgs.push_back(Arg);
4918   }
4919 
4920   // If this is a variadic call, handle args passed through "...".
4921   if (CallType != VariadicDoesNotApply) {
4922     // Assume that extern "C" functions with variadic arguments that
4923     // return __unknown_anytype aren't *really* variadic.
4924     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4925         FDecl->isExternC()) {
4926       for (Expr *A : Args.slice(ArgIx)) {
4927         QualType paramType; // ignored
4928         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4929         Invalid |= arg.isInvalid();
4930         AllArgs.push_back(arg.get());
4931       }
4932 
4933     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4934     } else {
4935       for (Expr *A : Args.slice(ArgIx)) {
4936         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4937         Invalid |= Arg.isInvalid();
4938         AllArgs.push_back(Arg.get());
4939       }
4940     }
4941 
4942     // Check for array bounds violations.
4943     for (Expr *A : Args.slice(ArgIx))
4944       CheckArrayAccess(A);
4945   }
4946   return Invalid;
4947 }
4948 
4949 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4950   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4951   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4952     TL = DTL.getOriginalLoc();
4953   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4954     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4955       << ATL.getLocalSourceRange();
4956 }
4957 
4958 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4959 /// array parameter, check that it is non-null, and that if it is formed by
4960 /// array-to-pointer decay, the underlying array is sufficiently large.
4961 ///
4962 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4963 /// array type derivation, then for each call to the function, the value of the
4964 /// corresponding actual argument shall provide access to the first element of
4965 /// an array with at least as many elements as specified by the size expression.
4966 void
4967 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4968                                ParmVarDecl *Param,
4969                                const Expr *ArgExpr) {
4970   // Static array parameters are not supported in C++.
4971   if (!Param || getLangOpts().CPlusPlus)
4972     return;
4973 
4974   QualType OrigTy = Param->getOriginalType();
4975 
4976   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4977   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4978     return;
4979 
4980   if (ArgExpr->isNullPointerConstant(Context,
4981                                      Expr::NPC_NeverValueDependent)) {
4982     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4983     DiagnoseCalleeStaticArrayParam(*this, Param);
4984     return;
4985   }
4986 
4987   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4988   if (!CAT)
4989     return;
4990 
4991   const ConstantArrayType *ArgCAT =
4992     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4993   if (!ArgCAT)
4994     return;
4995 
4996   if (ArgCAT->getSize().ult(CAT->getSize())) {
4997     Diag(CallLoc, diag::warn_static_array_too_small)
4998       << ArgExpr->getSourceRange()
4999       << (unsigned) ArgCAT->getSize().getZExtValue()
5000       << (unsigned) CAT->getSize().getZExtValue();
5001     DiagnoseCalleeStaticArrayParam(*this, Param);
5002   }
5003 }
5004 
5005 /// Given a function expression of unknown-any type, try to rebuild it
5006 /// to have a function type.
5007 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5008 
5009 /// Is the given type a placeholder that we need to lower out
5010 /// immediately during argument processing?
5011 static bool isPlaceholderToRemoveAsArg(QualType type) {
5012   // Placeholders are never sugared.
5013   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5014   if (!placeholder) return false;
5015 
5016   switch (placeholder->getKind()) {
5017   // Ignore all the non-placeholder types.
5018 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5019   case BuiltinType::Id:
5020 #include "clang/Basic/OpenCLImageTypes.def"
5021 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5022 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5023 #include "clang/AST/BuiltinTypes.def"
5024     return false;
5025 
5026   // We cannot lower out overload sets; they might validly be resolved
5027   // by the call machinery.
5028   case BuiltinType::Overload:
5029     return false;
5030 
5031   // Unbridged casts in ARC can be handled in some call positions and
5032   // should be left in place.
5033   case BuiltinType::ARCUnbridgedCast:
5034     return false;
5035 
5036   // Pseudo-objects should be converted as soon as possible.
5037   case BuiltinType::PseudoObject:
5038     return true;
5039 
5040   // The debugger mode could theoretically but currently does not try
5041   // to resolve unknown-typed arguments based on known parameter types.
5042   case BuiltinType::UnknownAny:
5043     return true;
5044 
5045   // These are always invalid as call arguments and should be reported.
5046   case BuiltinType::BoundMember:
5047   case BuiltinType::BuiltinFn:
5048   case BuiltinType::OMPArraySection:
5049     return true;
5050 
5051   }
5052   llvm_unreachable("bad builtin type kind");
5053 }
5054 
5055 /// Check an argument list for placeholders that we won't try to
5056 /// handle later.
5057 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5058   // Apply this processing to all the arguments at once instead of
5059   // dying at the first failure.
5060   bool hasInvalid = false;
5061   for (size_t i = 0, e = args.size(); i != e; i++) {
5062     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5063       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5064       if (result.isInvalid()) hasInvalid = true;
5065       else args[i] = result.get();
5066     } else if (hasInvalid) {
5067       (void)S.CorrectDelayedTyposInExpr(args[i]);
5068     }
5069   }
5070   return hasInvalid;
5071 }
5072 
5073 /// If a builtin function has a pointer argument with no explicit address
5074 /// space, then it should be able to accept a pointer to any address
5075 /// space as input.  In order to do this, we need to replace the
5076 /// standard builtin declaration with one that uses the same address space
5077 /// as the call.
5078 ///
5079 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5080 ///                  it does not contain any pointer arguments without
5081 ///                  an address space qualifer.  Otherwise the rewritten
5082 ///                  FunctionDecl is returned.
5083 /// TODO: Handle pointer return types.
5084 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5085                                                 const FunctionDecl *FDecl,
5086                                                 MultiExprArg ArgExprs) {
5087 
5088   QualType DeclType = FDecl->getType();
5089   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5090 
5091   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5092       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5093     return nullptr;
5094 
5095   bool NeedsNewDecl = false;
5096   unsigned i = 0;
5097   SmallVector<QualType, 8> OverloadParams;
5098 
5099   for (QualType ParamType : FT->param_types()) {
5100 
5101     // Convert array arguments to pointer to simplify type lookup.
5102     ExprResult ArgRes =
5103         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5104     if (ArgRes.isInvalid())
5105       return nullptr;
5106     Expr *Arg = ArgRes.get();
5107     QualType ArgType = Arg->getType();
5108     if (!ParamType->isPointerType() ||
5109         ParamType.getQualifiers().hasAddressSpace() ||
5110         !ArgType->isPointerType() ||
5111         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5112       OverloadParams.push_back(ParamType);
5113       continue;
5114     }
5115 
5116     NeedsNewDecl = true;
5117     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5118 
5119     QualType PointeeType = ParamType->getPointeeType();
5120     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5121     OverloadParams.push_back(Context.getPointerType(PointeeType));
5122   }
5123 
5124   if (!NeedsNewDecl)
5125     return nullptr;
5126 
5127   FunctionProtoType::ExtProtoInfo EPI;
5128   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5129                                                 OverloadParams, EPI);
5130   DeclContext *Parent = Context.getTranslationUnitDecl();
5131   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5132                                                     FDecl->getLocation(),
5133                                                     FDecl->getLocation(),
5134                                                     FDecl->getIdentifier(),
5135                                                     OverloadTy,
5136                                                     /*TInfo=*/nullptr,
5137                                                     SC_Extern, false,
5138                                                     /*hasPrototype=*/true);
5139   SmallVector<ParmVarDecl*, 16> Params;
5140   FT = cast<FunctionProtoType>(OverloadTy);
5141   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5142     QualType ParamType = FT->getParamType(i);
5143     ParmVarDecl *Parm =
5144         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5145                                 SourceLocation(), nullptr, ParamType,
5146                                 /*TInfo=*/nullptr, SC_None, nullptr);
5147     Parm->setScopeInfo(0, i);
5148     Params.push_back(Parm);
5149   }
5150   OverloadDecl->setParams(Params);
5151   return OverloadDecl;
5152 }
5153 
5154 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5155                                        std::size_t NumArgs) {
5156   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5157                          /*PartialOverloading=*/false))
5158     return Callee->isVariadic();
5159   return Callee->getMinRequiredArguments() <= NumArgs;
5160 }
5161 
5162 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5163 /// This provides the location of the left/right parens and a list of comma
5164 /// locations.
5165 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5166                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5167                                Expr *ExecConfig, bool IsExecConfig) {
5168   // Since this might be a postfix expression, get rid of ParenListExprs.
5169   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5170   if (Result.isInvalid()) return ExprError();
5171   Fn = Result.get();
5172 
5173   if (checkArgsForPlaceholders(*this, ArgExprs))
5174     return ExprError();
5175 
5176   if (getLangOpts().CPlusPlus) {
5177     // If this is a pseudo-destructor expression, build the call immediately.
5178     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5179       if (!ArgExprs.empty()) {
5180         // Pseudo-destructor calls should not have any arguments.
5181         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5182             << FixItHint::CreateRemoval(
5183                    SourceRange(ArgExprs.front()->getLocStart(),
5184                                ArgExprs.back()->getLocEnd()));
5185       }
5186 
5187       return new (Context)
5188           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5189     }
5190     if (Fn->getType() == Context.PseudoObjectTy) {
5191       ExprResult result = CheckPlaceholderExpr(Fn);
5192       if (result.isInvalid()) return ExprError();
5193       Fn = result.get();
5194     }
5195 
5196     // Determine whether this is a dependent call inside a C++ template,
5197     // in which case we won't do any semantic analysis now.
5198     bool Dependent = false;
5199     if (Fn->isTypeDependent())
5200       Dependent = true;
5201     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5202       Dependent = true;
5203 
5204     if (Dependent) {
5205       if (ExecConfig) {
5206         return new (Context) CUDAKernelCallExpr(
5207             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5208             Context.DependentTy, VK_RValue, RParenLoc);
5209       } else {
5210         return new (Context) CallExpr(
5211             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5212       }
5213     }
5214 
5215     // Determine whether this is a call to an object (C++ [over.call.object]).
5216     if (Fn->getType()->isRecordType())
5217       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5218                                           RParenLoc);
5219 
5220     if (Fn->getType() == Context.UnknownAnyTy) {
5221       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5222       if (result.isInvalid()) return ExprError();
5223       Fn = result.get();
5224     }
5225 
5226     if (Fn->getType() == Context.BoundMemberTy) {
5227       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5228                                        RParenLoc);
5229     }
5230   }
5231 
5232   // Check for overloaded calls.  This can happen even in C due to extensions.
5233   if (Fn->getType() == Context.OverloadTy) {
5234     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5235 
5236     // We aren't supposed to apply this logic for if there'Scope an '&'
5237     // involved.
5238     if (!find.HasFormOfMemberPointer) {
5239       OverloadExpr *ovl = find.Expression;
5240       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5241         return BuildOverloadedCallExpr(
5242             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5243             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5244       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5245                                        RParenLoc);
5246     }
5247   }
5248 
5249   // If we're directly calling a function, get the appropriate declaration.
5250   if (Fn->getType() == Context.UnknownAnyTy) {
5251     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5252     if (result.isInvalid()) return ExprError();
5253     Fn = result.get();
5254   }
5255 
5256   Expr *NakedFn = Fn->IgnoreParens();
5257 
5258   bool CallingNDeclIndirectly = false;
5259   NamedDecl *NDecl = nullptr;
5260   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5261     if (UnOp->getOpcode() == UO_AddrOf) {
5262       CallingNDeclIndirectly = true;
5263       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5264     }
5265   }
5266 
5267   if (isa<DeclRefExpr>(NakedFn)) {
5268     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5269 
5270     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5271     if (FDecl && FDecl->getBuiltinID()) {
5272       // Rewrite the function decl for this builtin by replacing parameters
5273       // with no explicit address space with the address space of the arguments
5274       // in ArgExprs.
5275       if ((FDecl =
5276                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5277         NDecl = FDecl;
5278         Fn = DeclRefExpr::Create(
5279             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5280             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5281       }
5282     }
5283   } else if (isa<MemberExpr>(NakedFn))
5284     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5285 
5286   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5287     if (CallingNDeclIndirectly &&
5288         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5289                                            Fn->getLocStart()))
5290       return ExprError();
5291 
5292     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5293       return ExprError();
5294 
5295     // CheckEnableIf assumes that the we're passing in a sane number of args for
5296     // FD, but that doesn't always hold true here. This is because, in some
5297     // cases, we'll emit a diag about an ill-formed function call, but then
5298     // we'll continue on as if the function call wasn't ill-formed. So, if the
5299     // number of args looks incorrect, don't do enable_if checks; we should've
5300     // already emitted an error about the bad call.
5301     if (FD->hasAttr<EnableIfAttr>() &&
5302         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5303       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5304         Diag(Fn->getLocStart(),
5305              isa<CXXMethodDecl>(FD)
5306                  ? diag::err_ovl_no_viable_member_function_in_call
5307                  : diag::err_ovl_no_viable_function_in_call)
5308             << FD << FD->getSourceRange();
5309         Diag(FD->getLocation(),
5310              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5311             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5312       }
5313     }
5314   }
5315 
5316   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5317                                ExecConfig, IsExecConfig);
5318 }
5319 
5320 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5321 ///
5322 /// __builtin_astype( value, dst type )
5323 ///
5324 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5325                                  SourceLocation BuiltinLoc,
5326                                  SourceLocation RParenLoc) {
5327   ExprValueKind VK = VK_RValue;
5328   ExprObjectKind OK = OK_Ordinary;
5329   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5330   QualType SrcTy = E->getType();
5331   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5332     return ExprError(Diag(BuiltinLoc,
5333                           diag::err_invalid_astype_of_different_size)
5334                      << DstTy
5335                      << SrcTy
5336                      << E->getSourceRange());
5337   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5338 }
5339 
5340 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5341 /// provided arguments.
5342 ///
5343 /// __builtin_convertvector( value, dst type )
5344 ///
5345 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5346                                         SourceLocation BuiltinLoc,
5347                                         SourceLocation RParenLoc) {
5348   TypeSourceInfo *TInfo;
5349   GetTypeFromParser(ParsedDestTy, &TInfo);
5350   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5351 }
5352 
5353 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5354 /// i.e. an expression not of \p OverloadTy.  The expression should
5355 /// unary-convert to an expression of function-pointer or
5356 /// block-pointer type.
5357 ///
5358 /// \param NDecl the declaration being called, if available
5359 ExprResult
5360 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5361                             SourceLocation LParenLoc,
5362                             ArrayRef<Expr *> Args,
5363                             SourceLocation RParenLoc,
5364                             Expr *Config, bool IsExecConfig) {
5365   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5366   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5367 
5368   // Functions with 'interrupt' attribute cannot be called directly.
5369   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5370     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5371     return ExprError();
5372   }
5373 
5374   // Promote the function operand.
5375   // We special-case function promotion here because we only allow promoting
5376   // builtin functions to function pointers in the callee of a call.
5377   ExprResult Result;
5378   if (BuiltinID &&
5379       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5380     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5381                                CK_BuiltinFnToFnPtr).get();
5382   } else {
5383     Result = CallExprUnaryConversions(Fn);
5384   }
5385   if (Result.isInvalid())
5386     return ExprError();
5387   Fn = Result.get();
5388 
5389   // Make the call expr early, before semantic checks.  This guarantees cleanup
5390   // of arguments and function on error.
5391   CallExpr *TheCall;
5392   if (Config)
5393     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5394                                                cast<CallExpr>(Config), Args,
5395                                                Context.BoolTy, VK_RValue,
5396                                                RParenLoc);
5397   else
5398     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5399                                      VK_RValue, RParenLoc);
5400 
5401   if (!getLangOpts().CPlusPlus) {
5402     // C cannot always handle TypoExpr nodes in builtin calls and direct
5403     // function calls as their argument checking don't necessarily handle
5404     // dependent types properly, so make sure any TypoExprs have been
5405     // dealt with.
5406     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5407     if (!Result.isUsable()) return ExprError();
5408     TheCall = dyn_cast<CallExpr>(Result.get());
5409     if (!TheCall) return Result;
5410     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5411   }
5412 
5413   // Bail out early if calling a builtin with custom typechecking.
5414   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5415     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5416 
5417  retry:
5418   const FunctionType *FuncT;
5419   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5420     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5421     // have type pointer to function".
5422     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5423     if (!FuncT)
5424       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5425                          << Fn->getType() << Fn->getSourceRange());
5426   } else if (const BlockPointerType *BPT =
5427                Fn->getType()->getAs<BlockPointerType>()) {
5428     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5429   } else {
5430     // Handle calls to expressions of unknown-any type.
5431     if (Fn->getType() == Context.UnknownAnyTy) {
5432       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5433       if (rewrite.isInvalid()) return ExprError();
5434       Fn = rewrite.get();
5435       TheCall->setCallee(Fn);
5436       goto retry;
5437     }
5438 
5439     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5440       << Fn->getType() << Fn->getSourceRange());
5441   }
5442 
5443   if (getLangOpts().CUDA) {
5444     if (Config) {
5445       // CUDA: Kernel calls must be to global functions
5446       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5447         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5448             << FDecl->getName() << Fn->getSourceRange());
5449 
5450       // CUDA: Kernel function must have 'void' return type
5451       if (!FuncT->getReturnType()->isVoidType())
5452         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5453             << Fn->getType() << Fn->getSourceRange());
5454     } else {
5455       // CUDA: Calls to global functions must be configured
5456       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5457         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5458             << FDecl->getName() << Fn->getSourceRange());
5459     }
5460   }
5461 
5462   // Check for a valid return type
5463   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5464                           FDecl))
5465     return ExprError();
5466 
5467   // We know the result type of the call, set it.
5468   TheCall->setType(FuncT->getCallResultType(Context));
5469   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5470 
5471   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5472   if (Proto) {
5473     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5474                                 IsExecConfig))
5475       return ExprError();
5476   } else {
5477     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5478 
5479     if (FDecl) {
5480       // Check if we have too few/too many template arguments, based
5481       // on our knowledge of the function definition.
5482       const FunctionDecl *Def = nullptr;
5483       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5484         Proto = Def->getType()->getAs<FunctionProtoType>();
5485        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5486           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5487           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5488       }
5489 
5490       // If the function we're calling isn't a function prototype, but we have
5491       // a function prototype from a prior declaratiom, use that prototype.
5492       if (!FDecl->hasPrototype())
5493         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5494     }
5495 
5496     // Promote the arguments (C99 6.5.2.2p6).
5497     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5498       Expr *Arg = Args[i];
5499 
5500       if (Proto && i < Proto->getNumParams()) {
5501         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5502             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5503         ExprResult ArgE =
5504             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5505         if (ArgE.isInvalid())
5506           return true;
5507 
5508         Arg = ArgE.getAs<Expr>();
5509 
5510       } else {
5511         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5512 
5513         if (ArgE.isInvalid())
5514           return true;
5515 
5516         Arg = ArgE.getAs<Expr>();
5517       }
5518 
5519       if (RequireCompleteType(Arg->getLocStart(),
5520                               Arg->getType(),
5521                               diag::err_call_incomplete_argument, Arg))
5522         return ExprError();
5523 
5524       TheCall->setArg(i, Arg);
5525     }
5526   }
5527 
5528   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5529     if (!Method->isStatic())
5530       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5531         << Fn->getSourceRange());
5532 
5533   // Check for sentinels
5534   if (NDecl)
5535     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5536 
5537   // Do special checking on direct calls to functions.
5538   if (FDecl) {
5539     if (CheckFunctionCall(FDecl, TheCall, Proto))
5540       return ExprError();
5541 
5542     if (BuiltinID)
5543       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5544   } else if (NDecl) {
5545     if (CheckPointerCall(NDecl, TheCall, Proto))
5546       return ExprError();
5547   } else {
5548     if (CheckOtherCall(TheCall, Proto))
5549       return ExprError();
5550   }
5551 
5552   return MaybeBindToTemporary(TheCall);
5553 }
5554 
5555 ExprResult
5556 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5557                            SourceLocation RParenLoc, Expr *InitExpr) {
5558   assert(Ty && "ActOnCompoundLiteral(): missing type");
5559   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5560 
5561   TypeSourceInfo *TInfo;
5562   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5563   if (!TInfo)
5564     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5565 
5566   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5567 }
5568 
5569 ExprResult
5570 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5571                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5572   QualType literalType = TInfo->getType();
5573 
5574   if (literalType->isArrayType()) {
5575     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5576           diag::err_illegal_decl_array_incomplete_type,
5577           SourceRange(LParenLoc,
5578                       LiteralExpr->getSourceRange().getEnd())))
5579       return ExprError();
5580     if (literalType->isVariableArrayType())
5581       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5582         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5583   } else if (!literalType->isDependentType() &&
5584              RequireCompleteType(LParenLoc, literalType,
5585                diag::err_typecheck_decl_incomplete_type,
5586                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5587     return ExprError();
5588 
5589   InitializedEntity Entity
5590     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5591   InitializationKind Kind
5592     = InitializationKind::CreateCStyleCast(LParenLoc,
5593                                            SourceRange(LParenLoc, RParenLoc),
5594                                            /*InitList=*/true);
5595   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5596   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5597                                       &literalType);
5598   if (Result.isInvalid())
5599     return ExprError();
5600   LiteralExpr = Result.get();
5601 
5602   bool isFileScope = !CurContext->isFunctionOrMethod();
5603   if (isFileScope &&
5604       !LiteralExpr->isTypeDependent() &&
5605       !LiteralExpr->isValueDependent() &&
5606       !literalType->isDependentType()) { // 6.5.2.5p3
5607     if (CheckForConstantInitializer(LiteralExpr, literalType))
5608       return ExprError();
5609   }
5610 
5611   // In C, compound literals are l-values for some reason.
5612   // For GCC compatibility, in C++, file-scope array compound literals with
5613   // constant initializers are also l-values, and compound literals are
5614   // otherwise prvalues.
5615   //
5616   // (GCC also treats C++ list-initialized file-scope array prvalues with
5617   // constant initializers as l-values, but that's non-conforming, so we don't
5618   // follow it there.)
5619   //
5620   // FIXME: It would be better to handle the lvalue cases as materializing and
5621   // lifetime-extending a temporary object, but our materialized temporaries
5622   // representation only supports lifetime extension from a variable, not "out
5623   // of thin air".
5624   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5625   // is bound to the result of applying array-to-pointer decay to the compound
5626   // literal.
5627   // FIXME: GCC supports compound literals of reference type, which should
5628   // obviously have a value kind derived from the kind of reference involved.
5629   ExprValueKind VK =
5630       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5631           ? VK_RValue
5632           : VK_LValue;
5633 
5634   return MaybeBindToTemporary(
5635       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5636                                         VK, LiteralExpr, isFileScope));
5637 }
5638 
5639 ExprResult
5640 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5641                     SourceLocation RBraceLoc) {
5642   // Immediately handle non-overload placeholders.  Overloads can be
5643   // resolved contextually, but everything else here can't.
5644   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5645     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5646       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5647 
5648       // Ignore failures; dropping the entire initializer list because
5649       // of one failure would be terrible for indexing/etc.
5650       if (result.isInvalid()) continue;
5651 
5652       InitArgList[I] = result.get();
5653     }
5654   }
5655 
5656   // Semantic analysis for initializers is done by ActOnDeclarator() and
5657   // CheckInitializer() - it requires knowledge of the object being intialized.
5658 
5659   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5660                                                RBraceLoc);
5661   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5662   return E;
5663 }
5664 
5665 /// Do an explicit extend of the given block pointer if we're in ARC.
5666 void Sema::maybeExtendBlockObject(ExprResult &E) {
5667   assert(E.get()->getType()->isBlockPointerType());
5668   assert(E.get()->isRValue());
5669 
5670   // Only do this in an r-value context.
5671   if (!getLangOpts().ObjCAutoRefCount) return;
5672 
5673   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5674                                CK_ARCExtendBlockObject, E.get(),
5675                                /*base path*/ nullptr, VK_RValue);
5676   Cleanup.setExprNeedsCleanups(true);
5677 }
5678 
5679 /// Prepare a conversion of the given expression to an ObjC object
5680 /// pointer type.
5681 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5682   QualType type = E.get()->getType();
5683   if (type->isObjCObjectPointerType()) {
5684     return CK_BitCast;
5685   } else if (type->isBlockPointerType()) {
5686     maybeExtendBlockObject(E);
5687     return CK_BlockPointerToObjCPointerCast;
5688   } else {
5689     assert(type->isPointerType());
5690     return CK_CPointerToObjCPointerCast;
5691   }
5692 }
5693 
5694 /// Prepares for a scalar cast, performing all the necessary stages
5695 /// except the final cast and returning the kind required.
5696 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5697   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5698   // Also, callers should have filtered out the invalid cases with
5699   // pointers.  Everything else should be possible.
5700 
5701   QualType SrcTy = Src.get()->getType();
5702   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5703     return CK_NoOp;
5704 
5705   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5706   case Type::STK_MemberPointer:
5707     llvm_unreachable("member pointer type in C");
5708 
5709   case Type::STK_CPointer:
5710   case Type::STK_BlockPointer:
5711   case Type::STK_ObjCObjectPointer:
5712     switch (DestTy->getScalarTypeKind()) {
5713     case Type::STK_CPointer: {
5714       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5715       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5716       if (SrcAS != DestAS)
5717         return CK_AddressSpaceConversion;
5718       return CK_BitCast;
5719     }
5720     case Type::STK_BlockPointer:
5721       return (SrcKind == Type::STK_BlockPointer
5722                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5723     case Type::STK_ObjCObjectPointer:
5724       if (SrcKind == Type::STK_ObjCObjectPointer)
5725         return CK_BitCast;
5726       if (SrcKind == Type::STK_CPointer)
5727         return CK_CPointerToObjCPointerCast;
5728       maybeExtendBlockObject(Src);
5729       return CK_BlockPointerToObjCPointerCast;
5730     case Type::STK_Bool:
5731       return CK_PointerToBoolean;
5732     case Type::STK_Integral:
5733       return CK_PointerToIntegral;
5734     case Type::STK_Floating:
5735     case Type::STK_FloatingComplex:
5736     case Type::STK_IntegralComplex:
5737     case Type::STK_MemberPointer:
5738       llvm_unreachable("illegal cast from pointer");
5739     }
5740     llvm_unreachable("Should have returned before this");
5741 
5742   case Type::STK_Bool: // casting from bool is like casting from an integer
5743   case Type::STK_Integral:
5744     switch (DestTy->getScalarTypeKind()) {
5745     case Type::STK_CPointer:
5746     case Type::STK_ObjCObjectPointer:
5747     case Type::STK_BlockPointer:
5748       if (Src.get()->isNullPointerConstant(Context,
5749                                            Expr::NPC_ValueDependentIsNull))
5750         return CK_NullToPointer;
5751       return CK_IntegralToPointer;
5752     case Type::STK_Bool:
5753       return CK_IntegralToBoolean;
5754     case Type::STK_Integral:
5755       return CK_IntegralCast;
5756     case Type::STK_Floating:
5757       return CK_IntegralToFloating;
5758     case Type::STK_IntegralComplex:
5759       Src = ImpCastExprToType(Src.get(),
5760                       DestTy->castAs<ComplexType>()->getElementType(),
5761                       CK_IntegralCast);
5762       return CK_IntegralRealToComplex;
5763     case Type::STK_FloatingComplex:
5764       Src = ImpCastExprToType(Src.get(),
5765                       DestTy->castAs<ComplexType>()->getElementType(),
5766                       CK_IntegralToFloating);
5767       return CK_FloatingRealToComplex;
5768     case Type::STK_MemberPointer:
5769       llvm_unreachable("member pointer type in C");
5770     }
5771     llvm_unreachable("Should have returned before this");
5772 
5773   case Type::STK_Floating:
5774     switch (DestTy->getScalarTypeKind()) {
5775     case Type::STK_Floating:
5776       return CK_FloatingCast;
5777     case Type::STK_Bool:
5778       return CK_FloatingToBoolean;
5779     case Type::STK_Integral:
5780       return CK_FloatingToIntegral;
5781     case Type::STK_FloatingComplex:
5782       Src = ImpCastExprToType(Src.get(),
5783                               DestTy->castAs<ComplexType>()->getElementType(),
5784                               CK_FloatingCast);
5785       return CK_FloatingRealToComplex;
5786     case Type::STK_IntegralComplex:
5787       Src = ImpCastExprToType(Src.get(),
5788                               DestTy->castAs<ComplexType>()->getElementType(),
5789                               CK_FloatingToIntegral);
5790       return CK_IntegralRealToComplex;
5791     case Type::STK_CPointer:
5792     case Type::STK_ObjCObjectPointer:
5793     case Type::STK_BlockPointer:
5794       llvm_unreachable("valid float->pointer cast?");
5795     case Type::STK_MemberPointer:
5796       llvm_unreachable("member pointer type in C");
5797     }
5798     llvm_unreachable("Should have returned before this");
5799 
5800   case Type::STK_FloatingComplex:
5801     switch (DestTy->getScalarTypeKind()) {
5802     case Type::STK_FloatingComplex:
5803       return CK_FloatingComplexCast;
5804     case Type::STK_IntegralComplex:
5805       return CK_FloatingComplexToIntegralComplex;
5806     case Type::STK_Floating: {
5807       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5808       if (Context.hasSameType(ET, DestTy))
5809         return CK_FloatingComplexToReal;
5810       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5811       return CK_FloatingCast;
5812     }
5813     case Type::STK_Bool:
5814       return CK_FloatingComplexToBoolean;
5815     case Type::STK_Integral:
5816       Src = ImpCastExprToType(Src.get(),
5817                               SrcTy->castAs<ComplexType>()->getElementType(),
5818                               CK_FloatingComplexToReal);
5819       return CK_FloatingToIntegral;
5820     case Type::STK_CPointer:
5821     case Type::STK_ObjCObjectPointer:
5822     case Type::STK_BlockPointer:
5823       llvm_unreachable("valid complex float->pointer cast?");
5824     case Type::STK_MemberPointer:
5825       llvm_unreachable("member pointer type in C");
5826     }
5827     llvm_unreachable("Should have returned before this");
5828 
5829   case Type::STK_IntegralComplex:
5830     switch (DestTy->getScalarTypeKind()) {
5831     case Type::STK_FloatingComplex:
5832       return CK_IntegralComplexToFloatingComplex;
5833     case Type::STK_IntegralComplex:
5834       return CK_IntegralComplexCast;
5835     case Type::STK_Integral: {
5836       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5837       if (Context.hasSameType(ET, DestTy))
5838         return CK_IntegralComplexToReal;
5839       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5840       return CK_IntegralCast;
5841     }
5842     case Type::STK_Bool:
5843       return CK_IntegralComplexToBoolean;
5844     case Type::STK_Floating:
5845       Src = ImpCastExprToType(Src.get(),
5846                               SrcTy->castAs<ComplexType>()->getElementType(),
5847                               CK_IntegralComplexToReal);
5848       return CK_IntegralToFloating;
5849     case Type::STK_CPointer:
5850     case Type::STK_ObjCObjectPointer:
5851     case Type::STK_BlockPointer:
5852       llvm_unreachable("valid complex int->pointer cast?");
5853     case Type::STK_MemberPointer:
5854       llvm_unreachable("member pointer type in C");
5855     }
5856     llvm_unreachable("Should have returned before this");
5857   }
5858 
5859   llvm_unreachable("Unhandled scalar cast");
5860 }
5861 
5862 static bool breakDownVectorType(QualType type, uint64_t &len,
5863                                 QualType &eltType) {
5864   // Vectors are simple.
5865   if (const VectorType *vecType = type->getAs<VectorType>()) {
5866     len = vecType->getNumElements();
5867     eltType = vecType->getElementType();
5868     assert(eltType->isScalarType());
5869     return true;
5870   }
5871 
5872   // We allow lax conversion to and from non-vector types, but only if
5873   // they're real types (i.e. non-complex, non-pointer scalar types).
5874   if (!type->isRealType()) return false;
5875 
5876   len = 1;
5877   eltType = type;
5878   return true;
5879 }
5880 
5881 /// Are the two types lax-compatible vector types?  That is, given
5882 /// that one of them is a vector, do they have equal storage sizes,
5883 /// where the storage size is the number of elements times the element
5884 /// size?
5885 ///
5886 /// This will also return false if either of the types is neither a
5887 /// vector nor a real type.
5888 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5889   assert(destTy->isVectorType() || srcTy->isVectorType());
5890 
5891   // Disallow lax conversions between scalars and ExtVectors (these
5892   // conversions are allowed for other vector types because common headers
5893   // depend on them).  Most scalar OP ExtVector cases are handled by the
5894   // splat path anyway, which does what we want (convert, not bitcast).
5895   // What this rules out for ExtVectors is crazy things like char4*float.
5896   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5897   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5898 
5899   uint64_t srcLen, destLen;
5900   QualType srcEltTy, destEltTy;
5901   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5902   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5903 
5904   // ASTContext::getTypeSize will return the size rounded up to a
5905   // power of 2, so instead of using that, we need to use the raw
5906   // element size multiplied by the element count.
5907   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5908   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5909 
5910   return (srcLen * srcEltSize == destLen * destEltSize);
5911 }
5912 
5913 /// Is this a legal conversion between two types, one of which is
5914 /// known to be a vector type?
5915 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5916   assert(destTy->isVectorType() || srcTy->isVectorType());
5917 
5918   if (!Context.getLangOpts().LaxVectorConversions)
5919     return false;
5920   return areLaxCompatibleVectorTypes(srcTy, destTy);
5921 }
5922 
5923 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5924                            CastKind &Kind) {
5925   assert(VectorTy->isVectorType() && "Not a vector type!");
5926 
5927   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5928     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5929       return Diag(R.getBegin(),
5930                   Ty->isVectorType() ?
5931                   diag::err_invalid_conversion_between_vectors :
5932                   diag::err_invalid_conversion_between_vector_and_integer)
5933         << VectorTy << Ty << R;
5934   } else
5935     return Diag(R.getBegin(),
5936                 diag::err_invalid_conversion_between_vector_and_scalar)
5937       << VectorTy << Ty << R;
5938 
5939   Kind = CK_BitCast;
5940   return false;
5941 }
5942 
5943 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5944   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5945 
5946   if (DestElemTy == SplattedExpr->getType())
5947     return SplattedExpr;
5948 
5949   assert(DestElemTy->isFloatingType() ||
5950          DestElemTy->isIntegralOrEnumerationType());
5951 
5952   CastKind CK;
5953   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5954     // OpenCL requires that we convert `true` boolean expressions to -1, but
5955     // only when splatting vectors.
5956     if (DestElemTy->isFloatingType()) {
5957       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5958       // in two steps: boolean to signed integral, then to floating.
5959       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5960                                                  CK_BooleanToSignedIntegral);
5961       SplattedExpr = CastExprRes.get();
5962       CK = CK_IntegralToFloating;
5963     } else {
5964       CK = CK_BooleanToSignedIntegral;
5965     }
5966   } else {
5967     ExprResult CastExprRes = SplattedExpr;
5968     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5969     if (CastExprRes.isInvalid())
5970       return ExprError();
5971     SplattedExpr = CastExprRes.get();
5972   }
5973   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5974 }
5975 
5976 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5977                                     Expr *CastExpr, CastKind &Kind) {
5978   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5979 
5980   QualType SrcTy = CastExpr->getType();
5981 
5982   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5983   // an ExtVectorType.
5984   // In OpenCL, casts between vectors of different types are not allowed.
5985   // (See OpenCL 6.2).
5986   if (SrcTy->isVectorType()) {
5987     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5988         || (getLangOpts().OpenCL &&
5989             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5990       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5991         << DestTy << SrcTy << R;
5992       return ExprError();
5993     }
5994     Kind = CK_BitCast;
5995     return CastExpr;
5996   }
5997 
5998   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5999   // conversion will take place first from scalar to elt type, and then
6000   // splat from elt type to vector.
6001   if (SrcTy->isPointerType())
6002     return Diag(R.getBegin(),
6003                 diag::err_invalid_conversion_between_vector_and_scalar)
6004       << DestTy << SrcTy << R;
6005 
6006   Kind = CK_VectorSplat;
6007   return prepareVectorSplat(DestTy, CastExpr);
6008 }
6009 
6010 ExprResult
6011 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6012                     Declarator &D, ParsedType &Ty,
6013                     SourceLocation RParenLoc, Expr *CastExpr) {
6014   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6015          "ActOnCastExpr(): missing type or expr");
6016 
6017   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6018   if (D.isInvalidType())
6019     return ExprError();
6020 
6021   if (getLangOpts().CPlusPlus) {
6022     // Check that there are no default arguments (C++ only).
6023     CheckExtraCXXDefaultArguments(D);
6024   } else {
6025     // Make sure any TypoExprs have been dealt with.
6026     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6027     if (!Res.isUsable())
6028       return ExprError();
6029     CastExpr = Res.get();
6030   }
6031 
6032   checkUnusedDeclAttributes(D);
6033 
6034   QualType castType = castTInfo->getType();
6035   Ty = CreateParsedType(castType, castTInfo);
6036 
6037   bool isVectorLiteral = false;
6038 
6039   // Check for an altivec or OpenCL literal,
6040   // i.e. all the elements are integer constants.
6041   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6042   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6043   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6044        && castType->isVectorType() && (PE || PLE)) {
6045     if (PLE && PLE->getNumExprs() == 0) {
6046       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6047       return ExprError();
6048     }
6049     if (PE || PLE->getNumExprs() == 1) {
6050       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6051       if (!E->getType()->isVectorType())
6052         isVectorLiteral = true;
6053     }
6054     else
6055       isVectorLiteral = true;
6056   }
6057 
6058   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6059   // then handle it as such.
6060   if (isVectorLiteral)
6061     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6062 
6063   // If the Expr being casted is a ParenListExpr, handle it specially.
6064   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6065   // sequence of BinOp comma operators.
6066   if (isa<ParenListExpr>(CastExpr)) {
6067     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6068     if (Result.isInvalid()) return ExprError();
6069     CastExpr = Result.get();
6070   }
6071 
6072   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6073       !getSourceManager().isInSystemMacro(LParenLoc))
6074     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6075 
6076   CheckTollFreeBridgeCast(castType, CastExpr);
6077 
6078   CheckObjCBridgeRelatedCast(castType, CastExpr);
6079 
6080   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6081 
6082   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6083 }
6084 
6085 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6086                                     SourceLocation RParenLoc, Expr *E,
6087                                     TypeSourceInfo *TInfo) {
6088   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6089          "Expected paren or paren list expression");
6090 
6091   Expr **exprs;
6092   unsigned numExprs;
6093   Expr *subExpr;
6094   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6095   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6096     LiteralLParenLoc = PE->getLParenLoc();
6097     LiteralRParenLoc = PE->getRParenLoc();
6098     exprs = PE->getExprs();
6099     numExprs = PE->getNumExprs();
6100   } else { // isa<ParenExpr> by assertion at function entrance
6101     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6102     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6103     subExpr = cast<ParenExpr>(E)->getSubExpr();
6104     exprs = &subExpr;
6105     numExprs = 1;
6106   }
6107 
6108   QualType Ty = TInfo->getType();
6109   assert(Ty->isVectorType() && "Expected vector type");
6110 
6111   SmallVector<Expr *, 8> initExprs;
6112   const VectorType *VTy = Ty->getAs<VectorType>();
6113   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6114 
6115   // '(...)' form of vector initialization in AltiVec: the number of
6116   // initializers must be one or must match the size of the vector.
6117   // If a single value is specified in the initializer then it will be
6118   // replicated to all the components of the vector
6119   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6120     // The number of initializers must be one or must match the size of the
6121     // vector. If a single value is specified in the initializer then it will
6122     // be replicated to all the components of the vector
6123     if (numExprs == 1) {
6124       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6125       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6126       if (Literal.isInvalid())
6127         return ExprError();
6128       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6129                                   PrepareScalarCast(Literal, ElemTy));
6130       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6131     }
6132     else if (numExprs < numElems) {
6133       Diag(E->getExprLoc(),
6134            diag::err_incorrect_number_of_vector_initializers);
6135       return ExprError();
6136     }
6137     else
6138       initExprs.append(exprs, exprs + numExprs);
6139   }
6140   else {
6141     // For OpenCL, when the number of initializers is a single value,
6142     // it will be replicated to all components of the vector.
6143     if (getLangOpts().OpenCL &&
6144         VTy->getVectorKind() == VectorType::GenericVector &&
6145         numExprs == 1) {
6146         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6147         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6148         if (Literal.isInvalid())
6149           return ExprError();
6150         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6151                                     PrepareScalarCast(Literal, ElemTy));
6152         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6153     }
6154 
6155     initExprs.append(exprs, exprs + numExprs);
6156   }
6157   // FIXME: This means that pretty-printing the final AST will produce curly
6158   // braces instead of the original commas.
6159   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6160                                                    initExprs, LiteralRParenLoc);
6161   initE->setType(Ty);
6162   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6163 }
6164 
6165 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6166 /// the ParenListExpr into a sequence of comma binary operators.
6167 ExprResult
6168 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6169   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6170   if (!E)
6171     return OrigExpr;
6172 
6173   ExprResult Result(E->getExpr(0));
6174 
6175   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6176     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6177                         E->getExpr(i));
6178 
6179   if (Result.isInvalid()) return ExprError();
6180 
6181   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6182 }
6183 
6184 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6185                                     SourceLocation R,
6186                                     MultiExprArg Val) {
6187   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6188   return expr;
6189 }
6190 
6191 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6192 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6193 /// emitted.
6194 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6195                                       SourceLocation QuestionLoc) {
6196   Expr *NullExpr = LHSExpr;
6197   Expr *NonPointerExpr = RHSExpr;
6198   Expr::NullPointerConstantKind NullKind =
6199       NullExpr->isNullPointerConstant(Context,
6200                                       Expr::NPC_ValueDependentIsNotNull);
6201 
6202   if (NullKind == Expr::NPCK_NotNull) {
6203     NullExpr = RHSExpr;
6204     NonPointerExpr = LHSExpr;
6205     NullKind =
6206         NullExpr->isNullPointerConstant(Context,
6207                                         Expr::NPC_ValueDependentIsNotNull);
6208   }
6209 
6210   if (NullKind == Expr::NPCK_NotNull)
6211     return false;
6212 
6213   if (NullKind == Expr::NPCK_ZeroExpression)
6214     return false;
6215 
6216   if (NullKind == Expr::NPCK_ZeroLiteral) {
6217     // In this case, check to make sure that we got here from a "NULL"
6218     // string in the source code.
6219     NullExpr = NullExpr->IgnoreParenImpCasts();
6220     SourceLocation loc = NullExpr->getExprLoc();
6221     if (!findMacroSpelling(loc, "NULL"))
6222       return false;
6223   }
6224 
6225   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6226   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6227       << NonPointerExpr->getType() << DiagType
6228       << NonPointerExpr->getSourceRange();
6229   return true;
6230 }
6231 
6232 /// \brief Return false if the condition expression is valid, true otherwise.
6233 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6234   QualType CondTy = Cond->getType();
6235 
6236   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6237   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6238     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6239       << CondTy << Cond->getSourceRange();
6240     return true;
6241   }
6242 
6243   // C99 6.5.15p2
6244   if (CondTy->isScalarType()) return false;
6245 
6246   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6247     << CondTy << Cond->getSourceRange();
6248   return true;
6249 }
6250 
6251 /// \brief Handle when one or both operands are void type.
6252 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6253                                          ExprResult &RHS) {
6254     Expr *LHSExpr = LHS.get();
6255     Expr *RHSExpr = RHS.get();
6256 
6257     if (!LHSExpr->getType()->isVoidType())
6258       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6259         << RHSExpr->getSourceRange();
6260     if (!RHSExpr->getType()->isVoidType())
6261       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6262         << LHSExpr->getSourceRange();
6263     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6264     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6265     return S.Context.VoidTy;
6266 }
6267 
6268 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6269 /// true otherwise.
6270 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6271                                         QualType PointerTy) {
6272   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6273       !NullExpr.get()->isNullPointerConstant(S.Context,
6274                                             Expr::NPC_ValueDependentIsNull))
6275     return true;
6276 
6277   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6278   return false;
6279 }
6280 
6281 /// \brief Checks compatibility between two pointers and return the resulting
6282 /// type.
6283 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6284                                                      ExprResult &RHS,
6285                                                      SourceLocation Loc) {
6286   QualType LHSTy = LHS.get()->getType();
6287   QualType RHSTy = RHS.get()->getType();
6288 
6289   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6290     // Two identical pointers types are always compatible.
6291     return LHSTy;
6292   }
6293 
6294   QualType lhptee, rhptee;
6295 
6296   // Get the pointee types.
6297   bool IsBlockPointer = false;
6298   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6299     lhptee = LHSBTy->getPointeeType();
6300     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6301     IsBlockPointer = true;
6302   } else {
6303     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6304     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6305   }
6306 
6307   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6308   // differently qualified versions of compatible types, the result type is
6309   // a pointer to an appropriately qualified version of the composite
6310   // type.
6311 
6312   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6313   // clause doesn't make sense for our extensions. E.g. address space 2 should
6314   // be incompatible with address space 3: they may live on different devices or
6315   // anything.
6316   Qualifiers lhQual = lhptee.getQualifiers();
6317   Qualifiers rhQual = rhptee.getQualifiers();
6318 
6319   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6320   lhQual.removeCVRQualifiers();
6321   rhQual.removeCVRQualifiers();
6322 
6323   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6324   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6325 
6326   // For OpenCL:
6327   // 1. If LHS and RHS types match exactly and:
6328   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6329   //  (b) AS overlap => generate addrspacecast
6330   //  (c) AS don't overlap => give an error
6331   // 2. if LHS and RHS types don't match:
6332   //  (a) AS match => use standard C rules, generate bitcast
6333   //  (b) AS overlap => generate addrspacecast instead of bitcast
6334   //  (c) AS don't overlap => give an error
6335 
6336   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6337   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6338 
6339   // OpenCL cases 1c, 2a, 2b, and 2c.
6340   if (CompositeTy.isNull()) {
6341     // In this situation, we assume void* type. No especially good
6342     // reason, but this is what gcc does, and we do have to pick
6343     // to get a consistent AST.
6344     QualType incompatTy;
6345     if (S.getLangOpts().OpenCL) {
6346       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6347       // spaces is disallowed.
6348       unsigned ResultAddrSpace;
6349       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6350         // Cases 2a and 2b.
6351         ResultAddrSpace = lhQual.getAddressSpace();
6352       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6353         // Cases 2a and 2b.
6354         ResultAddrSpace = rhQual.getAddressSpace();
6355       } else {
6356         // Cases 1c and 2c.
6357         S.Diag(Loc,
6358                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6359             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6360             << RHS.get()->getSourceRange();
6361         return QualType();
6362       }
6363 
6364       // Continue handling cases 2a and 2b.
6365       incompatTy = S.Context.getPointerType(
6366           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6367       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6368                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6369                                     ? CK_AddressSpaceConversion /* 2b */
6370                                     : CK_BitCast /* 2a */);
6371       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6372                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6373                                     ? CK_AddressSpaceConversion /* 2b */
6374                                     : CK_BitCast /* 2a */);
6375     } else {
6376       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6377           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6378           << RHS.get()->getSourceRange();
6379       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6380       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6381       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6382     }
6383     return incompatTy;
6384   }
6385 
6386   // The pointer types are compatible.
6387   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6388   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6389   if (IsBlockPointer)
6390     ResultTy = S.Context.getBlockPointerType(ResultTy);
6391   else {
6392     // Cases 1a and 1b for OpenCL.
6393     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6394     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6395                       ? CK_BitCast /* 1a */
6396                       : CK_AddressSpaceConversion /* 1b */;
6397     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6398                       ? CK_BitCast /* 1a */
6399                       : CK_AddressSpaceConversion /* 1b */;
6400     ResultTy = S.Context.getPointerType(ResultTy);
6401   }
6402 
6403   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6404   // if the target type does not change.
6405   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6406   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6407   return ResultTy;
6408 }
6409 
6410 /// \brief Return the resulting type when the operands are both block pointers.
6411 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6412                                                           ExprResult &LHS,
6413                                                           ExprResult &RHS,
6414                                                           SourceLocation Loc) {
6415   QualType LHSTy = LHS.get()->getType();
6416   QualType RHSTy = RHS.get()->getType();
6417 
6418   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6419     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6420       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6421       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6422       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6423       return destType;
6424     }
6425     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6426       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6427       << RHS.get()->getSourceRange();
6428     return QualType();
6429   }
6430 
6431   // We have 2 block pointer types.
6432   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6433 }
6434 
6435 /// \brief Return the resulting type when the operands are both pointers.
6436 static QualType
6437 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6438                                             ExprResult &RHS,
6439                                             SourceLocation Loc) {
6440   // get the pointer types
6441   QualType LHSTy = LHS.get()->getType();
6442   QualType RHSTy = RHS.get()->getType();
6443 
6444   // get the "pointed to" types
6445   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6446   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6447 
6448   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6449   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6450     // Figure out necessary qualifiers (C99 6.5.15p6)
6451     QualType destPointee
6452       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6453     QualType destType = S.Context.getPointerType(destPointee);
6454     // Add qualifiers if necessary.
6455     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6456     // Promote to void*.
6457     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6458     return destType;
6459   }
6460   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6461     QualType destPointee
6462       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6463     QualType destType = S.Context.getPointerType(destPointee);
6464     // Add qualifiers if necessary.
6465     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6466     // Promote to void*.
6467     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6468     return destType;
6469   }
6470 
6471   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6472 }
6473 
6474 /// \brief Return false if the first expression is not an integer and the second
6475 /// expression is not a pointer, true otherwise.
6476 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6477                                         Expr* PointerExpr, SourceLocation Loc,
6478                                         bool IsIntFirstExpr) {
6479   if (!PointerExpr->getType()->isPointerType() ||
6480       !Int.get()->getType()->isIntegerType())
6481     return false;
6482 
6483   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6484   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6485 
6486   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6487     << Expr1->getType() << Expr2->getType()
6488     << Expr1->getSourceRange() << Expr2->getSourceRange();
6489   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6490                             CK_IntegralToPointer);
6491   return true;
6492 }
6493 
6494 /// \brief Simple conversion between integer and floating point types.
6495 ///
6496 /// Used when handling the OpenCL conditional operator where the
6497 /// condition is a vector while the other operands are scalar.
6498 ///
6499 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6500 /// types are either integer or floating type. Between the two
6501 /// operands, the type with the higher rank is defined as the "result
6502 /// type". The other operand needs to be promoted to the same type. No
6503 /// other type promotion is allowed. We cannot use
6504 /// UsualArithmeticConversions() for this purpose, since it always
6505 /// promotes promotable types.
6506 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6507                                             ExprResult &RHS,
6508                                             SourceLocation QuestionLoc) {
6509   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6510   if (LHS.isInvalid())
6511     return QualType();
6512   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6513   if (RHS.isInvalid())
6514     return QualType();
6515 
6516   // For conversion purposes, we ignore any qualifiers.
6517   // For example, "const float" and "float" are equivalent.
6518   QualType LHSType =
6519     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6520   QualType RHSType =
6521     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6522 
6523   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6524     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6525       << LHSType << LHS.get()->getSourceRange();
6526     return QualType();
6527   }
6528 
6529   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6530     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6531       << RHSType << RHS.get()->getSourceRange();
6532     return QualType();
6533   }
6534 
6535   // If both types are identical, no conversion is needed.
6536   if (LHSType == RHSType)
6537     return LHSType;
6538 
6539   // Now handle "real" floating types (i.e. float, double, long double).
6540   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6541     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6542                                  /*IsCompAssign = */ false);
6543 
6544   // Finally, we have two differing integer types.
6545   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6546   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6547 }
6548 
6549 /// \brief Convert scalar operands to a vector that matches the
6550 ///        condition in length.
6551 ///
6552 /// Used when handling the OpenCL conditional operator where the
6553 /// condition is a vector while the other operands are scalar.
6554 ///
6555 /// We first compute the "result type" for the scalar operands
6556 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6557 /// into a vector of that type where the length matches the condition
6558 /// vector type. s6.11.6 requires that the element types of the result
6559 /// and the condition must have the same number of bits.
6560 static QualType
6561 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6562                               QualType CondTy, SourceLocation QuestionLoc) {
6563   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6564   if (ResTy.isNull()) return QualType();
6565 
6566   const VectorType *CV = CondTy->getAs<VectorType>();
6567   assert(CV);
6568 
6569   // Determine the vector result type
6570   unsigned NumElements = CV->getNumElements();
6571   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6572 
6573   // Ensure that all types have the same number of bits
6574   if (S.Context.getTypeSize(CV->getElementType())
6575       != S.Context.getTypeSize(ResTy)) {
6576     // Since VectorTy is created internally, it does not pretty print
6577     // with an OpenCL name. Instead, we just print a description.
6578     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6579     SmallString<64> Str;
6580     llvm::raw_svector_ostream OS(Str);
6581     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6582     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6583       << CondTy << OS.str();
6584     return QualType();
6585   }
6586 
6587   // Convert operands to the vector result type
6588   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6589   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6590 
6591   return VectorTy;
6592 }
6593 
6594 /// \brief Return false if this is a valid OpenCL condition vector
6595 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6596                                        SourceLocation QuestionLoc) {
6597   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6598   // integral type.
6599   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6600   assert(CondTy);
6601   QualType EleTy = CondTy->getElementType();
6602   if (EleTy->isIntegerType()) return false;
6603 
6604   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6605     << Cond->getType() << Cond->getSourceRange();
6606   return true;
6607 }
6608 
6609 /// \brief Return false if the vector condition type and the vector
6610 ///        result type are compatible.
6611 ///
6612 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6613 /// number of elements, and their element types have the same number
6614 /// of bits.
6615 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6616                               SourceLocation QuestionLoc) {
6617   const VectorType *CV = CondTy->getAs<VectorType>();
6618   const VectorType *RV = VecResTy->getAs<VectorType>();
6619   assert(CV && RV);
6620 
6621   if (CV->getNumElements() != RV->getNumElements()) {
6622     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6623       << CondTy << VecResTy;
6624     return true;
6625   }
6626 
6627   QualType CVE = CV->getElementType();
6628   QualType RVE = RV->getElementType();
6629 
6630   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6631     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6632       << CondTy << VecResTy;
6633     return true;
6634   }
6635 
6636   return false;
6637 }
6638 
6639 /// \brief Return the resulting type for the conditional operator in
6640 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6641 ///        s6.3.i) when the condition is a vector type.
6642 static QualType
6643 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6644                              ExprResult &LHS, ExprResult &RHS,
6645                              SourceLocation QuestionLoc) {
6646   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6647   if (Cond.isInvalid())
6648     return QualType();
6649   QualType CondTy = Cond.get()->getType();
6650 
6651   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6652     return QualType();
6653 
6654   // If either operand is a vector then find the vector type of the
6655   // result as specified in OpenCL v1.1 s6.3.i.
6656   if (LHS.get()->getType()->isVectorType() ||
6657       RHS.get()->getType()->isVectorType()) {
6658     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6659                                               /*isCompAssign*/false,
6660                                               /*AllowBothBool*/true,
6661                                               /*AllowBoolConversions*/false);
6662     if (VecResTy.isNull()) return QualType();
6663     // The result type must match the condition type as specified in
6664     // OpenCL v1.1 s6.11.6.
6665     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6666       return QualType();
6667     return VecResTy;
6668   }
6669 
6670   // Both operands are scalar.
6671   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6672 }
6673 
6674 /// \brief Return true if the Expr is block type
6675 static bool checkBlockType(Sema &S, const Expr *E) {
6676   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6677     QualType Ty = CE->getCallee()->getType();
6678     if (Ty->isBlockPointerType()) {
6679       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6680       return true;
6681     }
6682   }
6683   return false;
6684 }
6685 
6686 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6687 /// In that case, LHS = cond.
6688 /// C99 6.5.15
6689 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6690                                         ExprResult &RHS, ExprValueKind &VK,
6691                                         ExprObjectKind &OK,
6692                                         SourceLocation QuestionLoc) {
6693 
6694   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6695   if (!LHSResult.isUsable()) return QualType();
6696   LHS = LHSResult;
6697 
6698   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6699   if (!RHSResult.isUsable()) return QualType();
6700   RHS = RHSResult;
6701 
6702   // C++ is sufficiently different to merit its own checker.
6703   if (getLangOpts().CPlusPlus)
6704     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6705 
6706   VK = VK_RValue;
6707   OK = OK_Ordinary;
6708 
6709   // The OpenCL operator with a vector condition is sufficiently
6710   // different to merit its own checker.
6711   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6712     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6713 
6714   // First, check the condition.
6715   Cond = UsualUnaryConversions(Cond.get());
6716   if (Cond.isInvalid())
6717     return QualType();
6718   if (checkCondition(*this, Cond.get(), QuestionLoc))
6719     return QualType();
6720 
6721   // Now check the two expressions.
6722   if (LHS.get()->getType()->isVectorType() ||
6723       RHS.get()->getType()->isVectorType())
6724     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6725                                /*AllowBothBool*/true,
6726                                /*AllowBoolConversions*/false);
6727 
6728   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6729   if (LHS.isInvalid() || RHS.isInvalid())
6730     return QualType();
6731 
6732   QualType LHSTy = LHS.get()->getType();
6733   QualType RHSTy = RHS.get()->getType();
6734 
6735   // Diagnose attempts to convert between __float128 and long double where
6736   // such conversions currently can't be handled.
6737   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6738     Diag(QuestionLoc,
6739          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6740       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6741     return QualType();
6742   }
6743 
6744   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6745   // selection operator (?:).
6746   if (getLangOpts().OpenCL &&
6747       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6748     return QualType();
6749   }
6750 
6751   // If both operands have arithmetic type, do the usual arithmetic conversions
6752   // to find a common type: C99 6.5.15p3,5.
6753   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6754     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6755     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6756 
6757     return ResTy;
6758   }
6759 
6760   // If both operands are the same structure or union type, the result is that
6761   // type.
6762   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6763     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6764       if (LHSRT->getDecl() == RHSRT->getDecl())
6765         // "If both the operands have structure or union type, the result has
6766         // that type."  This implies that CV qualifiers are dropped.
6767         return LHSTy.getUnqualifiedType();
6768     // FIXME: Type of conditional expression must be complete in C mode.
6769   }
6770 
6771   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6772   // The following || allows only one side to be void (a GCC-ism).
6773   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6774     return checkConditionalVoidType(*this, LHS, RHS);
6775   }
6776 
6777   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6778   // the type of the other operand."
6779   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6780   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6781 
6782   // All objective-c pointer type analysis is done here.
6783   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6784                                                         QuestionLoc);
6785   if (LHS.isInvalid() || RHS.isInvalid())
6786     return QualType();
6787   if (!compositeType.isNull())
6788     return compositeType;
6789 
6790 
6791   // Handle block pointer types.
6792   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6793     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6794                                                      QuestionLoc);
6795 
6796   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6797   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6798     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6799                                                        QuestionLoc);
6800 
6801   // GCC compatibility: soften pointer/integer mismatch.  Note that
6802   // null pointers have been filtered out by this point.
6803   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6804       /*isIntFirstExpr=*/true))
6805     return RHSTy;
6806   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6807       /*isIntFirstExpr=*/false))
6808     return LHSTy;
6809 
6810   // Emit a better diagnostic if one of the expressions is a null pointer
6811   // constant and the other is not a pointer type. In this case, the user most
6812   // likely forgot to take the address of the other expression.
6813   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6814     return QualType();
6815 
6816   // Otherwise, the operands are not compatible.
6817   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6818     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6819     << RHS.get()->getSourceRange();
6820   return QualType();
6821 }
6822 
6823 /// FindCompositeObjCPointerType - Helper method to find composite type of
6824 /// two objective-c pointer types of the two input expressions.
6825 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6826                                             SourceLocation QuestionLoc) {
6827   QualType LHSTy = LHS.get()->getType();
6828   QualType RHSTy = RHS.get()->getType();
6829 
6830   // Handle things like Class and struct objc_class*.  Here we case the result
6831   // to the pseudo-builtin, because that will be implicitly cast back to the
6832   // redefinition type if an attempt is made to access its fields.
6833   if (LHSTy->isObjCClassType() &&
6834       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6835     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6836     return LHSTy;
6837   }
6838   if (RHSTy->isObjCClassType() &&
6839       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6840     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6841     return RHSTy;
6842   }
6843   // And the same for struct objc_object* / id
6844   if (LHSTy->isObjCIdType() &&
6845       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6846     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6847     return LHSTy;
6848   }
6849   if (RHSTy->isObjCIdType() &&
6850       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6851     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6852     return RHSTy;
6853   }
6854   // And the same for struct objc_selector* / SEL
6855   if (Context.isObjCSelType(LHSTy) &&
6856       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6857     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6858     return LHSTy;
6859   }
6860   if (Context.isObjCSelType(RHSTy) &&
6861       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6862     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6863     return RHSTy;
6864   }
6865   // Check constraints for Objective-C object pointers types.
6866   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6867 
6868     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6869       // Two identical object pointer types are always compatible.
6870       return LHSTy;
6871     }
6872     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6873     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6874     QualType compositeType = LHSTy;
6875 
6876     // If both operands are interfaces and either operand can be
6877     // assigned to the other, use that type as the composite
6878     // type. This allows
6879     //   xxx ? (A*) a : (B*) b
6880     // where B is a subclass of A.
6881     //
6882     // Additionally, as for assignment, if either type is 'id'
6883     // allow silent coercion. Finally, if the types are
6884     // incompatible then make sure to use 'id' as the composite
6885     // type so the result is acceptable for sending messages to.
6886 
6887     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6888     // It could return the composite type.
6889     if (!(compositeType =
6890           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6891       // Nothing more to do.
6892     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6893       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6894     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6895       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6896     } else if ((LHSTy->isObjCQualifiedIdType() ||
6897                 RHSTy->isObjCQualifiedIdType()) &&
6898                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6899       // Need to handle "id<xx>" explicitly.
6900       // GCC allows qualified id and any Objective-C type to devolve to
6901       // id. Currently localizing to here until clear this should be
6902       // part of ObjCQualifiedIdTypesAreCompatible.
6903       compositeType = Context.getObjCIdType();
6904     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6905       compositeType = Context.getObjCIdType();
6906     } else {
6907       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6908       << LHSTy << RHSTy
6909       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6910       QualType incompatTy = Context.getObjCIdType();
6911       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6912       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6913       return incompatTy;
6914     }
6915     // The object pointer types are compatible.
6916     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6917     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6918     return compositeType;
6919   }
6920   // Check Objective-C object pointer types and 'void *'
6921   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6922     if (getLangOpts().ObjCAutoRefCount) {
6923       // ARC forbids the implicit conversion of object pointers to 'void *',
6924       // so these types are not compatible.
6925       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6926           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6927       LHS = RHS = true;
6928       return QualType();
6929     }
6930     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6931     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6932     QualType destPointee
6933     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6934     QualType destType = Context.getPointerType(destPointee);
6935     // Add qualifiers if necessary.
6936     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6937     // Promote to void*.
6938     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6939     return destType;
6940   }
6941   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6942     if (getLangOpts().ObjCAutoRefCount) {
6943       // ARC forbids the implicit conversion of object pointers to 'void *',
6944       // so these types are not compatible.
6945       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6946           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6947       LHS = RHS = true;
6948       return QualType();
6949     }
6950     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6951     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6952     QualType destPointee
6953     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6954     QualType destType = Context.getPointerType(destPointee);
6955     // Add qualifiers if necessary.
6956     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6957     // Promote to void*.
6958     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6959     return destType;
6960   }
6961   return QualType();
6962 }
6963 
6964 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6965 /// ParenRange in parentheses.
6966 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6967                                const PartialDiagnostic &Note,
6968                                SourceRange ParenRange) {
6969   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6970   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6971       EndLoc.isValid()) {
6972     Self.Diag(Loc, Note)
6973       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6974       << FixItHint::CreateInsertion(EndLoc, ")");
6975   } else {
6976     // We can't display the parentheses, so just show the bare note.
6977     Self.Diag(Loc, Note) << ParenRange;
6978   }
6979 }
6980 
6981 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6982   return BinaryOperator::isAdditiveOp(Opc) ||
6983          BinaryOperator::isMultiplicativeOp(Opc) ||
6984          BinaryOperator::isShiftOp(Opc);
6985 }
6986 
6987 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6988 /// expression, either using a built-in or overloaded operator,
6989 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6990 /// expression.
6991 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6992                                    Expr **RHSExprs) {
6993   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6994   E = E->IgnoreImpCasts();
6995   E = E->IgnoreConversionOperator();
6996   E = E->IgnoreImpCasts();
6997 
6998   // Built-in binary operator.
6999   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7000     if (IsArithmeticOp(OP->getOpcode())) {
7001       *Opcode = OP->getOpcode();
7002       *RHSExprs = OP->getRHS();
7003       return true;
7004     }
7005   }
7006 
7007   // Overloaded operator.
7008   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7009     if (Call->getNumArgs() != 2)
7010       return false;
7011 
7012     // Make sure this is really a binary operator that is safe to pass into
7013     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7014     OverloadedOperatorKind OO = Call->getOperator();
7015     if (OO < OO_Plus || OO > OO_Arrow ||
7016         OO == OO_PlusPlus || OO == OO_MinusMinus)
7017       return false;
7018 
7019     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7020     if (IsArithmeticOp(OpKind)) {
7021       *Opcode = OpKind;
7022       *RHSExprs = Call->getArg(1);
7023       return true;
7024     }
7025   }
7026 
7027   return false;
7028 }
7029 
7030 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7031 /// or is a logical expression such as (x==y) which has int type, but is
7032 /// commonly interpreted as boolean.
7033 static bool ExprLooksBoolean(Expr *E) {
7034   E = E->IgnoreParenImpCasts();
7035 
7036   if (E->getType()->isBooleanType())
7037     return true;
7038   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7039     return OP->isComparisonOp() || OP->isLogicalOp();
7040   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7041     return OP->getOpcode() == UO_LNot;
7042   if (E->getType()->isPointerType())
7043     return true;
7044 
7045   return false;
7046 }
7047 
7048 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7049 /// and binary operator are mixed in a way that suggests the programmer assumed
7050 /// the conditional operator has higher precedence, for example:
7051 /// "int x = a + someBinaryCondition ? 1 : 2".
7052 static void DiagnoseConditionalPrecedence(Sema &Self,
7053                                           SourceLocation OpLoc,
7054                                           Expr *Condition,
7055                                           Expr *LHSExpr,
7056                                           Expr *RHSExpr) {
7057   BinaryOperatorKind CondOpcode;
7058   Expr *CondRHS;
7059 
7060   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7061     return;
7062   if (!ExprLooksBoolean(CondRHS))
7063     return;
7064 
7065   // The condition is an arithmetic binary expression, with a right-
7066   // hand side that looks boolean, so warn.
7067 
7068   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7069       << Condition->getSourceRange()
7070       << BinaryOperator::getOpcodeStr(CondOpcode);
7071 
7072   SuggestParentheses(Self, OpLoc,
7073     Self.PDiag(diag::note_precedence_silence)
7074       << BinaryOperator::getOpcodeStr(CondOpcode),
7075     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7076 
7077   SuggestParentheses(Self, OpLoc,
7078     Self.PDiag(diag::note_precedence_conditional_first),
7079     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7080 }
7081 
7082 /// Compute the nullability of a conditional expression.
7083 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7084                                               QualType LHSTy, QualType RHSTy,
7085                                               ASTContext &Ctx) {
7086   if (!ResTy->isAnyPointerType())
7087     return ResTy;
7088 
7089   auto GetNullability = [&Ctx](QualType Ty) {
7090     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7091     if (Kind)
7092       return *Kind;
7093     return NullabilityKind::Unspecified;
7094   };
7095 
7096   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7097   NullabilityKind MergedKind;
7098 
7099   // Compute nullability of a binary conditional expression.
7100   if (IsBin) {
7101     if (LHSKind == NullabilityKind::NonNull)
7102       MergedKind = NullabilityKind::NonNull;
7103     else
7104       MergedKind = RHSKind;
7105   // Compute nullability of a normal conditional expression.
7106   } else {
7107     if (LHSKind == NullabilityKind::Nullable ||
7108         RHSKind == NullabilityKind::Nullable)
7109       MergedKind = NullabilityKind::Nullable;
7110     else if (LHSKind == NullabilityKind::NonNull)
7111       MergedKind = RHSKind;
7112     else if (RHSKind == NullabilityKind::NonNull)
7113       MergedKind = LHSKind;
7114     else
7115       MergedKind = NullabilityKind::Unspecified;
7116   }
7117 
7118   // Return if ResTy already has the correct nullability.
7119   if (GetNullability(ResTy) == MergedKind)
7120     return ResTy;
7121 
7122   // Strip all nullability from ResTy.
7123   while (ResTy->getNullability(Ctx))
7124     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7125 
7126   // Create a new AttributedType with the new nullability kind.
7127   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7128   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7129 }
7130 
7131 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7132 /// in the case of a the GNU conditional expr extension.
7133 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7134                                     SourceLocation ColonLoc,
7135                                     Expr *CondExpr, Expr *LHSExpr,
7136                                     Expr *RHSExpr) {
7137   if (!getLangOpts().CPlusPlus) {
7138     // C cannot handle TypoExpr nodes in the condition because it
7139     // doesn't handle dependent types properly, so make sure any TypoExprs have
7140     // been dealt with before checking the operands.
7141     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7142     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7143     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7144 
7145     if (!CondResult.isUsable())
7146       return ExprError();
7147 
7148     if (LHSExpr) {
7149       if (!LHSResult.isUsable())
7150         return ExprError();
7151     }
7152 
7153     if (!RHSResult.isUsable())
7154       return ExprError();
7155 
7156     CondExpr = CondResult.get();
7157     LHSExpr = LHSResult.get();
7158     RHSExpr = RHSResult.get();
7159   }
7160 
7161   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7162   // was the condition.
7163   OpaqueValueExpr *opaqueValue = nullptr;
7164   Expr *commonExpr = nullptr;
7165   if (!LHSExpr) {
7166     commonExpr = CondExpr;
7167     // Lower out placeholder types first.  This is important so that we don't
7168     // try to capture a placeholder. This happens in few cases in C++; such
7169     // as Objective-C++'s dictionary subscripting syntax.
7170     if (commonExpr->hasPlaceholderType()) {
7171       ExprResult result = CheckPlaceholderExpr(commonExpr);
7172       if (!result.isUsable()) return ExprError();
7173       commonExpr = result.get();
7174     }
7175     // We usually want to apply unary conversions *before* saving, except
7176     // in the special case of a C++ l-value conditional.
7177     if (!(getLangOpts().CPlusPlus
7178           && !commonExpr->isTypeDependent()
7179           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7180           && commonExpr->isGLValue()
7181           && commonExpr->isOrdinaryOrBitFieldObject()
7182           && RHSExpr->isOrdinaryOrBitFieldObject()
7183           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7184       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7185       if (commonRes.isInvalid())
7186         return ExprError();
7187       commonExpr = commonRes.get();
7188     }
7189 
7190     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7191                                                 commonExpr->getType(),
7192                                                 commonExpr->getValueKind(),
7193                                                 commonExpr->getObjectKind(),
7194                                                 commonExpr);
7195     LHSExpr = CondExpr = opaqueValue;
7196   }
7197 
7198   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7199   ExprValueKind VK = VK_RValue;
7200   ExprObjectKind OK = OK_Ordinary;
7201   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7202   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7203                                              VK, OK, QuestionLoc);
7204   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7205       RHS.isInvalid())
7206     return ExprError();
7207 
7208   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7209                                 RHS.get());
7210 
7211   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7212 
7213   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7214                                          Context);
7215 
7216   if (!commonExpr)
7217     return new (Context)
7218         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7219                             RHS.get(), result, VK, OK);
7220 
7221   return new (Context) BinaryConditionalOperator(
7222       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7223       ColonLoc, result, VK, OK);
7224 }
7225 
7226 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7227 // being closely modeled after the C99 spec:-). The odd characteristic of this
7228 // routine is it effectively iqnores the qualifiers on the top level pointee.
7229 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7230 // FIXME: add a couple examples in this comment.
7231 static Sema::AssignConvertType
7232 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7233   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7234   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7235 
7236   // get the "pointed to" type (ignoring qualifiers at the top level)
7237   const Type *lhptee, *rhptee;
7238   Qualifiers lhq, rhq;
7239   std::tie(lhptee, lhq) =
7240       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7241   std::tie(rhptee, rhq) =
7242       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7243 
7244   Sema::AssignConvertType ConvTy = Sema::Compatible;
7245 
7246   // C99 6.5.16.1p1: This following citation is common to constraints
7247   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7248   // qualifiers of the type *pointed to* by the right;
7249 
7250   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7251   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7252       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7253     // Ignore lifetime for further calculation.
7254     lhq.removeObjCLifetime();
7255     rhq.removeObjCLifetime();
7256   }
7257 
7258   if (!lhq.compatiblyIncludes(rhq)) {
7259     // Treat address-space mismatches as fatal.  TODO: address subspaces
7260     if (!lhq.isAddressSpaceSupersetOf(rhq))
7261       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7262 
7263     // It's okay to add or remove GC or lifetime qualifiers when converting to
7264     // and from void*.
7265     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7266                         .compatiblyIncludes(
7267                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7268              && (lhptee->isVoidType() || rhptee->isVoidType()))
7269       ; // keep old
7270 
7271     // Treat lifetime mismatches as fatal.
7272     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7273       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7274 
7275     // For GCC/MS compatibility, other qualifier mismatches are treated
7276     // as still compatible in C.
7277     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7278   }
7279 
7280   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7281   // incomplete type and the other is a pointer to a qualified or unqualified
7282   // version of void...
7283   if (lhptee->isVoidType()) {
7284     if (rhptee->isIncompleteOrObjectType())
7285       return ConvTy;
7286 
7287     // As an extension, we allow cast to/from void* to function pointer.
7288     assert(rhptee->isFunctionType());
7289     return Sema::FunctionVoidPointer;
7290   }
7291 
7292   if (rhptee->isVoidType()) {
7293     if (lhptee->isIncompleteOrObjectType())
7294       return ConvTy;
7295 
7296     // As an extension, we allow cast to/from void* to function pointer.
7297     assert(lhptee->isFunctionType());
7298     return Sema::FunctionVoidPointer;
7299   }
7300 
7301   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7302   // unqualified versions of compatible types, ...
7303   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7304   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7305     // Check if the pointee types are compatible ignoring the sign.
7306     // We explicitly check for char so that we catch "char" vs
7307     // "unsigned char" on systems where "char" is unsigned.
7308     if (lhptee->isCharType())
7309       ltrans = S.Context.UnsignedCharTy;
7310     else if (lhptee->hasSignedIntegerRepresentation())
7311       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7312 
7313     if (rhptee->isCharType())
7314       rtrans = S.Context.UnsignedCharTy;
7315     else if (rhptee->hasSignedIntegerRepresentation())
7316       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7317 
7318     if (ltrans == rtrans) {
7319       // Types are compatible ignoring the sign. Qualifier incompatibility
7320       // takes priority over sign incompatibility because the sign
7321       // warning can be disabled.
7322       if (ConvTy != Sema::Compatible)
7323         return ConvTy;
7324 
7325       return Sema::IncompatiblePointerSign;
7326     }
7327 
7328     // If we are a multi-level pointer, it's possible that our issue is simply
7329     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7330     // the eventual target type is the same and the pointers have the same
7331     // level of indirection, this must be the issue.
7332     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7333       do {
7334         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7335         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7336       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7337 
7338       if (lhptee == rhptee)
7339         return Sema::IncompatibleNestedPointerQualifiers;
7340     }
7341 
7342     // General pointer incompatibility takes priority over qualifiers.
7343     return Sema::IncompatiblePointer;
7344   }
7345   if (!S.getLangOpts().CPlusPlus &&
7346       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7347     return Sema::IncompatiblePointer;
7348   return ConvTy;
7349 }
7350 
7351 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7352 /// block pointer types are compatible or whether a block and normal pointer
7353 /// are compatible. It is more restrict than comparing two function pointer
7354 // types.
7355 static Sema::AssignConvertType
7356 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7357                                     QualType RHSType) {
7358   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7359   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7360 
7361   QualType lhptee, rhptee;
7362 
7363   // get the "pointed to" type (ignoring qualifiers at the top level)
7364   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7365   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7366 
7367   // In C++, the types have to match exactly.
7368   if (S.getLangOpts().CPlusPlus)
7369     return Sema::IncompatibleBlockPointer;
7370 
7371   Sema::AssignConvertType ConvTy = Sema::Compatible;
7372 
7373   // For blocks we enforce that qualifiers are identical.
7374   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7375     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7376 
7377   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7378     return Sema::IncompatibleBlockPointer;
7379 
7380   return ConvTy;
7381 }
7382 
7383 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7384 /// for assignment compatibility.
7385 static Sema::AssignConvertType
7386 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7387                                    QualType RHSType) {
7388   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7389   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7390 
7391   if (LHSType->isObjCBuiltinType()) {
7392     // Class is not compatible with ObjC object pointers.
7393     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7394         !RHSType->isObjCQualifiedClassType())
7395       return Sema::IncompatiblePointer;
7396     return Sema::Compatible;
7397   }
7398   if (RHSType->isObjCBuiltinType()) {
7399     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7400         !LHSType->isObjCQualifiedClassType())
7401       return Sema::IncompatiblePointer;
7402     return Sema::Compatible;
7403   }
7404   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7405   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7406 
7407   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7408       // make an exception for id<P>
7409       !LHSType->isObjCQualifiedIdType())
7410     return Sema::CompatiblePointerDiscardsQualifiers;
7411 
7412   if (S.Context.typesAreCompatible(LHSType, RHSType))
7413     return Sema::Compatible;
7414   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7415     return Sema::IncompatibleObjCQualifiedId;
7416   return Sema::IncompatiblePointer;
7417 }
7418 
7419 Sema::AssignConvertType
7420 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7421                                  QualType LHSType, QualType RHSType) {
7422   // Fake up an opaque expression.  We don't actually care about what
7423   // cast operations are required, so if CheckAssignmentConstraints
7424   // adds casts to this they'll be wasted, but fortunately that doesn't
7425   // usually happen on valid code.
7426   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7427   ExprResult RHSPtr = &RHSExpr;
7428   CastKind K = CK_Invalid;
7429 
7430   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7431 }
7432 
7433 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7434 /// has code to accommodate several GCC extensions when type checking
7435 /// pointers. Here are some objectionable examples that GCC considers warnings:
7436 ///
7437 ///  int a, *pint;
7438 ///  short *pshort;
7439 ///  struct foo *pfoo;
7440 ///
7441 ///  pint = pshort; // warning: assignment from incompatible pointer type
7442 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7443 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7444 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7445 ///
7446 /// As a result, the code for dealing with pointers is more complex than the
7447 /// C99 spec dictates.
7448 ///
7449 /// Sets 'Kind' for any result kind except Incompatible.
7450 Sema::AssignConvertType
7451 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7452                                  CastKind &Kind, bool ConvertRHS) {
7453   QualType RHSType = RHS.get()->getType();
7454   QualType OrigLHSType = LHSType;
7455 
7456   // Get canonical types.  We're not formatting these types, just comparing
7457   // them.
7458   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7459   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7460 
7461   // Common case: no conversion required.
7462   if (LHSType == RHSType) {
7463     Kind = CK_NoOp;
7464     return Compatible;
7465   }
7466 
7467   // If we have an atomic type, try a non-atomic assignment, then just add an
7468   // atomic qualification step.
7469   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7470     Sema::AssignConvertType result =
7471       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7472     if (result != Compatible)
7473       return result;
7474     if (Kind != CK_NoOp && ConvertRHS)
7475       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7476     Kind = CK_NonAtomicToAtomic;
7477     return Compatible;
7478   }
7479 
7480   // If the left-hand side is a reference type, then we are in a
7481   // (rare!) case where we've allowed the use of references in C,
7482   // e.g., as a parameter type in a built-in function. In this case,
7483   // just make sure that the type referenced is compatible with the
7484   // right-hand side type. The caller is responsible for adjusting
7485   // LHSType so that the resulting expression does not have reference
7486   // type.
7487   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7488     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7489       Kind = CK_LValueBitCast;
7490       return Compatible;
7491     }
7492     return Incompatible;
7493   }
7494 
7495   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7496   // to the same ExtVector type.
7497   if (LHSType->isExtVectorType()) {
7498     if (RHSType->isExtVectorType())
7499       return Incompatible;
7500     if (RHSType->isArithmeticType()) {
7501       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7502       if (ConvertRHS)
7503         RHS = prepareVectorSplat(LHSType, RHS.get());
7504       Kind = CK_VectorSplat;
7505       return Compatible;
7506     }
7507   }
7508 
7509   // Conversions to or from vector type.
7510   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7511     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7512       // Allow assignments of an AltiVec vector type to an equivalent GCC
7513       // vector type and vice versa
7514       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7515         Kind = CK_BitCast;
7516         return Compatible;
7517       }
7518 
7519       // If we are allowing lax vector conversions, and LHS and RHS are both
7520       // vectors, the total size only needs to be the same. This is a bitcast;
7521       // no bits are changed but the result type is different.
7522       if (isLaxVectorConversion(RHSType, LHSType)) {
7523         Kind = CK_BitCast;
7524         return IncompatibleVectors;
7525       }
7526     }
7527 
7528     // When the RHS comes from another lax conversion (e.g. binops between
7529     // scalars and vectors) the result is canonicalized as a vector. When the
7530     // LHS is also a vector, the lax is allowed by the condition above. Handle
7531     // the case where LHS is a scalar.
7532     if (LHSType->isScalarType()) {
7533       const VectorType *VecType = RHSType->getAs<VectorType>();
7534       if (VecType && VecType->getNumElements() == 1 &&
7535           isLaxVectorConversion(RHSType, LHSType)) {
7536         ExprResult *VecExpr = &RHS;
7537         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7538         Kind = CK_BitCast;
7539         return Compatible;
7540       }
7541     }
7542 
7543     return Incompatible;
7544   }
7545 
7546   // Diagnose attempts to convert between __float128 and long double where
7547   // such conversions currently can't be handled.
7548   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7549     return Incompatible;
7550 
7551   // Arithmetic conversions.
7552   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7553       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7554     if (ConvertRHS)
7555       Kind = PrepareScalarCast(RHS, LHSType);
7556     return Compatible;
7557   }
7558 
7559   // Conversions to normal pointers.
7560   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7561     // U* -> T*
7562     if (isa<PointerType>(RHSType)) {
7563       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7564       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7565       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7566       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7567     }
7568 
7569     // int -> T*
7570     if (RHSType->isIntegerType()) {
7571       Kind = CK_IntegralToPointer; // FIXME: null?
7572       return IntToPointer;
7573     }
7574 
7575     // C pointers are not compatible with ObjC object pointers,
7576     // with two exceptions:
7577     if (isa<ObjCObjectPointerType>(RHSType)) {
7578       //  - conversions to void*
7579       if (LHSPointer->getPointeeType()->isVoidType()) {
7580         Kind = CK_BitCast;
7581         return Compatible;
7582       }
7583 
7584       //  - conversions from 'Class' to the redefinition type
7585       if (RHSType->isObjCClassType() &&
7586           Context.hasSameType(LHSType,
7587                               Context.getObjCClassRedefinitionType())) {
7588         Kind = CK_BitCast;
7589         return Compatible;
7590       }
7591 
7592       Kind = CK_BitCast;
7593       return IncompatiblePointer;
7594     }
7595 
7596     // U^ -> void*
7597     if (RHSType->getAs<BlockPointerType>()) {
7598       if (LHSPointer->getPointeeType()->isVoidType()) {
7599         Kind = CK_BitCast;
7600         return Compatible;
7601       }
7602     }
7603 
7604     return Incompatible;
7605   }
7606 
7607   // Conversions to block pointers.
7608   if (isa<BlockPointerType>(LHSType)) {
7609     // U^ -> T^
7610     if (RHSType->isBlockPointerType()) {
7611       Kind = CK_BitCast;
7612       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7613     }
7614 
7615     // int or null -> T^
7616     if (RHSType->isIntegerType()) {
7617       Kind = CK_IntegralToPointer; // FIXME: null
7618       return IntToBlockPointer;
7619     }
7620 
7621     // id -> T^
7622     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7623       Kind = CK_AnyPointerToBlockPointerCast;
7624       return Compatible;
7625     }
7626 
7627     // void* -> T^
7628     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7629       if (RHSPT->getPointeeType()->isVoidType()) {
7630         Kind = CK_AnyPointerToBlockPointerCast;
7631         return Compatible;
7632       }
7633 
7634     return Incompatible;
7635   }
7636 
7637   // Conversions to Objective-C pointers.
7638   if (isa<ObjCObjectPointerType>(LHSType)) {
7639     // A* -> B*
7640     if (RHSType->isObjCObjectPointerType()) {
7641       Kind = CK_BitCast;
7642       Sema::AssignConvertType result =
7643         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7644       if (getLangOpts().ObjCAutoRefCount &&
7645           result == Compatible &&
7646           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7647         result = IncompatibleObjCWeakRef;
7648       return result;
7649     }
7650 
7651     // int or null -> A*
7652     if (RHSType->isIntegerType()) {
7653       Kind = CK_IntegralToPointer; // FIXME: null
7654       return IntToPointer;
7655     }
7656 
7657     // In general, C pointers are not compatible with ObjC object pointers,
7658     // with two exceptions:
7659     if (isa<PointerType>(RHSType)) {
7660       Kind = CK_CPointerToObjCPointerCast;
7661 
7662       //  - conversions from 'void*'
7663       if (RHSType->isVoidPointerType()) {
7664         return Compatible;
7665       }
7666 
7667       //  - conversions to 'Class' from its redefinition type
7668       if (LHSType->isObjCClassType() &&
7669           Context.hasSameType(RHSType,
7670                               Context.getObjCClassRedefinitionType())) {
7671         return Compatible;
7672       }
7673 
7674       return IncompatiblePointer;
7675     }
7676 
7677     // Only under strict condition T^ is compatible with an Objective-C pointer.
7678     if (RHSType->isBlockPointerType() &&
7679         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7680       if (ConvertRHS)
7681         maybeExtendBlockObject(RHS);
7682       Kind = CK_BlockPointerToObjCPointerCast;
7683       return Compatible;
7684     }
7685 
7686     return Incompatible;
7687   }
7688 
7689   // Conversions from pointers that are not covered by the above.
7690   if (isa<PointerType>(RHSType)) {
7691     // T* -> _Bool
7692     if (LHSType == Context.BoolTy) {
7693       Kind = CK_PointerToBoolean;
7694       return Compatible;
7695     }
7696 
7697     // T* -> int
7698     if (LHSType->isIntegerType()) {
7699       Kind = CK_PointerToIntegral;
7700       return PointerToInt;
7701     }
7702 
7703     return Incompatible;
7704   }
7705 
7706   // Conversions from Objective-C pointers that are not covered by the above.
7707   if (isa<ObjCObjectPointerType>(RHSType)) {
7708     // T* -> _Bool
7709     if (LHSType == Context.BoolTy) {
7710       Kind = CK_PointerToBoolean;
7711       return Compatible;
7712     }
7713 
7714     // T* -> int
7715     if (LHSType->isIntegerType()) {
7716       Kind = CK_PointerToIntegral;
7717       return PointerToInt;
7718     }
7719 
7720     return Incompatible;
7721   }
7722 
7723   // struct A -> struct B
7724   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7725     if (Context.typesAreCompatible(LHSType, RHSType)) {
7726       Kind = CK_NoOp;
7727       return Compatible;
7728     }
7729   }
7730 
7731   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7732     Kind = CK_IntToOCLSampler;
7733     return Compatible;
7734   }
7735 
7736   return Incompatible;
7737 }
7738 
7739 /// \brief Constructs a transparent union from an expression that is
7740 /// used to initialize the transparent union.
7741 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7742                                       ExprResult &EResult, QualType UnionType,
7743                                       FieldDecl *Field) {
7744   // Build an initializer list that designates the appropriate member
7745   // of the transparent union.
7746   Expr *E = EResult.get();
7747   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7748                                                    E, SourceLocation());
7749   Initializer->setType(UnionType);
7750   Initializer->setInitializedFieldInUnion(Field);
7751 
7752   // Build a compound literal constructing a value of the transparent
7753   // union type from this initializer list.
7754   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7755   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7756                                         VK_RValue, Initializer, false);
7757 }
7758 
7759 Sema::AssignConvertType
7760 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7761                                                ExprResult &RHS) {
7762   QualType RHSType = RHS.get()->getType();
7763 
7764   // If the ArgType is a Union type, we want to handle a potential
7765   // transparent_union GCC extension.
7766   const RecordType *UT = ArgType->getAsUnionType();
7767   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7768     return Incompatible;
7769 
7770   // The field to initialize within the transparent union.
7771   RecordDecl *UD = UT->getDecl();
7772   FieldDecl *InitField = nullptr;
7773   // It's compatible if the expression matches any of the fields.
7774   for (auto *it : UD->fields()) {
7775     if (it->getType()->isPointerType()) {
7776       // If the transparent union contains a pointer type, we allow:
7777       // 1) void pointer
7778       // 2) null pointer constant
7779       if (RHSType->isPointerType())
7780         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7781           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7782           InitField = it;
7783           break;
7784         }
7785 
7786       if (RHS.get()->isNullPointerConstant(Context,
7787                                            Expr::NPC_ValueDependentIsNull)) {
7788         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7789                                 CK_NullToPointer);
7790         InitField = it;
7791         break;
7792       }
7793     }
7794 
7795     CastKind Kind = CK_Invalid;
7796     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7797           == Compatible) {
7798       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7799       InitField = it;
7800       break;
7801     }
7802   }
7803 
7804   if (!InitField)
7805     return Incompatible;
7806 
7807   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7808   return Compatible;
7809 }
7810 
7811 Sema::AssignConvertType
7812 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7813                                        bool Diagnose,
7814                                        bool DiagnoseCFAudited,
7815                                        bool ConvertRHS) {
7816   // We need to be able to tell the caller whether we diagnosed a problem, if
7817   // they ask us to issue diagnostics.
7818   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7819 
7820   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7821   // we can't avoid *all* modifications at the moment, so we need some somewhere
7822   // to put the updated value.
7823   ExprResult LocalRHS = CallerRHS;
7824   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7825 
7826   if (getLangOpts().CPlusPlus) {
7827     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7828       // C++ 5.17p3: If the left operand is not of class type, the
7829       // expression is implicitly converted (C++ 4) to the
7830       // cv-unqualified type of the left operand.
7831       QualType RHSType = RHS.get()->getType();
7832       if (Diagnose) {
7833         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7834                                         AA_Assigning);
7835       } else {
7836         ImplicitConversionSequence ICS =
7837             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7838                                   /*SuppressUserConversions=*/false,
7839                                   /*AllowExplicit=*/false,
7840                                   /*InOverloadResolution=*/false,
7841                                   /*CStyle=*/false,
7842                                   /*AllowObjCWritebackConversion=*/false);
7843         if (ICS.isFailure())
7844           return Incompatible;
7845         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7846                                         ICS, AA_Assigning);
7847       }
7848       if (RHS.isInvalid())
7849         return Incompatible;
7850       Sema::AssignConvertType result = Compatible;
7851       if (getLangOpts().ObjCAutoRefCount &&
7852           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7853         result = IncompatibleObjCWeakRef;
7854       return result;
7855     }
7856 
7857     // FIXME: Currently, we fall through and treat C++ classes like C
7858     // structures.
7859     // FIXME: We also fall through for atomics; not sure what should
7860     // happen there, though.
7861   } else if (RHS.get()->getType() == Context.OverloadTy) {
7862     // As a set of extensions to C, we support overloading on functions. These
7863     // functions need to be resolved here.
7864     DeclAccessPair DAP;
7865     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7866             RHS.get(), LHSType, /*Complain=*/false, DAP))
7867       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7868     else
7869       return Incompatible;
7870   }
7871 
7872   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7873   // a null pointer constant.
7874   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7875        LHSType->isBlockPointerType()) &&
7876       RHS.get()->isNullPointerConstant(Context,
7877                                        Expr::NPC_ValueDependentIsNull)) {
7878     if (Diagnose || ConvertRHS) {
7879       CastKind Kind;
7880       CXXCastPath Path;
7881       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7882                              /*IgnoreBaseAccess=*/false, Diagnose);
7883       if (ConvertRHS)
7884         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7885     }
7886     return Compatible;
7887   }
7888 
7889   // This check seems unnatural, however it is necessary to ensure the proper
7890   // conversion of functions/arrays. If the conversion were done for all
7891   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7892   // expressions that suppress this implicit conversion (&, sizeof).
7893   //
7894   // Suppress this for references: C++ 8.5.3p5.
7895   if (!LHSType->isReferenceType()) {
7896     // FIXME: We potentially allocate here even if ConvertRHS is false.
7897     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7898     if (RHS.isInvalid())
7899       return Incompatible;
7900   }
7901 
7902   Expr *PRE = RHS.get()->IgnoreParenCasts();
7903   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7904     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7905     if (PDecl && !PDecl->hasDefinition()) {
7906       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7907       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7908     }
7909   }
7910 
7911   CastKind Kind = CK_Invalid;
7912   Sema::AssignConvertType result =
7913     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7914 
7915   // C99 6.5.16.1p2: The value of the right operand is converted to the
7916   // type of the assignment expression.
7917   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7918   // so that we can use references in built-in functions even in C.
7919   // The getNonReferenceType() call makes sure that the resulting expression
7920   // does not have reference type.
7921   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7922     QualType Ty = LHSType.getNonLValueExprType(Context);
7923     Expr *E = RHS.get();
7924 
7925     // Check for various Objective-C errors. If we are not reporting
7926     // diagnostics and just checking for errors, e.g., during overload
7927     // resolution, return Incompatible to indicate the failure.
7928     if (getLangOpts().ObjCAutoRefCount &&
7929         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7930                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7931       if (!Diagnose)
7932         return Incompatible;
7933     }
7934     if (getLangOpts().ObjC1 &&
7935         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7936                                            E->getType(), E, Diagnose) ||
7937          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7938       if (!Diagnose)
7939         return Incompatible;
7940       // Replace the expression with a corrected version and continue so we
7941       // can find further errors.
7942       RHS = E;
7943       return Compatible;
7944     }
7945 
7946     if (ConvertRHS)
7947       RHS = ImpCastExprToType(E, Ty, Kind);
7948   }
7949   return result;
7950 }
7951 
7952 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7953                                ExprResult &RHS) {
7954   Diag(Loc, diag::err_typecheck_invalid_operands)
7955     << LHS.get()->getType() << RHS.get()->getType()
7956     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7957   return QualType();
7958 }
7959 
7960 /// Try to convert a value of non-vector type to a vector type by converting
7961 /// the type to the element type of the vector and then performing a splat.
7962 /// If the language is OpenCL, we only use conversions that promote scalar
7963 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7964 /// for float->int.
7965 ///
7966 /// \param scalar - if non-null, actually perform the conversions
7967 /// \return true if the operation fails (but without diagnosing the failure)
7968 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7969                                      QualType scalarTy,
7970                                      QualType vectorEltTy,
7971                                      QualType vectorTy) {
7972   // The conversion to apply to the scalar before splatting it,
7973   // if necessary.
7974   CastKind scalarCast = CK_Invalid;
7975 
7976   if (vectorEltTy->isIntegralType(S.Context)) {
7977     if (!scalarTy->isIntegralType(S.Context))
7978       return true;
7979     if (S.getLangOpts().OpenCL &&
7980         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7981       return true;
7982     scalarCast = CK_IntegralCast;
7983   } else if (vectorEltTy->isRealFloatingType()) {
7984     if (scalarTy->isRealFloatingType()) {
7985       if (S.getLangOpts().OpenCL &&
7986           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7987         return true;
7988       scalarCast = CK_FloatingCast;
7989     }
7990     else if (scalarTy->isIntegralType(S.Context))
7991       scalarCast = CK_IntegralToFloating;
7992     else
7993       return true;
7994   } else {
7995     return true;
7996   }
7997 
7998   // Adjust scalar if desired.
7999   if (scalar) {
8000     if (scalarCast != CK_Invalid)
8001       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8002     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8003   }
8004   return false;
8005 }
8006 
8007 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8008                                    SourceLocation Loc, bool IsCompAssign,
8009                                    bool AllowBothBool,
8010                                    bool AllowBoolConversions) {
8011   if (!IsCompAssign) {
8012     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8013     if (LHS.isInvalid())
8014       return QualType();
8015   }
8016   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8017   if (RHS.isInvalid())
8018     return QualType();
8019 
8020   // For conversion purposes, we ignore any qualifiers.
8021   // For example, "const float" and "float" are equivalent.
8022   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8023   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8024 
8025   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8026   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8027   assert(LHSVecType || RHSVecType);
8028 
8029   // AltiVec-style "vector bool op vector bool" combinations are allowed
8030   // for some operators but not others.
8031   if (!AllowBothBool &&
8032       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8033       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8034     return InvalidOperands(Loc, LHS, RHS);
8035 
8036   // If the vector types are identical, return.
8037   if (Context.hasSameType(LHSType, RHSType))
8038     return LHSType;
8039 
8040   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8041   if (LHSVecType && RHSVecType &&
8042       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8043     if (isa<ExtVectorType>(LHSVecType)) {
8044       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8045       return LHSType;
8046     }
8047 
8048     if (!IsCompAssign)
8049       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8050     return RHSType;
8051   }
8052 
8053   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8054   // can be mixed, with the result being the non-bool type.  The non-bool
8055   // operand must have integer element type.
8056   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8057       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8058       (Context.getTypeSize(LHSVecType->getElementType()) ==
8059        Context.getTypeSize(RHSVecType->getElementType()))) {
8060     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8061         LHSVecType->getElementType()->isIntegerType() &&
8062         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8063       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8064       return LHSType;
8065     }
8066     if (!IsCompAssign &&
8067         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8068         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8069         RHSVecType->getElementType()->isIntegerType()) {
8070       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8071       return RHSType;
8072     }
8073   }
8074 
8075   // If there's an ext-vector type and a scalar, try to convert the scalar to
8076   // the vector element type and splat.
8077   // FIXME: this should also work for regular vector types as supported in GCC.
8078   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8079     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8080                                   LHSVecType->getElementType(), LHSType))
8081       return LHSType;
8082   }
8083   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8084     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8085                                   LHSType, RHSVecType->getElementType(),
8086                                   RHSType))
8087       return RHSType;
8088   }
8089 
8090   // FIXME: The code below also handles convertion between vectors and
8091   // non-scalars, we should break this down into fine grained specific checks
8092   // and emit proper diagnostics.
8093   QualType VecType = LHSVecType ? LHSType : RHSType;
8094   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8095   QualType OtherType = LHSVecType ? RHSType : LHSType;
8096   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8097   if (isLaxVectorConversion(OtherType, VecType)) {
8098     // If we're allowing lax vector conversions, only the total (data) size
8099     // needs to be the same. For non compound assignment, if one of the types is
8100     // scalar, the result is always the vector type.
8101     if (!IsCompAssign) {
8102       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8103       return VecType;
8104     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8105     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8106     // type. Note that this is already done by non-compound assignments in
8107     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8108     // <1 x T> -> T. The result is also a vector type.
8109     } else if (OtherType->isExtVectorType() ||
8110                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8111       ExprResult *RHSExpr = &RHS;
8112       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8113       return VecType;
8114     }
8115   }
8116 
8117   // Okay, the expression is invalid.
8118 
8119   // If there's a non-vector, non-real operand, diagnose that.
8120   if ((!RHSVecType && !RHSType->isRealType()) ||
8121       (!LHSVecType && !LHSType->isRealType())) {
8122     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8123       << LHSType << RHSType
8124       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8125     return QualType();
8126   }
8127 
8128   // OpenCL V1.1 6.2.6.p1:
8129   // If the operands are of more than one vector type, then an error shall
8130   // occur. Implicit conversions between vector types are not permitted, per
8131   // section 6.2.1.
8132   if (getLangOpts().OpenCL &&
8133       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8134       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8135     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8136                                                            << RHSType;
8137     return QualType();
8138   }
8139 
8140   // Otherwise, use the generic diagnostic.
8141   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8142     << LHSType << RHSType
8143     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8144   return QualType();
8145 }
8146 
8147 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8148 // expression.  These are mainly cases where the null pointer is used as an
8149 // integer instead of a pointer.
8150 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8151                                 SourceLocation Loc, bool IsCompare) {
8152   // The canonical way to check for a GNU null is with isNullPointerConstant,
8153   // but we use a bit of a hack here for speed; this is a relatively
8154   // hot path, and isNullPointerConstant is slow.
8155   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8156   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8157 
8158   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8159 
8160   // Avoid analyzing cases where the result will either be invalid (and
8161   // diagnosed as such) or entirely valid and not something to warn about.
8162   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8163       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8164     return;
8165 
8166   // Comparison operations would not make sense with a null pointer no matter
8167   // what the other expression is.
8168   if (!IsCompare) {
8169     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8170         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8171         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8172     return;
8173   }
8174 
8175   // The rest of the operations only make sense with a null pointer
8176   // if the other expression is a pointer.
8177   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8178       NonNullType->canDecayToPointerType())
8179     return;
8180 
8181   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8182       << LHSNull /* LHS is NULL */ << NonNullType
8183       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8184 }
8185 
8186 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8187                                                ExprResult &RHS,
8188                                                SourceLocation Loc, bool IsDiv) {
8189   // Check for division/remainder by zero.
8190   llvm::APSInt RHSValue;
8191   if (!RHS.get()->isValueDependent() &&
8192       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8193     S.DiagRuntimeBehavior(Loc, RHS.get(),
8194                           S.PDiag(diag::warn_remainder_division_by_zero)
8195                             << IsDiv << RHS.get()->getSourceRange());
8196 }
8197 
8198 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8199                                            SourceLocation Loc,
8200                                            bool IsCompAssign, bool IsDiv) {
8201   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8202 
8203   if (LHS.get()->getType()->isVectorType() ||
8204       RHS.get()->getType()->isVectorType())
8205     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8206                                /*AllowBothBool*/getLangOpts().AltiVec,
8207                                /*AllowBoolConversions*/false);
8208 
8209   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8210   if (LHS.isInvalid() || RHS.isInvalid())
8211     return QualType();
8212 
8213 
8214   if (compType.isNull() || !compType->isArithmeticType())
8215     return InvalidOperands(Loc, LHS, RHS);
8216   if (IsDiv)
8217     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8218   return compType;
8219 }
8220 
8221 QualType Sema::CheckRemainderOperands(
8222   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8223   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8224 
8225   if (LHS.get()->getType()->isVectorType() ||
8226       RHS.get()->getType()->isVectorType()) {
8227     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8228         RHS.get()->getType()->hasIntegerRepresentation())
8229       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8230                                  /*AllowBothBool*/getLangOpts().AltiVec,
8231                                  /*AllowBoolConversions*/false);
8232     return InvalidOperands(Loc, LHS, RHS);
8233   }
8234 
8235   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8236   if (LHS.isInvalid() || RHS.isInvalid())
8237     return QualType();
8238 
8239   if (compType.isNull() || !compType->isIntegerType())
8240     return InvalidOperands(Loc, LHS, RHS);
8241   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8242   return compType;
8243 }
8244 
8245 /// \brief Diagnose invalid arithmetic on two void pointers.
8246 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8247                                                 Expr *LHSExpr, Expr *RHSExpr) {
8248   S.Diag(Loc, S.getLangOpts().CPlusPlus
8249                 ? diag::err_typecheck_pointer_arith_void_type
8250                 : diag::ext_gnu_void_ptr)
8251     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8252                             << RHSExpr->getSourceRange();
8253 }
8254 
8255 /// \brief Diagnose invalid arithmetic on a void pointer.
8256 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8257                                             Expr *Pointer) {
8258   S.Diag(Loc, S.getLangOpts().CPlusPlus
8259                 ? diag::err_typecheck_pointer_arith_void_type
8260                 : diag::ext_gnu_void_ptr)
8261     << 0 /* one pointer */ << Pointer->getSourceRange();
8262 }
8263 
8264 /// \brief Diagnose invalid arithmetic on two function pointers.
8265 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8266                                                     Expr *LHS, Expr *RHS) {
8267   assert(LHS->getType()->isAnyPointerType());
8268   assert(RHS->getType()->isAnyPointerType());
8269   S.Diag(Loc, S.getLangOpts().CPlusPlus
8270                 ? diag::err_typecheck_pointer_arith_function_type
8271                 : diag::ext_gnu_ptr_func_arith)
8272     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8273     // We only show the second type if it differs from the first.
8274     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8275                                                    RHS->getType())
8276     << RHS->getType()->getPointeeType()
8277     << LHS->getSourceRange() << RHS->getSourceRange();
8278 }
8279 
8280 /// \brief Diagnose invalid arithmetic on a function pointer.
8281 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8282                                                 Expr *Pointer) {
8283   assert(Pointer->getType()->isAnyPointerType());
8284   S.Diag(Loc, S.getLangOpts().CPlusPlus
8285                 ? diag::err_typecheck_pointer_arith_function_type
8286                 : diag::ext_gnu_ptr_func_arith)
8287     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8288     << 0 /* one pointer, so only one type */
8289     << Pointer->getSourceRange();
8290 }
8291 
8292 /// \brief Emit error if Operand is incomplete pointer type
8293 ///
8294 /// \returns True if pointer has incomplete type
8295 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8296                                                  Expr *Operand) {
8297   QualType ResType = Operand->getType();
8298   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8299     ResType = ResAtomicType->getValueType();
8300 
8301   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8302   QualType PointeeTy = ResType->getPointeeType();
8303   return S.RequireCompleteType(Loc, PointeeTy,
8304                                diag::err_typecheck_arithmetic_incomplete_type,
8305                                PointeeTy, Operand->getSourceRange());
8306 }
8307 
8308 /// \brief Check the validity of an arithmetic pointer operand.
8309 ///
8310 /// If the operand has pointer type, this code will check for pointer types
8311 /// which are invalid in arithmetic operations. These will be diagnosed
8312 /// appropriately, including whether or not the use is supported as an
8313 /// extension.
8314 ///
8315 /// \returns True when the operand is valid to use (even if as an extension).
8316 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8317                                             Expr *Operand) {
8318   QualType ResType = Operand->getType();
8319   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8320     ResType = ResAtomicType->getValueType();
8321 
8322   if (!ResType->isAnyPointerType()) return true;
8323 
8324   QualType PointeeTy = ResType->getPointeeType();
8325   if (PointeeTy->isVoidType()) {
8326     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8327     return !S.getLangOpts().CPlusPlus;
8328   }
8329   if (PointeeTy->isFunctionType()) {
8330     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8331     return !S.getLangOpts().CPlusPlus;
8332   }
8333 
8334   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8335 
8336   return true;
8337 }
8338 
8339 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8340 /// operands.
8341 ///
8342 /// This routine will diagnose any invalid arithmetic on pointer operands much
8343 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8344 /// for emitting a single diagnostic even for operations where both LHS and RHS
8345 /// are (potentially problematic) pointers.
8346 ///
8347 /// \returns True when the operand is valid to use (even if as an extension).
8348 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8349                                                 Expr *LHSExpr, Expr *RHSExpr) {
8350   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8351   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8352   if (!isLHSPointer && !isRHSPointer) return true;
8353 
8354   QualType LHSPointeeTy, RHSPointeeTy;
8355   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8356   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8357 
8358   // if both are pointers check if operation is valid wrt address spaces
8359   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8360     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8361     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8362     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8363       S.Diag(Loc,
8364              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8365           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8366           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8367       return false;
8368     }
8369   }
8370 
8371   // Check for arithmetic on pointers to incomplete types.
8372   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8373   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8374   if (isLHSVoidPtr || isRHSVoidPtr) {
8375     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8376     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8377     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8378 
8379     return !S.getLangOpts().CPlusPlus;
8380   }
8381 
8382   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8383   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8384   if (isLHSFuncPtr || isRHSFuncPtr) {
8385     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8386     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8387                                                                 RHSExpr);
8388     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8389 
8390     return !S.getLangOpts().CPlusPlus;
8391   }
8392 
8393   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8394     return false;
8395   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8396     return false;
8397 
8398   return true;
8399 }
8400 
8401 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8402 /// literal.
8403 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8404                                   Expr *LHSExpr, Expr *RHSExpr) {
8405   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8406   Expr* IndexExpr = RHSExpr;
8407   if (!StrExpr) {
8408     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8409     IndexExpr = LHSExpr;
8410   }
8411 
8412   bool IsStringPlusInt = StrExpr &&
8413       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8414   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8415     return;
8416 
8417   llvm::APSInt index;
8418   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8419     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8420     if (index.isNonNegative() &&
8421         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8422                               index.isUnsigned()))
8423       return;
8424   }
8425 
8426   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8427   Self.Diag(OpLoc, diag::warn_string_plus_int)
8428       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8429 
8430   // Only print a fixit for "str" + int, not for int + "str".
8431   if (IndexExpr == RHSExpr) {
8432     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8433     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8434         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8435         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8436         << FixItHint::CreateInsertion(EndLoc, "]");
8437   } else
8438     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8439 }
8440 
8441 /// \brief Emit a warning when adding a char literal to a string.
8442 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8443                                    Expr *LHSExpr, Expr *RHSExpr) {
8444   const Expr *StringRefExpr = LHSExpr;
8445   const CharacterLiteral *CharExpr =
8446       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8447 
8448   if (!CharExpr) {
8449     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8450     StringRefExpr = RHSExpr;
8451   }
8452 
8453   if (!CharExpr || !StringRefExpr)
8454     return;
8455 
8456   const QualType StringType = StringRefExpr->getType();
8457 
8458   // Return if not a PointerType.
8459   if (!StringType->isAnyPointerType())
8460     return;
8461 
8462   // Return if not a CharacterType.
8463   if (!StringType->getPointeeType()->isAnyCharacterType())
8464     return;
8465 
8466   ASTContext &Ctx = Self.getASTContext();
8467   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8468 
8469   const QualType CharType = CharExpr->getType();
8470   if (!CharType->isAnyCharacterType() &&
8471       CharType->isIntegerType() &&
8472       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8473     Self.Diag(OpLoc, diag::warn_string_plus_char)
8474         << DiagRange << Ctx.CharTy;
8475   } else {
8476     Self.Diag(OpLoc, diag::warn_string_plus_char)
8477         << DiagRange << CharExpr->getType();
8478   }
8479 
8480   // Only print a fixit for str + char, not for char + str.
8481   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8482     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8483     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8484         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8485         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8486         << FixItHint::CreateInsertion(EndLoc, "]");
8487   } else {
8488     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8489   }
8490 }
8491 
8492 /// \brief Emit error when two pointers are incompatible.
8493 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8494                                            Expr *LHSExpr, Expr *RHSExpr) {
8495   assert(LHSExpr->getType()->isAnyPointerType());
8496   assert(RHSExpr->getType()->isAnyPointerType());
8497   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8498     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8499     << RHSExpr->getSourceRange();
8500 }
8501 
8502 // C99 6.5.6
8503 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8504                                      SourceLocation Loc, BinaryOperatorKind Opc,
8505                                      QualType* CompLHSTy) {
8506   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8507 
8508   if (LHS.get()->getType()->isVectorType() ||
8509       RHS.get()->getType()->isVectorType()) {
8510     QualType compType = CheckVectorOperands(
8511         LHS, RHS, Loc, CompLHSTy,
8512         /*AllowBothBool*/getLangOpts().AltiVec,
8513         /*AllowBoolConversions*/getLangOpts().ZVector);
8514     if (CompLHSTy) *CompLHSTy = compType;
8515     return compType;
8516   }
8517 
8518   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8519   if (LHS.isInvalid() || RHS.isInvalid())
8520     return QualType();
8521 
8522   // Diagnose "string literal" '+' int and string '+' "char literal".
8523   if (Opc == BO_Add) {
8524     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8525     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8526   }
8527 
8528   // handle the common case first (both operands are arithmetic).
8529   if (!compType.isNull() && compType->isArithmeticType()) {
8530     if (CompLHSTy) *CompLHSTy = compType;
8531     return compType;
8532   }
8533 
8534   // Type-checking.  Ultimately the pointer's going to be in PExp;
8535   // note that we bias towards the LHS being the pointer.
8536   Expr *PExp = LHS.get(), *IExp = RHS.get();
8537 
8538   bool isObjCPointer;
8539   if (PExp->getType()->isPointerType()) {
8540     isObjCPointer = false;
8541   } else if (PExp->getType()->isObjCObjectPointerType()) {
8542     isObjCPointer = true;
8543   } else {
8544     std::swap(PExp, IExp);
8545     if (PExp->getType()->isPointerType()) {
8546       isObjCPointer = false;
8547     } else if (PExp->getType()->isObjCObjectPointerType()) {
8548       isObjCPointer = true;
8549     } else {
8550       return InvalidOperands(Loc, LHS, RHS);
8551     }
8552   }
8553   assert(PExp->getType()->isAnyPointerType());
8554 
8555   if (!IExp->getType()->isIntegerType())
8556     return InvalidOperands(Loc, LHS, RHS);
8557 
8558   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8559     return QualType();
8560 
8561   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8562     return QualType();
8563 
8564   // Check array bounds for pointer arithemtic
8565   CheckArrayAccess(PExp, IExp);
8566 
8567   if (CompLHSTy) {
8568     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8569     if (LHSTy.isNull()) {
8570       LHSTy = LHS.get()->getType();
8571       if (LHSTy->isPromotableIntegerType())
8572         LHSTy = Context.getPromotedIntegerType(LHSTy);
8573     }
8574     *CompLHSTy = LHSTy;
8575   }
8576 
8577   return PExp->getType();
8578 }
8579 
8580 // C99 6.5.6
8581 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8582                                         SourceLocation Loc,
8583                                         QualType* CompLHSTy) {
8584   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8585 
8586   if (LHS.get()->getType()->isVectorType() ||
8587       RHS.get()->getType()->isVectorType()) {
8588     QualType compType = CheckVectorOperands(
8589         LHS, RHS, Loc, CompLHSTy,
8590         /*AllowBothBool*/getLangOpts().AltiVec,
8591         /*AllowBoolConversions*/getLangOpts().ZVector);
8592     if (CompLHSTy) *CompLHSTy = compType;
8593     return compType;
8594   }
8595 
8596   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8597   if (LHS.isInvalid() || RHS.isInvalid())
8598     return QualType();
8599 
8600   // Enforce type constraints: C99 6.5.6p3.
8601 
8602   // Handle the common case first (both operands are arithmetic).
8603   if (!compType.isNull() && compType->isArithmeticType()) {
8604     if (CompLHSTy) *CompLHSTy = compType;
8605     return compType;
8606   }
8607 
8608   // Either ptr - int   or   ptr - ptr.
8609   if (LHS.get()->getType()->isAnyPointerType()) {
8610     QualType lpointee = LHS.get()->getType()->getPointeeType();
8611 
8612     // Diagnose bad cases where we step over interface counts.
8613     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8614         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8615       return QualType();
8616 
8617     // The result type of a pointer-int computation is the pointer type.
8618     if (RHS.get()->getType()->isIntegerType()) {
8619       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8620         return QualType();
8621 
8622       // Check array bounds for pointer arithemtic
8623       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8624                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8625 
8626       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8627       return LHS.get()->getType();
8628     }
8629 
8630     // Handle pointer-pointer subtractions.
8631     if (const PointerType *RHSPTy
8632           = RHS.get()->getType()->getAs<PointerType>()) {
8633       QualType rpointee = RHSPTy->getPointeeType();
8634 
8635       if (getLangOpts().CPlusPlus) {
8636         // Pointee types must be the same: C++ [expr.add]
8637         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8638           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8639         }
8640       } else {
8641         // Pointee types must be compatible C99 6.5.6p3
8642         if (!Context.typesAreCompatible(
8643                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8644                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8645           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8646           return QualType();
8647         }
8648       }
8649 
8650       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8651                                                LHS.get(), RHS.get()))
8652         return QualType();
8653 
8654       // The pointee type may have zero size.  As an extension, a structure or
8655       // union may have zero size or an array may have zero length.  In this
8656       // case subtraction does not make sense.
8657       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8658         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8659         if (ElementSize.isZero()) {
8660           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8661             << rpointee.getUnqualifiedType()
8662             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8663         }
8664       }
8665 
8666       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8667       return Context.getPointerDiffType();
8668     }
8669   }
8670 
8671   return InvalidOperands(Loc, LHS, RHS);
8672 }
8673 
8674 static bool isScopedEnumerationType(QualType T) {
8675   if (const EnumType *ET = T->getAs<EnumType>())
8676     return ET->getDecl()->isScoped();
8677   return false;
8678 }
8679 
8680 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8681                                    SourceLocation Loc, BinaryOperatorKind Opc,
8682                                    QualType LHSType) {
8683   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8684   // so skip remaining warnings as we don't want to modify values within Sema.
8685   if (S.getLangOpts().OpenCL)
8686     return;
8687 
8688   llvm::APSInt Right;
8689   // Check right/shifter operand
8690   if (RHS.get()->isValueDependent() ||
8691       !RHS.get()->EvaluateAsInt(Right, S.Context))
8692     return;
8693 
8694   if (Right.isNegative()) {
8695     S.DiagRuntimeBehavior(Loc, RHS.get(),
8696                           S.PDiag(diag::warn_shift_negative)
8697                             << RHS.get()->getSourceRange());
8698     return;
8699   }
8700   llvm::APInt LeftBits(Right.getBitWidth(),
8701                        S.Context.getTypeSize(LHS.get()->getType()));
8702   if (Right.uge(LeftBits)) {
8703     S.DiagRuntimeBehavior(Loc, RHS.get(),
8704                           S.PDiag(diag::warn_shift_gt_typewidth)
8705                             << RHS.get()->getSourceRange());
8706     return;
8707   }
8708   if (Opc != BO_Shl)
8709     return;
8710 
8711   // When left shifting an ICE which is signed, we can check for overflow which
8712   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8713   // integers have defined behavior modulo one more than the maximum value
8714   // representable in the result type, so never warn for those.
8715   llvm::APSInt Left;
8716   if (LHS.get()->isValueDependent() ||
8717       LHSType->hasUnsignedIntegerRepresentation() ||
8718       !LHS.get()->EvaluateAsInt(Left, S.Context))
8719     return;
8720 
8721   // If LHS does not have a signed type and non-negative value
8722   // then, the behavior is undefined. Warn about it.
8723   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8724     S.DiagRuntimeBehavior(Loc, LHS.get(),
8725                           S.PDiag(diag::warn_shift_lhs_negative)
8726                             << LHS.get()->getSourceRange());
8727     return;
8728   }
8729 
8730   llvm::APInt ResultBits =
8731       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8732   if (LeftBits.uge(ResultBits))
8733     return;
8734   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8735   Result = Result.shl(Right);
8736 
8737   // Print the bit representation of the signed integer as an unsigned
8738   // hexadecimal number.
8739   SmallString<40> HexResult;
8740   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8741 
8742   // If we are only missing a sign bit, this is less likely to result in actual
8743   // bugs -- if the result is cast back to an unsigned type, it will have the
8744   // expected value. Thus we place this behind a different warning that can be
8745   // turned off separately if needed.
8746   if (LeftBits == ResultBits - 1) {
8747     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8748         << HexResult << LHSType
8749         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8750     return;
8751   }
8752 
8753   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8754     << HexResult.str() << Result.getMinSignedBits() << LHSType
8755     << Left.getBitWidth() << LHS.get()->getSourceRange()
8756     << RHS.get()->getSourceRange();
8757 }
8758 
8759 /// \brief Return the resulting type when a vector is shifted
8760 ///        by a scalar or vector shift amount.
8761 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8762                                  SourceLocation Loc, bool IsCompAssign) {
8763   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8764   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8765       !LHS.get()->getType()->isVectorType()) {
8766     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8767       << RHS.get()->getType() << LHS.get()->getType()
8768       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8769     return QualType();
8770   }
8771 
8772   if (!IsCompAssign) {
8773     LHS = S.UsualUnaryConversions(LHS.get());
8774     if (LHS.isInvalid()) return QualType();
8775   }
8776 
8777   RHS = S.UsualUnaryConversions(RHS.get());
8778   if (RHS.isInvalid()) return QualType();
8779 
8780   QualType LHSType = LHS.get()->getType();
8781   // Note that LHS might be a scalar because the routine calls not only in
8782   // OpenCL case.
8783   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8784   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8785 
8786   // Note that RHS might not be a vector.
8787   QualType RHSType = RHS.get()->getType();
8788   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8789   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8790 
8791   // The operands need to be integers.
8792   if (!LHSEleType->isIntegerType()) {
8793     S.Diag(Loc, diag::err_typecheck_expect_int)
8794       << LHS.get()->getType() << LHS.get()->getSourceRange();
8795     return QualType();
8796   }
8797 
8798   if (!RHSEleType->isIntegerType()) {
8799     S.Diag(Loc, diag::err_typecheck_expect_int)
8800       << RHS.get()->getType() << RHS.get()->getSourceRange();
8801     return QualType();
8802   }
8803 
8804   if (!LHSVecTy) {
8805     assert(RHSVecTy);
8806     if (IsCompAssign)
8807       return RHSType;
8808     if (LHSEleType != RHSEleType) {
8809       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8810       LHSEleType = RHSEleType;
8811     }
8812     QualType VecTy =
8813         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8814     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8815     LHSType = VecTy;
8816   } else if (RHSVecTy) {
8817     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8818     // are applied component-wise. So if RHS is a vector, then ensure
8819     // that the number of elements is the same as LHS...
8820     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8821       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8822         << LHS.get()->getType() << RHS.get()->getType()
8823         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8824       return QualType();
8825     }
8826     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8827       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8828       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8829       if (LHSBT != RHSBT &&
8830           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8831         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8832             << LHS.get()->getType() << RHS.get()->getType()
8833             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8834       }
8835     }
8836   } else {
8837     // ...else expand RHS to match the number of elements in LHS.
8838     QualType VecTy =
8839       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8840     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8841   }
8842 
8843   return LHSType;
8844 }
8845 
8846 // C99 6.5.7
8847 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8848                                   SourceLocation Loc, BinaryOperatorKind Opc,
8849                                   bool IsCompAssign) {
8850   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8851 
8852   // Vector shifts promote their scalar inputs to vector type.
8853   if (LHS.get()->getType()->isVectorType() ||
8854       RHS.get()->getType()->isVectorType()) {
8855     if (LangOpts.ZVector) {
8856       // The shift operators for the z vector extensions work basically
8857       // like general shifts, except that neither the LHS nor the RHS is
8858       // allowed to be a "vector bool".
8859       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8860         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8861           return InvalidOperands(Loc, LHS, RHS);
8862       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8863         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8864           return InvalidOperands(Loc, LHS, RHS);
8865     }
8866     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8867   }
8868 
8869   // Shifts don't perform usual arithmetic conversions, they just do integer
8870   // promotions on each operand. C99 6.5.7p3
8871 
8872   // For the LHS, do usual unary conversions, but then reset them away
8873   // if this is a compound assignment.
8874   ExprResult OldLHS = LHS;
8875   LHS = UsualUnaryConversions(LHS.get());
8876   if (LHS.isInvalid())
8877     return QualType();
8878   QualType LHSType = LHS.get()->getType();
8879   if (IsCompAssign) LHS = OldLHS;
8880 
8881   // The RHS is simpler.
8882   RHS = UsualUnaryConversions(RHS.get());
8883   if (RHS.isInvalid())
8884     return QualType();
8885   QualType RHSType = RHS.get()->getType();
8886 
8887   // C99 6.5.7p2: Each of the operands shall have integer type.
8888   if (!LHSType->hasIntegerRepresentation() ||
8889       !RHSType->hasIntegerRepresentation())
8890     return InvalidOperands(Loc, LHS, RHS);
8891 
8892   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8893   // hasIntegerRepresentation() above instead of this.
8894   if (isScopedEnumerationType(LHSType) ||
8895       isScopedEnumerationType(RHSType)) {
8896     return InvalidOperands(Loc, LHS, RHS);
8897   }
8898   // Sanity-check shift operands
8899   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8900 
8901   // "The type of the result is that of the promoted left operand."
8902   return LHSType;
8903 }
8904 
8905 static bool IsWithinTemplateSpecialization(Decl *D) {
8906   if (DeclContext *DC = D->getDeclContext()) {
8907     if (isa<ClassTemplateSpecializationDecl>(DC))
8908       return true;
8909     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8910       return FD->isFunctionTemplateSpecialization();
8911   }
8912   return false;
8913 }
8914 
8915 /// If two different enums are compared, raise a warning.
8916 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8917                                 Expr *RHS) {
8918   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8919   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8920 
8921   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8922   if (!LHSEnumType)
8923     return;
8924   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8925   if (!RHSEnumType)
8926     return;
8927 
8928   // Ignore anonymous enums.
8929   if (!LHSEnumType->getDecl()->getIdentifier())
8930     return;
8931   if (!RHSEnumType->getDecl()->getIdentifier())
8932     return;
8933 
8934   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8935     return;
8936 
8937   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8938       << LHSStrippedType << RHSStrippedType
8939       << LHS->getSourceRange() << RHS->getSourceRange();
8940 }
8941 
8942 /// \brief Diagnose bad pointer comparisons.
8943 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8944                                               ExprResult &LHS, ExprResult &RHS,
8945                                               bool IsError) {
8946   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8947                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8948     << LHS.get()->getType() << RHS.get()->getType()
8949     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8950 }
8951 
8952 /// \brief Returns false if the pointers are converted to a composite type,
8953 /// true otherwise.
8954 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8955                                            ExprResult &LHS, ExprResult &RHS) {
8956   // C++ [expr.rel]p2:
8957   //   [...] Pointer conversions (4.10) and qualification
8958   //   conversions (4.4) are performed on pointer operands (or on
8959   //   a pointer operand and a null pointer constant) to bring
8960   //   them to their composite pointer type. [...]
8961   //
8962   // C++ [expr.eq]p1 uses the same notion for (in)equality
8963   // comparisons of pointers.
8964 
8965   QualType LHSType = LHS.get()->getType();
8966   QualType RHSType = RHS.get()->getType();
8967   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8968          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
8969 
8970   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
8971   if (T.isNull()) {
8972     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8973         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8974       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8975     else
8976       S.InvalidOperands(Loc, LHS, RHS);
8977     return true;
8978   }
8979 
8980   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8981   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8982   return false;
8983 }
8984 
8985 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8986                                                     ExprResult &LHS,
8987                                                     ExprResult &RHS,
8988                                                     bool IsError) {
8989   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8990                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8991     << LHS.get()->getType() << RHS.get()->getType()
8992     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8993 }
8994 
8995 static bool isObjCObjectLiteral(ExprResult &E) {
8996   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8997   case Stmt::ObjCArrayLiteralClass:
8998   case Stmt::ObjCDictionaryLiteralClass:
8999   case Stmt::ObjCStringLiteralClass:
9000   case Stmt::ObjCBoxedExprClass:
9001     return true;
9002   default:
9003     // Note that ObjCBoolLiteral is NOT an object literal!
9004     return false;
9005   }
9006 }
9007 
9008 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9009   const ObjCObjectPointerType *Type =
9010     LHS->getType()->getAs<ObjCObjectPointerType>();
9011 
9012   // If this is not actually an Objective-C object, bail out.
9013   if (!Type)
9014     return false;
9015 
9016   // Get the LHS object's interface type.
9017   QualType InterfaceType = Type->getPointeeType();
9018 
9019   // If the RHS isn't an Objective-C object, bail out.
9020   if (!RHS->getType()->isObjCObjectPointerType())
9021     return false;
9022 
9023   // Try to find the -isEqual: method.
9024   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9025   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9026                                                       InterfaceType,
9027                                                       /*instance=*/true);
9028   if (!Method) {
9029     if (Type->isObjCIdType()) {
9030       // For 'id', just check the global pool.
9031       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9032                                                   /*receiverId=*/true);
9033     } else {
9034       // Check protocols.
9035       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9036                                              /*instance=*/true);
9037     }
9038   }
9039 
9040   if (!Method)
9041     return false;
9042 
9043   QualType T = Method->parameters()[0]->getType();
9044   if (!T->isObjCObjectPointerType())
9045     return false;
9046 
9047   QualType R = Method->getReturnType();
9048   if (!R->isScalarType())
9049     return false;
9050 
9051   return true;
9052 }
9053 
9054 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9055   FromE = FromE->IgnoreParenImpCasts();
9056   switch (FromE->getStmtClass()) {
9057     default:
9058       break;
9059     case Stmt::ObjCStringLiteralClass:
9060       // "string literal"
9061       return LK_String;
9062     case Stmt::ObjCArrayLiteralClass:
9063       // "array literal"
9064       return LK_Array;
9065     case Stmt::ObjCDictionaryLiteralClass:
9066       // "dictionary literal"
9067       return LK_Dictionary;
9068     case Stmt::BlockExprClass:
9069       return LK_Block;
9070     case Stmt::ObjCBoxedExprClass: {
9071       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9072       switch (Inner->getStmtClass()) {
9073         case Stmt::IntegerLiteralClass:
9074         case Stmt::FloatingLiteralClass:
9075         case Stmt::CharacterLiteralClass:
9076         case Stmt::ObjCBoolLiteralExprClass:
9077         case Stmt::CXXBoolLiteralExprClass:
9078           // "numeric literal"
9079           return LK_Numeric;
9080         case Stmt::ImplicitCastExprClass: {
9081           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9082           // Boolean literals can be represented by implicit casts.
9083           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9084             return LK_Numeric;
9085           break;
9086         }
9087         default:
9088           break;
9089       }
9090       return LK_Boxed;
9091     }
9092   }
9093   return LK_None;
9094 }
9095 
9096 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9097                                           ExprResult &LHS, ExprResult &RHS,
9098                                           BinaryOperator::Opcode Opc){
9099   Expr *Literal;
9100   Expr *Other;
9101   if (isObjCObjectLiteral(LHS)) {
9102     Literal = LHS.get();
9103     Other = RHS.get();
9104   } else {
9105     Literal = RHS.get();
9106     Other = LHS.get();
9107   }
9108 
9109   // Don't warn on comparisons against nil.
9110   Other = Other->IgnoreParenCasts();
9111   if (Other->isNullPointerConstant(S.getASTContext(),
9112                                    Expr::NPC_ValueDependentIsNotNull))
9113     return;
9114 
9115   // This should be kept in sync with warn_objc_literal_comparison.
9116   // LK_String should always be after the other literals, since it has its own
9117   // warning flag.
9118   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9119   assert(LiteralKind != Sema::LK_Block);
9120   if (LiteralKind == Sema::LK_None) {
9121     llvm_unreachable("Unknown Objective-C object literal kind");
9122   }
9123 
9124   if (LiteralKind == Sema::LK_String)
9125     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9126       << Literal->getSourceRange();
9127   else
9128     S.Diag(Loc, diag::warn_objc_literal_comparison)
9129       << LiteralKind << Literal->getSourceRange();
9130 
9131   if (BinaryOperator::isEqualityOp(Opc) &&
9132       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9133     SourceLocation Start = LHS.get()->getLocStart();
9134     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9135     CharSourceRange OpRange =
9136       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9137 
9138     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9139       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9140       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9141       << FixItHint::CreateInsertion(End, "]");
9142   }
9143 }
9144 
9145 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9146 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9147                                            ExprResult &RHS, SourceLocation Loc,
9148                                            BinaryOperatorKind Opc) {
9149   // Check that left hand side is !something.
9150   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9151   if (!UO || UO->getOpcode() != UO_LNot) return;
9152 
9153   // Only check if the right hand side is non-bool arithmetic type.
9154   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9155 
9156   // Make sure that the something in !something is not bool.
9157   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9158   if (SubExpr->isKnownToHaveBooleanValue()) return;
9159 
9160   // Emit warning.
9161   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9162   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9163       << Loc << IsBitwiseOp;
9164 
9165   // First note suggest !(x < y)
9166   SourceLocation FirstOpen = SubExpr->getLocStart();
9167   SourceLocation FirstClose = RHS.get()->getLocEnd();
9168   FirstClose = S.getLocForEndOfToken(FirstClose);
9169   if (FirstClose.isInvalid())
9170     FirstOpen = SourceLocation();
9171   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9172       << IsBitwiseOp
9173       << FixItHint::CreateInsertion(FirstOpen, "(")
9174       << FixItHint::CreateInsertion(FirstClose, ")");
9175 
9176   // Second note suggests (!x) < y
9177   SourceLocation SecondOpen = LHS.get()->getLocStart();
9178   SourceLocation SecondClose = LHS.get()->getLocEnd();
9179   SecondClose = S.getLocForEndOfToken(SecondClose);
9180   if (SecondClose.isInvalid())
9181     SecondOpen = SourceLocation();
9182   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9183       << FixItHint::CreateInsertion(SecondOpen, "(")
9184       << FixItHint::CreateInsertion(SecondClose, ")");
9185 }
9186 
9187 // Get the decl for a simple expression: a reference to a variable,
9188 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9189 static ValueDecl *getCompareDecl(Expr *E) {
9190   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9191     return DR->getDecl();
9192   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9193     if (Ivar->isFreeIvar())
9194       return Ivar->getDecl();
9195   }
9196   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9197     if (Mem->isImplicitAccess())
9198       return Mem->getMemberDecl();
9199   }
9200   return nullptr;
9201 }
9202 
9203 // C99 6.5.8, C++ [expr.rel]
9204 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9205                                     SourceLocation Loc, BinaryOperatorKind Opc,
9206                                     bool IsRelational) {
9207   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9208 
9209   // Handle vector comparisons separately.
9210   if (LHS.get()->getType()->isVectorType() ||
9211       RHS.get()->getType()->isVectorType())
9212     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9213 
9214   QualType LHSType = LHS.get()->getType();
9215   QualType RHSType = RHS.get()->getType();
9216 
9217   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9218   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9219 
9220   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9221   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9222 
9223   if (!LHSType->hasFloatingRepresentation() &&
9224       !(LHSType->isBlockPointerType() && IsRelational) &&
9225       !LHS.get()->getLocStart().isMacroID() &&
9226       !RHS.get()->getLocStart().isMacroID() &&
9227       ActiveTemplateInstantiations.empty()) {
9228     // For non-floating point types, check for self-comparisons of the form
9229     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9230     // often indicate logic errors in the program.
9231     //
9232     // NOTE: Don't warn about comparison expressions resulting from macro
9233     // expansion. Also don't warn about comparisons which are only self
9234     // comparisons within a template specialization. The warnings should catch
9235     // obvious cases in the definition of the template anyways. The idea is to
9236     // warn when the typed comparison operator will always evaluate to the same
9237     // result.
9238     ValueDecl *DL = getCompareDecl(LHSStripped);
9239     ValueDecl *DR = getCompareDecl(RHSStripped);
9240     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9241       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9242                           << 0 // self-
9243                           << (Opc == BO_EQ
9244                               || Opc == BO_LE
9245                               || Opc == BO_GE));
9246     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9247                !DL->getType()->isReferenceType() &&
9248                !DR->getType()->isReferenceType()) {
9249         // what is it always going to eval to?
9250         char always_evals_to;
9251         switch(Opc) {
9252         case BO_EQ: // e.g. array1 == array2
9253           always_evals_to = 0; // false
9254           break;
9255         case BO_NE: // e.g. array1 != array2
9256           always_evals_to = 1; // true
9257           break;
9258         default:
9259           // best we can say is 'a constant'
9260           always_evals_to = 2; // e.g. array1 <= array2
9261           break;
9262         }
9263         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9264                             << 1 // array
9265                             << always_evals_to);
9266     }
9267 
9268     if (isa<CastExpr>(LHSStripped))
9269       LHSStripped = LHSStripped->IgnoreParenCasts();
9270     if (isa<CastExpr>(RHSStripped))
9271       RHSStripped = RHSStripped->IgnoreParenCasts();
9272 
9273     // Warn about comparisons against a string constant (unless the other
9274     // operand is null), the user probably wants strcmp.
9275     Expr *literalString = nullptr;
9276     Expr *literalStringStripped = nullptr;
9277     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9278         !RHSStripped->isNullPointerConstant(Context,
9279                                             Expr::NPC_ValueDependentIsNull)) {
9280       literalString = LHS.get();
9281       literalStringStripped = LHSStripped;
9282     } else if ((isa<StringLiteral>(RHSStripped) ||
9283                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9284                !LHSStripped->isNullPointerConstant(Context,
9285                                             Expr::NPC_ValueDependentIsNull)) {
9286       literalString = RHS.get();
9287       literalStringStripped = RHSStripped;
9288     }
9289 
9290     if (literalString) {
9291       DiagRuntimeBehavior(Loc, nullptr,
9292         PDiag(diag::warn_stringcompare)
9293           << isa<ObjCEncodeExpr>(literalStringStripped)
9294           << literalString->getSourceRange());
9295     }
9296   }
9297 
9298   // C99 6.5.8p3 / C99 6.5.9p4
9299   UsualArithmeticConversions(LHS, RHS);
9300   if (LHS.isInvalid() || RHS.isInvalid())
9301     return QualType();
9302 
9303   LHSType = LHS.get()->getType();
9304   RHSType = RHS.get()->getType();
9305 
9306   // The result of comparisons is 'bool' in C++, 'int' in C.
9307   QualType ResultTy = Context.getLogicalOperationType();
9308 
9309   if (IsRelational) {
9310     if (LHSType->isRealType() && RHSType->isRealType())
9311       return ResultTy;
9312   } else {
9313     // Check for comparisons of floating point operands using != and ==.
9314     if (LHSType->hasFloatingRepresentation())
9315       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9316 
9317     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9318       return ResultTy;
9319   }
9320 
9321   const Expr::NullPointerConstantKind LHSNullKind =
9322       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9323   const Expr::NullPointerConstantKind RHSNullKind =
9324       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9325   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9326   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9327 
9328   if (!IsRelational && LHSIsNull != RHSIsNull) {
9329     bool IsEquality = Opc == BO_EQ;
9330     if (RHSIsNull)
9331       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9332                                    RHS.get()->getSourceRange());
9333     else
9334       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9335                                    LHS.get()->getSourceRange());
9336   }
9337 
9338   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9339       (RHSType->isIntegerType() && !RHSIsNull)) {
9340     // Skip normal pointer conversion checks in this case; we have better
9341     // diagnostics for this below.
9342   } else if (getLangOpts().CPlusPlus) {
9343     // Equality comparison of a function pointer to a void pointer is invalid,
9344     // but we allow it as an extension.
9345     // FIXME: If we really want to allow this, should it be part of composite
9346     // pointer type computation so it works in conditionals too?
9347     if (!IsRelational &&
9348         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9349          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9350       // This is a gcc extension compatibility comparison.
9351       // In a SFINAE context, we treat this as a hard error to maintain
9352       // conformance with the C++ standard.
9353       diagnoseFunctionPointerToVoidComparison(
9354           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9355 
9356       if (isSFINAEContext())
9357         return QualType();
9358 
9359       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9360       return ResultTy;
9361     }
9362 
9363     // C++ [expr.eq]p2:
9364     //   If at least one operand is a pointer [...] bring them to their
9365     //   composite pointer type.
9366     // C++ [expr.rel]p2:
9367     //   If both operands are pointers, [...] bring them to their composite
9368     //   pointer type.
9369     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9370         (IsRelational ? 2 : 1)) {
9371       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9372         return QualType();
9373       else
9374         return ResultTy;
9375     }
9376   } else if (LHSType->isPointerType() &&
9377              RHSType->isPointerType()) { // C99 6.5.8p2
9378     // All of the following pointer-related warnings are GCC extensions, except
9379     // when handling null pointer constants.
9380     QualType LCanPointeeTy =
9381       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9382     QualType RCanPointeeTy =
9383       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9384 
9385     // C99 6.5.9p2 and C99 6.5.8p2
9386     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9387                                    RCanPointeeTy.getUnqualifiedType())) {
9388       // Valid unless a relational comparison of function pointers
9389       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9390         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9391           << LHSType << RHSType << LHS.get()->getSourceRange()
9392           << RHS.get()->getSourceRange();
9393       }
9394     } else if (!IsRelational &&
9395                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9396       // Valid unless comparison between non-null pointer and function pointer
9397       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9398           && !LHSIsNull && !RHSIsNull)
9399         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9400                                                 /*isError*/false);
9401     } else {
9402       // Invalid
9403       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9404     }
9405     if (LCanPointeeTy != RCanPointeeTy) {
9406       // Treat NULL constant as a special case in OpenCL.
9407       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9408         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9409         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9410           Diag(Loc,
9411                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9412               << LHSType << RHSType << 0 /* comparison */
9413               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9414         }
9415       }
9416       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9417       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9418       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9419                                                : CK_BitCast;
9420       if (LHSIsNull && !RHSIsNull)
9421         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9422       else
9423         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9424     }
9425     return ResultTy;
9426   }
9427 
9428   if (getLangOpts().CPlusPlus) {
9429     // C++ [expr.eq]p4:
9430     //   Two operands of type std::nullptr_t or one operand of type
9431     //   std::nullptr_t and the other a null pointer constant compare equal.
9432     if (!IsRelational && LHSIsNull && RHSIsNull) {
9433       if (LHSType->isNullPtrType()) {
9434         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9435         return ResultTy;
9436       }
9437       if (RHSType->isNullPtrType()) {
9438         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9439         return ResultTy;
9440       }
9441     }
9442 
9443     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9444     // These aren't covered by the composite pointer type rules.
9445     if (!IsRelational && RHSType->isNullPtrType() &&
9446         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9447       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9448       return ResultTy;
9449     }
9450     if (!IsRelational && LHSType->isNullPtrType() &&
9451         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9452       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9453       return ResultTy;
9454     }
9455 
9456     if (IsRelational &&
9457         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9458          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9459       // HACK: Relational comparison of nullptr_t against a pointer type is
9460       // invalid per DR583, but we allow it within std::less<> and friends,
9461       // since otherwise common uses of it break.
9462       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9463       // friends to have std::nullptr_t overload candidates.
9464       DeclContext *DC = CurContext;
9465       if (isa<FunctionDecl>(DC))
9466         DC = DC->getParent();
9467       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9468         if (CTSD->isInStdNamespace() &&
9469             llvm::StringSwitch<bool>(CTSD->getName())
9470                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9471                 .Default(false)) {
9472           if (RHSType->isNullPtrType())
9473             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9474           else
9475             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9476           return ResultTy;
9477         }
9478       }
9479     }
9480 
9481     // C++ [expr.eq]p2:
9482     //   If at least one operand is a pointer to member, [...] bring them to
9483     //   their composite pointer type.
9484     if (!IsRelational &&
9485         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9486       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9487         return QualType();
9488       else
9489         return ResultTy;
9490     }
9491 
9492     // Handle scoped enumeration types specifically, since they don't promote
9493     // to integers.
9494     if (LHS.get()->getType()->isEnumeralType() &&
9495         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9496                                        RHS.get()->getType()))
9497       return ResultTy;
9498   }
9499 
9500   // Handle block pointer types.
9501   if (!IsRelational && LHSType->isBlockPointerType() &&
9502       RHSType->isBlockPointerType()) {
9503     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9504     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9505 
9506     if (!LHSIsNull && !RHSIsNull &&
9507         !Context.typesAreCompatible(lpointee, rpointee)) {
9508       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9509         << LHSType << RHSType << LHS.get()->getSourceRange()
9510         << RHS.get()->getSourceRange();
9511     }
9512     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9513     return ResultTy;
9514   }
9515 
9516   // Allow block pointers to be compared with null pointer constants.
9517   if (!IsRelational
9518       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9519           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9520     if (!LHSIsNull && !RHSIsNull) {
9521       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9522              ->getPointeeType()->isVoidType())
9523             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9524                 ->getPointeeType()->isVoidType())))
9525         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9526           << LHSType << RHSType << LHS.get()->getSourceRange()
9527           << RHS.get()->getSourceRange();
9528     }
9529     if (LHSIsNull && !RHSIsNull)
9530       LHS = ImpCastExprToType(LHS.get(), RHSType,
9531                               RHSType->isPointerType() ? CK_BitCast
9532                                 : CK_AnyPointerToBlockPointerCast);
9533     else
9534       RHS = ImpCastExprToType(RHS.get(), LHSType,
9535                               LHSType->isPointerType() ? CK_BitCast
9536                                 : CK_AnyPointerToBlockPointerCast);
9537     return ResultTy;
9538   }
9539 
9540   if (LHSType->isObjCObjectPointerType() ||
9541       RHSType->isObjCObjectPointerType()) {
9542     const PointerType *LPT = LHSType->getAs<PointerType>();
9543     const PointerType *RPT = RHSType->getAs<PointerType>();
9544     if (LPT || RPT) {
9545       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9546       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9547 
9548       if (!LPtrToVoid && !RPtrToVoid &&
9549           !Context.typesAreCompatible(LHSType, RHSType)) {
9550         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9551                                           /*isError*/false);
9552       }
9553       if (LHSIsNull && !RHSIsNull) {
9554         Expr *E = LHS.get();
9555         if (getLangOpts().ObjCAutoRefCount)
9556           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9557         LHS = ImpCastExprToType(E, RHSType,
9558                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9559       }
9560       else {
9561         Expr *E = RHS.get();
9562         if (getLangOpts().ObjCAutoRefCount)
9563           CheckObjCARCConversion(SourceRange(), LHSType, E,
9564                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9565                                  /*DiagnoseCFAudited=*/false, Opc);
9566         RHS = ImpCastExprToType(E, LHSType,
9567                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9568       }
9569       return ResultTy;
9570     }
9571     if (LHSType->isObjCObjectPointerType() &&
9572         RHSType->isObjCObjectPointerType()) {
9573       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9574         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9575                                           /*isError*/false);
9576       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9577         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9578 
9579       if (LHSIsNull && !RHSIsNull)
9580         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9581       else
9582         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9583       return ResultTy;
9584     }
9585   }
9586   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9587       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9588     unsigned DiagID = 0;
9589     bool isError = false;
9590     if (LangOpts.DebuggerSupport) {
9591       // Under a debugger, allow the comparison of pointers to integers,
9592       // since users tend to want to compare addresses.
9593     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9594                (RHSIsNull && RHSType->isIntegerType())) {
9595       if (IsRelational) {
9596         isError = getLangOpts().CPlusPlus;
9597         DiagID =
9598           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9599                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9600       }
9601     } else if (getLangOpts().CPlusPlus) {
9602       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9603       isError = true;
9604     } else if (IsRelational)
9605       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9606     else
9607       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9608 
9609     if (DiagID) {
9610       Diag(Loc, DiagID)
9611         << LHSType << RHSType << LHS.get()->getSourceRange()
9612         << RHS.get()->getSourceRange();
9613       if (isError)
9614         return QualType();
9615     }
9616 
9617     if (LHSType->isIntegerType())
9618       LHS = ImpCastExprToType(LHS.get(), RHSType,
9619                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9620     else
9621       RHS = ImpCastExprToType(RHS.get(), LHSType,
9622                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9623     return ResultTy;
9624   }
9625 
9626   // Handle block pointers.
9627   if (!IsRelational && RHSIsNull
9628       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9629     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9630     return ResultTy;
9631   }
9632   if (!IsRelational && LHSIsNull
9633       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9634     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9635     return ResultTy;
9636   }
9637 
9638   if (getLangOpts().OpenCLVersion >= 200) {
9639     if (LHSIsNull && RHSType->isQueueT()) {
9640       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9641       return ResultTy;
9642     }
9643 
9644     if (LHSType->isQueueT() && RHSIsNull) {
9645       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9646       return ResultTy;
9647     }
9648   }
9649 
9650   return InvalidOperands(Loc, LHS, RHS);
9651 }
9652 
9653 
9654 // Return a signed type that is of identical size and number of elements.
9655 // For floating point vectors, return an integer type of identical size
9656 // and number of elements.
9657 QualType Sema::GetSignedVectorType(QualType V) {
9658   const VectorType *VTy = V->getAs<VectorType>();
9659   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9660   if (TypeSize == Context.getTypeSize(Context.CharTy))
9661     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9662   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9663     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9664   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9665     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9666   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9667     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9668   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9669          "Unhandled vector element size in vector compare");
9670   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9671 }
9672 
9673 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9674 /// operates on extended vector types.  Instead of producing an IntTy result,
9675 /// like a scalar comparison, a vector comparison produces a vector of integer
9676 /// types.
9677 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9678                                           SourceLocation Loc,
9679                                           bool IsRelational) {
9680   // Check to make sure we're operating on vectors of the same type and width,
9681   // Allowing one side to be a scalar of element type.
9682   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9683                               /*AllowBothBool*/true,
9684                               /*AllowBoolConversions*/getLangOpts().ZVector);
9685   if (vType.isNull())
9686     return vType;
9687 
9688   QualType LHSType = LHS.get()->getType();
9689 
9690   // If AltiVec, the comparison results in a numeric type, i.e.
9691   // bool for C++, int for C
9692   if (getLangOpts().AltiVec &&
9693       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9694     return Context.getLogicalOperationType();
9695 
9696   // For non-floating point types, check for self-comparisons of the form
9697   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9698   // often indicate logic errors in the program.
9699   if (!LHSType->hasFloatingRepresentation() &&
9700       ActiveTemplateInstantiations.empty()) {
9701     if (DeclRefExpr* DRL
9702           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9703       if (DeclRefExpr* DRR
9704             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9705         if (DRL->getDecl() == DRR->getDecl())
9706           DiagRuntimeBehavior(Loc, nullptr,
9707                               PDiag(diag::warn_comparison_always)
9708                                 << 0 // self-
9709                                 << 2 // "a constant"
9710                               );
9711   }
9712 
9713   // Check for comparisons of floating point operands using != and ==.
9714   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9715     assert (RHS.get()->getType()->hasFloatingRepresentation());
9716     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9717   }
9718 
9719   // Return a signed type for the vector.
9720   return GetSignedVectorType(vType);
9721 }
9722 
9723 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9724                                           SourceLocation Loc) {
9725   // Ensure that either both operands are of the same vector type, or
9726   // one operand is of a vector type and the other is of its element type.
9727   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9728                                        /*AllowBothBool*/true,
9729                                        /*AllowBoolConversions*/false);
9730   if (vType.isNull())
9731     return InvalidOperands(Loc, LHS, RHS);
9732   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9733       vType->hasFloatingRepresentation())
9734     return InvalidOperands(Loc, LHS, RHS);
9735 
9736   return GetSignedVectorType(LHS.get()->getType());
9737 }
9738 
9739 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9740                                            SourceLocation Loc,
9741                                            BinaryOperatorKind Opc) {
9742   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9743 
9744   bool IsCompAssign =
9745       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9746 
9747   if (LHS.get()->getType()->isVectorType() ||
9748       RHS.get()->getType()->isVectorType()) {
9749     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9750         RHS.get()->getType()->hasIntegerRepresentation())
9751       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9752                         /*AllowBothBool*/true,
9753                         /*AllowBoolConversions*/getLangOpts().ZVector);
9754     return InvalidOperands(Loc, LHS, RHS);
9755   }
9756 
9757   if (Opc == BO_And)
9758     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9759 
9760   ExprResult LHSResult = LHS, RHSResult = RHS;
9761   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9762                                                  IsCompAssign);
9763   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9764     return QualType();
9765   LHS = LHSResult.get();
9766   RHS = RHSResult.get();
9767 
9768   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9769     return compType;
9770   return InvalidOperands(Loc, LHS, RHS);
9771 }
9772 
9773 // C99 6.5.[13,14]
9774 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9775                                            SourceLocation Loc,
9776                                            BinaryOperatorKind Opc) {
9777   // Check vector operands differently.
9778   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9779     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9780 
9781   // Diagnose cases where the user write a logical and/or but probably meant a
9782   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9783   // is a constant.
9784   if (LHS.get()->getType()->isIntegerType() &&
9785       !LHS.get()->getType()->isBooleanType() &&
9786       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9787       // Don't warn in macros or template instantiations.
9788       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9789     // If the RHS can be constant folded, and if it constant folds to something
9790     // that isn't 0 or 1 (which indicate a potential logical operation that
9791     // happened to fold to true/false) then warn.
9792     // Parens on the RHS are ignored.
9793     llvm::APSInt Result;
9794     if (RHS.get()->EvaluateAsInt(Result, Context))
9795       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9796            !RHS.get()->getExprLoc().isMacroID()) ||
9797           (Result != 0 && Result != 1)) {
9798         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9799           << RHS.get()->getSourceRange()
9800           << (Opc == BO_LAnd ? "&&" : "||");
9801         // Suggest replacing the logical operator with the bitwise version
9802         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9803             << (Opc == BO_LAnd ? "&" : "|")
9804             << FixItHint::CreateReplacement(SourceRange(
9805                                                  Loc, getLocForEndOfToken(Loc)),
9806                                             Opc == BO_LAnd ? "&" : "|");
9807         if (Opc == BO_LAnd)
9808           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9809           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9810               << FixItHint::CreateRemoval(
9811                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9812                               RHS.get()->getLocEnd()));
9813       }
9814   }
9815 
9816   if (!Context.getLangOpts().CPlusPlus) {
9817     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9818     // not operate on the built-in scalar and vector float types.
9819     if (Context.getLangOpts().OpenCL &&
9820         Context.getLangOpts().OpenCLVersion < 120) {
9821       if (LHS.get()->getType()->isFloatingType() ||
9822           RHS.get()->getType()->isFloatingType())
9823         return InvalidOperands(Loc, LHS, RHS);
9824     }
9825 
9826     LHS = UsualUnaryConversions(LHS.get());
9827     if (LHS.isInvalid())
9828       return QualType();
9829 
9830     RHS = UsualUnaryConversions(RHS.get());
9831     if (RHS.isInvalid())
9832       return QualType();
9833 
9834     if (!LHS.get()->getType()->isScalarType() ||
9835         !RHS.get()->getType()->isScalarType())
9836       return InvalidOperands(Loc, LHS, RHS);
9837 
9838     return Context.IntTy;
9839   }
9840 
9841   // The following is safe because we only use this method for
9842   // non-overloadable operands.
9843 
9844   // C++ [expr.log.and]p1
9845   // C++ [expr.log.or]p1
9846   // The operands are both contextually converted to type bool.
9847   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9848   if (LHSRes.isInvalid())
9849     return InvalidOperands(Loc, LHS, RHS);
9850   LHS = LHSRes;
9851 
9852   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9853   if (RHSRes.isInvalid())
9854     return InvalidOperands(Loc, LHS, RHS);
9855   RHS = RHSRes;
9856 
9857   // C++ [expr.log.and]p2
9858   // C++ [expr.log.or]p2
9859   // The result is a bool.
9860   return Context.BoolTy;
9861 }
9862 
9863 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9864   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9865   if (!ME) return false;
9866   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9867   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9868       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9869   if (!Base) return false;
9870   return Base->getMethodDecl() != nullptr;
9871 }
9872 
9873 /// Is the given expression (which must be 'const') a reference to a
9874 /// variable which was originally non-const, but which has become
9875 /// 'const' due to being captured within a block?
9876 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9877 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9878   assert(E->isLValue() && E->getType().isConstQualified());
9879   E = E->IgnoreParens();
9880 
9881   // Must be a reference to a declaration from an enclosing scope.
9882   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9883   if (!DRE) return NCCK_None;
9884   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9885 
9886   // The declaration must be a variable which is not declared 'const'.
9887   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9888   if (!var) return NCCK_None;
9889   if (var->getType().isConstQualified()) return NCCK_None;
9890   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9891 
9892   // Decide whether the first capture was for a block or a lambda.
9893   DeclContext *DC = S.CurContext, *Prev = nullptr;
9894   // Decide whether the first capture was for a block or a lambda.
9895   while (DC) {
9896     // For init-capture, it is possible that the variable belongs to the
9897     // template pattern of the current context.
9898     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9899       if (var->isInitCapture() &&
9900           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9901         break;
9902     if (DC == var->getDeclContext())
9903       break;
9904     Prev = DC;
9905     DC = DC->getParent();
9906   }
9907   // Unless we have an init-capture, we've gone one step too far.
9908   if (!var->isInitCapture())
9909     DC = Prev;
9910   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9911 }
9912 
9913 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9914   Ty = Ty.getNonReferenceType();
9915   if (IsDereference && Ty->isPointerType())
9916     Ty = Ty->getPointeeType();
9917   return !Ty.isConstQualified();
9918 }
9919 
9920 /// Emit the "read-only variable not assignable" error and print notes to give
9921 /// more information about why the variable is not assignable, such as pointing
9922 /// to the declaration of a const variable, showing that a method is const, or
9923 /// that the function is returning a const reference.
9924 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9925                                     SourceLocation Loc) {
9926   // Update err_typecheck_assign_const and note_typecheck_assign_const
9927   // when this enum is changed.
9928   enum {
9929     ConstFunction,
9930     ConstVariable,
9931     ConstMember,
9932     ConstMethod,
9933     ConstUnknown,  // Keep as last element
9934   };
9935 
9936   SourceRange ExprRange = E->getSourceRange();
9937 
9938   // Only emit one error on the first const found.  All other consts will emit
9939   // a note to the error.
9940   bool DiagnosticEmitted = false;
9941 
9942   // Track if the current expression is the result of a dereference, and if the
9943   // next checked expression is the result of a dereference.
9944   bool IsDereference = false;
9945   bool NextIsDereference = false;
9946 
9947   // Loop to process MemberExpr chains.
9948   while (true) {
9949     IsDereference = NextIsDereference;
9950 
9951     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9952     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9953       NextIsDereference = ME->isArrow();
9954       const ValueDecl *VD = ME->getMemberDecl();
9955       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9956         // Mutable fields can be modified even if the class is const.
9957         if (Field->isMutable()) {
9958           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9959           break;
9960         }
9961 
9962         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9963           if (!DiagnosticEmitted) {
9964             S.Diag(Loc, diag::err_typecheck_assign_const)
9965                 << ExprRange << ConstMember << false /*static*/ << Field
9966                 << Field->getType();
9967             DiagnosticEmitted = true;
9968           }
9969           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9970               << ConstMember << false /*static*/ << Field << Field->getType()
9971               << Field->getSourceRange();
9972         }
9973         E = ME->getBase();
9974         continue;
9975       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9976         if (VDecl->getType().isConstQualified()) {
9977           if (!DiagnosticEmitted) {
9978             S.Diag(Loc, diag::err_typecheck_assign_const)
9979                 << ExprRange << ConstMember << true /*static*/ << VDecl
9980                 << VDecl->getType();
9981             DiagnosticEmitted = true;
9982           }
9983           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9984               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9985               << VDecl->getSourceRange();
9986         }
9987         // Static fields do not inherit constness from parents.
9988         break;
9989       }
9990       break;
9991     } // End MemberExpr
9992     break;
9993   }
9994 
9995   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9996     // Function calls
9997     const FunctionDecl *FD = CE->getDirectCallee();
9998     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9999       if (!DiagnosticEmitted) {
10000         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10001                                                       << ConstFunction << FD;
10002         DiagnosticEmitted = true;
10003       }
10004       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10005              diag::note_typecheck_assign_const)
10006           << ConstFunction << FD << FD->getReturnType()
10007           << FD->getReturnTypeSourceRange();
10008     }
10009   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10010     // Point to variable declaration.
10011     if (const ValueDecl *VD = DRE->getDecl()) {
10012       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10013         if (!DiagnosticEmitted) {
10014           S.Diag(Loc, diag::err_typecheck_assign_const)
10015               << ExprRange << ConstVariable << VD << VD->getType();
10016           DiagnosticEmitted = true;
10017         }
10018         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10019             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10020       }
10021     }
10022   } else if (isa<CXXThisExpr>(E)) {
10023     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10024       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10025         if (MD->isConst()) {
10026           if (!DiagnosticEmitted) {
10027             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10028                                                           << ConstMethod << MD;
10029             DiagnosticEmitted = true;
10030           }
10031           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10032               << ConstMethod << MD << MD->getSourceRange();
10033         }
10034       }
10035     }
10036   }
10037 
10038   if (DiagnosticEmitted)
10039     return;
10040 
10041   // Can't determine a more specific message, so display the generic error.
10042   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10043 }
10044 
10045 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10046 /// emit an error and return true.  If so, return false.
10047 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10048   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10049 
10050   S.CheckShadowingDeclModification(E, Loc);
10051 
10052   SourceLocation OrigLoc = Loc;
10053   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10054                                                               &Loc);
10055   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10056     IsLV = Expr::MLV_InvalidMessageExpression;
10057   if (IsLV == Expr::MLV_Valid)
10058     return false;
10059 
10060   unsigned DiagID = 0;
10061   bool NeedType = false;
10062   switch (IsLV) { // C99 6.5.16p2
10063   case Expr::MLV_ConstQualified:
10064     // Use a specialized diagnostic when we're assigning to an object
10065     // from an enclosing function or block.
10066     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10067       if (NCCK == NCCK_Block)
10068         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10069       else
10070         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10071       break;
10072     }
10073 
10074     // In ARC, use some specialized diagnostics for occasions where we
10075     // infer 'const'.  These are always pseudo-strong variables.
10076     if (S.getLangOpts().ObjCAutoRefCount) {
10077       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10078       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10079         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10080 
10081         // Use the normal diagnostic if it's pseudo-__strong but the
10082         // user actually wrote 'const'.
10083         if (var->isARCPseudoStrong() &&
10084             (!var->getTypeSourceInfo() ||
10085              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10086           // There are two pseudo-strong cases:
10087           //  - self
10088           ObjCMethodDecl *method = S.getCurMethodDecl();
10089           if (method && var == method->getSelfDecl())
10090             DiagID = method->isClassMethod()
10091               ? diag::err_typecheck_arc_assign_self_class_method
10092               : diag::err_typecheck_arc_assign_self;
10093 
10094           //  - fast enumeration variables
10095           else
10096             DiagID = diag::err_typecheck_arr_assign_enumeration;
10097 
10098           SourceRange Assign;
10099           if (Loc != OrigLoc)
10100             Assign = SourceRange(OrigLoc, OrigLoc);
10101           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10102           // We need to preserve the AST regardless, so migration tool
10103           // can do its job.
10104           return false;
10105         }
10106       }
10107     }
10108 
10109     // If none of the special cases above are triggered, then this is a
10110     // simple const assignment.
10111     if (DiagID == 0) {
10112       DiagnoseConstAssignment(S, E, Loc);
10113       return true;
10114     }
10115 
10116     break;
10117   case Expr::MLV_ConstAddrSpace:
10118     DiagnoseConstAssignment(S, E, Loc);
10119     return true;
10120   case Expr::MLV_ArrayType:
10121   case Expr::MLV_ArrayTemporary:
10122     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10123     NeedType = true;
10124     break;
10125   case Expr::MLV_NotObjectType:
10126     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10127     NeedType = true;
10128     break;
10129   case Expr::MLV_LValueCast:
10130     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10131     break;
10132   case Expr::MLV_Valid:
10133     llvm_unreachable("did not take early return for MLV_Valid");
10134   case Expr::MLV_InvalidExpression:
10135   case Expr::MLV_MemberFunction:
10136   case Expr::MLV_ClassTemporary:
10137     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10138     break;
10139   case Expr::MLV_IncompleteType:
10140   case Expr::MLV_IncompleteVoidType:
10141     return S.RequireCompleteType(Loc, E->getType(),
10142              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10143   case Expr::MLV_DuplicateVectorComponents:
10144     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10145     break;
10146   case Expr::MLV_NoSetterProperty:
10147     llvm_unreachable("readonly properties should be processed differently");
10148   case Expr::MLV_InvalidMessageExpression:
10149     DiagID = diag::err_readonly_message_assignment;
10150     break;
10151   case Expr::MLV_SubObjCPropertySetting:
10152     DiagID = diag::err_no_subobject_property_setting;
10153     break;
10154   }
10155 
10156   SourceRange Assign;
10157   if (Loc != OrigLoc)
10158     Assign = SourceRange(OrigLoc, OrigLoc);
10159   if (NeedType)
10160     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10161   else
10162     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10163   return true;
10164 }
10165 
10166 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10167                                          SourceLocation Loc,
10168                                          Sema &Sema) {
10169   // C / C++ fields
10170   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10171   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10172   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10173     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10174       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10175   }
10176 
10177   // Objective-C instance variables
10178   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10179   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10180   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10181     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10182     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10183     if (RL && RR && RL->getDecl() == RR->getDecl())
10184       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10185   }
10186 }
10187 
10188 // C99 6.5.16.1
10189 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10190                                        SourceLocation Loc,
10191                                        QualType CompoundType) {
10192   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10193 
10194   // Verify that LHS is a modifiable lvalue, and emit error if not.
10195   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10196     return QualType();
10197 
10198   QualType LHSType = LHSExpr->getType();
10199   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10200                                              CompoundType;
10201   // OpenCL v1.2 s6.1.1.1 p2:
10202   // The half data type can only be used to declare a pointer to a buffer that
10203   // contains half values
10204   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10205     LHSType->isHalfType()) {
10206     Diag(Loc, diag::err_opencl_half_load_store) << 1
10207         << LHSType.getUnqualifiedType();
10208     return QualType();
10209   }
10210 
10211   AssignConvertType ConvTy;
10212   if (CompoundType.isNull()) {
10213     Expr *RHSCheck = RHS.get();
10214 
10215     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10216 
10217     QualType LHSTy(LHSType);
10218     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10219     if (RHS.isInvalid())
10220       return QualType();
10221     // Special case of NSObject attributes on c-style pointer types.
10222     if (ConvTy == IncompatiblePointer &&
10223         ((Context.isObjCNSObjectType(LHSType) &&
10224           RHSType->isObjCObjectPointerType()) ||
10225          (Context.isObjCNSObjectType(RHSType) &&
10226           LHSType->isObjCObjectPointerType())))
10227       ConvTy = Compatible;
10228 
10229     if (ConvTy == Compatible &&
10230         LHSType->isObjCObjectType())
10231         Diag(Loc, diag::err_objc_object_assignment)
10232           << LHSType;
10233 
10234     // If the RHS is a unary plus or minus, check to see if they = and + are
10235     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10236     // instead of "x += 4".
10237     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10238       RHSCheck = ICE->getSubExpr();
10239     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10240       if ((UO->getOpcode() == UO_Plus ||
10241            UO->getOpcode() == UO_Minus) &&
10242           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10243           // Only if the two operators are exactly adjacent.
10244           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10245           // And there is a space or other character before the subexpr of the
10246           // unary +/-.  We don't want to warn on "x=-1".
10247           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10248           UO->getSubExpr()->getLocStart().isFileID()) {
10249         Diag(Loc, diag::warn_not_compound_assign)
10250           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10251           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10252       }
10253     }
10254 
10255     if (ConvTy == Compatible) {
10256       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10257         // Warn about retain cycles where a block captures the LHS, but
10258         // not if the LHS is a simple variable into which the block is
10259         // being stored...unless that variable can be captured by reference!
10260         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10261         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10262         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10263           checkRetainCycles(LHSExpr, RHS.get());
10264 
10265         // It is safe to assign a weak reference into a strong variable.
10266         // Although this code can still have problems:
10267         //   id x = self.weakProp;
10268         //   id y = self.weakProp;
10269         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10270         // paths through the function. This should be revisited if
10271         // -Wrepeated-use-of-weak is made flow-sensitive.
10272         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10273                              RHS.get()->getLocStart()))
10274           getCurFunction()->markSafeWeakUse(RHS.get());
10275 
10276       } else if (getLangOpts().ObjCAutoRefCount) {
10277         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10278       }
10279     }
10280   } else {
10281     // Compound assignment "x += y"
10282     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10283   }
10284 
10285   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10286                                RHS.get(), AA_Assigning))
10287     return QualType();
10288 
10289   CheckForNullPointerDereference(*this, LHSExpr);
10290 
10291   // C99 6.5.16p3: The type of an assignment expression is the type of the
10292   // left operand unless the left operand has qualified type, in which case
10293   // it is the unqualified version of the type of the left operand.
10294   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10295   // is converted to the type of the assignment expression (above).
10296   // C++ 5.17p1: the type of the assignment expression is that of its left
10297   // operand.
10298   return (getLangOpts().CPlusPlus
10299           ? LHSType : LHSType.getUnqualifiedType());
10300 }
10301 
10302 // Only ignore explicit casts to void.
10303 static bool IgnoreCommaOperand(const Expr *E) {
10304   E = E->IgnoreParens();
10305 
10306   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10307     if (CE->getCastKind() == CK_ToVoid) {
10308       return true;
10309     }
10310   }
10311 
10312   return false;
10313 }
10314 
10315 // Look for instances where it is likely the comma operator is confused with
10316 // another operator.  There is a whitelist of acceptable expressions for the
10317 // left hand side of the comma operator, otherwise emit a warning.
10318 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10319   // No warnings in macros
10320   if (Loc.isMacroID())
10321     return;
10322 
10323   // Don't warn in template instantiations.
10324   if (!ActiveTemplateInstantiations.empty())
10325     return;
10326 
10327   // Scope isn't fine-grained enough to whitelist the specific cases, so
10328   // instead, skip more than needed, then call back into here with the
10329   // CommaVisitor in SemaStmt.cpp.
10330   // The whitelisted locations are the initialization and increment portions
10331   // of a for loop.  The additional checks are on the condition of
10332   // if statements, do/while loops, and for loops.
10333   const unsigned ForIncrementFlags =
10334       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10335   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10336   const unsigned ScopeFlags = getCurScope()->getFlags();
10337   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10338       (ScopeFlags & ForInitFlags) == ForInitFlags)
10339     return;
10340 
10341   // If there are multiple comma operators used together, get the RHS of the
10342   // of the comma operator as the LHS.
10343   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10344     if (BO->getOpcode() != BO_Comma)
10345       break;
10346     LHS = BO->getRHS();
10347   }
10348 
10349   // Only allow some expressions on LHS to not warn.
10350   if (IgnoreCommaOperand(LHS))
10351     return;
10352 
10353   Diag(Loc, diag::warn_comma_operator);
10354   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10355       << LHS->getSourceRange()
10356       << FixItHint::CreateInsertion(LHS->getLocStart(),
10357                                     LangOpts.CPlusPlus ? "static_cast<void>("
10358                                                        : "(void)(")
10359       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10360                                     ")");
10361 }
10362 
10363 // C99 6.5.17
10364 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10365                                    SourceLocation Loc) {
10366   LHS = S.CheckPlaceholderExpr(LHS.get());
10367   RHS = S.CheckPlaceholderExpr(RHS.get());
10368   if (LHS.isInvalid() || RHS.isInvalid())
10369     return QualType();
10370 
10371   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10372   // operands, but not unary promotions.
10373   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10374 
10375   // So we treat the LHS as a ignored value, and in C++ we allow the
10376   // containing site to determine what should be done with the RHS.
10377   LHS = S.IgnoredValueConversions(LHS.get());
10378   if (LHS.isInvalid())
10379     return QualType();
10380 
10381   S.DiagnoseUnusedExprResult(LHS.get());
10382 
10383   if (!S.getLangOpts().CPlusPlus) {
10384     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10385     if (RHS.isInvalid())
10386       return QualType();
10387     if (!RHS.get()->getType()->isVoidType())
10388       S.RequireCompleteType(Loc, RHS.get()->getType(),
10389                             diag::err_incomplete_type);
10390   }
10391 
10392   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10393     S.DiagnoseCommaOperator(LHS.get(), Loc);
10394 
10395   return RHS.get()->getType();
10396 }
10397 
10398 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10399 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10400 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10401                                                ExprValueKind &VK,
10402                                                ExprObjectKind &OK,
10403                                                SourceLocation OpLoc,
10404                                                bool IsInc, bool IsPrefix) {
10405   if (Op->isTypeDependent())
10406     return S.Context.DependentTy;
10407 
10408   QualType ResType = Op->getType();
10409   // Atomic types can be used for increment / decrement where the non-atomic
10410   // versions can, so ignore the _Atomic() specifier for the purpose of
10411   // checking.
10412   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10413     ResType = ResAtomicType->getValueType();
10414 
10415   assert(!ResType.isNull() && "no type for increment/decrement expression");
10416 
10417   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10418     // Decrement of bool is not allowed.
10419     if (!IsInc) {
10420       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10421       return QualType();
10422     }
10423     // Increment of bool sets it to true, but is deprecated.
10424     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10425                                               : diag::warn_increment_bool)
10426       << Op->getSourceRange();
10427   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10428     // Error on enum increments and decrements in C++ mode
10429     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10430     return QualType();
10431   } else if (ResType->isRealType()) {
10432     // OK!
10433   } else if (ResType->isPointerType()) {
10434     // C99 6.5.2.4p2, 6.5.6p2
10435     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10436       return QualType();
10437   } else if (ResType->isObjCObjectPointerType()) {
10438     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10439     // Otherwise, we just need a complete type.
10440     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10441         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10442       return QualType();
10443   } else if (ResType->isAnyComplexType()) {
10444     // C99 does not support ++/-- on complex types, we allow as an extension.
10445     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10446       << ResType << Op->getSourceRange();
10447   } else if (ResType->isPlaceholderType()) {
10448     ExprResult PR = S.CheckPlaceholderExpr(Op);
10449     if (PR.isInvalid()) return QualType();
10450     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10451                                           IsInc, IsPrefix);
10452   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10453     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10454   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10455              (ResType->getAs<VectorType>()->getVectorKind() !=
10456               VectorType::AltiVecBool)) {
10457     // The z vector extensions allow ++ and -- for non-bool vectors.
10458   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10459             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10460     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10461   } else {
10462     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10463       << ResType << int(IsInc) << Op->getSourceRange();
10464     return QualType();
10465   }
10466   // At this point, we know we have a real, complex or pointer type.
10467   // Now make sure the operand is a modifiable lvalue.
10468   if (CheckForModifiableLvalue(Op, OpLoc, S))
10469     return QualType();
10470   // In C++, a prefix increment is the same type as the operand. Otherwise
10471   // (in C or with postfix), the increment is the unqualified type of the
10472   // operand.
10473   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10474     VK = VK_LValue;
10475     OK = Op->getObjectKind();
10476     return ResType;
10477   } else {
10478     VK = VK_RValue;
10479     return ResType.getUnqualifiedType();
10480   }
10481 }
10482 
10483 
10484 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10485 /// This routine allows us to typecheck complex/recursive expressions
10486 /// where the declaration is needed for type checking. We only need to
10487 /// handle cases when the expression references a function designator
10488 /// or is an lvalue. Here are some examples:
10489 ///  - &(x) => x
10490 ///  - &*****f => f for f a function designator.
10491 ///  - &s.xx => s
10492 ///  - &s.zz[1].yy -> s, if zz is an array
10493 ///  - *(x + 1) -> x, if x is an array
10494 ///  - &"123"[2] -> 0
10495 ///  - & __real__ x -> x
10496 static ValueDecl *getPrimaryDecl(Expr *E) {
10497   switch (E->getStmtClass()) {
10498   case Stmt::DeclRefExprClass:
10499     return cast<DeclRefExpr>(E)->getDecl();
10500   case Stmt::MemberExprClass:
10501     // If this is an arrow operator, the address is an offset from
10502     // the base's value, so the object the base refers to is
10503     // irrelevant.
10504     if (cast<MemberExpr>(E)->isArrow())
10505       return nullptr;
10506     // Otherwise, the expression refers to a part of the base
10507     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10508   case Stmt::ArraySubscriptExprClass: {
10509     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10510     // promotion of register arrays earlier.
10511     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10512     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10513       if (ICE->getSubExpr()->getType()->isArrayType())
10514         return getPrimaryDecl(ICE->getSubExpr());
10515     }
10516     return nullptr;
10517   }
10518   case Stmt::UnaryOperatorClass: {
10519     UnaryOperator *UO = cast<UnaryOperator>(E);
10520 
10521     switch(UO->getOpcode()) {
10522     case UO_Real:
10523     case UO_Imag:
10524     case UO_Extension:
10525       return getPrimaryDecl(UO->getSubExpr());
10526     default:
10527       return nullptr;
10528     }
10529   }
10530   case Stmt::ParenExprClass:
10531     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10532   case Stmt::ImplicitCastExprClass:
10533     // If the result of an implicit cast is an l-value, we care about
10534     // the sub-expression; otherwise, the result here doesn't matter.
10535     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10536   default:
10537     return nullptr;
10538   }
10539 }
10540 
10541 namespace {
10542   enum {
10543     AO_Bit_Field = 0,
10544     AO_Vector_Element = 1,
10545     AO_Property_Expansion = 2,
10546     AO_Register_Variable = 3,
10547     AO_No_Error = 4
10548   };
10549 }
10550 /// \brief Diagnose invalid operand for address of operations.
10551 ///
10552 /// \param Type The type of operand which cannot have its address taken.
10553 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10554                                          Expr *E, unsigned Type) {
10555   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10556 }
10557 
10558 /// CheckAddressOfOperand - The operand of & must be either a function
10559 /// designator or an lvalue designating an object. If it is an lvalue, the
10560 /// object cannot be declared with storage class register or be a bit field.
10561 /// Note: The usual conversions are *not* applied to the operand of the &
10562 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10563 /// In C++, the operand might be an overloaded function name, in which case
10564 /// we allow the '&' but retain the overloaded-function type.
10565 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10566   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10567     if (PTy->getKind() == BuiltinType::Overload) {
10568       Expr *E = OrigOp.get()->IgnoreParens();
10569       if (!isa<OverloadExpr>(E)) {
10570         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10571         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10572           << OrigOp.get()->getSourceRange();
10573         return QualType();
10574       }
10575 
10576       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10577       if (isa<UnresolvedMemberExpr>(Ovl))
10578         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10579           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10580             << OrigOp.get()->getSourceRange();
10581           return QualType();
10582         }
10583 
10584       return Context.OverloadTy;
10585     }
10586 
10587     if (PTy->getKind() == BuiltinType::UnknownAny)
10588       return Context.UnknownAnyTy;
10589 
10590     if (PTy->getKind() == BuiltinType::BoundMember) {
10591       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10592         << OrigOp.get()->getSourceRange();
10593       return QualType();
10594     }
10595 
10596     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10597     if (OrigOp.isInvalid()) return QualType();
10598   }
10599 
10600   if (OrigOp.get()->isTypeDependent())
10601     return Context.DependentTy;
10602 
10603   assert(!OrigOp.get()->getType()->isPlaceholderType());
10604 
10605   // Make sure to ignore parentheses in subsequent checks
10606   Expr *op = OrigOp.get()->IgnoreParens();
10607 
10608   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10609   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10610     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10611     return QualType();
10612   }
10613 
10614   if (getLangOpts().C99) {
10615     // Implement C99-only parts of addressof rules.
10616     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10617       if (uOp->getOpcode() == UO_Deref)
10618         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10619         // (assuming the deref expression is valid).
10620         return uOp->getSubExpr()->getType();
10621     }
10622     // Technically, there should be a check for array subscript
10623     // expressions here, but the result of one is always an lvalue anyway.
10624   }
10625   ValueDecl *dcl = getPrimaryDecl(op);
10626 
10627   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10628     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10629                                            op->getLocStart()))
10630       return QualType();
10631 
10632   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10633   unsigned AddressOfError = AO_No_Error;
10634 
10635   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10636     bool sfinae = (bool)isSFINAEContext();
10637     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10638                                   : diag::ext_typecheck_addrof_temporary)
10639       << op->getType() << op->getSourceRange();
10640     if (sfinae)
10641       return QualType();
10642     // Materialize the temporary as an lvalue so that we can take its address.
10643     OrigOp = op =
10644         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10645   } else if (isa<ObjCSelectorExpr>(op)) {
10646     return Context.getPointerType(op->getType());
10647   } else if (lval == Expr::LV_MemberFunction) {
10648     // If it's an instance method, make a member pointer.
10649     // The expression must have exactly the form &A::foo.
10650 
10651     // If the underlying expression isn't a decl ref, give up.
10652     if (!isa<DeclRefExpr>(op)) {
10653       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10654         << OrigOp.get()->getSourceRange();
10655       return QualType();
10656     }
10657     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10658     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10659 
10660     // The id-expression was parenthesized.
10661     if (OrigOp.get() != DRE) {
10662       Diag(OpLoc, diag::err_parens_pointer_member_function)
10663         << OrigOp.get()->getSourceRange();
10664 
10665     // The method was named without a qualifier.
10666     } else if (!DRE->getQualifier()) {
10667       if (MD->getParent()->getName().empty())
10668         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10669           << op->getSourceRange();
10670       else {
10671         SmallString<32> Str;
10672         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10673         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10674           << op->getSourceRange()
10675           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10676       }
10677     }
10678 
10679     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10680     if (isa<CXXDestructorDecl>(MD))
10681       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10682 
10683     QualType MPTy = Context.getMemberPointerType(
10684         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10685     // Under the MS ABI, lock down the inheritance model now.
10686     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10687       (void)isCompleteType(OpLoc, MPTy);
10688     return MPTy;
10689   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10690     // C99 6.5.3.2p1
10691     // The operand must be either an l-value or a function designator
10692     if (!op->getType()->isFunctionType()) {
10693       // Use a special diagnostic for loads from property references.
10694       if (isa<PseudoObjectExpr>(op)) {
10695         AddressOfError = AO_Property_Expansion;
10696       } else {
10697         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10698           << op->getType() << op->getSourceRange();
10699         return QualType();
10700       }
10701     }
10702   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10703     // The operand cannot be a bit-field
10704     AddressOfError = AO_Bit_Field;
10705   } else if (op->getObjectKind() == OK_VectorComponent) {
10706     // The operand cannot be an element of a vector
10707     AddressOfError = AO_Vector_Element;
10708   } else if (dcl) { // C99 6.5.3.2p1
10709     // We have an lvalue with a decl. Make sure the decl is not declared
10710     // with the register storage-class specifier.
10711     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10712       // in C++ it is not error to take address of a register
10713       // variable (c++03 7.1.1P3)
10714       if (vd->getStorageClass() == SC_Register &&
10715           !getLangOpts().CPlusPlus) {
10716         AddressOfError = AO_Register_Variable;
10717       }
10718     } else if (isa<MSPropertyDecl>(dcl)) {
10719       AddressOfError = AO_Property_Expansion;
10720     } else if (isa<FunctionTemplateDecl>(dcl)) {
10721       return Context.OverloadTy;
10722     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10723       // Okay: we can take the address of a field.
10724       // Could be a pointer to member, though, if there is an explicit
10725       // scope qualifier for the class.
10726       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10727         DeclContext *Ctx = dcl->getDeclContext();
10728         if (Ctx && Ctx->isRecord()) {
10729           if (dcl->getType()->isReferenceType()) {
10730             Diag(OpLoc,
10731                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10732               << dcl->getDeclName() << dcl->getType();
10733             return QualType();
10734           }
10735 
10736           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10737             Ctx = Ctx->getParent();
10738 
10739           QualType MPTy = Context.getMemberPointerType(
10740               op->getType(),
10741               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10742           // Under the MS ABI, lock down the inheritance model now.
10743           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10744             (void)isCompleteType(OpLoc, MPTy);
10745           return MPTy;
10746         }
10747       }
10748     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10749                !isa<BindingDecl>(dcl))
10750       llvm_unreachable("Unknown/unexpected decl type");
10751   }
10752 
10753   if (AddressOfError != AO_No_Error) {
10754     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10755     return QualType();
10756   }
10757 
10758   if (lval == Expr::LV_IncompleteVoidType) {
10759     // Taking the address of a void variable is technically illegal, but we
10760     // allow it in cases which are otherwise valid.
10761     // Example: "extern void x; void* y = &x;".
10762     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10763   }
10764 
10765   // If the operand has type "type", the result has type "pointer to type".
10766   if (op->getType()->isObjCObjectType())
10767     return Context.getObjCObjectPointerType(op->getType());
10768 
10769   CheckAddressOfPackedMember(op);
10770 
10771   return Context.getPointerType(op->getType());
10772 }
10773 
10774 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10775   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10776   if (!DRE)
10777     return;
10778   const Decl *D = DRE->getDecl();
10779   if (!D)
10780     return;
10781   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10782   if (!Param)
10783     return;
10784   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10785     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10786       return;
10787   if (FunctionScopeInfo *FD = S.getCurFunction())
10788     if (!FD->ModifiedNonNullParams.count(Param))
10789       FD->ModifiedNonNullParams.insert(Param);
10790 }
10791 
10792 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10793 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10794                                         SourceLocation OpLoc) {
10795   if (Op->isTypeDependent())
10796     return S.Context.DependentTy;
10797 
10798   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10799   if (ConvResult.isInvalid())
10800     return QualType();
10801   Op = ConvResult.get();
10802   QualType OpTy = Op->getType();
10803   QualType Result;
10804 
10805   if (isa<CXXReinterpretCastExpr>(Op)) {
10806     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10807     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10808                                      Op->getSourceRange());
10809   }
10810 
10811   if (const PointerType *PT = OpTy->getAs<PointerType>())
10812   {
10813     Result = PT->getPointeeType();
10814   }
10815   else if (const ObjCObjectPointerType *OPT =
10816              OpTy->getAs<ObjCObjectPointerType>())
10817     Result = OPT->getPointeeType();
10818   else {
10819     ExprResult PR = S.CheckPlaceholderExpr(Op);
10820     if (PR.isInvalid()) return QualType();
10821     if (PR.get() != Op)
10822       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10823   }
10824 
10825   if (Result.isNull()) {
10826     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10827       << OpTy << Op->getSourceRange();
10828     return QualType();
10829   }
10830 
10831   // Note that per both C89 and C99, indirection is always legal, even if Result
10832   // is an incomplete type or void.  It would be possible to warn about
10833   // dereferencing a void pointer, but it's completely well-defined, and such a
10834   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10835   // for pointers to 'void' but is fine for any other pointer type:
10836   //
10837   // C++ [expr.unary.op]p1:
10838   //   [...] the expression to which [the unary * operator] is applied shall
10839   //   be a pointer to an object type, or a pointer to a function type
10840   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10841     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10842       << OpTy << Op->getSourceRange();
10843 
10844   // Dereferences are usually l-values...
10845   VK = VK_LValue;
10846 
10847   // ...except that certain expressions are never l-values in C.
10848   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10849     VK = VK_RValue;
10850 
10851   return Result;
10852 }
10853 
10854 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10855   BinaryOperatorKind Opc;
10856   switch (Kind) {
10857   default: llvm_unreachable("Unknown binop!");
10858   case tok::periodstar:           Opc = BO_PtrMemD; break;
10859   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10860   case tok::star:                 Opc = BO_Mul; break;
10861   case tok::slash:                Opc = BO_Div; break;
10862   case tok::percent:              Opc = BO_Rem; break;
10863   case tok::plus:                 Opc = BO_Add; break;
10864   case tok::minus:                Opc = BO_Sub; break;
10865   case tok::lessless:             Opc = BO_Shl; break;
10866   case tok::greatergreater:       Opc = BO_Shr; break;
10867   case tok::lessequal:            Opc = BO_LE; break;
10868   case tok::less:                 Opc = BO_LT; break;
10869   case tok::greaterequal:         Opc = BO_GE; break;
10870   case tok::greater:              Opc = BO_GT; break;
10871   case tok::exclaimequal:         Opc = BO_NE; break;
10872   case tok::equalequal:           Opc = BO_EQ; break;
10873   case tok::amp:                  Opc = BO_And; break;
10874   case tok::caret:                Opc = BO_Xor; break;
10875   case tok::pipe:                 Opc = BO_Or; break;
10876   case tok::ampamp:               Opc = BO_LAnd; break;
10877   case tok::pipepipe:             Opc = BO_LOr; break;
10878   case tok::equal:                Opc = BO_Assign; break;
10879   case tok::starequal:            Opc = BO_MulAssign; break;
10880   case tok::slashequal:           Opc = BO_DivAssign; break;
10881   case tok::percentequal:         Opc = BO_RemAssign; break;
10882   case tok::plusequal:            Opc = BO_AddAssign; break;
10883   case tok::minusequal:           Opc = BO_SubAssign; break;
10884   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10885   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10886   case tok::ampequal:             Opc = BO_AndAssign; break;
10887   case tok::caretequal:           Opc = BO_XorAssign; break;
10888   case tok::pipeequal:            Opc = BO_OrAssign; break;
10889   case tok::comma:                Opc = BO_Comma; break;
10890   }
10891   return Opc;
10892 }
10893 
10894 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10895   tok::TokenKind Kind) {
10896   UnaryOperatorKind Opc;
10897   switch (Kind) {
10898   default: llvm_unreachable("Unknown unary op!");
10899   case tok::plusplus:     Opc = UO_PreInc; break;
10900   case tok::minusminus:   Opc = UO_PreDec; break;
10901   case tok::amp:          Opc = UO_AddrOf; break;
10902   case tok::star:         Opc = UO_Deref; break;
10903   case tok::plus:         Opc = UO_Plus; break;
10904   case tok::minus:        Opc = UO_Minus; break;
10905   case tok::tilde:        Opc = UO_Not; break;
10906   case tok::exclaim:      Opc = UO_LNot; break;
10907   case tok::kw___real:    Opc = UO_Real; break;
10908   case tok::kw___imag:    Opc = UO_Imag; break;
10909   case tok::kw___extension__: Opc = UO_Extension; break;
10910   }
10911   return Opc;
10912 }
10913 
10914 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10915 /// This warning is only emitted for builtin assignment operations. It is also
10916 /// suppressed in the event of macro expansions.
10917 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10918                                    SourceLocation OpLoc) {
10919   if (!S.ActiveTemplateInstantiations.empty())
10920     return;
10921   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10922     return;
10923   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10924   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10925   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10926   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10927   if (!LHSDeclRef || !RHSDeclRef ||
10928       LHSDeclRef->getLocation().isMacroID() ||
10929       RHSDeclRef->getLocation().isMacroID())
10930     return;
10931   const ValueDecl *LHSDecl =
10932     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10933   const ValueDecl *RHSDecl =
10934     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10935   if (LHSDecl != RHSDecl)
10936     return;
10937   if (LHSDecl->getType().isVolatileQualified())
10938     return;
10939   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10940     if (RefTy->getPointeeType().isVolatileQualified())
10941       return;
10942 
10943   S.Diag(OpLoc, diag::warn_self_assignment)
10944       << LHSDeclRef->getType()
10945       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10946 }
10947 
10948 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10949 /// is usually indicative of introspection within the Objective-C pointer.
10950 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10951                                           SourceLocation OpLoc) {
10952   if (!S.getLangOpts().ObjC1)
10953     return;
10954 
10955   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10956   const Expr *LHS = L.get();
10957   const Expr *RHS = R.get();
10958 
10959   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10960     ObjCPointerExpr = LHS;
10961     OtherExpr = RHS;
10962   }
10963   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10964     ObjCPointerExpr = RHS;
10965     OtherExpr = LHS;
10966   }
10967 
10968   // This warning is deliberately made very specific to reduce false
10969   // positives with logic that uses '&' for hashing.  This logic mainly
10970   // looks for code trying to introspect into tagged pointers, which
10971   // code should generally never do.
10972   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10973     unsigned Diag = diag::warn_objc_pointer_masking;
10974     // Determine if we are introspecting the result of performSelectorXXX.
10975     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10976     // Special case messages to -performSelector and friends, which
10977     // can return non-pointer values boxed in a pointer value.
10978     // Some clients may wish to silence warnings in this subcase.
10979     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10980       Selector S = ME->getSelector();
10981       StringRef SelArg0 = S.getNameForSlot(0);
10982       if (SelArg0.startswith("performSelector"))
10983         Diag = diag::warn_objc_pointer_masking_performSelector;
10984     }
10985 
10986     S.Diag(OpLoc, Diag)
10987       << ObjCPointerExpr->getSourceRange();
10988   }
10989 }
10990 
10991 static NamedDecl *getDeclFromExpr(Expr *E) {
10992   if (!E)
10993     return nullptr;
10994   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10995     return DRE->getDecl();
10996   if (auto *ME = dyn_cast<MemberExpr>(E))
10997     return ME->getMemberDecl();
10998   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10999     return IRE->getDecl();
11000   return nullptr;
11001 }
11002 
11003 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11004 /// operator @p Opc at location @c TokLoc. This routine only supports
11005 /// built-in operations; ActOnBinOp handles overloaded operators.
11006 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11007                                     BinaryOperatorKind Opc,
11008                                     Expr *LHSExpr, Expr *RHSExpr) {
11009   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11010     // The syntax only allows initializer lists on the RHS of assignment,
11011     // so we don't need to worry about accepting invalid code for
11012     // non-assignment operators.
11013     // C++11 5.17p9:
11014     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11015     //   of x = {} is x = T().
11016     InitializationKind Kind =
11017         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11018     InitializedEntity Entity =
11019         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11020     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11021     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11022     if (Init.isInvalid())
11023       return Init;
11024     RHSExpr = Init.get();
11025   }
11026 
11027   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11028   QualType ResultTy;     // Result type of the binary operator.
11029   // The following two variables are used for compound assignment operators
11030   QualType CompLHSTy;    // Type of LHS after promotions for computation
11031   QualType CompResultTy; // Type of computation result
11032   ExprValueKind VK = VK_RValue;
11033   ExprObjectKind OK = OK_Ordinary;
11034 
11035   if (!getLangOpts().CPlusPlus) {
11036     // C cannot handle TypoExpr nodes on either side of a binop because it
11037     // doesn't handle dependent types properly, so make sure any TypoExprs have
11038     // been dealt with before checking the operands.
11039     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11040     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11041       if (Opc != BO_Assign)
11042         return ExprResult(E);
11043       // Avoid correcting the RHS to the same Expr as the LHS.
11044       Decl *D = getDeclFromExpr(E);
11045       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11046     });
11047     if (!LHS.isUsable() || !RHS.isUsable())
11048       return ExprError();
11049   }
11050 
11051   if (getLangOpts().OpenCL) {
11052     QualType LHSTy = LHSExpr->getType();
11053     QualType RHSTy = RHSExpr->getType();
11054     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11055     // the ATOMIC_VAR_INIT macro.
11056     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11057       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11058       if (BO_Assign == Opc)
11059         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11060       else
11061         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11062       return ExprError();
11063     }
11064 
11065     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11066     // only with a builtin functions and therefore should be disallowed here.
11067     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11068         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11069         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11070         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11071       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11072       return ExprError();
11073     }
11074   }
11075 
11076   switch (Opc) {
11077   case BO_Assign:
11078     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11079     if (getLangOpts().CPlusPlus &&
11080         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11081       VK = LHS.get()->getValueKind();
11082       OK = LHS.get()->getObjectKind();
11083     }
11084     if (!ResultTy.isNull()) {
11085       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11086       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11087     }
11088     RecordModifiableNonNullParam(*this, LHS.get());
11089     break;
11090   case BO_PtrMemD:
11091   case BO_PtrMemI:
11092     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11093                                             Opc == BO_PtrMemI);
11094     break;
11095   case BO_Mul:
11096   case BO_Div:
11097     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11098                                            Opc == BO_Div);
11099     break;
11100   case BO_Rem:
11101     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11102     break;
11103   case BO_Add:
11104     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11105     break;
11106   case BO_Sub:
11107     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11108     break;
11109   case BO_Shl:
11110   case BO_Shr:
11111     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11112     break;
11113   case BO_LE:
11114   case BO_LT:
11115   case BO_GE:
11116   case BO_GT:
11117     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11118     break;
11119   case BO_EQ:
11120   case BO_NE:
11121     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11122     break;
11123   case BO_And:
11124     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11125   case BO_Xor:
11126   case BO_Or:
11127     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11128     break;
11129   case BO_LAnd:
11130   case BO_LOr:
11131     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11132     break;
11133   case BO_MulAssign:
11134   case BO_DivAssign:
11135     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11136                                                Opc == BO_DivAssign);
11137     CompLHSTy = CompResultTy;
11138     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11139       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11140     break;
11141   case BO_RemAssign:
11142     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11143     CompLHSTy = CompResultTy;
11144     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11145       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11146     break;
11147   case BO_AddAssign:
11148     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11149     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11150       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11151     break;
11152   case BO_SubAssign:
11153     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11154     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11155       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11156     break;
11157   case BO_ShlAssign:
11158   case BO_ShrAssign:
11159     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11160     CompLHSTy = CompResultTy;
11161     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11162       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11163     break;
11164   case BO_AndAssign:
11165   case BO_OrAssign: // fallthrough
11166     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11167   case BO_XorAssign:
11168     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11169     CompLHSTy = CompResultTy;
11170     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11171       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11172     break;
11173   case BO_Comma:
11174     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11175     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11176       VK = RHS.get()->getValueKind();
11177       OK = RHS.get()->getObjectKind();
11178     }
11179     break;
11180   }
11181   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11182     return ExprError();
11183 
11184   // Check for array bounds violations for both sides of the BinaryOperator
11185   CheckArrayAccess(LHS.get());
11186   CheckArrayAccess(RHS.get());
11187 
11188   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11189     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11190                                                  &Context.Idents.get("object_setClass"),
11191                                                  SourceLocation(), LookupOrdinaryName);
11192     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11193       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11194       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11195       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11196       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11197       FixItHint::CreateInsertion(RHSLocEnd, ")");
11198     }
11199     else
11200       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11201   }
11202   else if (const ObjCIvarRefExpr *OIRE =
11203            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11204     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11205 
11206   if (CompResultTy.isNull())
11207     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11208                                         OK, OpLoc, FPFeatures.fp_contract);
11209   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11210       OK_ObjCProperty) {
11211     VK = VK_LValue;
11212     OK = LHS.get()->getObjectKind();
11213   }
11214   return new (Context) CompoundAssignOperator(
11215       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11216       OpLoc, FPFeatures.fp_contract);
11217 }
11218 
11219 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11220 /// operators are mixed in a way that suggests that the programmer forgot that
11221 /// comparison operators have higher precedence. The most typical example of
11222 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11223 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11224                                       SourceLocation OpLoc, Expr *LHSExpr,
11225                                       Expr *RHSExpr) {
11226   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11227   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11228 
11229   // Check that one of the sides is a comparison operator and the other isn't.
11230   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11231   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11232   if (isLeftComp == isRightComp)
11233     return;
11234 
11235   // Bitwise operations are sometimes used as eager logical ops.
11236   // Don't diagnose this.
11237   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11238   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11239   if (isLeftBitwise || isRightBitwise)
11240     return;
11241 
11242   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11243                                                    OpLoc)
11244                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11245   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11246   SourceRange ParensRange = isLeftComp ?
11247       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11248     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11249 
11250   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11251     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11252   SuggestParentheses(Self, OpLoc,
11253     Self.PDiag(diag::note_precedence_silence) << OpStr,
11254     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11255   SuggestParentheses(Self, OpLoc,
11256     Self.PDiag(diag::note_precedence_bitwise_first)
11257       << BinaryOperator::getOpcodeStr(Opc),
11258     ParensRange);
11259 }
11260 
11261 /// \brief It accepts a '&&' expr that is inside a '||' one.
11262 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11263 /// in parentheses.
11264 static void
11265 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11266                                        BinaryOperator *Bop) {
11267   assert(Bop->getOpcode() == BO_LAnd);
11268   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11269       << Bop->getSourceRange() << OpLoc;
11270   SuggestParentheses(Self, Bop->getOperatorLoc(),
11271     Self.PDiag(diag::note_precedence_silence)
11272       << Bop->getOpcodeStr(),
11273     Bop->getSourceRange());
11274 }
11275 
11276 /// \brief Returns true if the given expression can be evaluated as a constant
11277 /// 'true'.
11278 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11279   bool Res;
11280   return !E->isValueDependent() &&
11281          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11282 }
11283 
11284 /// \brief Returns true if the given expression can be evaluated as a constant
11285 /// 'false'.
11286 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11287   bool Res;
11288   return !E->isValueDependent() &&
11289          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11290 }
11291 
11292 /// \brief Look for '&&' in the left hand of a '||' expr.
11293 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11294                                              Expr *LHSExpr, Expr *RHSExpr) {
11295   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11296     if (Bop->getOpcode() == BO_LAnd) {
11297       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11298       if (EvaluatesAsFalse(S, RHSExpr))
11299         return;
11300       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11301       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11302         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11303     } else if (Bop->getOpcode() == BO_LOr) {
11304       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11305         // If it's "a || b && 1 || c" we didn't warn earlier for
11306         // "a || b && 1", but warn now.
11307         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11308           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11309       }
11310     }
11311   }
11312 }
11313 
11314 /// \brief Look for '&&' in the right hand of a '||' expr.
11315 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11316                                              Expr *LHSExpr, Expr *RHSExpr) {
11317   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11318     if (Bop->getOpcode() == BO_LAnd) {
11319       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11320       if (EvaluatesAsFalse(S, LHSExpr))
11321         return;
11322       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11323       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11324         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11325     }
11326   }
11327 }
11328 
11329 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11330 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11331 /// the '&' expression in parentheses.
11332 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11333                                          SourceLocation OpLoc, Expr *SubExpr) {
11334   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11335     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11336       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11337         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11338         << Bop->getSourceRange() << OpLoc;
11339       SuggestParentheses(S, Bop->getOperatorLoc(),
11340         S.PDiag(diag::note_precedence_silence)
11341           << Bop->getOpcodeStr(),
11342         Bop->getSourceRange());
11343     }
11344   }
11345 }
11346 
11347 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11348                                     Expr *SubExpr, StringRef Shift) {
11349   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11350     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11351       StringRef Op = Bop->getOpcodeStr();
11352       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11353           << Bop->getSourceRange() << OpLoc << Shift << Op;
11354       SuggestParentheses(S, Bop->getOperatorLoc(),
11355           S.PDiag(diag::note_precedence_silence) << Op,
11356           Bop->getSourceRange());
11357     }
11358   }
11359 }
11360 
11361 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11362                                  Expr *LHSExpr, Expr *RHSExpr) {
11363   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11364   if (!OCE)
11365     return;
11366 
11367   FunctionDecl *FD = OCE->getDirectCallee();
11368   if (!FD || !FD->isOverloadedOperator())
11369     return;
11370 
11371   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11372   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11373     return;
11374 
11375   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11376       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11377       << (Kind == OO_LessLess);
11378   SuggestParentheses(S, OCE->getOperatorLoc(),
11379                      S.PDiag(diag::note_precedence_silence)
11380                          << (Kind == OO_LessLess ? "<<" : ">>"),
11381                      OCE->getSourceRange());
11382   SuggestParentheses(S, OpLoc,
11383                      S.PDiag(diag::note_evaluate_comparison_first),
11384                      SourceRange(OCE->getArg(1)->getLocStart(),
11385                                  RHSExpr->getLocEnd()));
11386 }
11387 
11388 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11389 /// precedence.
11390 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11391                                     SourceLocation OpLoc, Expr *LHSExpr,
11392                                     Expr *RHSExpr){
11393   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11394   if (BinaryOperator::isBitwiseOp(Opc))
11395     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11396 
11397   // Diagnose "arg1 & arg2 | arg3"
11398   if ((Opc == BO_Or || Opc == BO_Xor) &&
11399       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11400     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11401     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11402   }
11403 
11404   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11405   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11406   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11407     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11408     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11409   }
11410 
11411   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11412       || Opc == BO_Shr) {
11413     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11414     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11415     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11416   }
11417 
11418   // Warn on overloaded shift operators and comparisons, such as:
11419   // cout << 5 == 4;
11420   if (BinaryOperator::isComparisonOp(Opc))
11421     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11422 }
11423 
11424 // Binary Operators.  'Tok' is the token for the operator.
11425 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11426                             tok::TokenKind Kind,
11427                             Expr *LHSExpr, Expr *RHSExpr) {
11428   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11429   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11430   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11431 
11432   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11433   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11434 
11435   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11436 }
11437 
11438 /// Build an overloaded binary operator expression in the given scope.
11439 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11440                                        BinaryOperatorKind Opc,
11441                                        Expr *LHS, Expr *RHS) {
11442   // Find all of the overloaded operators visible from this
11443   // point. We perform both an operator-name lookup from the local
11444   // scope and an argument-dependent lookup based on the types of
11445   // the arguments.
11446   UnresolvedSet<16> Functions;
11447   OverloadedOperatorKind OverOp
11448     = BinaryOperator::getOverloadedOperator(Opc);
11449   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11450     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11451                                    RHS->getType(), Functions);
11452 
11453   // Build the (potentially-overloaded, potentially-dependent)
11454   // binary operation.
11455   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11456 }
11457 
11458 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11459                             BinaryOperatorKind Opc,
11460                             Expr *LHSExpr, Expr *RHSExpr) {
11461   // We want to end up calling one of checkPseudoObjectAssignment
11462   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11463   // both expressions are overloadable or either is type-dependent),
11464   // or CreateBuiltinBinOp (in any other case).  We also want to get
11465   // any placeholder types out of the way.
11466 
11467   // Handle pseudo-objects in the LHS.
11468   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11469     // Assignments with a pseudo-object l-value need special analysis.
11470     if (pty->getKind() == BuiltinType::PseudoObject &&
11471         BinaryOperator::isAssignmentOp(Opc))
11472       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11473 
11474     // Don't resolve overloads if the other type is overloadable.
11475     if (pty->getKind() == BuiltinType::Overload) {
11476       // We can't actually test that if we still have a placeholder,
11477       // though.  Fortunately, none of the exceptions we see in that
11478       // code below are valid when the LHS is an overload set.  Note
11479       // that an overload set can be dependently-typed, but it never
11480       // instantiates to having an overloadable type.
11481       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11482       if (resolvedRHS.isInvalid()) return ExprError();
11483       RHSExpr = resolvedRHS.get();
11484 
11485       if (RHSExpr->isTypeDependent() ||
11486           RHSExpr->getType()->isOverloadableType())
11487         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11488     }
11489 
11490     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11491     if (LHS.isInvalid()) return ExprError();
11492     LHSExpr = LHS.get();
11493   }
11494 
11495   // Handle pseudo-objects in the RHS.
11496   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11497     // An overload in the RHS can potentially be resolved by the type
11498     // being assigned to.
11499     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11500       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11501         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11502 
11503       if (LHSExpr->getType()->isOverloadableType())
11504         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11505 
11506       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11507     }
11508 
11509     // Don't resolve overloads if the other type is overloadable.
11510     if (pty->getKind() == BuiltinType::Overload &&
11511         LHSExpr->getType()->isOverloadableType())
11512       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11513 
11514     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11515     if (!resolvedRHS.isUsable()) return ExprError();
11516     RHSExpr = resolvedRHS.get();
11517   }
11518 
11519   if (getLangOpts().CPlusPlus) {
11520     // If either expression is type-dependent, always build an
11521     // overloaded op.
11522     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11523       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11524 
11525     // Otherwise, build an overloaded op if either expression has an
11526     // overloadable type.
11527     if (LHSExpr->getType()->isOverloadableType() ||
11528         RHSExpr->getType()->isOverloadableType())
11529       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11530   }
11531 
11532   // Build a built-in binary operation.
11533   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11534 }
11535 
11536 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11537                                       UnaryOperatorKind Opc,
11538                                       Expr *InputExpr) {
11539   ExprResult Input = InputExpr;
11540   ExprValueKind VK = VK_RValue;
11541   ExprObjectKind OK = OK_Ordinary;
11542   QualType resultType;
11543   if (getLangOpts().OpenCL) {
11544     QualType Ty = InputExpr->getType();
11545     // The only legal unary operation for atomics is '&'.
11546     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11547     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11548     // only with a builtin functions and therefore should be disallowed here.
11549         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11550         || Ty->isBlockPointerType())) {
11551       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11552                        << InputExpr->getType()
11553                        << Input.get()->getSourceRange());
11554     }
11555   }
11556   switch (Opc) {
11557   case UO_PreInc:
11558   case UO_PreDec:
11559   case UO_PostInc:
11560   case UO_PostDec:
11561     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11562                                                 OpLoc,
11563                                                 Opc == UO_PreInc ||
11564                                                 Opc == UO_PostInc,
11565                                                 Opc == UO_PreInc ||
11566                                                 Opc == UO_PreDec);
11567     break;
11568   case UO_AddrOf:
11569     resultType = CheckAddressOfOperand(Input, OpLoc);
11570     RecordModifiableNonNullParam(*this, InputExpr);
11571     break;
11572   case UO_Deref: {
11573     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11574     if (Input.isInvalid()) return ExprError();
11575     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11576     break;
11577   }
11578   case UO_Plus:
11579   case UO_Minus:
11580     Input = UsualUnaryConversions(Input.get());
11581     if (Input.isInvalid()) return ExprError();
11582     resultType = Input.get()->getType();
11583     if (resultType->isDependentType())
11584       break;
11585     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11586       break;
11587     else if (resultType->isVectorType() &&
11588              // The z vector extensions don't allow + or - with bool vectors.
11589              (!Context.getLangOpts().ZVector ||
11590               resultType->getAs<VectorType>()->getVectorKind() !=
11591               VectorType::AltiVecBool))
11592       break;
11593     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11594              Opc == UO_Plus &&
11595              resultType->isPointerType())
11596       break;
11597 
11598     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11599       << resultType << Input.get()->getSourceRange());
11600 
11601   case UO_Not: // bitwise complement
11602     Input = UsualUnaryConversions(Input.get());
11603     if (Input.isInvalid())
11604       return ExprError();
11605     resultType = Input.get()->getType();
11606     if (resultType->isDependentType())
11607       break;
11608     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11609     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11610       // C99 does not support '~' for complex conjugation.
11611       Diag(OpLoc, diag::ext_integer_complement_complex)
11612           << resultType << Input.get()->getSourceRange();
11613     else if (resultType->hasIntegerRepresentation())
11614       break;
11615     else if (resultType->isExtVectorType()) {
11616       if (Context.getLangOpts().OpenCL) {
11617         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11618         // on vector float types.
11619         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11620         if (!T->isIntegerType())
11621           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11622                            << resultType << Input.get()->getSourceRange());
11623       }
11624       break;
11625     } else {
11626       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11627                        << resultType << Input.get()->getSourceRange());
11628     }
11629     break;
11630 
11631   case UO_LNot: // logical negation
11632     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11633     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11634     if (Input.isInvalid()) return ExprError();
11635     resultType = Input.get()->getType();
11636 
11637     // Though we still have to promote half FP to float...
11638     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11639       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11640       resultType = Context.FloatTy;
11641     }
11642 
11643     if (resultType->isDependentType())
11644       break;
11645     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11646       // C99 6.5.3.3p1: ok, fallthrough;
11647       if (Context.getLangOpts().CPlusPlus) {
11648         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11649         // operand contextually converted to bool.
11650         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11651                                   ScalarTypeToBooleanCastKind(resultType));
11652       } else if (Context.getLangOpts().OpenCL &&
11653                  Context.getLangOpts().OpenCLVersion < 120) {
11654         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11655         // operate on scalar float types.
11656         if (!resultType->isIntegerType())
11657           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11658                            << resultType << Input.get()->getSourceRange());
11659       }
11660     } else if (resultType->isExtVectorType()) {
11661       if (Context.getLangOpts().OpenCL &&
11662           Context.getLangOpts().OpenCLVersion < 120) {
11663         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11664         // operate on vector float types.
11665         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11666         if (!T->isIntegerType())
11667           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11668                            << resultType << Input.get()->getSourceRange());
11669       }
11670       // Vector logical not returns the signed variant of the operand type.
11671       resultType = GetSignedVectorType(resultType);
11672       break;
11673     } else {
11674       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11675         << resultType << Input.get()->getSourceRange());
11676     }
11677 
11678     // LNot always has type int. C99 6.5.3.3p5.
11679     // In C++, it's bool. C++ 5.3.1p8
11680     resultType = Context.getLogicalOperationType();
11681     break;
11682   case UO_Real:
11683   case UO_Imag:
11684     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11685     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11686     // complex l-values to ordinary l-values and all other values to r-values.
11687     if (Input.isInvalid()) return ExprError();
11688     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11689       if (Input.get()->getValueKind() != VK_RValue &&
11690           Input.get()->getObjectKind() == OK_Ordinary)
11691         VK = Input.get()->getValueKind();
11692     } else if (!getLangOpts().CPlusPlus) {
11693       // In C, a volatile scalar is read by __imag. In C++, it is not.
11694       Input = DefaultLvalueConversion(Input.get());
11695     }
11696     break;
11697   case UO_Extension:
11698   case UO_Coawait:
11699     resultType = Input.get()->getType();
11700     VK = Input.get()->getValueKind();
11701     OK = Input.get()->getObjectKind();
11702     break;
11703   }
11704   if (resultType.isNull() || Input.isInvalid())
11705     return ExprError();
11706 
11707   // Check for array bounds violations in the operand of the UnaryOperator,
11708   // except for the '*' and '&' operators that have to be handled specially
11709   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11710   // that are explicitly defined as valid by the standard).
11711   if (Opc != UO_AddrOf && Opc != UO_Deref)
11712     CheckArrayAccess(Input.get());
11713 
11714   return new (Context)
11715       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11716 }
11717 
11718 /// \brief Determine whether the given expression is a qualified member
11719 /// access expression, of a form that could be turned into a pointer to member
11720 /// with the address-of operator.
11721 static bool isQualifiedMemberAccess(Expr *E) {
11722   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11723     if (!DRE->getQualifier())
11724       return false;
11725 
11726     ValueDecl *VD = DRE->getDecl();
11727     if (!VD->isCXXClassMember())
11728       return false;
11729 
11730     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11731       return true;
11732     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11733       return Method->isInstance();
11734 
11735     return false;
11736   }
11737 
11738   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11739     if (!ULE->getQualifier())
11740       return false;
11741 
11742     for (NamedDecl *D : ULE->decls()) {
11743       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11744         if (Method->isInstance())
11745           return true;
11746       } else {
11747         // Overload set does not contain methods.
11748         break;
11749       }
11750     }
11751 
11752     return false;
11753   }
11754 
11755   return false;
11756 }
11757 
11758 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11759                               UnaryOperatorKind Opc, Expr *Input) {
11760   // First things first: handle placeholders so that the
11761   // overloaded-operator check considers the right type.
11762   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11763     // Increment and decrement of pseudo-object references.
11764     if (pty->getKind() == BuiltinType::PseudoObject &&
11765         UnaryOperator::isIncrementDecrementOp(Opc))
11766       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11767 
11768     // extension is always a builtin operator.
11769     if (Opc == UO_Extension)
11770       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11771 
11772     // & gets special logic for several kinds of placeholder.
11773     // The builtin code knows what to do.
11774     if (Opc == UO_AddrOf &&
11775         (pty->getKind() == BuiltinType::Overload ||
11776          pty->getKind() == BuiltinType::UnknownAny ||
11777          pty->getKind() == BuiltinType::BoundMember))
11778       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11779 
11780     // Anything else needs to be handled now.
11781     ExprResult Result = CheckPlaceholderExpr(Input);
11782     if (Result.isInvalid()) return ExprError();
11783     Input = Result.get();
11784   }
11785 
11786   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11787       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11788       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11789     // Find all of the overloaded operators visible from this
11790     // point. We perform both an operator-name lookup from the local
11791     // scope and an argument-dependent lookup based on the types of
11792     // the arguments.
11793     UnresolvedSet<16> Functions;
11794     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11795     if (S && OverOp != OO_None)
11796       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11797                                    Functions);
11798 
11799     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11800   }
11801 
11802   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11803 }
11804 
11805 // Unary Operators.  'Tok' is the token for the operator.
11806 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11807                               tok::TokenKind Op, Expr *Input) {
11808   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11809 }
11810 
11811 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11812 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11813                                 LabelDecl *TheDecl) {
11814   TheDecl->markUsed(Context);
11815   // Create the AST node.  The address of a label always has type 'void*'.
11816   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11817                                      Context.getPointerType(Context.VoidTy));
11818 }
11819 
11820 /// Given the last statement in a statement-expression, check whether
11821 /// the result is a producing expression (like a call to an
11822 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11823 /// release out of the full-expression.  Otherwise, return null.
11824 /// Cannot fail.
11825 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11826   // Should always be wrapped with one of these.
11827   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11828   if (!cleanups) return nullptr;
11829 
11830   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11831   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11832     return nullptr;
11833 
11834   // Splice out the cast.  This shouldn't modify any interesting
11835   // features of the statement.
11836   Expr *producer = cast->getSubExpr();
11837   assert(producer->getType() == cast->getType());
11838   assert(producer->getValueKind() == cast->getValueKind());
11839   cleanups->setSubExpr(producer);
11840   return cleanups;
11841 }
11842 
11843 void Sema::ActOnStartStmtExpr() {
11844   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11845 }
11846 
11847 void Sema::ActOnStmtExprError() {
11848   // Note that function is also called by TreeTransform when leaving a
11849   // StmtExpr scope without rebuilding anything.
11850 
11851   DiscardCleanupsInEvaluationContext();
11852   PopExpressionEvaluationContext();
11853 }
11854 
11855 ExprResult
11856 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11857                     SourceLocation RPLoc) { // "({..})"
11858   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11859   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11860 
11861   if (hasAnyUnrecoverableErrorsInThisFunction())
11862     DiscardCleanupsInEvaluationContext();
11863   assert(!Cleanup.exprNeedsCleanups() &&
11864          "cleanups within StmtExpr not correctly bound!");
11865   PopExpressionEvaluationContext();
11866 
11867   // FIXME: there are a variety of strange constraints to enforce here, for
11868   // example, it is not possible to goto into a stmt expression apparently.
11869   // More semantic analysis is needed.
11870 
11871   // If there are sub-stmts in the compound stmt, take the type of the last one
11872   // as the type of the stmtexpr.
11873   QualType Ty = Context.VoidTy;
11874   bool StmtExprMayBindToTemp = false;
11875   if (!Compound->body_empty()) {
11876     Stmt *LastStmt = Compound->body_back();
11877     LabelStmt *LastLabelStmt = nullptr;
11878     // If LastStmt is a label, skip down through into the body.
11879     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11880       LastLabelStmt = Label;
11881       LastStmt = Label->getSubStmt();
11882     }
11883 
11884     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11885       // Do function/array conversion on the last expression, but not
11886       // lvalue-to-rvalue.  However, initialize an unqualified type.
11887       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11888       if (LastExpr.isInvalid())
11889         return ExprError();
11890       Ty = LastExpr.get()->getType().getUnqualifiedType();
11891 
11892       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11893         // In ARC, if the final expression ends in a consume, splice
11894         // the consume out and bind it later.  In the alternate case
11895         // (when dealing with a retainable type), the result
11896         // initialization will create a produce.  In both cases the
11897         // result will be +1, and we'll need to balance that out with
11898         // a bind.
11899         if (Expr *rebuiltLastStmt
11900               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11901           LastExpr = rebuiltLastStmt;
11902         } else {
11903           LastExpr = PerformCopyInitialization(
11904                             InitializedEntity::InitializeResult(LPLoc,
11905                                                                 Ty,
11906                                                                 false),
11907                                                    SourceLocation(),
11908                                                LastExpr);
11909         }
11910 
11911         if (LastExpr.isInvalid())
11912           return ExprError();
11913         if (LastExpr.get() != nullptr) {
11914           if (!LastLabelStmt)
11915             Compound->setLastStmt(LastExpr.get());
11916           else
11917             LastLabelStmt->setSubStmt(LastExpr.get());
11918           StmtExprMayBindToTemp = true;
11919         }
11920       }
11921     }
11922   }
11923 
11924   // FIXME: Check that expression type is complete/non-abstract; statement
11925   // expressions are not lvalues.
11926   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11927   if (StmtExprMayBindToTemp)
11928     return MaybeBindToTemporary(ResStmtExpr);
11929   return ResStmtExpr;
11930 }
11931 
11932 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11933                                       TypeSourceInfo *TInfo,
11934                                       ArrayRef<OffsetOfComponent> Components,
11935                                       SourceLocation RParenLoc) {
11936   QualType ArgTy = TInfo->getType();
11937   bool Dependent = ArgTy->isDependentType();
11938   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11939 
11940   // We must have at least one component that refers to the type, and the first
11941   // one is known to be a field designator.  Verify that the ArgTy represents
11942   // a struct/union/class.
11943   if (!Dependent && !ArgTy->isRecordType())
11944     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11945                        << ArgTy << TypeRange);
11946 
11947   // Type must be complete per C99 7.17p3 because a declaring a variable
11948   // with an incomplete type would be ill-formed.
11949   if (!Dependent
11950       && RequireCompleteType(BuiltinLoc, ArgTy,
11951                              diag::err_offsetof_incomplete_type, TypeRange))
11952     return ExprError();
11953 
11954   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11955   // GCC extension, diagnose them.
11956   // FIXME: This diagnostic isn't actually visible because the location is in
11957   // a system header!
11958   if (Components.size() != 1)
11959     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11960       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11961 
11962   bool DidWarnAboutNonPOD = false;
11963   QualType CurrentType = ArgTy;
11964   SmallVector<OffsetOfNode, 4> Comps;
11965   SmallVector<Expr*, 4> Exprs;
11966   for (const OffsetOfComponent &OC : Components) {
11967     if (OC.isBrackets) {
11968       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11969       if (!CurrentType->isDependentType()) {
11970         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11971         if(!AT)
11972           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11973                            << CurrentType);
11974         CurrentType = AT->getElementType();
11975       } else
11976         CurrentType = Context.DependentTy;
11977 
11978       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11979       if (IdxRval.isInvalid())
11980         return ExprError();
11981       Expr *Idx = IdxRval.get();
11982 
11983       // The expression must be an integral expression.
11984       // FIXME: An integral constant expression?
11985       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11986           !Idx->getType()->isIntegerType())
11987         return ExprError(Diag(Idx->getLocStart(),
11988                               diag::err_typecheck_subscript_not_integer)
11989                          << Idx->getSourceRange());
11990 
11991       // Record this array index.
11992       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11993       Exprs.push_back(Idx);
11994       continue;
11995     }
11996 
11997     // Offset of a field.
11998     if (CurrentType->isDependentType()) {
11999       // We have the offset of a field, but we can't look into the dependent
12000       // type. Just record the identifier of the field.
12001       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12002       CurrentType = Context.DependentTy;
12003       continue;
12004     }
12005 
12006     // We need to have a complete type to look into.
12007     if (RequireCompleteType(OC.LocStart, CurrentType,
12008                             diag::err_offsetof_incomplete_type))
12009       return ExprError();
12010 
12011     // Look for the designated field.
12012     const RecordType *RC = CurrentType->getAs<RecordType>();
12013     if (!RC)
12014       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12015                        << CurrentType);
12016     RecordDecl *RD = RC->getDecl();
12017 
12018     // C++ [lib.support.types]p5:
12019     //   The macro offsetof accepts a restricted set of type arguments in this
12020     //   International Standard. type shall be a POD structure or a POD union
12021     //   (clause 9).
12022     // C++11 [support.types]p4:
12023     //   If type is not a standard-layout class (Clause 9), the results are
12024     //   undefined.
12025     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12026       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12027       unsigned DiagID =
12028         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12029                             : diag::ext_offsetof_non_pod_type;
12030 
12031       if (!IsSafe && !DidWarnAboutNonPOD &&
12032           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12033                               PDiag(DiagID)
12034                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12035                               << CurrentType))
12036         DidWarnAboutNonPOD = true;
12037     }
12038 
12039     // Look for the field.
12040     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12041     LookupQualifiedName(R, RD);
12042     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12043     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12044     if (!MemberDecl) {
12045       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12046         MemberDecl = IndirectMemberDecl->getAnonField();
12047     }
12048 
12049     if (!MemberDecl)
12050       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12051                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12052                                                               OC.LocEnd));
12053 
12054     // C99 7.17p3:
12055     //   (If the specified member is a bit-field, the behavior is undefined.)
12056     //
12057     // We diagnose this as an error.
12058     if (MemberDecl->isBitField()) {
12059       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12060         << MemberDecl->getDeclName()
12061         << SourceRange(BuiltinLoc, RParenLoc);
12062       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12063       return ExprError();
12064     }
12065 
12066     RecordDecl *Parent = MemberDecl->getParent();
12067     if (IndirectMemberDecl)
12068       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12069 
12070     // If the member was found in a base class, introduce OffsetOfNodes for
12071     // the base class indirections.
12072     CXXBasePaths Paths;
12073     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12074                       Paths)) {
12075       if (Paths.getDetectedVirtual()) {
12076         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12077           << MemberDecl->getDeclName()
12078           << SourceRange(BuiltinLoc, RParenLoc);
12079         return ExprError();
12080       }
12081 
12082       CXXBasePath &Path = Paths.front();
12083       for (const CXXBasePathElement &B : Path)
12084         Comps.push_back(OffsetOfNode(B.Base));
12085     }
12086 
12087     if (IndirectMemberDecl) {
12088       for (auto *FI : IndirectMemberDecl->chain()) {
12089         assert(isa<FieldDecl>(FI));
12090         Comps.push_back(OffsetOfNode(OC.LocStart,
12091                                      cast<FieldDecl>(FI), OC.LocEnd));
12092       }
12093     } else
12094       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12095 
12096     CurrentType = MemberDecl->getType().getNonReferenceType();
12097   }
12098 
12099   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12100                               Comps, Exprs, RParenLoc);
12101 }
12102 
12103 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12104                                       SourceLocation BuiltinLoc,
12105                                       SourceLocation TypeLoc,
12106                                       ParsedType ParsedArgTy,
12107                                       ArrayRef<OffsetOfComponent> Components,
12108                                       SourceLocation RParenLoc) {
12109 
12110   TypeSourceInfo *ArgTInfo;
12111   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12112   if (ArgTy.isNull())
12113     return ExprError();
12114 
12115   if (!ArgTInfo)
12116     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12117 
12118   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12119 }
12120 
12121 
12122 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12123                                  Expr *CondExpr,
12124                                  Expr *LHSExpr, Expr *RHSExpr,
12125                                  SourceLocation RPLoc) {
12126   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12127 
12128   ExprValueKind VK = VK_RValue;
12129   ExprObjectKind OK = OK_Ordinary;
12130   QualType resType;
12131   bool ValueDependent = false;
12132   bool CondIsTrue = false;
12133   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12134     resType = Context.DependentTy;
12135     ValueDependent = true;
12136   } else {
12137     // The conditional expression is required to be a constant expression.
12138     llvm::APSInt condEval(32);
12139     ExprResult CondICE
12140       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12141           diag::err_typecheck_choose_expr_requires_constant, false);
12142     if (CondICE.isInvalid())
12143       return ExprError();
12144     CondExpr = CondICE.get();
12145     CondIsTrue = condEval.getZExtValue();
12146 
12147     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12148     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12149 
12150     resType = ActiveExpr->getType();
12151     ValueDependent = ActiveExpr->isValueDependent();
12152     VK = ActiveExpr->getValueKind();
12153     OK = ActiveExpr->getObjectKind();
12154   }
12155 
12156   return new (Context)
12157       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12158                  CondIsTrue, resType->isDependentType(), ValueDependent);
12159 }
12160 
12161 //===----------------------------------------------------------------------===//
12162 // Clang Extensions.
12163 //===----------------------------------------------------------------------===//
12164 
12165 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12166 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12167   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12168 
12169   if (LangOpts.CPlusPlus) {
12170     Decl *ManglingContextDecl;
12171     if (MangleNumberingContext *MCtx =
12172             getCurrentMangleNumberContext(Block->getDeclContext(),
12173                                           ManglingContextDecl)) {
12174       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12175       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12176     }
12177   }
12178 
12179   PushBlockScope(CurScope, Block);
12180   CurContext->addDecl(Block);
12181   if (CurScope)
12182     PushDeclContext(CurScope, Block);
12183   else
12184     CurContext = Block;
12185 
12186   getCurBlock()->HasImplicitReturnType = true;
12187 
12188   // Enter a new evaluation context to insulate the block from any
12189   // cleanups from the enclosing full-expression.
12190   PushExpressionEvaluationContext(PotentiallyEvaluated);
12191 }
12192 
12193 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12194                                Scope *CurScope) {
12195   assert(ParamInfo.getIdentifier() == nullptr &&
12196          "block-id should have no identifier!");
12197   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12198   BlockScopeInfo *CurBlock = getCurBlock();
12199 
12200   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12201   QualType T = Sig->getType();
12202 
12203   // FIXME: We should allow unexpanded parameter packs here, but that would,
12204   // in turn, make the block expression contain unexpanded parameter packs.
12205   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12206     // Drop the parameters.
12207     FunctionProtoType::ExtProtoInfo EPI;
12208     EPI.HasTrailingReturn = false;
12209     EPI.TypeQuals |= DeclSpec::TQ_const;
12210     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12211     Sig = Context.getTrivialTypeSourceInfo(T);
12212   }
12213 
12214   // GetTypeForDeclarator always produces a function type for a block
12215   // literal signature.  Furthermore, it is always a FunctionProtoType
12216   // unless the function was written with a typedef.
12217   assert(T->isFunctionType() &&
12218          "GetTypeForDeclarator made a non-function block signature");
12219 
12220   // Look for an explicit signature in that function type.
12221   FunctionProtoTypeLoc ExplicitSignature;
12222 
12223   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12224   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12225 
12226     // Check whether that explicit signature was synthesized by
12227     // GetTypeForDeclarator.  If so, don't save that as part of the
12228     // written signature.
12229     if (ExplicitSignature.getLocalRangeBegin() ==
12230         ExplicitSignature.getLocalRangeEnd()) {
12231       // This would be much cheaper if we stored TypeLocs instead of
12232       // TypeSourceInfos.
12233       TypeLoc Result = ExplicitSignature.getReturnLoc();
12234       unsigned Size = Result.getFullDataSize();
12235       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12236       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12237 
12238       ExplicitSignature = FunctionProtoTypeLoc();
12239     }
12240   }
12241 
12242   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12243   CurBlock->FunctionType = T;
12244 
12245   const FunctionType *Fn = T->getAs<FunctionType>();
12246   QualType RetTy = Fn->getReturnType();
12247   bool isVariadic =
12248     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12249 
12250   CurBlock->TheDecl->setIsVariadic(isVariadic);
12251 
12252   // Context.DependentTy is used as a placeholder for a missing block
12253   // return type.  TODO:  what should we do with declarators like:
12254   //   ^ * { ... }
12255   // If the answer is "apply template argument deduction"....
12256   if (RetTy != Context.DependentTy) {
12257     CurBlock->ReturnType = RetTy;
12258     CurBlock->TheDecl->setBlockMissingReturnType(false);
12259     CurBlock->HasImplicitReturnType = false;
12260   }
12261 
12262   // Push block parameters from the declarator if we had them.
12263   SmallVector<ParmVarDecl*, 8> Params;
12264   if (ExplicitSignature) {
12265     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12266       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12267       if (Param->getIdentifier() == nullptr &&
12268           !Param->isImplicit() &&
12269           !Param->isInvalidDecl() &&
12270           !getLangOpts().CPlusPlus)
12271         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12272       Params.push_back(Param);
12273     }
12274 
12275   // Fake up parameter variables if we have a typedef, like
12276   //   ^ fntype { ... }
12277   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12278     for (const auto &I : Fn->param_types()) {
12279       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12280           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12281       Params.push_back(Param);
12282     }
12283   }
12284 
12285   // Set the parameters on the block decl.
12286   if (!Params.empty()) {
12287     CurBlock->TheDecl->setParams(Params);
12288     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12289                              /*CheckParameterNames=*/false);
12290   }
12291 
12292   // Finally we can process decl attributes.
12293   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12294 
12295   // Put the parameter variables in scope.
12296   for (auto AI : CurBlock->TheDecl->parameters()) {
12297     AI->setOwningFunction(CurBlock->TheDecl);
12298 
12299     // If this has an identifier, add it to the scope stack.
12300     if (AI->getIdentifier()) {
12301       CheckShadow(CurBlock->TheScope, AI);
12302 
12303       PushOnScopeChains(AI, CurBlock->TheScope);
12304     }
12305   }
12306 }
12307 
12308 /// ActOnBlockError - If there is an error parsing a block, this callback
12309 /// is invoked to pop the information about the block from the action impl.
12310 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12311   // Leave the expression-evaluation context.
12312   DiscardCleanupsInEvaluationContext();
12313   PopExpressionEvaluationContext();
12314 
12315   // Pop off CurBlock, handle nested blocks.
12316   PopDeclContext();
12317   PopFunctionScopeInfo();
12318 }
12319 
12320 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12321 /// literal was successfully completed.  ^(int x){...}
12322 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12323                                     Stmt *Body, Scope *CurScope) {
12324   // If blocks are disabled, emit an error.
12325   if (!LangOpts.Blocks)
12326     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12327 
12328   // Leave the expression-evaluation context.
12329   if (hasAnyUnrecoverableErrorsInThisFunction())
12330     DiscardCleanupsInEvaluationContext();
12331   assert(!Cleanup.exprNeedsCleanups() &&
12332          "cleanups within block not correctly bound!");
12333   PopExpressionEvaluationContext();
12334 
12335   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12336 
12337   if (BSI->HasImplicitReturnType)
12338     deduceClosureReturnType(*BSI);
12339 
12340   PopDeclContext();
12341 
12342   QualType RetTy = Context.VoidTy;
12343   if (!BSI->ReturnType.isNull())
12344     RetTy = BSI->ReturnType;
12345 
12346   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12347   QualType BlockTy;
12348 
12349   // Set the captured variables on the block.
12350   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12351   SmallVector<BlockDecl::Capture, 4> Captures;
12352   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12353     if (Cap.isThisCapture())
12354       continue;
12355     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12356                               Cap.isNested(), Cap.getInitExpr());
12357     Captures.push_back(NewCap);
12358   }
12359   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12360 
12361   // If the user wrote a function type in some form, try to use that.
12362   if (!BSI->FunctionType.isNull()) {
12363     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12364 
12365     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12366     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12367 
12368     // Turn protoless block types into nullary block types.
12369     if (isa<FunctionNoProtoType>(FTy)) {
12370       FunctionProtoType::ExtProtoInfo EPI;
12371       EPI.ExtInfo = Ext;
12372       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12373 
12374     // Otherwise, if we don't need to change anything about the function type,
12375     // preserve its sugar structure.
12376     } else if (FTy->getReturnType() == RetTy &&
12377                (!NoReturn || FTy->getNoReturnAttr())) {
12378       BlockTy = BSI->FunctionType;
12379 
12380     // Otherwise, make the minimal modifications to the function type.
12381     } else {
12382       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12383       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12384       EPI.TypeQuals = 0; // FIXME: silently?
12385       EPI.ExtInfo = Ext;
12386       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12387     }
12388 
12389   // If we don't have a function type, just build one from nothing.
12390   } else {
12391     FunctionProtoType::ExtProtoInfo EPI;
12392     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12393     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12394   }
12395 
12396   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12397   BlockTy = Context.getBlockPointerType(BlockTy);
12398 
12399   // If needed, diagnose invalid gotos and switches in the block.
12400   if (getCurFunction()->NeedsScopeChecking() &&
12401       !PP.isCodeCompletionEnabled())
12402     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12403 
12404   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12405 
12406   // Try to apply the named return value optimization. We have to check again
12407   // if we can do this, though, because blocks keep return statements around
12408   // to deduce an implicit return type.
12409   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12410       !BSI->TheDecl->isDependentContext())
12411     computeNRVO(Body, BSI);
12412 
12413   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12414   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12415   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12416 
12417   // If the block isn't obviously global, i.e. it captures anything at
12418   // all, then we need to do a few things in the surrounding context:
12419   if (Result->getBlockDecl()->hasCaptures()) {
12420     // First, this expression has a new cleanup object.
12421     ExprCleanupObjects.push_back(Result->getBlockDecl());
12422     Cleanup.setExprNeedsCleanups(true);
12423 
12424     // It also gets a branch-protected scope if any of the captured
12425     // variables needs destruction.
12426     for (const auto &CI : Result->getBlockDecl()->captures()) {
12427       const VarDecl *var = CI.getVariable();
12428       if (var->getType().isDestructedType() != QualType::DK_none) {
12429         getCurFunction()->setHasBranchProtectedScope();
12430         break;
12431       }
12432     }
12433   }
12434 
12435   return Result;
12436 }
12437 
12438 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12439                             SourceLocation RPLoc) {
12440   TypeSourceInfo *TInfo;
12441   GetTypeFromParser(Ty, &TInfo);
12442   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12443 }
12444 
12445 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12446                                 Expr *E, TypeSourceInfo *TInfo,
12447                                 SourceLocation RPLoc) {
12448   Expr *OrigExpr = E;
12449   bool IsMS = false;
12450 
12451   // CUDA device code does not support varargs.
12452   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12453     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12454       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12455       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12456         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12457     }
12458   }
12459 
12460   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12461   // as Microsoft ABI on an actual Microsoft platform, where
12462   // __builtin_ms_va_list and __builtin_va_list are the same.)
12463   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12464       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12465     QualType MSVaListType = Context.getBuiltinMSVaListType();
12466     if (Context.hasSameType(MSVaListType, E->getType())) {
12467       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12468         return ExprError();
12469       IsMS = true;
12470     }
12471   }
12472 
12473   // Get the va_list type
12474   QualType VaListType = Context.getBuiltinVaListType();
12475   if (!IsMS) {
12476     if (VaListType->isArrayType()) {
12477       // Deal with implicit array decay; for example, on x86-64,
12478       // va_list is an array, but it's supposed to decay to
12479       // a pointer for va_arg.
12480       VaListType = Context.getArrayDecayedType(VaListType);
12481       // Make sure the input expression also decays appropriately.
12482       ExprResult Result = UsualUnaryConversions(E);
12483       if (Result.isInvalid())
12484         return ExprError();
12485       E = Result.get();
12486     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12487       // If va_list is a record type and we are compiling in C++ mode,
12488       // check the argument using reference binding.
12489       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12490           Context, Context.getLValueReferenceType(VaListType), false);
12491       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12492       if (Init.isInvalid())
12493         return ExprError();
12494       E = Init.getAs<Expr>();
12495     } else {
12496       // Otherwise, the va_list argument must be an l-value because
12497       // it is modified by va_arg.
12498       if (!E->isTypeDependent() &&
12499           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12500         return ExprError();
12501     }
12502   }
12503 
12504   if (!IsMS && !E->isTypeDependent() &&
12505       !Context.hasSameType(VaListType, E->getType()))
12506     return ExprError(Diag(E->getLocStart(),
12507                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12508       << OrigExpr->getType() << E->getSourceRange());
12509 
12510   if (!TInfo->getType()->isDependentType()) {
12511     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12512                             diag::err_second_parameter_to_va_arg_incomplete,
12513                             TInfo->getTypeLoc()))
12514       return ExprError();
12515 
12516     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12517                                TInfo->getType(),
12518                                diag::err_second_parameter_to_va_arg_abstract,
12519                                TInfo->getTypeLoc()))
12520       return ExprError();
12521 
12522     if (!TInfo->getType().isPODType(Context)) {
12523       Diag(TInfo->getTypeLoc().getBeginLoc(),
12524            TInfo->getType()->isObjCLifetimeType()
12525              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12526              : diag::warn_second_parameter_to_va_arg_not_pod)
12527         << TInfo->getType()
12528         << TInfo->getTypeLoc().getSourceRange();
12529     }
12530 
12531     // Check for va_arg where arguments of the given type will be promoted
12532     // (i.e. this va_arg is guaranteed to have undefined behavior).
12533     QualType PromoteType;
12534     if (TInfo->getType()->isPromotableIntegerType()) {
12535       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12536       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12537         PromoteType = QualType();
12538     }
12539     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12540       PromoteType = Context.DoubleTy;
12541     if (!PromoteType.isNull())
12542       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12543                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12544                           << TInfo->getType()
12545                           << PromoteType
12546                           << TInfo->getTypeLoc().getSourceRange());
12547   }
12548 
12549   QualType T = TInfo->getType().getNonLValueExprType(Context);
12550   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12551 }
12552 
12553 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12554   // The type of __null will be int or long, depending on the size of
12555   // pointers on the target.
12556   QualType Ty;
12557   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12558   if (pw == Context.getTargetInfo().getIntWidth())
12559     Ty = Context.IntTy;
12560   else if (pw == Context.getTargetInfo().getLongWidth())
12561     Ty = Context.LongTy;
12562   else if (pw == Context.getTargetInfo().getLongLongWidth())
12563     Ty = Context.LongLongTy;
12564   else {
12565     llvm_unreachable("I don't know size of pointer!");
12566   }
12567 
12568   return new (Context) GNUNullExpr(Ty, TokenLoc);
12569 }
12570 
12571 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12572                                               bool Diagnose) {
12573   if (!getLangOpts().ObjC1)
12574     return false;
12575 
12576   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12577   if (!PT)
12578     return false;
12579 
12580   if (!PT->isObjCIdType()) {
12581     // Check if the destination is the 'NSString' interface.
12582     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12583     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12584       return false;
12585   }
12586 
12587   // Ignore any parens, implicit casts (should only be
12588   // array-to-pointer decays), and not-so-opaque values.  The last is
12589   // important for making this trigger for property assignments.
12590   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12591   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12592     if (OV->getSourceExpr())
12593       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12594 
12595   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12596   if (!SL || !SL->isAscii())
12597     return false;
12598   if (Diagnose) {
12599     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12600       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12601     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12602   }
12603   return true;
12604 }
12605 
12606 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12607                                               const Expr *SrcExpr) {
12608   if (!DstType->isFunctionPointerType() ||
12609       !SrcExpr->getType()->isFunctionType())
12610     return false;
12611 
12612   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12613   if (!DRE)
12614     return false;
12615 
12616   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12617   if (!FD)
12618     return false;
12619 
12620   return !S.checkAddressOfFunctionIsAvailable(FD,
12621                                               /*Complain=*/true,
12622                                               SrcExpr->getLocStart());
12623 }
12624 
12625 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12626                                     SourceLocation Loc,
12627                                     QualType DstType, QualType SrcType,
12628                                     Expr *SrcExpr, AssignmentAction Action,
12629                                     bool *Complained) {
12630   if (Complained)
12631     *Complained = false;
12632 
12633   // Decode the result (notice that AST's are still created for extensions).
12634   bool CheckInferredResultType = false;
12635   bool isInvalid = false;
12636   unsigned DiagKind = 0;
12637   FixItHint Hint;
12638   ConversionFixItGenerator ConvHints;
12639   bool MayHaveConvFixit = false;
12640   bool MayHaveFunctionDiff = false;
12641   const ObjCInterfaceDecl *IFace = nullptr;
12642   const ObjCProtocolDecl *PDecl = nullptr;
12643 
12644   switch (ConvTy) {
12645   case Compatible:
12646       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12647       return false;
12648 
12649   case PointerToInt:
12650     DiagKind = diag::ext_typecheck_convert_pointer_int;
12651     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12652     MayHaveConvFixit = true;
12653     break;
12654   case IntToPointer:
12655     DiagKind = diag::ext_typecheck_convert_int_pointer;
12656     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12657     MayHaveConvFixit = true;
12658     break;
12659   case IncompatiblePointer:
12660     if (Action == AA_Passing_CFAudited)
12661       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12662     else if (SrcType->isFunctionPointerType() &&
12663              DstType->isFunctionPointerType())
12664       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12665     else
12666       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12667 
12668     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12669       SrcType->isObjCObjectPointerType();
12670     if (Hint.isNull() && !CheckInferredResultType) {
12671       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12672     }
12673     else if (CheckInferredResultType) {
12674       SrcType = SrcType.getUnqualifiedType();
12675       DstType = DstType.getUnqualifiedType();
12676     }
12677     MayHaveConvFixit = true;
12678     break;
12679   case IncompatiblePointerSign:
12680     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12681     break;
12682   case FunctionVoidPointer:
12683     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12684     break;
12685   case IncompatiblePointerDiscardsQualifiers: {
12686     // Perform array-to-pointer decay if necessary.
12687     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12688 
12689     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12690     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12691     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12692       DiagKind = diag::err_typecheck_incompatible_address_space;
12693       break;
12694 
12695 
12696     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12697       DiagKind = diag::err_typecheck_incompatible_ownership;
12698       break;
12699     }
12700 
12701     llvm_unreachable("unknown error case for discarding qualifiers!");
12702     // fallthrough
12703   }
12704   case CompatiblePointerDiscardsQualifiers:
12705     // If the qualifiers lost were because we were applying the
12706     // (deprecated) C++ conversion from a string literal to a char*
12707     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12708     // Ideally, this check would be performed in
12709     // checkPointerTypesForAssignment. However, that would require a
12710     // bit of refactoring (so that the second argument is an
12711     // expression, rather than a type), which should be done as part
12712     // of a larger effort to fix checkPointerTypesForAssignment for
12713     // C++ semantics.
12714     if (getLangOpts().CPlusPlus &&
12715         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12716       return false;
12717     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12718     break;
12719   case IncompatibleNestedPointerQualifiers:
12720     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12721     break;
12722   case IntToBlockPointer:
12723     DiagKind = diag::err_int_to_block_pointer;
12724     break;
12725   case IncompatibleBlockPointer:
12726     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12727     break;
12728   case IncompatibleObjCQualifiedId: {
12729     if (SrcType->isObjCQualifiedIdType()) {
12730       const ObjCObjectPointerType *srcOPT =
12731                 SrcType->getAs<ObjCObjectPointerType>();
12732       for (auto *srcProto : srcOPT->quals()) {
12733         PDecl = srcProto;
12734         break;
12735       }
12736       if (const ObjCInterfaceType *IFaceT =
12737             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12738         IFace = IFaceT->getDecl();
12739     }
12740     else if (DstType->isObjCQualifiedIdType()) {
12741       const ObjCObjectPointerType *dstOPT =
12742         DstType->getAs<ObjCObjectPointerType>();
12743       for (auto *dstProto : dstOPT->quals()) {
12744         PDecl = dstProto;
12745         break;
12746       }
12747       if (const ObjCInterfaceType *IFaceT =
12748             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12749         IFace = IFaceT->getDecl();
12750     }
12751     DiagKind = diag::warn_incompatible_qualified_id;
12752     break;
12753   }
12754   case IncompatibleVectors:
12755     DiagKind = diag::warn_incompatible_vectors;
12756     break;
12757   case IncompatibleObjCWeakRef:
12758     DiagKind = diag::err_arc_weak_unavailable_assign;
12759     break;
12760   case Incompatible:
12761     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12762       if (Complained)
12763         *Complained = true;
12764       return true;
12765     }
12766 
12767     DiagKind = diag::err_typecheck_convert_incompatible;
12768     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12769     MayHaveConvFixit = true;
12770     isInvalid = true;
12771     MayHaveFunctionDiff = true;
12772     break;
12773   }
12774 
12775   QualType FirstType, SecondType;
12776   switch (Action) {
12777   case AA_Assigning:
12778   case AA_Initializing:
12779     // The destination type comes first.
12780     FirstType = DstType;
12781     SecondType = SrcType;
12782     break;
12783 
12784   case AA_Returning:
12785   case AA_Passing:
12786   case AA_Passing_CFAudited:
12787   case AA_Converting:
12788   case AA_Sending:
12789   case AA_Casting:
12790     // The source type comes first.
12791     FirstType = SrcType;
12792     SecondType = DstType;
12793     break;
12794   }
12795 
12796   PartialDiagnostic FDiag = PDiag(DiagKind);
12797   if (Action == AA_Passing_CFAudited)
12798     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12799   else
12800     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12801 
12802   // If we can fix the conversion, suggest the FixIts.
12803   assert(ConvHints.isNull() || Hint.isNull());
12804   if (!ConvHints.isNull()) {
12805     for (FixItHint &H : ConvHints.Hints)
12806       FDiag << H;
12807   } else {
12808     FDiag << Hint;
12809   }
12810   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12811 
12812   if (MayHaveFunctionDiff)
12813     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12814 
12815   Diag(Loc, FDiag);
12816   if (DiagKind == diag::warn_incompatible_qualified_id &&
12817       PDecl && IFace && !IFace->hasDefinition())
12818       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12819         << IFace->getName() << PDecl->getName();
12820 
12821   if (SecondType == Context.OverloadTy)
12822     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12823                               FirstType, /*TakingAddress=*/true);
12824 
12825   if (CheckInferredResultType)
12826     EmitRelatedResultTypeNote(SrcExpr);
12827 
12828   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12829     EmitRelatedResultTypeNoteForReturn(DstType);
12830 
12831   if (Complained)
12832     *Complained = true;
12833   return isInvalid;
12834 }
12835 
12836 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12837                                                  llvm::APSInt *Result) {
12838   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12839   public:
12840     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12841       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12842     }
12843   } Diagnoser;
12844 
12845   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12846 }
12847 
12848 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12849                                                  llvm::APSInt *Result,
12850                                                  unsigned DiagID,
12851                                                  bool AllowFold) {
12852   class IDDiagnoser : public VerifyICEDiagnoser {
12853     unsigned DiagID;
12854 
12855   public:
12856     IDDiagnoser(unsigned DiagID)
12857       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12858 
12859     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12860       S.Diag(Loc, DiagID) << SR;
12861     }
12862   } Diagnoser(DiagID);
12863 
12864   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12865 }
12866 
12867 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12868                                             SourceRange SR) {
12869   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12870 }
12871 
12872 ExprResult
12873 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12874                                       VerifyICEDiagnoser &Diagnoser,
12875                                       bool AllowFold) {
12876   SourceLocation DiagLoc = E->getLocStart();
12877 
12878   if (getLangOpts().CPlusPlus11) {
12879     // C++11 [expr.const]p5:
12880     //   If an expression of literal class type is used in a context where an
12881     //   integral constant expression is required, then that class type shall
12882     //   have a single non-explicit conversion function to an integral or
12883     //   unscoped enumeration type
12884     ExprResult Converted;
12885     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12886     public:
12887       CXX11ConvertDiagnoser(bool Silent)
12888           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12889                                 Silent, true) {}
12890 
12891       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12892                                            QualType T) override {
12893         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12894       }
12895 
12896       SemaDiagnosticBuilder diagnoseIncomplete(
12897           Sema &S, SourceLocation Loc, QualType T) override {
12898         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12899       }
12900 
12901       SemaDiagnosticBuilder diagnoseExplicitConv(
12902           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12903         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12904       }
12905 
12906       SemaDiagnosticBuilder noteExplicitConv(
12907           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12908         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12909                  << ConvTy->isEnumeralType() << ConvTy;
12910       }
12911 
12912       SemaDiagnosticBuilder diagnoseAmbiguous(
12913           Sema &S, SourceLocation Loc, QualType T) override {
12914         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12915       }
12916 
12917       SemaDiagnosticBuilder noteAmbiguous(
12918           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12919         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12920                  << ConvTy->isEnumeralType() << ConvTy;
12921       }
12922 
12923       SemaDiagnosticBuilder diagnoseConversion(
12924           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12925         llvm_unreachable("conversion functions are permitted");
12926       }
12927     } ConvertDiagnoser(Diagnoser.Suppress);
12928 
12929     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12930                                                     ConvertDiagnoser);
12931     if (Converted.isInvalid())
12932       return Converted;
12933     E = Converted.get();
12934     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12935       return ExprError();
12936   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12937     // An ICE must be of integral or unscoped enumeration type.
12938     if (!Diagnoser.Suppress)
12939       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12940     return ExprError();
12941   }
12942 
12943   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12944   // in the non-ICE case.
12945   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12946     if (Result)
12947       *Result = E->EvaluateKnownConstInt(Context);
12948     return E;
12949   }
12950 
12951   Expr::EvalResult EvalResult;
12952   SmallVector<PartialDiagnosticAt, 8> Notes;
12953   EvalResult.Diag = &Notes;
12954 
12955   // Try to evaluate the expression, and produce diagnostics explaining why it's
12956   // not a constant expression as a side-effect.
12957   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12958                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12959 
12960   // In C++11, we can rely on diagnostics being produced for any expression
12961   // which is not a constant expression. If no diagnostics were produced, then
12962   // this is a constant expression.
12963   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12964     if (Result)
12965       *Result = EvalResult.Val.getInt();
12966     return E;
12967   }
12968 
12969   // If our only note is the usual "invalid subexpression" note, just point
12970   // the caret at its location rather than producing an essentially
12971   // redundant note.
12972   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12973         diag::note_invalid_subexpr_in_const_expr) {
12974     DiagLoc = Notes[0].first;
12975     Notes.clear();
12976   }
12977 
12978   if (!Folded || !AllowFold) {
12979     if (!Diagnoser.Suppress) {
12980       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12981       for (const PartialDiagnosticAt &Note : Notes)
12982         Diag(Note.first, Note.second);
12983     }
12984 
12985     return ExprError();
12986   }
12987 
12988   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12989   for (const PartialDiagnosticAt &Note : Notes)
12990     Diag(Note.first, Note.second);
12991 
12992   if (Result)
12993     *Result = EvalResult.Val.getInt();
12994   return E;
12995 }
12996 
12997 namespace {
12998   // Handle the case where we conclude a expression which we speculatively
12999   // considered to be unevaluated is actually evaluated.
13000   class TransformToPE : public TreeTransform<TransformToPE> {
13001     typedef TreeTransform<TransformToPE> BaseTransform;
13002 
13003   public:
13004     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13005 
13006     // Make sure we redo semantic analysis
13007     bool AlwaysRebuild() { return true; }
13008 
13009     // Make sure we handle LabelStmts correctly.
13010     // FIXME: This does the right thing, but maybe we need a more general
13011     // fix to TreeTransform?
13012     StmtResult TransformLabelStmt(LabelStmt *S) {
13013       S->getDecl()->setStmt(nullptr);
13014       return BaseTransform::TransformLabelStmt(S);
13015     }
13016 
13017     // We need to special-case DeclRefExprs referring to FieldDecls which
13018     // are not part of a member pointer formation; normal TreeTransforming
13019     // doesn't catch this case because of the way we represent them in the AST.
13020     // FIXME: This is a bit ugly; is it really the best way to handle this
13021     // case?
13022     //
13023     // Error on DeclRefExprs referring to FieldDecls.
13024     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13025       if (isa<FieldDecl>(E->getDecl()) &&
13026           !SemaRef.isUnevaluatedContext())
13027         return SemaRef.Diag(E->getLocation(),
13028                             diag::err_invalid_non_static_member_use)
13029             << E->getDecl() << E->getSourceRange();
13030 
13031       return BaseTransform::TransformDeclRefExpr(E);
13032     }
13033 
13034     // Exception: filter out member pointer formation
13035     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13036       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13037         return E;
13038 
13039       return BaseTransform::TransformUnaryOperator(E);
13040     }
13041 
13042     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13043       // Lambdas never need to be transformed.
13044       return E;
13045     }
13046   };
13047 }
13048 
13049 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13050   assert(isUnevaluatedContext() &&
13051          "Should only transform unevaluated expressions");
13052   ExprEvalContexts.back().Context =
13053       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13054   if (isUnevaluatedContext())
13055     return E;
13056   return TransformToPE(*this).TransformExpr(E);
13057 }
13058 
13059 void
13060 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13061                                       Decl *LambdaContextDecl,
13062                                       bool IsDecltype) {
13063   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13064                                 LambdaContextDecl, IsDecltype);
13065   Cleanup.reset();
13066   if (!MaybeODRUseExprs.empty())
13067     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13068 }
13069 
13070 void
13071 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13072                                       ReuseLambdaContextDecl_t,
13073                                       bool IsDecltype) {
13074   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13075   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13076 }
13077 
13078 void Sema::PopExpressionEvaluationContext() {
13079   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13080   unsigned NumTypos = Rec.NumTypos;
13081 
13082   if (!Rec.Lambdas.empty()) {
13083     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13084       unsigned D;
13085       if (Rec.isUnevaluated()) {
13086         // C++11 [expr.prim.lambda]p2:
13087         //   A lambda-expression shall not appear in an unevaluated operand
13088         //   (Clause 5).
13089         D = diag::err_lambda_unevaluated_operand;
13090       } else {
13091         // C++1y [expr.const]p2:
13092         //   A conditional-expression e is a core constant expression unless the
13093         //   evaluation of e, following the rules of the abstract machine, would
13094         //   evaluate [...] a lambda-expression.
13095         D = diag::err_lambda_in_constant_expression;
13096       }
13097       for (const auto *L : Rec.Lambdas)
13098         Diag(L->getLocStart(), D);
13099     } else {
13100       // Mark the capture expressions odr-used. This was deferred
13101       // during lambda expression creation.
13102       for (auto *Lambda : Rec.Lambdas) {
13103         for (auto *C : Lambda->capture_inits())
13104           MarkDeclarationsReferencedInExpr(C);
13105       }
13106     }
13107   }
13108 
13109   // When are coming out of an unevaluated context, clear out any
13110   // temporaries that we may have created as part of the evaluation of
13111   // the expression in that context: they aren't relevant because they
13112   // will never be constructed.
13113   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13114     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13115                              ExprCleanupObjects.end());
13116     Cleanup = Rec.ParentCleanup;
13117     CleanupVarDeclMarking();
13118     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13119   // Otherwise, merge the contexts together.
13120   } else {
13121     Cleanup.mergeFrom(Rec.ParentCleanup);
13122     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13123                             Rec.SavedMaybeODRUseExprs.end());
13124   }
13125 
13126   // Pop the current expression evaluation context off the stack.
13127   ExprEvalContexts.pop_back();
13128 
13129   if (!ExprEvalContexts.empty())
13130     ExprEvalContexts.back().NumTypos += NumTypos;
13131   else
13132     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13133                             "last ExpressionEvaluationContextRecord");
13134 }
13135 
13136 void Sema::DiscardCleanupsInEvaluationContext() {
13137   ExprCleanupObjects.erase(
13138          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13139          ExprCleanupObjects.end());
13140   Cleanup.reset();
13141   MaybeODRUseExprs.clear();
13142 }
13143 
13144 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13145   if (!E->getType()->isVariablyModifiedType())
13146     return E;
13147   return TransformToPotentiallyEvaluated(E);
13148 }
13149 
13150 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
13151   // Do not mark anything as "used" within a dependent context; wait for
13152   // an instantiation.
13153   if (SemaRef.CurContext->isDependentContext())
13154     return false;
13155 
13156   switch (SemaRef.ExprEvalContexts.back().Context) {
13157     case Sema::Unevaluated:
13158     case Sema::UnevaluatedAbstract:
13159       // We are in an expression that is not potentially evaluated; do nothing.
13160       // (Depending on how you read the standard, we actually do need to do
13161       // something here for null pointer constants, but the standard's
13162       // definition of a null pointer constant is completely crazy.)
13163       return false;
13164 
13165     case Sema::DiscardedStatement:
13166       // These are technically a potentially evaluated but they have the effect
13167       // of suppressing use marking.
13168       return false;
13169 
13170     case Sema::ConstantEvaluated:
13171     case Sema::PotentiallyEvaluated:
13172       // We are in a potentially evaluated expression (or a constant-expression
13173       // in C++03); we need to do implicit template instantiation, implicitly
13174       // define class members, and mark most declarations as used.
13175       return true;
13176 
13177     case Sema::PotentiallyEvaluatedIfUsed:
13178       // Referenced declarations will only be used if the construct in the
13179       // containing expression is used.
13180       return false;
13181   }
13182   llvm_unreachable("Invalid context");
13183 }
13184 
13185 /// \brief Mark a function referenced, and check whether it is odr-used
13186 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13187 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13188                                   bool MightBeOdrUse) {
13189   assert(Func && "No function?");
13190 
13191   Func->setReferenced();
13192 
13193   // C++11 [basic.def.odr]p3:
13194   //   A function whose name appears as a potentially-evaluated expression is
13195   //   odr-used if it is the unique lookup result or the selected member of a
13196   //   set of overloaded functions [...].
13197   //
13198   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13199   // can just check that here.
13200   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13201 
13202   // Determine whether we require a function definition to exist, per
13203   // C++11 [temp.inst]p3:
13204   //   Unless a function template specialization has been explicitly
13205   //   instantiated or explicitly specialized, the function template
13206   //   specialization is implicitly instantiated when the specialization is
13207   //   referenced in a context that requires a function definition to exist.
13208   //
13209   // We consider constexpr function templates to be referenced in a context
13210   // that requires a definition to exist whenever they are referenced.
13211   //
13212   // FIXME: This instantiates constexpr functions too frequently. If this is
13213   // really an unevaluated context (and we're not just in the definition of a
13214   // function template or overload resolution or other cases which we
13215   // incorrectly consider to be unevaluated contexts), and we're not in a
13216   // subexpression which we actually need to evaluate (for instance, a
13217   // template argument, array bound or an expression in a braced-init-list),
13218   // we are not permitted to instantiate this constexpr function definition.
13219   //
13220   // FIXME: This also implicitly defines special members too frequently. They
13221   // are only supposed to be implicitly defined if they are odr-used, but they
13222   // are not odr-used from constant expressions in unevaluated contexts.
13223   // However, they cannot be referenced if they are deleted, and they are
13224   // deleted whenever the implicit definition of the special member would
13225   // fail (with very few exceptions).
13226   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13227   bool NeedDefinition =
13228       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13229                                          (MD && !MD->isUserProvided())));
13230 
13231   // C++14 [temp.expl.spec]p6:
13232   //   If a template [...] is explicitly specialized then that specialization
13233   //   shall be declared before the first use of that specialization that would
13234   //   cause an implicit instantiation to take place, in every translation unit
13235   //   in which such a use occurs
13236   if (NeedDefinition &&
13237       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13238        Func->getMemberSpecializationInfo()))
13239     checkSpecializationVisibility(Loc, Func);
13240 
13241   // C++14 [except.spec]p17:
13242   //   An exception-specification is considered to be needed when:
13243   //   - the function is odr-used or, if it appears in an unevaluated operand,
13244   //     would be odr-used if the expression were potentially-evaluated;
13245   //
13246   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13247   // function is a pure virtual function we're calling, and in that case the
13248   // function was selected by overload resolution and we need to resolve its
13249   // exception specification for a different reason.
13250   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13251   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13252     ResolveExceptionSpec(Loc, FPT);
13253 
13254   // If we don't need to mark the function as used, and we don't need to
13255   // try to provide a definition, there's nothing more to do.
13256   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13257       (!NeedDefinition || Func->getBody()))
13258     return;
13259 
13260   // Note that this declaration has been used.
13261   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13262     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13263     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13264       if (Constructor->isDefaultConstructor()) {
13265         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13266           return;
13267         DefineImplicitDefaultConstructor(Loc, Constructor);
13268       } else if (Constructor->isCopyConstructor()) {
13269         DefineImplicitCopyConstructor(Loc, Constructor);
13270       } else if (Constructor->isMoveConstructor()) {
13271         DefineImplicitMoveConstructor(Loc, Constructor);
13272       }
13273     } else if (Constructor->getInheritedConstructor()) {
13274       DefineInheritingConstructor(Loc, Constructor);
13275     }
13276   } else if (CXXDestructorDecl *Destructor =
13277                  dyn_cast<CXXDestructorDecl>(Func)) {
13278     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13279     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13280       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13281         return;
13282       DefineImplicitDestructor(Loc, Destructor);
13283     }
13284     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13285       MarkVTableUsed(Loc, Destructor->getParent());
13286   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13287     if (MethodDecl->isOverloadedOperator() &&
13288         MethodDecl->getOverloadedOperator() == OO_Equal) {
13289       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13290       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13291         if (MethodDecl->isCopyAssignmentOperator())
13292           DefineImplicitCopyAssignment(Loc, MethodDecl);
13293         else if (MethodDecl->isMoveAssignmentOperator())
13294           DefineImplicitMoveAssignment(Loc, MethodDecl);
13295       }
13296     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13297                MethodDecl->getParent()->isLambda()) {
13298       CXXConversionDecl *Conversion =
13299           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13300       if (Conversion->isLambdaToBlockPointerConversion())
13301         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13302       else
13303         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13304     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13305       MarkVTableUsed(Loc, MethodDecl->getParent());
13306   }
13307 
13308   // Recursive functions should be marked when used from another function.
13309   // FIXME: Is this really right?
13310   if (CurContext == Func) return;
13311 
13312   // Implicit instantiation of function templates and member functions of
13313   // class templates.
13314   if (Func->isImplicitlyInstantiable()) {
13315     bool AlreadyInstantiated = false;
13316     SourceLocation PointOfInstantiation = Loc;
13317     if (FunctionTemplateSpecializationInfo *SpecInfo
13318                               = Func->getTemplateSpecializationInfo()) {
13319       if (SpecInfo->getPointOfInstantiation().isInvalid())
13320         SpecInfo->setPointOfInstantiation(Loc);
13321       else if (SpecInfo->getTemplateSpecializationKind()
13322                  == TSK_ImplicitInstantiation) {
13323         AlreadyInstantiated = true;
13324         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13325       }
13326     } else if (MemberSpecializationInfo *MSInfo
13327                                 = Func->getMemberSpecializationInfo()) {
13328       if (MSInfo->getPointOfInstantiation().isInvalid())
13329         MSInfo->setPointOfInstantiation(Loc);
13330       else if (MSInfo->getTemplateSpecializationKind()
13331                  == TSK_ImplicitInstantiation) {
13332         AlreadyInstantiated = true;
13333         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13334       }
13335     }
13336 
13337     if (!AlreadyInstantiated || Func->isConstexpr()) {
13338       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13339           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13340           ActiveTemplateInstantiations.size())
13341         PendingLocalImplicitInstantiations.push_back(
13342             std::make_pair(Func, PointOfInstantiation));
13343       else if (Func->isConstexpr())
13344         // Do not defer instantiations of constexpr functions, to avoid the
13345         // expression evaluator needing to call back into Sema if it sees a
13346         // call to such a function.
13347         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13348       else {
13349         PendingInstantiations.push_back(std::make_pair(Func,
13350                                                        PointOfInstantiation));
13351         // Notify the consumer that a function was implicitly instantiated.
13352         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13353       }
13354     }
13355   } else {
13356     // Walk redefinitions, as some of them may be instantiable.
13357     for (auto i : Func->redecls()) {
13358       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13359         MarkFunctionReferenced(Loc, i, OdrUse);
13360     }
13361   }
13362 
13363   if (!OdrUse) return;
13364 
13365   // Keep track of used but undefined functions.
13366   if (!Func->isDefined()) {
13367     if (mightHaveNonExternalLinkage(Func))
13368       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13369     else if (Func->getMostRecentDecl()->isInlined() &&
13370              !LangOpts.GNUInline &&
13371              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13372       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13373   }
13374 
13375   Func->markUsed(Context);
13376 }
13377 
13378 static void
13379 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13380                                    ValueDecl *var, DeclContext *DC) {
13381   DeclContext *VarDC = var->getDeclContext();
13382 
13383   //  If the parameter still belongs to the translation unit, then
13384   //  we're actually just using one parameter in the declaration of
13385   //  the next.
13386   if (isa<ParmVarDecl>(var) &&
13387       isa<TranslationUnitDecl>(VarDC))
13388     return;
13389 
13390   // For C code, don't diagnose about capture if we're not actually in code
13391   // right now; it's impossible to write a non-constant expression outside of
13392   // function context, so we'll get other (more useful) diagnostics later.
13393   //
13394   // For C++, things get a bit more nasty... it would be nice to suppress this
13395   // diagnostic for certain cases like using a local variable in an array bound
13396   // for a member of a local class, but the correct predicate is not obvious.
13397   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13398     return;
13399 
13400   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13401   unsigned ContextKind = 3; // unknown
13402   if (isa<CXXMethodDecl>(VarDC) &&
13403       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13404     ContextKind = 2;
13405   } else if (isa<FunctionDecl>(VarDC)) {
13406     ContextKind = 0;
13407   } else if (isa<BlockDecl>(VarDC)) {
13408     ContextKind = 1;
13409   }
13410 
13411   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13412     << var << ValueKind << ContextKind << VarDC;
13413   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13414       << var;
13415 
13416   // FIXME: Add additional diagnostic info about class etc. which prevents
13417   // capture.
13418 }
13419 
13420 
13421 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13422                                       bool &SubCapturesAreNested,
13423                                       QualType &CaptureType,
13424                                       QualType &DeclRefType) {
13425    // Check whether we've already captured it.
13426   if (CSI->CaptureMap.count(Var)) {
13427     // If we found a capture, any subcaptures are nested.
13428     SubCapturesAreNested = true;
13429 
13430     // Retrieve the capture type for this variable.
13431     CaptureType = CSI->getCapture(Var).getCaptureType();
13432 
13433     // Compute the type of an expression that refers to this variable.
13434     DeclRefType = CaptureType.getNonReferenceType();
13435 
13436     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13437     // are mutable in the sense that user can change their value - they are
13438     // private instances of the captured declarations.
13439     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13440     if (Cap.isCopyCapture() &&
13441         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13442         !(isa<CapturedRegionScopeInfo>(CSI) &&
13443           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13444       DeclRefType.addConst();
13445     return true;
13446   }
13447   return false;
13448 }
13449 
13450 // Only block literals, captured statements, and lambda expressions can
13451 // capture; other scopes don't work.
13452 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13453                                  SourceLocation Loc,
13454                                  const bool Diagnose, Sema &S) {
13455   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13456     return getLambdaAwareParentOfDeclContext(DC);
13457   else if (Var->hasLocalStorage()) {
13458     if (Diagnose)
13459        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13460   }
13461   return nullptr;
13462 }
13463 
13464 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13465 // certain types of variables (unnamed, variably modified types etc.)
13466 // so check for eligibility.
13467 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13468                                  SourceLocation Loc,
13469                                  const bool Diagnose, Sema &S) {
13470 
13471   bool IsBlock = isa<BlockScopeInfo>(CSI);
13472   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13473 
13474   // Lambdas are not allowed to capture unnamed variables
13475   // (e.g. anonymous unions).
13476   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13477   // assuming that's the intent.
13478   if (IsLambda && !Var->getDeclName()) {
13479     if (Diagnose) {
13480       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13481       S.Diag(Var->getLocation(), diag::note_declared_at);
13482     }
13483     return false;
13484   }
13485 
13486   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13487   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13488     if (Diagnose) {
13489       S.Diag(Loc, diag::err_ref_vm_type);
13490       S.Diag(Var->getLocation(), diag::note_previous_decl)
13491         << Var->getDeclName();
13492     }
13493     return false;
13494   }
13495   // Prohibit structs with flexible array members too.
13496   // We cannot capture what is in the tail end of the struct.
13497   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13498     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13499       if (Diagnose) {
13500         if (IsBlock)
13501           S.Diag(Loc, diag::err_ref_flexarray_type);
13502         else
13503           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13504             << Var->getDeclName();
13505         S.Diag(Var->getLocation(), diag::note_previous_decl)
13506           << Var->getDeclName();
13507       }
13508       return false;
13509     }
13510   }
13511   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13512   // Lambdas and captured statements are not allowed to capture __block
13513   // variables; they don't support the expected semantics.
13514   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13515     if (Diagnose) {
13516       S.Diag(Loc, diag::err_capture_block_variable)
13517         << Var->getDeclName() << !IsLambda;
13518       S.Diag(Var->getLocation(), diag::note_previous_decl)
13519         << Var->getDeclName();
13520     }
13521     return false;
13522   }
13523 
13524   return true;
13525 }
13526 
13527 // Returns true if the capture by block was successful.
13528 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13529                                  SourceLocation Loc,
13530                                  const bool BuildAndDiagnose,
13531                                  QualType &CaptureType,
13532                                  QualType &DeclRefType,
13533                                  const bool Nested,
13534                                  Sema &S) {
13535   Expr *CopyExpr = nullptr;
13536   bool ByRef = false;
13537 
13538   // Blocks are not allowed to capture arrays.
13539   if (CaptureType->isArrayType()) {
13540     if (BuildAndDiagnose) {
13541       S.Diag(Loc, diag::err_ref_array_type);
13542       S.Diag(Var->getLocation(), diag::note_previous_decl)
13543       << Var->getDeclName();
13544     }
13545     return false;
13546   }
13547 
13548   // Forbid the block-capture of autoreleasing variables.
13549   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13550     if (BuildAndDiagnose) {
13551       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13552         << /*block*/ 0;
13553       S.Diag(Var->getLocation(), diag::note_previous_decl)
13554         << Var->getDeclName();
13555     }
13556     return false;
13557   }
13558 
13559   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13560   if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13561     QualType PointeeTy = PT->getPointeeType();
13562     if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13563         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13564         !isa<AttributedType>(PointeeTy)) {
13565       if (BuildAndDiagnose) {
13566         SourceLocation VarLoc = Var->getLocation();
13567         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13568         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13569             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13570         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13571       }
13572     }
13573   }
13574 
13575   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13576   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13577       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13578     // Block capture by reference does not change the capture or
13579     // declaration reference types.
13580     ByRef = true;
13581   } else {
13582     // Block capture by copy introduces 'const'.
13583     CaptureType = CaptureType.getNonReferenceType().withConst();
13584     DeclRefType = CaptureType;
13585 
13586     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13587       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13588         // The capture logic needs the destructor, so make sure we mark it.
13589         // Usually this is unnecessary because most local variables have
13590         // their destructors marked at declaration time, but parameters are
13591         // an exception because it's technically only the call site that
13592         // actually requires the destructor.
13593         if (isa<ParmVarDecl>(Var))
13594           S.FinalizeVarWithDestructor(Var, Record);
13595 
13596         // Enter a new evaluation context to insulate the copy
13597         // full-expression.
13598         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13599 
13600         // According to the blocks spec, the capture of a variable from
13601         // the stack requires a const copy constructor.  This is not true
13602         // of the copy/move done to move a __block variable to the heap.
13603         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13604                                                   DeclRefType.withConst(),
13605                                                   VK_LValue, Loc);
13606 
13607         ExprResult Result
13608           = S.PerformCopyInitialization(
13609               InitializedEntity::InitializeBlock(Var->getLocation(),
13610                                                   CaptureType, false),
13611               Loc, DeclRef);
13612 
13613         // Build a full-expression copy expression if initialization
13614         // succeeded and used a non-trivial constructor.  Recover from
13615         // errors by pretending that the copy isn't necessary.
13616         if (!Result.isInvalid() &&
13617             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13618                 ->isTrivial()) {
13619           Result = S.MaybeCreateExprWithCleanups(Result);
13620           CopyExpr = Result.get();
13621         }
13622       }
13623     }
13624   }
13625 
13626   // Actually capture the variable.
13627   if (BuildAndDiagnose)
13628     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13629                     SourceLocation(), CaptureType, CopyExpr);
13630 
13631   return true;
13632 
13633 }
13634 
13635 
13636 /// \brief Capture the given variable in the captured region.
13637 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13638                                     VarDecl *Var,
13639                                     SourceLocation Loc,
13640                                     const bool BuildAndDiagnose,
13641                                     QualType &CaptureType,
13642                                     QualType &DeclRefType,
13643                                     const bool RefersToCapturedVariable,
13644                                     Sema &S) {
13645   // By default, capture variables by reference.
13646   bool ByRef = true;
13647   // Using an LValue reference type is consistent with Lambdas (see below).
13648   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13649     if (S.IsOpenMPCapturedDecl(Var))
13650       DeclRefType = DeclRefType.getUnqualifiedType();
13651     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13652   }
13653 
13654   if (ByRef)
13655     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13656   else
13657     CaptureType = DeclRefType;
13658 
13659   Expr *CopyExpr = nullptr;
13660   if (BuildAndDiagnose) {
13661     // The current implementation assumes that all variables are captured
13662     // by references. Since there is no capture by copy, no expression
13663     // evaluation will be needed.
13664     RecordDecl *RD = RSI->TheRecordDecl;
13665 
13666     FieldDecl *Field
13667       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13668                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13669                           nullptr, false, ICIS_NoInit);
13670     Field->setImplicit(true);
13671     Field->setAccess(AS_private);
13672     RD->addDecl(Field);
13673 
13674     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13675                                             DeclRefType, VK_LValue, Loc);
13676     Var->setReferenced(true);
13677     Var->markUsed(S.Context);
13678   }
13679 
13680   // Actually capture the variable.
13681   if (BuildAndDiagnose)
13682     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13683                     SourceLocation(), CaptureType, CopyExpr);
13684 
13685 
13686   return true;
13687 }
13688 
13689 /// \brief Create a field within the lambda class for the variable
13690 /// being captured.
13691 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13692                                     QualType FieldType, QualType DeclRefType,
13693                                     SourceLocation Loc,
13694                                     bool RefersToCapturedVariable) {
13695   CXXRecordDecl *Lambda = LSI->Lambda;
13696 
13697   // Build the non-static data member.
13698   FieldDecl *Field
13699     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13700                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13701                         nullptr, false, ICIS_NoInit);
13702   Field->setImplicit(true);
13703   Field->setAccess(AS_private);
13704   Lambda->addDecl(Field);
13705 }
13706 
13707 /// \brief Capture the given variable in the lambda.
13708 static bool captureInLambda(LambdaScopeInfo *LSI,
13709                             VarDecl *Var,
13710                             SourceLocation Loc,
13711                             const bool BuildAndDiagnose,
13712                             QualType &CaptureType,
13713                             QualType &DeclRefType,
13714                             const bool RefersToCapturedVariable,
13715                             const Sema::TryCaptureKind Kind,
13716                             SourceLocation EllipsisLoc,
13717                             const bool IsTopScope,
13718                             Sema &S) {
13719 
13720   // Determine whether we are capturing by reference or by value.
13721   bool ByRef = false;
13722   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13723     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13724   } else {
13725     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13726   }
13727 
13728   // Compute the type of the field that will capture this variable.
13729   if (ByRef) {
13730     // C++11 [expr.prim.lambda]p15:
13731     //   An entity is captured by reference if it is implicitly or
13732     //   explicitly captured but not captured by copy. It is
13733     //   unspecified whether additional unnamed non-static data
13734     //   members are declared in the closure type for entities
13735     //   captured by reference.
13736     //
13737     // FIXME: It is not clear whether we want to build an lvalue reference
13738     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13739     // to do the former, while EDG does the latter. Core issue 1249 will
13740     // clarify, but for now we follow GCC because it's a more permissive and
13741     // easily defensible position.
13742     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13743   } else {
13744     // C++11 [expr.prim.lambda]p14:
13745     //   For each entity captured by copy, an unnamed non-static
13746     //   data member is declared in the closure type. The
13747     //   declaration order of these members is unspecified. The type
13748     //   of such a data member is the type of the corresponding
13749     //   captured entity if the entity is not a reference to an
13750     //   object, or the referenced type otherwise. [Note: If the
13751     //   captured entity is a reference to a function, the
13752     //   corresponding data member is also a reference to a
13753     //   function. - end note ]
13754     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13755       if (!RefType->getPointeeType()->isFunctionType())
13756         CaptureType = RefType->getPointeeType();
13757     }
13758 
13759     // Forbid the lambda copy-capture of autoreleasing variables.
13760     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13761       if (BuildAndDiagnose) {
13762         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13763         S.Diag(Var->getLocation(), diag::note_previous_decl)
13764           << Var->getDeclName();
13765       }
13766       return false;
13767     }
13768 
13769     // Make sure that by-copy captures are of a complete and non-abstract type.
13770     if (BuildAndDiagnose) {
13771       if (!CaptureType->isDependentType() &&
13772           S.RequireCompleteType(Loc, CaptureType,
13773                                 diag::err_capture_of_incomplete_type,
13774                                 Var->getDeclName()))
13775         return false;
13776 
13777       if (S.RequireNonAbstractType(Loc, CaptureType,
13778                                    diag::err_capture_of_abstract_type))
13779         return false;
13780     }
13781   }
13782 
13783   // Capture this variable in the lambda.
13784   if (BuildAndDiagnose)
13785     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13786                             RefersToCapturedVariable);
13787 
13788   // Compute the type of a reference to this captured variable.
13789   if (ByRef)
13790     DeclRefType = CaptureType.getNonReferenceType();
13791   else {
13792     // C++ [expr.prim.lambda]p5:
13793     //   The closure type for a lambda-expression has a public inline
13794     //   function call operator [...]. This function call operator is
13795     //   declared const (9.3.1) if and only if the lambda-expression's
13796     //   parameter-declaration-clause is not followed by mutable.
13797     DeclRefType = CaptureType.getNonReferenceType();
13798     if (!LSI->Mutable && !CaptureType->isReferenceType())
13799       DeclRefType.addConst();
13800   }
13801 
13802   // Add the capture.
13803   if (BuildAndDiagnose)
13804     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13805                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13806 
13807   return true;
13808 }
13809 
13810 bool Sema::tryCaptureVariable(
13811     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13812     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13813     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13814   // An init-capture is notionally from the context surrounding its
13815   // declaration, but its parent DC is the lambda class.
13816   DeclContext *VarDC = Var->getDeclContext();
13817   if (Var->isInitCapture())
13818     VarDC = VarDC->getParent();
13819 
13820   DeclContext *DC = CurContext;
13821   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13822       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13823   // We need to sync up the Declaration Context with the
13824   // FunctionScopeIndexToStopAt
13825   if (FunctionScopeIndexToStopAt) {
13826     unsigned FSIndex = FunctionScopes.size() - 1;
13827     while (FSIndex != MaxFunctionScopesIndex) {
13828       DC = getLambdaAwareParentOfDeclContext(DC);
13829       --FSIndex;
13830     }
13831   }
13832 
13833 
13834   // If the variable is declared in the current context, there is no need to
13835   // capture it.
13836   if (VarDC == DC) return true;
13837 
13838   // Capture global variables if it is required to use private copy of this
13839   // variable.
13840   bool IsGlobal = !Var->hasLocalStorage();
13841   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13842     return true;
13843 
13844   // Walk up the stack to determine whether we can capture the variable,
13845   // performing the "simple" checks that don't depend on type. We stop when
13846   // we've either hit the declared scope of the variable or find an existing
13847   // capture of that variable.  We start from the innermost capturing-entity
13848   // (the DC) and ensure that all intervening capturing-entities
13849   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13850   // declcontext can either capture the variable or have already captured
13851   // the variable.
13852   CaptureType = Var->getType();
13853   DeclRefType = CaptureType.getNonReferenceType();
13854   bool Nested = false;
13855   bool Explicit = (Kind != TryCapture_Implicit);
13856   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13857   do {
13858     // Only block literals, captured statements, and lambda expressions can
13859     // capture; other scopes don't work.
13860     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13861                                                               ExprLoc,
13862                                                               BuildAndDiagnose,
13863                                                               *this);
13864     // We need to check for the parent *first* because, if we *have*
13865     // private-captured a global variable, we need to recursively capture it in
13866     // intermediate blocks, lambdas, etc.
13867     if (!ParentDC) {
13868       if (IsGlobal) {
13869         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13870         break;
13871       }
13872       return true;
13873     }
13874 
13875     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13876     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13877 
13878 
13879     // Check whether we've already captured it.
13880     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13881                                              DeclRefType))
13882       break;
13883     // If we are instantiating a generic lambda call operator body,
13884     // we do not want to capture new variables.  What was captured
13885     // during either a lambdas transformation or initial parsing
13886     // should be used.
13887     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13888       if (BuildAndDiagnose) {
13889         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13890         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13891           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13892           Diag(Var->getLocation(), diag::note_previous_decl)
13893              << Var->getDeclName();
13894           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13895         } else
13896           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13897       }
13898       return true;
13899     }
13900     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13901     // certain types of variables (unnamed, variably modified types etc.)
13902     // so check for eligibility.
13903     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13904        return true;
13905 
13906     // Try to capture variable-length arrays types.
13907     if (Var->getType()->isVariablyModifiedType()) {
13908       // We're going to walk down into the type and look for VLA
13909       // expressions.
13910       QualType QTy = Var->getType();
13911       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13912         QTy = PVD->getOriginalType();
13913       captureVariablyModifiedType(Context, QTy, CSI);
13914     }
13915 
13916     if (getLangOpts().OpenMP) {
13917       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13918         // OpenMP private variables should not be captured in outer scope, so
13919         // just break here. Similarly, global variables that are captured in a
13920         // target region should not be captured outside the scope of the region.
13921         if (RSI->CapRegionKind == CR_OpenMP) {
13922           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13923           // When we detect target captures we are looking from inside the
13924           // target region, therefore we need to propagate the capture from the
13925           // enclosing region. Therefore, the capture is not initially nested.
13926           if (IsTargetCap)
13927             FunctionScopesIndex--;
13928 
13929           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13930             Nested = !IsTargetCap;
13931             DeclRefType = DeclRefType.getUnqualifiedType();
13932             CaptureType = Context.getLValueReferenceType(DeclRefType);
13933             break;
13934           }
13935         }
13936       }
13937     }
13938     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13939       // No capture-default, and this is not an explicit capture
13940       // so cannot capture this variable.
13941       if (BuildAndDiagnose) {
13942         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13943         Diag(Var->getLocation(), diag::note_previous_decl)
13944           << Var->getDeclName();
13945         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13946           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13947                diag::note_lambda_decl);
13948         // FIXME: If we error out because an outer lambda can not implicitly
13949         // capture a variable that an inner lambda explicitly captures, we
13950         // should have the inner lambda do the explicit capture - because
13951         // it makes for cleaner diagnostics later.  This would purely be done
13952         // so that the diagnostic does not misleadingly claim that a variable
13953         // can not be captured by a lambda implicitly even though it is captured
13954         // explicitly.  Suggestion:
13955         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13956         //    at the function head
13957         //  - cache the StartingDeclContext - this must be a lambda
13958         //  - captureInLambda in the innermost lambda the variable.
13959       }
13960       return true;
13961     }
13962 
13963     FunctionScopesIndex--;
13964     DC = ParentDC;
13965     Explicit = false;
13966   } while (!VarDC->Equals(DC));
13967 
13968   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13969   // computing the type of the capture at each step, checking type-specific
13970   // requirements, and adding captures if requested.
13971   // If the variable had already been captured previously, we start capturing
13972   // at the lambda nested within that one.
13973   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13974        ++I) {
13975     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13976 
13977     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13978       if (!captureInBlock(BSI, Var, ExprLoc,
13979                           BuildAndDiagnose, CaptureType,
13980                           DeclRefType, Nested, *this))
13981         return true;
13982       Nested = true;
13983     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13984       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13985                                    BuildAndDiagnose, CaptureType,
13986                                    DeclRefType, Nested, *this))
13987         return true;
13988       Nested = true;
13989     } else {
13990       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13991       if (!captureInLambda(LSI, Var, ExprLoc,
13992                            BuildAndDiagnose, CaptureType,
13993                            DeclRefType, Nested, Kind, EllipsisLoc,
13994                             /*IsTopScope*/I == N - 1, *this))
13995         return true;
13996       Nested = true;
13997     }
13998   }
13999   return false;
14000 }
14001 
14002 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14003                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14004   QualType CaptureType;
14005   QualType DeclRefType;
14006   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14007                             /*BuildAndDiagnose=*/true, CaptureType,
14008                             DeclRefType, nullptr);
14009 }
14010 
14011 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14012   QualType CaptureType;
14013   QualType DeclRefType;
14014   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14015                              /*BuildAndDiagnose=*/false, CaptureType,
14016                              DeclRefType, nullptr);
14017 }
14018 
14019 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14020   QualType CaptureType;
14021   QualType DeclRefType;
14022 
14023   // Determine whether we can capture this variable.
14024   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14025                          /*BuildAndDiagnose=*/false, CaptureType,
14026                          DeclRefType, nullptr))
14027     return QualType();
14028 
14029   return DeclRefType;
14030 }
14031 
14032 
14033 
14034 // If either the type of the variable or the initializer is dependent,
14035 // return false. Otherwise, determine whether the variable is a constant
14036 // expression. Use this if you need to know if a variable that might or
14037 // might not be dependent is truly a constant expression.
14038 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14039     ASTContext &Context) {
14040 
14041   if (Var->getType()->isDependentType())
14042     return false;
14043   const VarDecl *DefVD = nullptr;
14044   Var->getAnyInitializer(DefVD);
14045   if (!DefVD)
14046     return false;
14047   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14048   Expr *Init = cast<Expr>(Eval->Value);
14049   if (Init->isValueDependent())
14050     return false;
14051   return IsVariableAConstantExpression(Var, Context);
14052 }
14053 
14054 
14055 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14056   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14057   // an object that satisfies the requirements for appearing in a
14058   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14059   // is immediately applied."  This function handles the lvalue-to-rvalue
14060   // conversion part.
14061   MaybeODRUseExprs.erase(E->IgnoreParens());
14062 
14063   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14064   // to a variable that is a constant expression, and if so, identify it as
14065   // a reference to a variable that does not involve an odr-use of that
14066   // variable.
14067   if (LambdaScopeInfo *LSI = getCurLambda()) {
14068     Expr *SansParensExpr = E->IgnoreParens();
14069     VarDecl *Var = nullptr;
14070     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14071       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14072     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14073       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14074 
14075     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14076       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14077   }
14078 }
14079 
14080 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14081   Res = CorrectDelayedTyposInExpr(Res);
14082 
14083   if (!Res.isUsable())
14084     return Res;
14085 
14086   // If a constant-expression is a reference to a variable where we delay
14087   // deciding whether it is an odr-use, just assume we will apply the
14088   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14089   // (a non-type template argument), we have special handling anyway.
14090   UpdateMarkingForLValueToRValue(Res.get());
14091   return Res;
14092 }
14093 
14094 void Sema::CleanupVarDeclMarking() {
14095   for (Expr *E : MaybeODRUseExprs) {
14096     VarDecl *Var;
14097     SourceLocation Loc;
14098     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14099       Var = cast<VarDecl>(DRE->getDecl());
14100       Loc = DRE->getLocation();
14101     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14102       Var = cast<VarDecl>(ME->getMemberDecl());
14103       Loc = ME->getMemberLoc();
14104     } else {
14105       llvm_unreachable("Unexpected expression");
14106     }
14107 
14108     MarkVarDeclODRUsed(Var, Loc, *this,
14109                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14110   }
14111 
14112   MaybeODRUseExprs.clear();
14113 }
14114 
14115 
14116 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14117                                     VarDecl *Var, Expr *E) {
14118   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14119          "Invalid Expr argument to DoMarkVarDeclReferenced");
14120   Var->setReferenced();
14121 
14122   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14123   bool MarkODRUsed = true;
14124 
14125   // If the context is not potentially evaluated, this is not an odr-use and
14126   // does not trigger instantiation.
14127   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
14128     if (SemaRef.isUnevaluatedContext())
14129       return;
14130 
14131     // If we don't yet know whether this context is going to end up being an
14132     // evaluated context, and we're referencing a variable from an enclosing
14133     // scope, add a potential capture.
14134     //
14135     // FIXME: Is this necessary? These contexts are only used for default
14136     // arguments, where local variables can't be used.
14137     const bool RefersToEnclosingScope =
14138         (SemaRef.CurContext != Var->getDeclContext() &&
14139          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14140     if (RefersToEnclosingScope) {
14141       if (LambdaScopeInfo *const LSI =
14142               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14143         // If a variable could potentially be odr-used, defer marking it so
14144         // until we finish analyzing the full expression for any
14145         // lvalue-to-rvalue
14146         // or discarded value conversions that would obviate odr-use.
14147         // Add it to the list of potential captures that will be analyzed
14148         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14149         // unless the variable is a reference that was initialized by a constant
14150         // expression (this will never need to be captured or odr-used).
14151         assert(E && "Capture variable should be used in an expression.");
14152         if (!Var->getType()->isReferenceType() ||
14153             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14154           LSI->addPotentialCapture(E->IgnoreParens());
14155       }
14156     }
14157 
14158     if (!isTemplateInstantiation(TSK))
14159       return;
14160 
14161     // Instantiate, but do not mark as odr-used, variable templates.
14162     MarkODRUsed = false;
14163   }
14164 
14165   VarTemplateSpecializationDecl *VarSpec =
14166       dyn_cast<VarTemplateSpecializationDecl>(Var);
14167   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14168          "Can't instantiate a partial template specialization.");
14169 
14170   // If this might be a member specialization of a static data member, check
14171   // the specialization is visible. We already did the checks for variable
14172   // template specializations when we created them.
14173   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14174     SemaRef.checkSpecializationVisibility(Loc, Var);
14175 
14176   // Perform implicit instantiation of static data members, static data member
14177   // templates of class templates, and variable template specializations. Delay
14178   // instantiations of variable templates, except for those that could be used
14179   // in a constant expression.
14180   if (isTemplateInstantiation(TSK)) {
14181     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14182 
14183     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14184       if (Var->getPointOfInstantiation().isInvalid()) {
14185         // This is a modification of an existing AST node. Notify listeners.
14186         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14187           L->StaticDataMemberInstantiated(Var);
14188       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14189         // Don't bother trying to instantiate it again, unless we might need
14190         // its initializer before we get to the end of the TU.
14191         TryInstantiating = false;
14192     }
14193 
14194     if (Var->getPointOfInstantiation().isInvalid())
14195       Var->setTemplateSpecializationKind(TSK, Loc);
14196 
14197     if (TryInstantiating) {
14198       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14199       bool InstantiationDependent = false;
14200       bool IsNonDependent =
14201           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14202                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14203                   : true;
14204 
14205       // Do not instantiate specializations that are still type-dependent.
14206       if (IsNonDependent) {
14207         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14208           // Do not defer instantiations of variables which could be used in a
14209           // constant expression.
14210           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14211         } else {
14212           SemaRef.PendingInstantiations
14213               .push_back(std::make_pair(Var, PointOfInstantiation));
14214         }
14215       }
14216     }
14217   }
14218 
14219   if (!MarkODRUsed)
14220     return;
14221 
14222   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14223   // the requirements for appearing in a constant expression (5.19) and, if
14224   // it is an object, the lvalue-to-rvalue conversion (4.1)
14225   // is immediately applied."  We check the first part here, and
14226   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14227   // Note that we use the C++11 definition everywhere because nothing in
14228   // C++03 depends on whether we get the C++03 version correct. The second
14229   // part does not apply to references, since they are not objects.
14230   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14231     // A reference initialized by a constant expression can never be
14232     // odr-used, so simply ignore it.
14233     if (!Var->getType()->isReferenceType())
14234       SemaRef.MaybeODRUseExprs.insert(E);
14235   } else
14236     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14237                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14238 }
14239 
14240 /// \brief Mark a variable referenced, and check whether it is odr-used
14241 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14242 /// used directly for normal expressions referring to VarDecl.
14243 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14244   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14245 }
14246 
14247 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14248                                Decl *D, Expr *E, bool MightBeOdrUse) {
14249   if (SemaRef.isInOpenMPDeclareTargetContext())
14250     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14251 
14252   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14253     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14254     return;
14255   }
14256 
14257   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14258 
14259   // If this is a call to a method via a cast, also mark the method in the
14260   // derived class used in case codegen can devirtualize the call.
14261   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14262   if (!ME)
14263     return;
14264   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14265   if (!MD)
14266     return;
14267   // Only attempt to devirtualize if this is truly a virtual call.
14268   bool IsVirtualCall = MD->isVirtual() &&
14269                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14270   if (!IsVirtualCall)
14271     return;
14272   const Expr *Base = ME->getBase();
14273   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14274   if (!MostDerivedClassDecl)
14275     return;
14276   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14277   if (!DM || DM->isPure())
14278     return;
14279   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14280 }
14281 
14282 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14283 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14284   // TODO: update this with DR# once a defect report is filed.
14285   // C++11 defect. The address of a pure member should not be an ODR use, even
14286   // if it's a qualified reference.
14287   bool OdrUse = true;
14288   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14289     if (Method->isVirtual())
14290       OdrUse = false;
14291   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14292 }
14293 
14294 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14295 void Sema::MarkMemberReferenced(MemberExpr *E) {
14296   // C++11 [basic.def.odr]p2:
14297   //   A non-overloaded function whose name appears as a potentially-evaluated
14298   //   expression or a member of a set of candidate functions, if selected by
14299   //   overload resolution when referred to from a potentially-evaluated
14300   //   expression, is odr-used, unless it is a pure virtual function and its
14301   //   name is not explicitly qualified.
14302   bool MightBeOdrUse = true;
14303   if (E->performsVirtualDispatch(getLangOpts())) {
14304     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14305       if (Method->isPure())
14306         MightBeOdrUse = false;
14307   }
14308   SourceLocation Loc = E->getMemberLoc().isValid() ?
14309                             E->getMemberLoc() : E->getLocStart();
14310   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14311 }
14312 
14313 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14314 /// marks the declaration referenced, and performs odr-use checking for
14315 /// functions and variables. This method should not be used when building a
14316 /// normal expression which refers to a variable.
14317 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14318                                  bool MightBeOdrUse) {
14319   if (MightBeOdrUse) {
14320     if (auto *VD = dyn_cast<VarDecl>(D)) {
14321       MarkVariableReferenced(Loc, VD);
14322       return;
14323     }
14324   }
14325   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14326     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14327     return;
14328   }
14329   D->setReferenced();
14330 }
14331 
14332 namespace {
14333   // Mark all of the declarations referenced
14334   // FIXME: Not fully implemented yet! We need to have a better understanding
14335   // of when we're entering
14336   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14337     Sema &S;
14338     SourceLocation Loc;
14339 
14340   public:
14341     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14342 
14343     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14344 
14345     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14346     bool TraverseRecordType(RecordType *T);
14347   };
14348 }
14349 
14350 bool MarkReferencedDecls::TraverseTemplateArgument(
14351     const TemplateArgument &Arg) {
14352   if (Arg.getKind() == TemplateArgument::Declaration) {
14353     if (Decl *D = Arg.getAsDecl())
14354       S.MarkAnyDeclReferenced(Loc, D, true);
14355   }
14356 
14357   return Inherited::TraverseTemplateArgument(Arg);
14358 }
14359 
14360 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14361   if (ClassTemplateSpecializationDecl *Spec
14362                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14363     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14364     return TraverseTemplateArguments(Args.data(), Args.size());
14365   }
14366 
14367   return true;
14368 }
14369 
14370 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14371   MarkReferencedDecls Marker(*this, Loc);
14372   Marker.TraverseType(Context.getCanonicalType(T));
14373 }
14374 
14375 namespace {
14376   /// \brief Helper class that marks all of the declarations referenced by
14377   /// potentially-evaluated subexpressions as "referenced".
14378   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14379     Sema &S;
14380     bool SkipLocalVariables;
14381 
14382   public:
14383     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14384 
14385     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14386       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14387 
14388     void VisitDeclRefExpr(DeclRefExpr *E) {
14389       // If we were asked not to visit local variables, don't.
14390       if (SkipLocalVariables) {
14391         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14392           if (VD->hasLocalStorage())
14393             return;
14394       }
14395 
14396       S.MarkDeclRefReferenced(E);
14397     }
14398 
14399     void VisitMemberExpr(MemberExpr *E) {
14400       S.MarkMemberReferenced(E);
14401       Inherited::VisitMemberExpr(E);
14402     }
14403 
14404     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14405       S.MarkFunctionReferenced(E->getLocStart(),
14406             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14407       Visit(E->getSubExpr());
14408     }
14409 
14410     void VisitCXXNewExpr(CXXNewExpr *E) {
14411       if (E->getOperatorNew())
14412         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14413       if (E->getOperatorDelete())
14414         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14415       Inherited::VisitCXXNewExpr(E);
14416     }
14417 
14418     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14419       if (E->getOperatorDelete())
14420         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14421       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14422       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14423         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14424         S.MarkFunctionReferenced(E->getLocStart(),
14425                                     S.LookupDestructor(Record));
14426       }
14427 
14428       Inherited::VisitCXXDeleteExpr(E);
14429     }
14430 
14431     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14432       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14433       Inherited::VisitCXXConstructExpr(E);
14434     }
14435 
14436     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14437       Visit(E->getExpr());
14438     }
14439 
14440     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14441       Inherited::VisitImplicitCastExpr(E);
14442 
14443       if (E->getCastKind() == CK_LValueToRValue)
14444         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14445     }
14446   };
14447 }
14448 
14449 /// \brief Mark any declarations that appear within this expression or any
14450 /// potentially-evaluated subexpressions as "referenced".
14451 ///
14452 /// \param SkipLocalVariables If true, don't mark local variables as
14453 /// 'referenced'.
14454 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14455                                             bool SkipLocalVariables) {
14456   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14457 }
14458 
14459 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14460 /// of the program being compiled.
14461 ///
14462 /// This routine emits the given diagnostic when the code currently being
14463 /// type-checked is "potentially evaluated", meaning that there is a
14464 /// possibility that the code will actually be executable. Code in sizeof()
14465 /// expressions, code used only during overload resolution, etc., are not
14466 /// potentially evaluated. This routine will suppress such diagnostics or,
14467 /// in the absolutely nutty case of potentially potentially evaluated
14468 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14469 /// later.
14470 ///
14471 /// This routine should be used for all diagnostics that describe the run-time
14472 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14473 /// Failure to do so will likely result in spurious diagnostics or failures
14474 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14475 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14476                                const PartialDiagnostic &PD) {
14477   switch (ExprEvalContexts.back().Context) {
14478   case Unevaluated:
14479   case UnevaluatedAbstract:
14480   case DiscardedStatement:
14481     // The argument will never be evaluated, so don't complain.
14482     break;
14483 
14484   case ConstantEvaluated:
14485     // Relevant diagnostics should be produced by constant evaluation.
14486     break;
14487 
14488   case PotentiallyEvaluated:
14489   case PotentiallyEvaluatedIfUsed:
14490     if (Statement && getCurFunctionOrMethodDecl()) {
14491       FunctionScopes.back()->PossiblyUnreachableDiags.
14492         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14493     }
14494     else
14495       Diag(Loc, PD);
14496 
14497     return true;
14498   }
14499 
14500   return false;
14501 }
14502 
14503 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14504                                CallExpr *CE, FunctionDecl *FD) {
14505   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14506     return false;
14507 
14508   // If we're inside a decltype's expression, don't check for a valid return
14509   // type or construct temporaries until we know whether this is the last call.
14510   if (ExprEvalContexts.back().IsDecltype) {
14511     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14512     return false;
14513   }
14514 
14515   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14516     FunctionDecl *FD;
14517     CallExpr *CE;
14518 
14519   public:
14520     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14521       : FD(FD), CE(CE) { }
14522 
14523     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14524       if (!FD) {
14525         S.Diag(Loc, diag::err_call_incomplete_return)
14526           << T << CE->getSourceRange();
14527         return;
14528       }
14529 
14530       S.Diag(Loc, diag::err_call_function_incomplete_return)
14531         << CE->getSourceRange() << FD->getDeclName() << T;
14532       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14533           << FD->getDeclName();
14534     }
14535   } Diagnoser(FD, CE);
14536 
14537   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14538     return true;
14539 
14540   return false;
14541 }
14542 
14543 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14544 // will prevent this condition from triggering, which is what we want.
14545 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14546   SourceLocation Loc;
14547 
14548   unsigned diagnostic = diag::warn_condition_is_assignment;
14549   bool IsOrAssign = false;
14550 
14551   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14552     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14553       return;
14554 
14555     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14556 
14557     // Greylist some idioms by putting them into a warning subcategory.
14558     if (ObjCMessageExpr *ME
14559           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14560       Selector Sel = ME->getSelector();
14561 
14562       // self = [<foo> init...]
14563       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14564         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14565 
14566       // <foo> = [<bar> nextObject]
14567       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14568         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14569     }
14570 
14571     Loc = Op->getOperatorLoc();
14572   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14573     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14574       return;
14575 
14576     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14577     Loc = Op->getOperatorLoc();
14578   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14579     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14580   else {
14581     // Not an assignment.
14582     return;
14583   }
14584 
14585   Diag(Loc, diagnostic) << E->getSourceRange();
14586 
14587   SourceLocation Open = E->getLocStart();
14588   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14589   Diag(Loc, diag::note_condition_assign_silence)
14590         << FixItHint::CreateInsertion(Open, "(")
14591         << FixItHint::CreateInsertion(Close, ")");
14592 
14593   if (IsOrAssign)
14594     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14595       << FixItHint::CreateReplacement(Loc, "!=");
14596   else
14597     Diag(Loc, diag::note_condition_assign_to_comparison)
14598       << FixItHint::CreateReplacement(Loc, "==");
14599 }
14600 
14601 /// \brief Redundant parentheses over an equality comparison can indicate
14602 /// that the user intended an assignment used as condition.
14603 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14604   // Don't warn if the parens came from a macro.
14605   SourceLocation parenLoc = ParenE->getLocStart();
14606   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14607     return;
14608   // Don't warn for dependent expressions.
14609   if (ParenE->isTypeDependent())
14610     return;
14611 
14612   Expr *E = ParenE->IgnoreParens();
14613 
14614   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14615     if (opE->getOpcode() == BO_EQ &&
14616         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14617                                                            == Expr::MLV_Valid) {
14618       SourceLocation Loc = opE->getOperatorLoc();
14619 
14620       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14621       SourceRange ParenERange = ParenE->getSourceRange();
14622       Diag(Loc, diag::note_equality_comparison_silence)
14623         << FixItHint::CreateRemoval(ParenERange.getBegin())
14624         << FixItHint::CreateRemoval(ParenERange.getEnd());
14625       Diag(Loc, diag::note_equality_comparison_to_assign)
14626         << FixItHint::CreateReplacement(Loc, "=");
14627     }
14628 }
14629 
14630 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14631                                        bool IsConstexpr) {
14632   DiagnoseAssignmentAsCondition(E);
14633   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14634     DiagnoseEqualityWithExtraParens(parenE);
14635 
14636   ExprResult result = CheckPlaceholderExpr(E);
14637   if (result.isInvalid()) return ExprError();
14638   E = result.get();
14639 
14640   if (!E->isTypeDependent()) {
14641     if (getLangOpts().CPlusPlus)
14642       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14643 
14644     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14645     if (ERes.isInvalid())
14646       return ExprError();
14647     E = ERes.get();
14648 
14649     QualType T = E->getType();
14650     if (!T->isScalarType()) { // C99 6.8.4.1p1
14651       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14652         << T << E->getSourceRange();
14653       return ExprError();
14654     }
14655     CheckBoolLikeConversion(E, Loc);
14656   }
14657 
14658   return E;
14659 }
14660 
14661 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14662                                            Expr *SubExpr, ConditionKind CK) {
14663   // Empty conditions are valid in for-statements.
14664   if (!SubExpr)
14665     return ConditionResult();
14666 
14667   ExprResult Cond;
14668   switch (CK) {
14669   case ConditionKind::Boolean:
14670     Cond = CheckBooleanCondition(Loc, SubExpr);
14671     break;
14672 
14673   case ConditionKind::ConstexprIf:
14674     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14675     break;
14676 
14677   case ConditionKind::Switch:
14678     Cond = CheckSwitchCondition(Loc, SubExpr);
14679     break;
14680   }
14681   if (Cond.isInvalid())
14682     return ConditionError();
14683 
14684   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14685   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14686   if (!FullExpr.get())
14687     return ConditionError();
14688 
14689   return ConditionResult(*this, nullptr, FullExpr,
14690                          CK == ConditionKind::ConstexprIf);
14691 }
14692 
14693 namespace {
14694   /// A visitor for rebuilding a call to an __unknown_any expression
14695   /// to have an appropriate type.
14696   struct RebuildUnknownAnyFunction
14697     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14698 
14699     Sema &S;
14700 
14701     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14702 
14703     ExprResult VisitStmt(Stmt *S) {
14704       llvm_unreachable("unexpected statement!");
14705     }
14706 
14707     ExprResult VisitExpr(Expr *E) {
14708       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14709         << E->getSourceRange();
14710       return ExprError();
14711     }
14712 
14713     /// Rebuild an expression which simply semantically wraps another
14714     /// expression which it shares the type and value kind of.
14715     template <class T> ExprResult rebuildSugarExpr(T *E) {
14716       ExprResult SubResult = Visit(E->getSubExpr());
14717       if (SubResult.isInvalid()) return ExprError();
14718 
14719       Expr *SubExpr = SubResult.get();
14720       E->setSubExpr(SubExpr);
14721       E->setType(SubExpr->getType());
14722       E->setValueKind(SubExpr->getValueKind());
14723       assert(E->getObjectKind() == OK_Ordinary);
14724       return E;
14725     }
14726 
14727     ExprResult VisitParenExpr(ParenExpr *E) {
14728       return rebuildSugarExpr(E);
14729     }
14730 
14731     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14732       return rebuildSugarExpr(E);
14733     }
14734 
14735     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14736       ExprResult SubResult = Visit(E->getSubExpr());
14737       if (SubResult.isInvalid()) return ExprError();
14738 
14739       Expr *SubExpr = SubResult.get();
14740       E->setSubExpr(SubExpr);
14741       E->setType(S.Context.getPointerType(SubExpr->getType()));
14742       assert(E->getValueKind() == VK_RValue);
14743       assert(E->getObjectKind() == OK_Ordinary);
14744       return E;
14745     }
14746 
14747     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14748       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14749 
14750       E->setType(VD->getType());
14751 
14752       assert(E->getValueKind() == VK_RValue);
14753       if (S.getLangOpts().CPlusPlus &&
14754           !(isa<CXXMethodDecl>(VD) &&
14755             cast<CXXMethodDecl>(VD)->isInstance()))
14756         E->setValueKind(VK_LValue);
14757 
14758       return E;
14759     }
14760 
14761     ExprResult VisitMemberExpr(MemberExpr *E) {
14762       return resolveDecl(E, E->getMemberDecl());
14763     }
14764 
14765     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14766       return resolveDecl(E, E->getDecl());
14767     }
14768   };
14769 }
14770 
14771 /// Given a function expression of unknown-any type, try to rebuild it
14772 /// to have a function type.
14773 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14774   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14775   if (Result.isInvalid()) return ExprError();
14776   return S.DefaultFunctionArrayConversion(Result.get());
14777 }
14778 
14779 namespace {
14780   /// A visitor for rebuilding an expression of type __unknown_anytype
14781   /// into one which resolves the type directly on the referring
14782   /// expression.  Strict preservation of the original source
14783   /// structure is not a goal.
14784   struct RebuildUnknownAnyExpr
14785     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14786 
14787     Sema &S;
14788 
14789     /// The current destination type.
14790     QualType DestType;
14791 
14792     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14793       : S(S), DestType(CastType) {}
14794 
14795     ExprResult VisitStmt(Stmt *S) {
14796       llvm_unreachable("unexpected statement!");
14797     }
14798 
14799     ExprResult VisitExpr(Expr *E) {
14800       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14801         << E->getSourceRange();
14802       return ExprError();
14803     }
14804 
14805     ExprResult VisitCallExpr(CallExpr *E);
14806     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14807 
14808     /// Rebuild an expression which simply semantically wraps another
14809     /// expression which it shares the type and value kind of.
14810     template <class T> ExprResult rebuildSugarExpr(T *E) {
14811       ExprResult SubResult = Visit(E->getSubExpr());
14812       if (SubResult.isInvalid()) return ExprError();
14813       Expr *SubExpr = SubResult.get();
14814       E->setSubExpr(SubExpr);
14815       E->setType(SubExpr->getType());
14816       E->setValueKind(SubExpr->getValueKind());
14817       assert(E->getObjectKind() == OK_Ordinary);
14818       return E;
14819     }
14820 
14821     ExprResult VisitParenExpr(ParenExpr *E) {
14822       return rebuildSugarExpr(E);
14823     }
14824 
14825     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14826       return rebuildSugarExpr(E);
14827     }
14828 
14829     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14830       const PointerType *Ptr = DestType->getAs<PointerType>();
14831       if (!Ptr) {
14832         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14833           << E->getSourceRange();
14834         return ExprError();
14835       }
14836 
14837       if (isa<CallExpr>(E->getSubExpr())) {
14838         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14839           << E->getSourceRange();
14840         return ExprError();
14841       }
14842 
14843       assert(E->getValueKind() == VK_RValue);
14844       assert(E->getObjectKind() == OK_Ordinary);
14845       E->setType(DestType);
14846 
14847       // Build the sub-expression as if it were an object of the pointee type.
14848       DestType = Ptr->getPointeeType();
14849       ExprResult SubResult = Visit(E->getSubExpr());
14850       if (SubResult.isInvalid()) return ExprError();
14851       E->setSubExpr(SubResult.get());
14852       return E;
14853     }
14854 
14855     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14856 
14857     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14858 
14859     ExprResult VisitMemberExpr(MemberExpr *E) {
14860       return resolveDecl(E, E->getMemberDecl());
14861     }
14862 
14863     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14864       return resolveDecl(E, E->getDecl());
14865     }
14866   };
14867 }
14868 
14869 /// Rebuilds a call expression which yielded __unknown_anytype.
14870 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14871   Expr *CalleeExpr = E->getCallee();
14872 
14873   enum FnKind {
14874     FK_MemberFunction,
14875     FK_FunctionPointer,
14876     FK_BlockPointer
14877   };
14878 
14879   FnKind Kind;
14880   QualType CalleeType = CalleeExpr->getType();
14881   if (CalleeType == S.Context.BoundMemberTy) {
14882     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14883     Kind = FK_MemberFunction;
14884     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14885   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14886     CalleeType = Ptr->getPointeeType();
14887     Kind = FK_FunctionPointer;
14888   } else {
14889     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14890     Kind = FK_BlockPointer;
14891   }
14892   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14893 
14894   // Verify that this is a legal result type of a function.
14895   if (DestType->isArrayType() || DestType->isFunctionType()) {
14896     unsigned diagID = diag::err_func_returning_array_function;
14897     if (Kind == FK_BlockPointer)
14898       diagID = diag::err_block_returning_array_function;
14899 
14900     S.Diag(E->getExprLoc(), diagID)
14901       << DestType->isFunctionType() << DestType;
14902     return ExprError();
14903   }
14904 
14905   // Otherwise, go ahead and set DestType as the call's result.
14906   E->setType(DestType.getNonLValueExprType(S.Context));
14907   E->setValueKind(Expr::getValueKindForType(DestType));
14908   assert(E->getObjectKind() == OK_Ordinary);
14909 
14910   // Rebuild the function type, replacing the result type with DestType.
14911   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14912   if (Proto) {
14913     // __unknown_anytype(...) is a special case used by the debugger when
14914     // it has no idea what a function's signature is.
14915     //
14916     // We want to build this call essentially under the K&R
14917     // unprototyped rules, but making a FunctionNoProtoType in C++
14918     // would foul up all sorts of assumptions.  However, we cannot
14919     // simply pass all arguments as variadic arguments, nor can we
14920     // portably just call the function under a non-variadic type; see
14921     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14922     // However, it turns out that in practice it is generally safe to
14923     // call a function declared as "A foo(B,C,D);" under the prototype
14924     // "A foo(B,C,D,...);".  The only known exception is with the
14925     // Windows ABI, where any variadic function is implicitly cdecl
14926     // regardless of its normal CC.  Therefore we change the parameter
14927     // types to match the types of the arguments.
14928     //
14929     // This is a hack, but it is far superior to moving the
14930     // corresponding target-specific code from IR-gen to Sema/AST.
14931 
14932     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14933     SmallVector<QualType, 8> ArgTypes;
14934     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14935       ArgTypes.reserve(E->getNumArgs());
14936       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14937         Expr *Arg = E->getArg(i);
14938         QualType ArgType = Arg->getType();
14939         if (E->isLValue()) {
14940           ArgType = S.Context.getLValueReferenceType(ArgType);
14941         } else if (E->isXValue()) {
14942           ArgType = S.Context.getRValueReferenceType(ArgType);
14943         }
14944         ArgTypes.push_back(ArgType);
14945       }
14946       ParamTypes = ArgTypes;
14947     }
14948     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14949                                          Proto->getExtProtoInfo());
14950   } else {
14951     DestType = S.Context.getFunctionNoProtoType(DestType,
14952                                                 FnType->getExtInfo());
14953   }
14954 
14955   // Rebuild the appropriate pointer-to-function type.
14956   switch (Kind) {
14957   case FK_MemberFunction:
14958     // Nothing to do.
14959     break;
14960 
14961   case FK_FunctionPointer:
14962     DestType = S.Context.getPointerType(DestType);
14963     break;
14964 
14965   case FK_BlockPointer:
14966     DestType = S.Context.getBlockPointerType(DestType);
14967     break;
14968   }
14969 
14970   // Finally, we can recurse.
14971   ExprResult CalleeResult = Visit(CalleeExpr);
14972   if (!CalleeResult.isUsable()) return ExprError();
14973   E->setCallee(CalleeResult.get());
14974 
14975   // Bind a temporary if necessary.
14976   return S.MaybeBindToTemporary(E);
14977 }
14978 
14979 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14980   // Verify that this is a legal result type of a call.
14981   if (DestType->isArrayType() || DestType->isFunctionType()) {
14982     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14983       << DestType->isFunctionType() << DestType;
14984     return ExprError();
14985   }
14986 
14987   // Rewrite the method result type if available.
14988   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14989     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14990     Method->setReturnType(DestType);
14991   }
14992 
14993   // Change the type of the message.
14994   E->setType(DestType.getNonReferenceType());
14995   E->setValueKind(Expr::getValueKindForType(DestType));
14996 
14997   return S.MaybeBindToTemporary(E);
14998 }
14999 
15000 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15001   // The only case we should ever see here is a function-to-pointer decay.
15002   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15003     assert(E->getValueKind() == VK_RValue);
15004     assert(E->getObjectKind() == OK_Ordinary);
15005 
15006     E->setType(DestType);
15007 
15008     // Rebuild the sub-expression as the pointee (function) type.
15009     DestType = DestType->castAs<PointerType>()->getPointeeType();
15010 
15011     ExprResult Result = Visit(E->getSubExpr());
15012     if (!Result.isUsable()) return ExprError();
15013 
15014     E->setSubExpr(Result.get());
15015     return E;
15016   } else if (E->getCastKind() == CK_LValueToRValue) {
15017     assert(E->getValueKind() == VK_RValue);
15018     assert(E->getObjectKind() == OK_Ordinary);
15019 
15020     assert(isa<BlockPointerType>(E->getType()));
15021 
15022     E->setType(DestType);
15023 
15024     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15025     DestType = S.Context.getLValueReferenceType(DestType);
15026 
15027     ExprResult Result = Visit(E->getSubExpr());
15028     if (!Result.isUsable()) return ExprError();
15029 
15030     E->setSubExpr(Result.get());
15031     return E;
15032   } else {
15033     llvm_unreachable("Unhandled cast type!");
15034   }
15035 }
15036 
15037 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15038   ExprValueKind ValueKind = VK_LValue;
15039   QualType Type = DestType;
15040 
15041   // We know how to make this work for certain kinds of decls:
15042 
15043   //  - functions
15044   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15045     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15046       DestType = Ptr->getPointeeType();
15047       ExprResult Result = resolveDecl(E, VD);
15048       if (Result.isInvalid()) return ExprError();
15049       return S.ImpCastExprToType(Result.get(), Type,
15050                                  CK_FunctionToPointerDecay, VK_RValue);
15051     }
15052 
15053     if (!Type->isFunctionType()) {
15054       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15055         << VD << E->getSourceRange();
15056       return ExprError();
15057     }
15058     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15059       // We must match the FunctionDecl's type to the hack introduced in
15060       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15061       // type. See the lengthy commentary in that routine.
15062       QualType FDT = FD->getType();
15063       const FunctionType *FnType = FDT->castAs<FunctionType>();
15064       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15065       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15066       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15067         SourceLocation Loc = FD->getLocation();
15068         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15069                                       FD->getDeclContext(),
15070                                       Loc, Loc, FD->getNameInfo().getName(),
15071                                       DestType, FD->getTypeSourceInfo(),
15072                                       SC_None, false/*isInlineSpecified*/,
15073                                       FD->hasPrototype(),
15074                                       false/*isConstexprSpecified*/);
15075 
15076         if (FD->getQualifier())
15077           NewFD->setQualifierInfo(FD->getQualifierLoc());
15078 
15079         SmallVector<ParmVarDecl*, 16> Params;
15080         for (const auto &AI : FT->param_types()) {
15081           ParmVarDecl *Param =
15082             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15083           Param->setScopeInfo(0, Params.size());
15084           Params.push_back(Param);
15085         }
15086         NewFD->setParams(Params);
15087         DRE->setDecl(NewFD);
15088         VD = DRE->getDecl();
15089       }
15090     }
15091 
15092     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15093       if (MD->isInstance()) {
15094         ValueKind = VK_RValue;
15095         Type = S.Context.BoundMemberTy;
15096       }
15097 
15098     // Function references aren't l-values in C.
15099     if (!S.getLangOpts().CPlusPlus)
15100       ValueKind = VK_RValue;
15101 
15102   //  - variables
15103   } else if (isa<VarDecl>(VD)) {
15104     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15105       Type = RefTy->getPointeeType();
15106     } else if (Type->isFunctionType()) {
15107       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15108         << VD << E->getSourceRange();
15109       return ExprError();
15110     }
15111 
15112   //  - nothing else
15113   } else {
15114     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15115       << VD << E->getSourceRange();
15116     return ExprError();
15117   }
15118 
15119   // Modifying the declaration like this is friendly to IR-gen but
15120   // also really dangerous.
15121   VD->setType(DestType);
15122   E->setType(Type);
15123   E->setValueKind(ValueKind);
15124   return E;
15125 }
15126 
15127 /// Check a cast of an unknown-any type.  We intentionally only
15128 /// trigger this for C-style casts.
15129 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15130                                      Expr *CastExpr, CastKind &CastKind,
15131                                      ExprValueKind &VK, CXXCastPath &Path) {
15132   // The type we're casting to must be either void or complete.
15133   if (!CastType->isVoidType() &&
15134       RequireCompleteType(TypeRange.getBegin(), CastType,
15135                           diag::err_typecheck_cast_to_incomplete))
15136     return ExprError();
15137 
15138   // Rewrite the casted expression from scratch.
15139   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15140   if (!result.isUsable()) return ExprError();
15141 
15142   CastExpr = result.get();
15143   VK = CastExpr->getValueKind();
15144   CastKind = CK_NoOp;
15145 
15146   return CastExpr;
15147 }
15148 
15149 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15150   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15151 }
15152 
15153 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15154                                     Expr *arg, QualType &paramType) {
15155   // If the syntactic form of the argument is not an explicit cast of
15156   // any sort, just do default argument promotion.
15157   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15158   if (!castArg) {
15159     ExprResult result = DefaultArgumentPromotion(arg);
15160     if (result.isInvalid()) return ExprError();
15161     paramType = result.get()->getType();
15162     return result;
15163   }
15164 
15165   // Otherwise, use the type that was written in the explicit cast.
15166   assert(!arg->hasPlaceholderType());
15167   paramType = castArg->getTypeAsWritten();
15168 
15169   // Copy-initialize a parameter of that type.
15170   InitializedEntity entity =
15171     InitializedEntity::InitializeParameter(Context, paramType,
15172                                            /*consumed*/ false);
15173   return PerformCopyInitialization(entity, callLoc, arg);
15174 }
15175 
15176 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15177   Expr *orig = E;
15178   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15179   while (true) {
15180     E = E->IgnoreParenImpCasts();
15181     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15182       E = call->getCallee();
15183       diagID = diag::err_uncasted_call_of_unknown_any;
15184     } else {
15185       break;
15186     }
15187   }
15188 
15189   SourceLocation loc;
15190   NamedDecl *d;
15191   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15192     loc = ref->getLocation();
15193     d = ref->getDecl();
15194   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15195     loc = mem->getMemberLoc();
15196     d = mem->getMemberDecl();
15197   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15198     diagID = diag::err_uncasted_call_of_unknown_any;
15199     loc = msg->getSelectorStartLoc();
15200     d = msg->getMethodDecl();
15201     if (!d) {
15202       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15203         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15204         << orig->getSourceRange();
15205       return ExprError();
15206     }
15207   } else {
15208     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15209       << E->getSourceRange();
15210     return ExprError();
15211   }
15212 
15213   S.Diag(loc, diagID) << d << orig->getSourceRange();
15214 
15215   // Never recoverable.
15216   return ExprError();
15217 }
15218 
15219 /// Check for operands with placeholder types and complain if found.
15220 /// Returns true if there was an error and no recovery was possible.
15221 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15222   if (!getLangOpts().CPlusPlus) {
15223     // C cannot handle TypoExpr nodes on either side of a binop because it
15224     // doesn't handle dependent types properly, so make sure any TypoExprs have
15225     // been dealt with before checking the operands.
15226     ExprResult Result = CorrectDelayedTyposInExpr(E);
15227     if (!Result.isUsable()) return ExprError();
15228     E = Result.get();
15229   }
15230 
15231   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15232   if (!placeholderType) return E;
15233 
15234   switch (placeholderType->getKind()) {
15235 
15236   // Overloaded expressions.
15237   case BuiltinType::Overload: {
15238     // Try to resolve a single function template specialization.
15239     // This is obligatory.
15240     ExprResult Result = E;
15241     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15242       return Result;
15243 
15244     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15245     // leaves Result unchanged on failure.
15246     Result = E;
15247     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15248       return Result;
15249 
15250     // If that failed, try to recover with a call.
15251     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15252                          /*complain*/ true);
15253     return Result;
15254   }
15255 
15256   // Bound member functions.
15257   case BuiltinType::BoundMember: {
15258     ExprResult result = E;
15259     const Expr *BME = E->IgnoreParens();
15260     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15261     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15262     if (isa<CXXPseudoDestructorExpr>(BME)) {
15263       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15264     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15265       if (ME->getMemberNameInfo().getName().getNameKind() ==
15266           DeclarationName::CXXDestructorName)
15267         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15268     }
15269     tryToRecoverWithCall(result, PD,
15270                          /*complain*/ true);
15271     return result;
15272   }
15273 
15274   // ARC unbridged casts.
15275   case BuiltinType::ARCUnbridgedCast: {
15276     Expr *realCast = stripARCUnbridgedCast(E);
15277     diagnoseARCUnbridgedCast(realCast);
15278     return realCast;
15279   }
15280 
15281   // Expressions of unknown type.
15282   case BuiltinType::UnknownAny:
15283     return diagnoseUnknownAnyExpr(*this, E);
15284 
15285   // Pseudo-objects.
15286   case BuiltinType::PseudoObject:
15287     return checkPseudoObjectRValue(E);
15288 
15289   case BuiltinType::BuiltinFn: {
15290     // Accept __noop without parens by implicitly converting it to a call expr.
15291     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15292     if (DRE) {
15293       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15294       if (FD->getBuiltinID() == Builtin::BI__noop) {
15295         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15296                               CK_BuiltinFnToFnPtr).get();
15297         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15298                                       VK_RValue, SourceLocation());
15299       }
15300     }
15301 
15302     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15303     return ExprError();
15304   }
15305 
15306   // Expressions of unknown type.
15307   case BuiltinType::OMPArraySection:
15308     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15309     return ExprError();
15310 
15311   // Everything else should be impossible.
15312 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15313   case BuiltinType::Id:
15314 #include "clang/Basic/OpenCLImageTypes.def"
15315 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15316 #define PLACEHOLDER_TYPE(Id, SingletonId)
15317 #include "clang/AST/BuiltinTypes.def"
15318     break;
15319   }
15320 
15321   llvm_unreachable("invalid placeholder type!");
15322 }
15323 
15324 bool Sema::CheckCaseExpression(Expr *E) {
15325   if (E->isTypeDependent())
15326     return true;
15327   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15328     return E->getType()->isIntegralOrEnumerationType();
15329   return false;
15330 }
15331 
15332 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15333 ExprResult
15334 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15335   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15336          "Unknown Objective-C Boolean value!");
15337   QualType BoolT = Context.ObjCBuiltinBoolTy;
15338   if (!Context.getBOOLDecl()) {
15339     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15340                         Sema::LookupOrdinaryName);
15341     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15342       NamedDecl *ND = Result.getFoundDecl();
15343       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15344         Context.setBOOLDecl(TD);
15345     }
15346   }
15347   if (Context.getBOOLDecl())
15348     BoolT = Context.getBOOLType();
15349   return new (Context)
15350       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15351 }
15352 
15353 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15354     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15355     SourceLocation RParen) {
15356 
15357   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15358 
15359   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15360                            [&](const AvailabilitySpec &Spec) {
15361                              return Spec.getPlatform() == Platform;
15362                            });
15363 
15364   VersionTuple Version;
15365   if (Spec != AvailSpecs.end())
15366     Version = Spec->getVersion();
15367 
15368   return new (Context)
15369       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15370 }
15371