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   SmallVector<DiagnoseIfAttr *, 4> DiagnoseIfWarnings;
346   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
347     if (FD->isDeleted()) {
348       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
349       if (Ctor && Ctor->isInheritingConstructor())
350         Diag(Loc, diag::err_deleted_inherited_ctor_use)
351             << Ctor->getParent()
352             << Ctor->getInheritedConstructor().getConstructor()->getParent();
353       else
354         Diag(Loc, diag::err_deleted_function_use);
355       NoteDeletedFunction(FD);
356       return true;
357     }
358 
359     // If the function has a deduced return type, and we can't deduce it,
360     // then we can't use it either.
361     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
362         DeduceReturnType(FD, Loc))
363       return true;
364 
365     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
366       return true;
367 
368     if (const DiagnoseIfAttr *A =
369             checkArgIndependentDiagnoseIf(FD, DiagnoseIfWarnings)) {
370       emitDiagnoseIfDiagnostic(Loc, A);
371       return true;
372     }
373   }
374 
375   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
376   // Only the variables omp_in and omp_out are allowed in the combiner.
377   // Only the variables omp_priv and omp_orig are allowed in the
378   // initializer-clause.
379   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
380   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
381       isa<VarDecl>(D)) {
382     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
383         << getCurFunction()->HasOMPDeclareReductionCombiner;
384     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
385     return true;
386   }
387 
388   for (const auto *W : DiagnoseIfWarnings)
389     emitDiagnoseIfDiagnostic(Loc, W);
390 
391   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
392                              ObjCPropertyAccess);
393 
394   DiagnoseUnusedOfDecl(*this, D, Loc);
395 
396   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
397 
398   return false;
399 }
400 
401 /// \brief Retrieve the message suffix that should be added to a
402 /// diagnostic complaining about the given function being deleted or
403 /// unavailable.
404 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
405   std::string Message;
406   if (FD->getAvailability(&Message))
407     return ": " + Message;
408 
409   return std::string();
410 }
411 
412 /// DiagnoseSentinelCalls - This routine checks whether a call or
413 /// message-send is to a declaration with the sentinel attribute, and
414 /// if so, it checks that the requirements of the sentinel are
415 /// satisfied.
416 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
417                                  ArrayRef<Expr *> Args) {
418   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
419   if (!attr)
420     return;
421 
422   // The number of formal parameters of the declaration.
423   unsigned numFormalParams;
424 
425   // The kind of declaration.  This is also an index into a %select in
426   // the diagnostic.
427   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
428 
429   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
430     numFormalParams = MD->param_size();
431     calleeType = CT_Method;
432   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433     numFormalParams = FD->param_size();
434     calleeType = CT_Function;
435   } else if (isa<VarDecl>(D)) {
436     QualType type = cast<ValueDecl>(D)->getType();
437     const FunctionType *fn = nullptr;
438     if (const PointerType *ptr = type->getAs<PointerType>()) {
439       fn = ptr->getPointeeType()->getAs<FunctionType>();
440       if (!fn) return;
441       calleeType = CT_Function;
442     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
443       fn = ptr->getPointeeType()->castAs<FunctionType>();
444       calleeType = CT_Block;
445     } else {
446       return;
447     }
448 
449     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
450       numFormalParams = proto->getNumParams();
451     } else {
452       numFormalParams = 0;
453     }
454   } else {
455     return;
456   }
457 
458   // "nullPos" is the number of formal parameters at the end which
459   // effectively count as part of the variadic arguments.  This is
460   // useful if you would prefer to not have *any* formal parameters,
461   // but the language forces you to have at least one.
462   unsigned nullPos = attr->getNullPos();
463   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
464   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
465 
466   // The number of arguments which should follow the sentinel.
467   unsigned numArgsAfterSentinel = attr->getSentinel();
468 
469   // If there aren't enough arguments for all the formal parameters,
470   // the sentinel, and the args after the sentinel, complain.
471   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
472     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
474     return;
475   }
476 
477   // Otherwise, find the sentinel expression.
478   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
479   if (!sentinelExpr) return;
480   if (sentinelExpr->isValueDependent()) return;
481   if (Context.isSentinelNullExpr(sentinelExpr)) return;
482 
483   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
484   // or 'NULL' if those are actually defined in the context.  Only use
485   // 'nil' for ObjC methods, where it's much more likely that the
486   // variadic arguments form a list of object pointers.
487   SourceLocation MissingNilLoc
488     = getLocForEndOfToken(sentinelExpr->getLocEnd());
489   std::string NullValue;
490   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
491     NullValue = "nil";
492   else if (getLangOpts().CPlusPlus11)
493     NullValue = "nullptr";
494   else if (PP.isMacroDefined("NULL"))
495     NullValue = "NULL";
496   else
497     NullValue = "(void*) 0";
498 
499   if (MissingNilLoc.isInvalid())
500     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
501   else
502     Diag(MissingNilLoc, diag::warn_missing_sentinel)
503       << int(calleeType)
504       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
505   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
506 }
507 
508 SourceRange Sema::getExprRange(Expr *E) const {
509   return E ? E->getSourceRange() : SourceRange();
510 }
511 
512 //===----------------------------------------------------------------------===//
513 //  Standard Promotions and Conversions
514 //===----------------------------------------------------------------------===//
515 
516 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
518   // Handle any placeholder expressions which made it here.
519   if (E->getType()->isPlaceholderType()) {
520     ExprResult result = CheckPlaceholderExpr(E);
521     if (result.isInvalid()) return ExprError();
522     E = result.get();
523   }
524 
525   QualType Ty = E->getType();
526   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
527 
528   if (Ty->isFunctionType()) {
529     // If we are here, we are not calling a function but taking
530     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
531     if (getLangOpts().OpenCL) {
532       if (Diagnose)
533         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
534       return ExprError();
535     }
536 
537     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
538       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
539         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
540           return ExprError();
541 
542     E = ImpCastExprToType(E, Context.getPointerType(Ty),
543                           CK_FunctionToPointerDecay).get();
544   } else if (Ty->isArrayType()) {
545     // In C90 mode, arrays only promote to pointers if the array expression is
546     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
547     // type 'array of type' is converted to an expression that has type 'pointer
548     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
549     // that has type 'array of type' ...".  The relevant change is "an lvalue"
550     // (C90) to "an expression" (C99).
551     //
552     // C++ 4.2p1:
553     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
554     // T" can be converted to an rvalue of type "pointer to T".
555     //
556     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
557       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
558                             CK_ArrayToPointerDecay).get();
559   }
560   return E;
561 }
562 
563 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
564   // Check to see if we are dereferencing a null pointer.  If so,
565   // and if not volatile-qualified, this is undefined behavior that the
566   // optimizer will delete, so warn about it.  People sometimes try to use this
567   // to get a deterministic trap and are surprised by clang's behavior.  This
568   // only handles the pattern "*null", which is a very syntactic check.
569   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
570     if (UO->getOpcode() == UO_Deref &&
571         UO->getSubExpr()->IgnoreParenCasts()->
572           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
573         !UO->getType().isVolatileQualified()) {
574     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575                           S.PDiag(diag::warn_indirection_through_null)
576                             << UO->getSubExpr()->getSourceRange());
577     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578                         S.PDiag(diag::note_indirection_through_null));
579   }
580 }
581 
582 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
583                                     SourceLocation AssignLoc,
584                                     const Expr* RHS) {
585   const ObjCIvarDecl *IV = OIRE->getDecl();
586   if (!IV)
587     return;
588 
589   DeclarationName MemberName = IV->getDeclName();
590   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
591   if (!Member || !Member->isStr("isa"))
592     return;
593 
594   const Expr *Base = OIRE->getBase();
595   QualType BaseType = Base->getType();
596   if (OIRE->isArrow())
597     BaseType = BaseType->getPointeeType();
598   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
599     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
600       ObjCInterfaceDecl *ClassDeclared = nullptr;
601       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
602       if (!ClassDeclared->getSuperClass()
603           && (*ClassDeclared->ivar_begin()) == IV) {
604         if (RHS) {
605           NamedDecl *ObjectSetClass =
606             S.LookupSingleName(S.TUScope,
607                                &S.Context.Idents.get("object_setClass"),
608                                SourceLocation(), S.LookupOrdinaryName);
609           if (ObjectSetClass) {
610             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
611             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
612             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
613             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
614                                                      AssignLoc), ",") <<
615             FixItHint::CreateInsertion(RHSLocEnd, ")");
616           }
617           else
618             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
619         } else {
620           NamedDecl *ObjectGetClass =
621             S.LookupSingleName(S.TUScope,
622                                &S.Context.Idents.get("object_getClass"),
623                                SourceLocation(), S.LookupOrdinaryName);
624           if (ObjectGetClass)
625             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
626             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
627             FixItHint::CreateReplacement(
628                                          SourceRange(OIRE->getOpLoc(),
629                                                      OIRE->getLocEnd()), ")");
630           else
631             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
632         }
633         S.Diag(IV->getLocation(), diag::note_ivar_decl);
634       }
635     }
636 }
637 
638 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
639   // Handle any placeholder expressions which made it here.
640   if (E->getType()->isPlaceholderType()) {
641     ExprResult result = CheckPlaceholderExpr(E);
642     if (result.isInvalid()) return ExprError();
643     E = result.get();
644   }
645 
646   // C++ [conv.lval]p1:
647   //   A glvalue of a non-function, non-array type T can be
648   //   converted to a prvalue.
649   if (!E->isGLValue()) return E;
650 
651   QualType T = E->getType();
652   assert(!T.isNull() && "r-value conversion on typeless expression?");
653 
654   // We don't want to throw lvalue-to-rvalue casts on top of
655   // expressions of certain types in C++.
656   if (getLangOpts().CPlusPlus &&
657       (E->getType() == Context.OverloadTy ||
658        T->isDependentType() ||
659        T->isRecordType()))
660     return E;
661 
662   // The C standard is actually really unclear on this point, and
663   // DR106 tells us what the result should be but not why.  It's
664   // generally best to say that void types just doesn't undergo
665   // lvalue-to-rvalue at all.  Note that expressions of unqualified
666   // 'void' type are never l-values, but qualified void can be.
667   if (T->isVoidType())
668     return E;
669 
670   // OpenCL usually rejects direct accesses to values of 'half' type.
671   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
672       T->isHalfType()) {
673     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
674       << 0 << T;
675     return ExprError();
676   }
677 
678   CheckForNullPointerDereference(*this, E);
679   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
680     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
681                                      &Context.Idents.get("object_getClass"),
682                                      SourceLocation(), LookupOrdinaryName);
683     if (ObjectGetClass)
684       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
685         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
686         FixItHint::CreateReplacement(
687                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
688     else
689       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
690   }
691   else if (const ObjCIvarRefExpr *OIRE =
692             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
693     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
694 
695   // C++ [conv.lval]p1:
696   //   [...] If T is a non-class type, the type of the prvalue is the
697   //   cv-unqualified version of T. Otherwise, the type of the
698   //   rvalue is T.
699   //
700   // C99 6.3.2.1p2:
701   //   If the lvalue has qualified type, the value has the unqualified
702   //   version of the type of the lvalue; otherwise, the value has the
703   //   type of the lvalue.
704   if (T.hasQualifiers())
705     T = T.getUnqualifiedType();
706 
707   // Under the MS ABI, lock down the inheritance model now.
708   if (T->isMemberPointerType() &&
709       Context.getTargetInfo().getCXXABI().isMicrosoft())
710     (void)isCompleteType(E->getExprLoc(), T);
711 
712   UpdateMarkingForLValueToRValue(E);
713 
714   // Loading a __weak object implicitly retains the value, so we need a cleanup to
715   // balance that.
716   if (getLangOpts().ObjCAutoRefCount &&
717       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
718     Cleanup.setExprNeedsCleanups(true);
719 
720   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
721                                             nullptr, VK_RValue);
722 
723   // C11 6.3.2.1p2:
724   //   ... if the lvalue has atomic type, the value has the non-atomic version
725   //   of the type of the lvalue ...
726   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
727     T = Atomic->getValueType().getUnqualifiedType();
728     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
729                                    nullptr, VK_RValue);
730   }
731 
732   return Res;
733 }
734 
735 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
736   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
737   if (Res.isInvalid())
738     return ExprError();
739   Res = DefaultLvalueConversion(Res.get());
740   if (Res.isInvalid())
741     return ExprError();
742   return Res;
743 }
744 
745 /// CallExprUnaryConversions - a special case of an unary conversion
746 /// performed on a function designator of a call expression.
747 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
748   QualType Ty = E->getType();
749   ExprResult Res = E;
750   // Only do implicit cast for a function type, but not for a pointer
751   // to function type.
752   if (Ty->isFunctionType()) {
753     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
754                             CK_FunctionToPointerDecay).get();
755     if (Res.isInvalid())
756       return ExprError();
757   }
758   Res = DefaultLvalueConversion(Res.get());
759   if (Res.isInvalid())
760     return ExprError();
761   return Res.get();
762 }
763 
764 /// UsualUnaryConversions - Performs various conversions that are common to most
765 /// operators (C99 6.3). The conversions of array and function types are
766 /// sometimes suppressed. For example, the array->pointer conversion doesn't
767 /// apply if the array is an argument to the sizeof or address (&) operators.
768 /// In these instances, this routine should *not* be called.
769 ExprResult Sema::UsualUnaryConversions(Expr *E) {
770   // First, convert to an r-value.
771   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
772   if (Res.isInvalid())
773     return ExprError();
774   E = Res.get();
775 
776   QualType Ty = E->getType();
777   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
778 
779   // Half FP have to be promoted to float unless it is natively supported
780   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
781     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
782 
783   // Try to perform integral promotions if the object has a theoretically
784   // promotable type.
785   if (Ty->isIntegralOrUnscopedEnumerationType()) {
786     // C99 6.3.1.1p2:
787     //
788     //   The following may be used in an expression wherever an int or
789     //   unsigned int may be used:
790     //     - an object or expression with an integer type whose integer
791     //       conversion rank is less than or equal to the rank of int
792     //       and unsigned int.
793     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
794     //
795     //   If an int can represent all values of the original type, the
796     //   value is converted to an int; otherwise, it is converted to an
797     //   unsigned int. These are called the integer promotions. All
798     //   other types are unchanged by the integer promotions.
799 
800     QualType PTy = Context.isPromotableBitField(E);
801     if (!PTy.isNull()) {
802       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
803       return E;
804     }
805     if (Ty->isPromotableIntegerType()) {
806       QualType PT = Context.getPromotedIntegerType(Ty);
807       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
808       return E;
809     }
810   }
811   return E;
812 }
813 
814 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
815 /// do not have a prototype. Arguments that have type float or __fp16
816 /// are promoted to double. All other argument types are converted by
817 /// UsualUnaryConversions().
818 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
819   QualType Ty = E->getType();
820   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
821 
822   ExprResult Res = UsualUnaryConversions(E);
823   if (Res.isInvalid())
824     return ExprError();
825   E = Res.get();
826 
827   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
828   // double.
829   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
830   if (BTy && (BTy->getKind() == BuiltinType::Half ||
831               BTy->getKind() == BuiltinType::Float)) {
832     if (getLangOpts().OpenCL &&
833         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
834         if (BTy->getKind() == BuiltinType::Half) {
835             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
836         }
837     } else {
838       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
839     }
840   }
841 
842   // C++ performs lvalue-to-rvalue conversion as a default argument
843   // promotion, even on class types, but note:
844   //   C++11 [conv.lval]p2:
845   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
846   //     operand or a subexpression thereof the value contained in the
847   //     referenced object is not accessed. Otherwise, if the glvalue
848   //     has a class type, the conversion copy-initializes a temporary
849   //     of type T from the glvalue and the result of the conversion
850   //     is a prvalue for the temporary.
851   // FIXME: add some way to gate this entire thing for correctness in
852   // potentially potentially evaluated contexts.
853   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
854     ExprResult Temp = PerformCopyInitialization(
855                        InitializedEntity::InitializeTemporary(E->getType()),
856                                                 E->getExprLoc(), E);
857     if (Temp.isInvalid())
858       return ExprError();
859     E = Temp.get();
860   }
861 
862   return E;
863 }
864 
865 /// Determine the degree of POD-ness for an expression.
866 /// Incomplete types are considered POD, since this check can be performed
867 /// when we're in an unevaluated context.
868 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
869   if (Ty->isIncompleteType()) {
870     // C++11 [expr.call]p7:
871     //   After these conversions, if the argument does not have arithmetic,
872     //   enumeration, pointer, pointer to member, or class type, the program
873     //   is ill-formed.
874     //
875     // Since we've already performed array-to-pointer and function-to-pointer
876     // decay, the only such type in C++ is cv void. This also handles
877     // initializer lists as variadic arguments.
878     if (Ty->isVoidType())
879       return VAK_Invalid;
880 
881     if (Ty->isObjCObjectType())
882       return VAK_Invalid;
883     return VAK_Valid;
884   }
885 
886   if (Ty.isCXX98PODType(Context))
887     return VAK_Valid;
888 
889   // C++11 [expr.call]p7:
890   //   Passing a potentially-evaluated argument of class type (Clause 9)
891   //   having a non-trivial copy constructor, a non-trivial move constructor,
892   //   or a non-trivial destructor, with no corresponding parameter,
893   //   is conditionally-supported with implementation-defined semantics.
894   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
895     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
896       if (!Record->hasNonTrivialCopyConstructor() &&
897           !Record->hasNonTrivialMoveConstructor() &&
898           !Record->hasNonTrivialDestructor())
899         return VAK_ValidInCXX11;
900 
901   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
902     return VAK_Valid;
903 
904   if (Ty->isObjCObjectType())
905     return VAK_Invalid;
906 
907   if (getLangOpts().MSVCCompat)
908     return VAK_MSVCUndefined;
909 
910   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
911   // permitted to reject them. We should consider doing so.
912   return VAK_Undefined;
913 }
914 
915 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
916   // Don't allow one to pass an Objective-C interface to a vararg.
917   const QualType &Ty = E->getType();
918   VarArgKind VAK = isValidVarArgType(Ty);
919 
920   // Complain about passing non-POD types through varargs.
921   switch (VAK) {
922   case VAK_ValidInCXX11:
923     DiagRuntimeBehavior(
924         E->getLocStart(), nullptr,
925         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
926           << Ty << CT);
927     // Fall through.
928   case VAK_Valid:
929     if (Ty->isRecordType()) {
930       // This is unlikely to be what the user intended. If the class has a
931       // 'c_str' member function, the user probably meant to call that.
932       DiagRuntimeBehavior(E->getLocStart(), nullptr,
933                           PDiag(diag::warn_pass_class_arg_to_vararg)
934                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
935     }
936     break;
937 
938   case VAK_Undefined:
939   case VAK_MSVCUndefined:
940     DiagRuntimeBehavior(
941         E->getLocStart(), nullptr,
942         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
943           << getLangOpts().CPlusPlus11 << Ty << CT);
944     break;
945 
946   case VAK_Invalid:
947     if (Ty->isObjCObjectType())
948       DiagRuntimeBehavior(
949           E->getLocStart(), nullptr,
950           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
951             << Ty << CT);
952     else
953       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
954         << isa<InitListExpr>(E) << Ty << CT;
955     break;
956   }
957 }
958 
959 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
960 /// will create a trap if the resulting type is not a POD type.
961 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
962                                                   FunctionDecl *FDecl) {
963   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
964     // Strip the unbridged-cast placeholder expression off, if applicable.
965     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
966         (CT == VariadicMethod ||
967          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
968       E = stripARCUnbridgedCast(E);
969 
970     // Otherwise, do normal placeholder checking.
971     } else {
972       ExprResult ExprRes = CheckPlaceholderExpr(E);
973       if (ExprRes.isInvalid())
974         return ExprError();
975       E = ExprRes.get();
976     }
977   }
978 
979   ExprResult ExprRes = DefaultArgumentPromotion(E);
980   if (ExprRes.isInvalid())
981     return ExprError();
982   E = ExprRes.get();
983 
984   // Diagnostics regarding non-POD argument types are
985   // emitted along with format string checking in Sema::CheckFunctionCall().
986   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
987     // Turn this into a trap.
988     CXXScopeSpec SS;
989     SourceLocation TemplateKWLoc;
990     UnqualifiedId Name;
991     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
992                        E->getLocStart());
993     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
994                                           Name, true, false);
995     if (TrapFn.isInvalid())
996       return ExprError();
997 
998     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
999                                     E->getLocStart(), None,
1000                                     E->getLocEnd());
1001     if (Call.isInvalid())
1002       return ExprError();
1003 
1004     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1005                                   Call.get(), E);
1006     if (Comma.isInvalid())
1007       return ExprError();
1008     return Comma.get();
1009   }
1010 
1011   if (!getLangOpts().CPlusPlus &&
1012       RequireCompleteType(E->getExprLoc(), E->getType(),
1013                           diag::err_call_incomplete_argument))
1014     return ExprError();
1015 
1016   return E;
1017 }
1018 
1019 /// \brief Converts an integer to complex float type.  Helper function of
1020 /// UsualArithmeticConversions()
1021 ///
1022 /// \return false if the integer expression is an integer type and is
1023 /// successfully converted to the complex type.
1024 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1025                                                   ExprResult &ComplexExpr,
1026                                                   QualType IntTy,
1027                                                   QualType ComplexTy,
1028                                                   bool SkipCast) {
1029   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1030   if (SkipCast) return false;
1031   if (IntTy->isIntegerType()) {
1032     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1033     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1034     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1035                                   CK_FloatingRealToComplex);
1036   } else {
1037     assert(IntTy->isComplexIntegerType());
1038     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1039                                   CK_IntegralComplexToFloatingComplex);
1040   }
1041   return false;
1042 }
1043 
1044 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1045 /// UsualArithmeticConversions()
1046 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1047                                              ExprResult &RHS, QualType LHSType,
1048                                              QualType RHSType,
1049                                              bool IsCompAssign) {
1050   // if we have an integer operand, the result is the complex type.
1051   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1052                                              /*skipCast*/false))
1053     return LHSType;
1054   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1055                                              /*skipCast*/IsCompAssign))
1056     return RHSType;
1057 
1058   // This handles complex/complex, complex/float, or float/complex.
1059   // When both operands are complex, the shorter operand is converted to the
1060   // type of the longer, and that is the type of the result. This corresponds
1061   // to what is done when combining two real floating-point operands.
1062   // The fun begins when size promotion occur across type domains.
1063   // From H&S 6.3.4: When one operand is complex and the other is a real
1064   // floating-point type, the less precise type is converted, within it's
1065   // real or complex domain, to the precision of the other type. For example,
1066   // when combining a "long double" with a "double _Complex", the
1067   // "double _Complex" is promoted to "long double _Complex".
1068 
1069   // Compute the rank of the two types, regardless of whether they are complex.
1070   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1071 
1072   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1073   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1074   QualType LHSElementType =
1075       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1076   QualType RHSElementType =
1077       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1078 
1079   QualType ResultType = S.Context.getComplexType(LHSElementType);
1080   if (Order < 0) {
1081     // Promote the precision of the LHS if not an assignment.
1082     ResultType = S.Context.getComplexType(RHSElementType);
1083     if (!IsCompAssign) {
1084       if (LHSComplexType)
1085         LHS =
1086             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1087       else
1088         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1089     }
1090   } else if (Order > 0) {
1091     // Promote the precision of the RHS.
1092     if (RHSComplexType)
1093       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1094     else
1095       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1096   }
1097   return ResultType;
1098 }
1099 
1100 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1101 /// of UsualArithmeticConversions()
1102 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1103                                            ExprResult &IntExpr,
1104                                            QualType FloatTy, QualType IntTy,
1105                                            bool ConvertFloat, bool ConvertInt) {
1106   if (IntTy->isIntegerType()) {
1107     if (ConvertInt)
1108       // Convert intExpr to the lhs floating point type.
1109       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1110                                     CK_IntegralToFloating);
1111     return FloatTy;
1112   }
1113 
1114   // Convert both sides to the appropriate complex float.
1115   assert(IntTy->isComplexIntegerType());
1116   QualType result = S.Context.getComplexType(FloatTy);
1117 
1118   // _Complex int -> _Complex float
1119   if (ConvertInt)
1120     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1121                                   CK_IntegralComplexToFloatingComplex);
1122 
1123   // float -> _Complex float
1124   if (ConvertFloat)
1125     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1126                                     CK_FloatingRealToComplex);
1127 
1128   return result;
1129 }
1130 
1131 /// \brief Handle arithmethic conversion with floating point types.  Helper
1132 /// function of UsualArithmeticConversions()
1133 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1134                                       ExprResult &RHS, QualType LHSType,
1135                                       QualType RHSType, bool IsCompAssign) {
1136   bool LHSFloat = LHSType->isRealFloatingType();
1137   bool RHSFloat = RHSType->isRealFloatingType();
1138 
1139   // If we have two real floating types, convert the smaller operand
1140   // to the bigger result.
1141   if (LHSFloat && RHSFloat) {
1142     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1143     if (order > 0) {
1144       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1145       return LHSType;
1146     }
1147 
1148     assert(order < 0 && "illegal float comparison");
1149     if (!IsCompAssign)
1150       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1151     return RHSType;
1152   }
1153 
1154   if (LHSFloat) {
1155     // Half FP has to be promoted to float unless it is natively supported
1156     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1157       LHSType = S.Context.FloatTy;
1158 
1159     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1160                                       /*convertFloat=*/!IsCompAssign,
1161                                       /*convertInt=*/ true);
1162   }
1163   assert(RHSFloat);
1164   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1165                                     /*convertInt=*/ true,
1166                                     /*convertFloat=*/!IsCompAssign);
1167 }
1168 
1169 /// \brief Diagnose attempts to convert between __float128 and long double if
1170 /// there is no support for such conversion. Helper function of
1171 /// UsualArithmeticConversions().
1172 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1173                                       QualType RHSType) {
1174   /*  No issue converting if at least one of the types is not a floating point
1175       type or the two types have the same rank.
1176   */
1177   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1178       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1179     return false;
1180 
1181   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1182          "The remaining types must be floating point types.");
1183 
1184   auto *LHSComplex = LHSType->getAs<ComplexType>();
1185   auto *RHSComplex = RHSType->getAs<ComplexType>();
1186 
1187   QualType LHSElemType = LHSComplex ?
1188     LHSComplex->getElementType() : LHSType;
1189   QualType RHSElemType = RHSComplex ?
1190     RHSComplex->getElementType() : RHSType;
1191 
1192   // No issue if the two types have the same representation
1193   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1194       &S.Context.getFloatTypeSemantics(RHSElemType))
1195     return false;
1196 
1197   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1198                                 RHSElemType == S.Context.LongDoubleTy);
1199   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1200                             RHSElemType == S.Context.Float128Ty);
1201 
1202   /* We've handled the situation where __float128 and long double have the same
1203      representation. The only other allowable conversion is if long double is
1204      really just double.
1205   */
1206   return Float128AndLongDouble &&
1207     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1208      &llvm::APFloat::IEEEdouble());
1209 }
1210 
1211 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1212 
1213 namespace {
1214 /// These helper callbacks are placed in an anonymous namespace to
1215 /// permit their use as function template parameters.
1216 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1217   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1218 }
1219 
1220 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1221   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1222                              CK_IntegralComplexCast);
1223 }
1224 }
1225 
1226 /// \brief Handle integer arithmetic conversions.  Helper function of
1227 /// UsualArithmeticConversions()
1228 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1229 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1230                                         ExprResult &RHS, QualType LHSType,
1231                                         QualType RHSType, bool IsCompAssign) {
1232   // The rules for this case are in C99 6.3.1.8
1233   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1234   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1235   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1236   if (LHSSigned == RHSSigned) {
1237     // Same signedness; use the higher-ranked type
1238     if (order >= 0) {
1239       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240       return LHSType;
1241     } else if (!IsCompAssign)
1242       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243     return RHSType;
1244   } else if (order != (LHSSigned ? 1 : -1)) {
1245     // The unsigned type has greater than or equal rank to the
1246     // signed type, so use the unsigned type
1247     if (RHSSigned) {
1248       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1249       return LHSType;
1250     } else if (!IsCompAssign)
1251       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1252     return RHSType;
1253   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1254     // The two types are different widths; if we are here, that
1255     // means the signed type is larger than the unsigned type, so
1256     // use the signed type.
1257     if (LHSSigned) {
1258       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1259       return LHSType;
1260     } else if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1262     return RHSType;
1263   } else {
1264     // The signed type is higher-ranked than the unsigned type,
1265     // but isn't actually any bigger (like unsigned int and long
1266     // on most 32-bit systems).  Use the unsigned type corresponding
1267     // to the signed type.
1268     QualType result =
1269       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1270     RHS = (*doRHSCast)(S, RHS.get(), result);
1271     if (!IsCompAssign)
1272       LHS = (*doLHSCast)(S, LHS.get(), result);
1273     return result;
1274   }
1275 }
1276 
1277 /// \brief Handle conversions with GCC complex int extension.  Helper function
1278 /// of UsualArithmeticConversions()
1279 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1280                                            ExprResult &RHS, QualType LHSType,
1281                                            QualType RHSType,
1282                                            bool IsCompAssign) {
1283   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1284   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1285 
1286   if (LHSComplexInt && RHSComplexInt) {
1287     QualType LHSEltType = LHSComplexInt->getElementType();
1288     QualType RHSEltType = RHSComplexInt->getElementType();
1289     QualType ScalarType =
1290       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1291         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1292 
1293     return S.Context.getComplexType(ScalarType);
1294   }
1295 
1296   if (LHSComplexInt) {
1297     QualType LHSEltType = LHSComplexInt->getElementType();
1298     QualType ScalarType =
1299       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1300         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1301     QualType ComplexType = S.Context.getComplexType(ScalarType);
1302     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1303                               CK_IntegralRealToComplex);
1304 
1305     return ComplexType;
1306   }
1307 
1308   assert(RHSComplexInt);
1309 
1310   QualType RHSEltType = RHSComplexInt->getElementType();
1311   QualType ScalarType =
1312     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1313       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1314   QualType ComplexType = S.Context.getComplexType(ScalarType);
1315 
1316   if (!IsCompAssign)
1317     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1318                               CK_IntegralRealToComplex);
1319   return ComplexType;
1320 }
1321 
1322 /// UsualArithmeticConversions - Performs various conversions that are common to
1323 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1324 /// routine returns the first non-arithmetic type found. The client is
1325 /// responsible for emitting appropriate error diagnostics.
1326 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1327                                           bool IsCompAssign) {
1328   if (!IsCompAssign) {
1329     LHS = UsualUnaryConversions(LHS.get());
1330     if (LHS.isInvalid())
1331       return QualType();
1332   }
1333 
1334   RHS = UsualUnaryConversions(RHS.get());
1335   if (RHS.isInvalid())
1336     return QualType();
1337 
1338   // For conversion purposes, we ignore any qualifiers.
1339   // For example, "const float" and "float" are equivalent.
1340   QualType LHSType =
1341     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1342   QualType RHSType =
1343     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1344 
1345   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1346   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1347     LHSType = AtomicLHS->getValueType();
1348 
1349   // If both types are identical, no conversion is needed.
1350   if (LHSType == RHSType)
1351     return LHSType;
1352 
1353   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1354   // The caller can deal with this (e.g. pointer + int).
1355   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1356     return QualType();
1357 
1358   // Apply unary and bitfield promotions to the LHS's type.
1359   QualType LHSUnpromotedType = LHSType;
1360   if (LHSType->isPromotableIntegerType())
1361     LHSType = Context.getPromotedIntegerType(LHSType);
1362   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1363   if (!LHSBitfieldPromoteTy.isNull())
1364     LHSType = LHSBitfieldPromoteTy;
1365   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1366     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1367 
1368   // If both types are identical, no conversion is needed.
1369   if (LHSType == RHSType)
1370     return LHSType;
1371 
1372   // At this point, we have two different arithmetic types.
1373 
1374   // Diagnose attempts to convert between __float128 and long double where
1375   // such conversions currently can't be handled.
1376   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1377     return QualType();
1378 
1379   // Handle complex types first (C99 6.3.1.8p1).
1380   if (LHSType->isComplexType() || RHSType->isComplexType())
1381     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1382                                         IsCompAssign);
1383 
1384   // Now handle "real" floating types (i.e. float, double, long double).
1385   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1386     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1387                                  IsCompAssign);
1388 
1389   // Handle GCC complex int extension.
1390   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1391     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1392                                       IsCompAssign);
1393 
1394   // Finally, we have two differing integer types.
1395   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1396            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1397 }
1398 
1399 
1400 //===----------------------------------------------------------------------===//
1401 //  Semantic Analysis for various Expression Types
1402 //===----------------------------------------------------------------------===//
1403 
1404 
1405 ExprResult
1406 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1407                                 SourceLocation DefaultLoc,
1408                                 SourceLocation RParenLoc,
1409                                 Expr *ControllingExpr,
1410                                 ArrayRef<ParsedType> ArgTypes,
1411                                 ArrayRef<Expr *> ArgExprs) {
1412   unsigned NumAssocs = ArgTypes.size();
1413   assert(NumAssocs == ArgExprs.size());
1414 
1415   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1416   for (unsigned i = 0; i < NumAssocs; ++i) {
1417     if (ArgTypes[i])
1418       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1419     else
1420       Types[i] = nullptr;
1421   }
1422 
1423   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1424                                              ControllingExpr,
1425                                              llvm::makeArrayRef(Types, NumAssocs),
1426                                              ArgExprs);
1427   delete [] Types;
1428   return ER;
1429 }
1430 
1431 ExprResult
1432 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1433                                  SourceLocation DefaultLoc,
1434                                  SourceLocation RParenLoc,
1435                                  Expr *ControllingExpr,
1436                                  ArrayRef<TypeSourceInfo *> Types,
1437                                  ArrayRef<Expr *> Exprs) {
1438   unsigned NumAssocs = Types.size();
1439   assert(NumAssocs == Exprs.size());
1440 
1441   // Decay and strip qualifiers for the controlling expression type, and handle
1442   // placeholder type replacement. See committee discussion from WG14 DR423.
1443   {
1444     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1445     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1446     if (R.isInvalid())
1447       return ExprError();
1448     ControllingExpr = R.get();
1449   }
1450 
1451   // The controlling expression is an unevaluated operand, so side effects are
1452   // likely unintended.
1453   if (ActiveTemplateInstantiations.empty() &&
1454       ControllingExpr->HasSideEffects(Context, false))
1455     Diag(ControllingExpr->getExprLoc(),
1456          diag::warn_side_effects_unevaluated_context);
1457 
1458   bool TypeErrorFound = false,
1459        IsResultDependent = ControllingExpr->isTypeDependent(),
1460        ContainsUnexpandedParameterPack
1461          = ControllingExpr->containsUnexpandedParameterPack();
1462 
1463   for (unsigned i = 0; i < NumAssocs; ++i) {
1464     if (Exprs[i]->containsUnexpandedParameterPack())
1465       ContainsUnexpandedParameterPack = true;
1466 
1467     if (Types[i]) {
1468       if (Types[i]->getType()->containsUnexpandedParameterPack())
1469         ContainsUnexpandedParameterPack = true;
1470 
1471       if (Types[i]->getType()->isDependentType()) {
1472         IsResultDependent = true;
1473       } else {
1474         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1475         // complete object type other than a variably modified type."
1476         unsigned D = 0;
1477         if (Types[i]->getType()->isIncompleteType())
1478           D = diag::err_assoc_type_incomplete;
1479         else if (!Types[i]->getType()->isObjectType())
1480           D = diag::err_assoc_type_nonobject;
1481         else if (Types[i]->getType()->isVariablyModifiedType())
1482           D = diag::err_assoc_type_variably_modified;
1483 
1484         if (D != 0) {
1485           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1486             << Types[i]->getTypeLoc().getSourceRange()
1487             << Types[i]->getType();
1488           TypeErrorFound = true;
1489         }
1490 
1491         // C11 6.5.1.1p2 "No two generic associations in the same generic
1492         // selection shall specify compatible types."
1493         for (unsigned j = i+1; j < NumAssocs; ++j)
1494           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1495               Context.typesAreCompatible(Types[i]->getType(),
1496                                          Types[j]->getType())) {
1497             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1498                  diag::err_assoc_compatible_types)
1499               << Types[j]->getTypeLoc().getSourceRange()
1500               << Types[j]->getType()
1501               << Types[i]->getType();
1502             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1503                  diag::note_compat_assoc)
1504               << Types[i]->getTypeLoc().getSourceRange()
1505               << Types[i]->getType();
1506             TypeErrorFound = true;
1507           }
1508       }
1509     }
1510   }
1511   if (TypeErrorFound)
1512     return ExprError();
1513 
1514   // If we determined that the generic selection is result-dependent, don't
1515   // try to compute the result expression.
1516   if (IsResultDependent)
1517     return new (Context) GenericSelectionExpr(
1518         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1519         ContainsUnexpandedParameterPack);
1520 
1521   SmallVector<unsigned, 1> CompatIndices;
1522   unsigned DefaultIndex = -1U;
1523   for (unsigned i = 0; i < NumAssocs; ++i) {
1524     if (!Types[i])
1525       DefaultIndex = i;
1526     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1527                                         Types[i]->getType()))
1528       CompatIndices.push_back(i);
1529   }
1530 
1531   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1532   // type compatible with at most one of the types named in its generic
1533   // association list."
1534   if (CompatIndices.size() > 1) {
1535     // We strip parens here because the controlling expression is typically
1536     // parenthesized in macro definitions.
1537     ControllingExpr = ControllingExpr->IgnoreParens();
1538     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1539       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1540       << (unsigned) CompatIndices.size();
1541     for (unsigned I : CompatIndices) {
1542       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1543            diag::note_compat_assoc)
1544         << Types[I]->getTypeLoc().getSourceRange()
1545         << Types[I]->getType();
1546     }
1547     return ExprError();
1548   }
1549 
1550   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1551   // its controlling expression shall have type compatible with exactly one of
1552   // the types named in its generic association list."
1553   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1554     // We strip parens here because the controlling expression is typically
1555     // parenthesized in macro definitions.
1556     ControllingExpr = ControllingExpr->IgnoreParens();
1557     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1558       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1559     return ExprError();
1560   }
1561 
1562   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1563   // type name that is compatible with the type of the controlling expression,
1564   // then the result expression of the generic selection is the expression
1565   // in that generic association. Otherwise, the result expression of the
1566   // generic selection is the expression in the default generic association."
1567   unsigned ResultIndex =
1568     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1569 
1570   return new (Context) GenericSelectionExpr(
1571       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1572       ContainsUnexpandedParameterPack, ResultIndex);
1573 }
1574 
1575 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1576 /// location of the token and the offset of the ud-suffix within it.
1577 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1578                                      unsigned Offset) {
1579   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1580                                         S.getLangOpts());
1581 }
1582 
1583 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1584 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1585 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1586                                                  IdentifierInfo *UDSuffix,
1587                                                  SourceLocation UDSuffixLoc,
1588                                                  ArrayRef<Expr*> Args,
1589                                                  SourceLocation LitEndLoc) {
1590   assert(Args.size() <= 2 && "too many arguments for literal operator");
1591 
1592   QualType ArgTy[2];
1593   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1594     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1595     if (ArgTy[ArgIdx]->isArrayType())
1596       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1597   }
1598 
1599   DeclarationName OpName =
1600     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1601   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1602   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1603 
1604   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1605   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1606                               /*AllowRaw*/false, /*AllowTemplate*/false,
1607                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1608     return ExprError();
1609 
1610   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1611 }
1612 
1613 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1614 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1615 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1616 /// multiple tokens.  However, the common case is that StringToks points to one
1617 /// string.
1618 ///
1619 ExprResult
1620 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1621   assert(!StringToks.empty() && "Must have at least one string!");
1622 
1623   StringLiteralParser Literal(StringToks, PP);
1624   if (Literal.hadError)
1625     return ExprError();
1626 
1627   SmallVector<SourceLocation, 4> StringTokLocs;
1628   for (const Token &Tok : StringToks)
1629     StringTokLocs.push_back(Tok.getLocation());
1630 
1631   QualType CharTy = Context.CharTy;
1632   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1633   if (Literal.isWide()) {
1634     CharTy = Context.getWideCharType();
1635     Kind = StringLiteral::Wide;
1636   } else if (Literal.isUTF8()) {
1637     Kind = StringLiteral::UTF8;
1638   } else if (Literal.isUTF16()) {
1639     CharTy = Context.Char16Ty;
1640     Kind = StringLiteral::UTF16;
1641   } else if (Literal.isUTF32()) {
1642     CharTy = Context.Char32Ty;
1643     Kind = StringLiteral::UTF32;
1644   } else if (Literal.isPascal()) {
1645     CharTy = Context.UnsignedCharTy;
1646   }
1647 
1648   QualType CharTyConst = CharTy;
1649   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1650   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1651     CharTyConst.addConst();
1652 
1653   // Get an array type for the string, according to C99 6.4.5.  This includes
1654   // the nul terminator character as well as the string length for pascal
1655   // strings.
1656   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1657                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1658                                  ArrayType::Normal, 0);
1659 
1660   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1661   if (getLangOpts().OpenCL) {
1662     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1663   }
1664 
1665   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1666   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1667                                              Kind, Literal.Pascal, StrTy,
1668                                              &StringTokLocs[0],
1669                                              StringTokLocs.size());
1670   if (Literal.getUDSuffix().empty())
1671     return Lit;
1672 
1673   // We're building a user-defined literal.
1674   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1675   SourceLocation UDSuffixLoc =
1676     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1677                    Literal.getUDSuffixOffset());
1678 
1679   // Make sure we're allowed user-defined literals here.
1680   if (!UDLScope)
1681     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1682 
1683   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1684   //   operator "" X (str, len)
1685   QualType SizeType = Context.getSizeType();
1686 
1687   DeclarationName OpName =
1688     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1689   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1690   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1691 
1692   QualType ArgTy[] = {
1693     Context.getArrayDecayedType(StrTy), SizeType
1694   };
1695 
1696   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1697   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1698                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1699                                 /*AllowStringTemplate*/true)) {
1700 
1701   case LOLR_Cooked: {
1702     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1703     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1704                                                     StringTokLocs[0]);
1705     Expr *Args[] = { Lit, LenArg };
1706 
1707     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1708   }
1709 
1710   case LOLR_StringTemplate: {
1711     TemplateArgumentListInfo ExplicitArgs;
1712 
1713     unsigned CharBits = Context.getIntWidth(CharTy);
1714     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1715     llvm::APSInt Value(CharBits, CharIsUnsigned);
1716 
1717     TemplateArgument TypeArg(CharTy);
1718     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1719     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1720 
1721     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1722       Value = Lit->getCodeUnit(I);
1723       TemplateArgument Arg(Context, Value, CharTy);
1724       TemplateArgumentLocInfo ArgInfo;
1725       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1726     }
1727     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1728                                     &ExplicitArgs);
1729   }
1730   case LOLR_Raw:
1731   case LOLR_Template:
1732     llvm_unreachable("unexpected literal operator lookup result");
1733   case LOLR_Error:
1734     return ExprError();
1735   }
1736   llvm_unreachable("unexpected literal operator lookup result");
1737 }
1738 
1739 ExprResult
1740 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1741                        SourceLocation Loc,
1742                        const CXXScopeSpec *SS) {
1743   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1744   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1745 }
1746 
1747 /// BuildDeclRefExpr - Build an expression that references a
1748 /// declaration that does not require a closure capture.
1749 ExprResult
1750 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1751                        const DeclarationNameInfo &NameInfo,
1752                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1753                        const TemplateArgumentListInfo *TemplateArgs) {
1754   bool RefersToCapturedVariable =
1755       isa<VarDecl>(D) &&
1756       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1757 
1758   DeclRefExpr *E;
1759   if (isa<VarTemplateSpecializationDecl>(D)) {
1760     VarTemplateSpecializationDecl *VarSpec =
1761         cast<VarTemplateSpecializationDecl>(D);
1762 
1763     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1764                                         : NestedNameSpecifierLoc(),
1765                             VarSpec->getTemplateKeywordLoc(), D,
1766                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1767                             FoundD, TemplateArgs);
1768   } else {
1769     assert(!TemplateArgs && "No template arguments for non-variable"
1770                             " template specialization references");
1771     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1772                                         : NestedNameSpecifierLoc(),
1773                             SourceLocation(), D, RefersToCapturedVariable,
1774                             NameInfo, Ty, VK, FoundD);
1775   }
1776 
1777   MarkDeclRefReferenced(E);
1778 
1779   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1780       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1781       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1782       recordUseOfEvaluatedWeak(E);
1783 
1784   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1785     UnusedPrivateFields.remove(FD);
1786     // Just in case we're building an illegal pointer-to-member.
1787     if (FD->isBitField())
1788       E->setObjectKind(OK_BitField);
1789   }
1790 
1791   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1792   // designates a bit-field.
1793   if (auto *BD = dyn_cast<BindingDecl>(D))
1794     if (auto *BE = BD->getBinding())
1795       E->setObjectKind(BE->getObjectKind());
1796 
1797   return E;
1798 }
1799 
1800 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1801 /// possibly a list of template arguments.
1802 ///
1803 /// If this produces template arguments, it is permitted to call
1804 /// DecomposeTemplateName.
1805 ///
1806 /// This actually loses a lot of source location information for
1807 /// non-standard name kinds; we should consider preserving that in
1808 /// some way.
1809 void
1810 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1811                              TemplateArgumentListInfo &Buffer,
1812                              DeclarationNameInfo &NameInfo,
1813                              const TemplateArgumentListInfo *&TemplateArgs) {
1814   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1815     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1816     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1817 
1818     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1819                                        Id.TemplateId->NumArgs);
1820     translateTemplateArguments(TemplateArgsPtr, Buffer);
1821 
1822     TemplateName TName = Id.TemplateId->Template.get();
1823     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1824     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1825     TemplateArgs = &Buffer;
1826   } else {
1827     NameInfo = GetNameFromUnqualifiedId(Id);
1828     TemplateArgs = nullptr;
1829   }
1830 }
1831 
1832 static void emitEmptyLookupTypoDiagnostic(
1833     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1834     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1835     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1836   DeclContext *Ctx =
1837       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1838   if (!TC) {
1839     // Emit a special diagnostic for failed member lookups.
1840     // FIXME: computing the declaration context might fail here (?)
1841     if (Ctx)
1842       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1843                                                  << SS.getRange();
1844     else
1845       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1846     return;
1847   }
1848 
1849   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1850   bool DroppedSpecifier =
1851       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1852   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1853                         ? diag::note_implicit_param_decl
1854                         : diag::note_previous_decl;
1855   if (!Ctx)
1856     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1857                          SemaRef.PDiag(NoteID));
1858   else
1859     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1860                                  << Typo << Ctx << DroppedSpecifier
1861                                  << SS.getRange(),
1862                          SemaRef.PDiag(NoteID));
1863 }
1864 
1865 /// Diagnose an empty lookup.
1866 ///
1867 /// \return false if new lookup candidates were found
1868 bool
1869 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1870                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1871                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1872                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1873   DeclarationName Name = R.getLookupName();
1874 
1875   unsigned diagnostic = diag::err_undeclared_var_use;
1876   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1877   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1878       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1879       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1880     diagnostic = diag::err_undeclared_use;
1881     diagnostic_suggest = diag::err_undeclared_use_suggest;
1882   }
1883 
1884   // If the original lookup was an unqualified lookup, fake an
1885   // unqualified lookup.  This is useful when (for example) the
1886   // original lookup would not have found something because it was a
1887   // dependent name.
1888   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1889   while (DC) {
1890     if (isa<CXXRecordDecl>(DC)) {
1891       LookupQualifiedName(R, DC);
1892 
1893       if (!R.empty()) {
1894         // Don't give errors about ambiguities in this lookup.
1895         R.suppressDiagnostics();
1896 
1897         // During a default argument instantiation the CurContext points
1898         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1899         // function parameter list, hence add an explicit check.
1900         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1901                               ActiveTemplateInstantiations.back().Kind ==
1902             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1903         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1904         bool isInstance = CurMethod &&
1905                           CurMethod->isInstance() &&
1906                           DC == CurMethod->getParent() && !isDefaultArgument;
1907 
1908         // Give a code modification hint to insert 'this->'.
1909         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1910         // Actually quite difficult!
1911         if (getLangOpts().MSVCCompat)
1912           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1913         if (isInstance) {
1914           Diag(R.getNameLoc(), diagnostic) << Name
1915             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1916           CheckCXXThisCapture(R.getNameLoc());
1917         } else {
1918           Diag(R.getNameLoc(), diagnostic) << Name;
1919         }
1920 
1921         // Do we really want to note all of these?
1922         for (NamedDecl *D : R)
1923           Diag(D->getLocation(), diag::note_dependent_var_use);
1924 
1925         // Return true if we are inside a default argument instantiation
1926         // and the found name refers to an instance member function, otherwise
1927         // the function calling DiagnoseEmptyLookup will try to create an
1928         // implicit member call and this is wrong for default argument.
1929         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1930           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1931           return true;
1932         }
1933 
1934         // Tell the callee to try to recover.
1935         return false;
1936       }
1937 
1938       R.clear();
1939     }
1940 
1941     // In Microsoft mode, if we are performing lookup from within a friend
1942     // function definition declared at class scope then we must set
1943     // DC to the lexical parent to be able to search into the parent
1944     // class.
1945     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1946         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1947         DC->getLexicalParent()->isRecord())
1948       DC = DC->getLexicalParent();
1949     else
1950       DC = DC->getParent();
1951   }
1952 
1953   // We didn't find anything, so try to correct for a typo.
1954   TypoCorrection Corrected;
1955   if (S && Out) {
1956     SourceLocation TypoLoc = R.getNameLoc();
1957     assert(!ExplicitTemplateArgs &&
1958            "Diagnosing an empty lookup with explicit template args!");
1959     *Out = CorrectTypoDelayed(
1960         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1961         [=](const TypoCorrection &TC) {
1962           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1963                                         diagnostic, diagnostic_suggest);
1964         },
1965         nullptr, CTK_ErrorRecovery);
1966     if (*Out)
1967       return true;
1968   } else if (S && (Corrected =
1969                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1970                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1971     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1972     bool DroppedSpecifier =
1973         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1974     R.setLookupName(Corrected.getCorrection());
1975 
1976     bool AcceptableWithRecovery = false;
1977     bool AcceptableWithoutRecovery = false;
1978     NamedDecl *ND = Corrected.getFoundDecl();
1979     if (ND) {
1980       if (Corrected.isOverloaded()) {
1981         OverloadCandidateSet OCS(R.getNameLoc(),
1982                                  OverloadCandidateSet::CSK_Normal);
1983         OverloadCandidateSet::iterator Best;
1984         for (NamedDecl *CD : Corrected) {
1985           if (FunctionTemplateDecl *FTD =
1986                    dyn_cast<FunctionTemplateDecl>(CD))
1987             AddTemplateOverloadCandidate(
1988                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1989                 Args, OCS);
1990           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1991             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1992               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1993                                    Args, OCS);
1994         }
1995         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1996         case OR_Success:
1997           ND = Best->FoundDecl;
1998           Corrected.setCorrectionDecl(ND);
1999           break;
2000         default:
2001           // FIXME: Arbitrarily pick the first declaration for the note.
2002           Corrected.setCorrectionDecl(ND);
2003           break;
2004         }
2005       }
2006       R.addDecl(ND);
2007       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2008         CXXRecordDecl *Record = nullptr;
2009         if (Corrected.getCorrectionSpecifier()) {
2010           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2011           Record = Ty->getAsCXXRecordDecl();
2012         }
2013         if (!Record)
2014           Record = cast<CXXRecordDecl>(
2015               ND->getDeclContext()->getRedeclContext());
2016         R.setNamingClass(Record);
2017       }
2018 
2019       auto *UnderlyingND = ND->getUnderlyingDecl();
2020       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2021                                isa<FunctionTemplateDecl>(UnderlyingND);
2022       // FIXME: If we ended up with a typo for a type name or
2023       // Objective-C class name, we're in trouble because the parser
2024       // is in the wrong place to recover. Suggest the typo
2025       // correction, but don't make it a fix-it since we're not going
2026       // to recover well anyway.
2027       AcceptableWithoutRecovery =
2028           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2029     } else {
2030       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2031       // because we aren't able to recover.
2032       AcceptableWithoutRecovery = true;
2033     }
2034 
2035     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2036       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2037                             ? diag::note_implicit_param_decl
2038                             : diag::note_previous_decl;
2039       if (SS.isEmpty())
2040         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2041                      PDiag(NoteID), AcceptableWithRecovery);
2042       else
2043         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2044                                   << Name << computeDeclContext(SS, false)
2045                                   << DroppedSpecifier << SS.getRange(),
2046                      PDiag(NoteID), AcceptableWithRecovery);
2047 
2048       // Tell the callee whether to try to recover.
2049       return !AcceptableWithRecovery;
2050     }
2051   }
2052   R.clear();
2053 
2054   // Emit a special diagnostic for failed member lookups.
2055   // FIXME: computing the declaration context might fail here (?)
2056   if (!SS.isEmpty()) {
2057     Diag(R.getNameLoc(), diag::err_no_member)
2058       << Name << computeDeclContext(SS, false)
2059       << SS.getRange();
2060     return true;
2061   }
2062 
2063   // Give up, we can't recover.
2064   Diag(R.getNameLoc(), diagnostic) << Name;
2065   return true;
2066 }
2067 
2068 /// In Microsoft mode, if we are inside a template class whose parent class has
2069 /// dependent base classes, and we can't resolve an unqualified identifier, then
2070 /// assume the identifier is a member of a dependent base class.  We can only
2071 /// recover successfully in static methods, instance methods, and other contexts
2072 /// where 'this' is available.  This doesn't precisely match MSVC's
2073 /// instantiation model, but it's close enough.
2074 static Expr *
2075 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2076                                DeclarationNameInfo &NameInfo,
2077                                SourceLocation TemplateKWLoc,
2078                                const TemplateArgumentListInfo *TemplateArgs) {
2079   // Only try to recover from lookup into dependent bases in static methods or
2080   // contexts where 'this' is available.
2081   QualType ThisType = S.getCurrentThisType();
2082   const CXXRecordDecl *RD = nullptr;
2083   if (!ThisType.isNull())
2084     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2085   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2086     RD = MD->getParent();
2087   if (!RD || !RD->hasAnyDependentBases())
2088     return nullptr;
2089 
2090   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2091   // is available, suggest inserting 'this->' as a fixit.
2092   SourceLocation Loc = NameInfo.getLoc();
2093   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2094   DB << NameInfo.getName() << RD;
2095 
2096   if (!ThisType.isNull()) {
2097     DB << FixItHint::CreateInsertion(Loc, "this->");
2098     return CXXDependentScopeMemberExpr::Create(
2099         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2100         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2101         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2102   }
2103 
2104   // Synthesize a fake NNS that points to the derived class.  This will
2105   // perform name lookup during template instantiation.
2106   CXXScopeSpec SS;
2107   auto *NNS =
2108       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2109   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2110   return DependentScopeDeclRefExpr::Create(
2111       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2112       TemplateArgs);
2113 }
2114 
2115 ExprResult
2116 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2117                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2118                         bool HasTrailingLParen, bool IsAddressOfOperand,
2119                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2120                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2121   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2122          "cannot be direct & operand and have a trailing lparen");
2123   if (SS.isInvalid())
2124     return ExprError();
2125 
2126   TemplateArgumentListInfo TemplateArgsBuffer;
2127 
2128   // Decompose the UnqualifiedId into the following data.
2129   DeclarationNameInfo NameInfo;
2130   const TemplateArgumentListInfo *TemplateArgs;
2131   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2132 
2133   DeclarationName Name = NameInfo.getName();
2134   IdentifierInfo *II = Name.getAsIdentifierInfo();
2135   SourceLocation NameLoc = NameInfo.getLoc();
2136 
2137   // C++ [temp.dep.expr]p3:
2138   //   An id-expression is type-dependent if it contains:
2139   //     -- an identifier that was declared with a dependent type,
2140   //        (note: handled after lookup)
2141   //     -- a template-id that is dependent,
2142   //        (note: handled in BuildTemplateIdExpr)
2143   //     -- a conversion-function-id that specifies a dependent type,
2144   //     -- a nested-name-specifier that contains a class-name that
2145   //        names a dependent type.
2146   // Determine whether this is a member of an unknown specialization;
2147   // we need to handle these differently.
2148   bool DependentID = false;
2149   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2150       Name.getCXXNameType()->isDependentType()) {
2151     DependentID = true;
2152   } else if (SS.isSet()) {
2153     if (DeclContext *DC = computeDeclContext(SS, false)) {
2154       if (RequireCompleteDeclContext(SS, DC))
2155         return ExprError();
2156     } else {
2157       DependentID = true;
2158     }
2159   }
2160 
2161   if (DependentID)
2162     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2163                                       IsAddressOfOperand, TemplateArgs);
2164 
2165   // Perform the required lookup.
2166   LookupResult R(*this, NameInfo,
2167                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2168                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2169   if (TemplateArgs) {
2170     // Lookup the template name again to correctly establish the context in
2171     // which it was found. This is really unfortunate as we already did the
2172     // lookup to determine that it was a template name in the first place. If
2173     // this becomes a performance hit, we can work harder to preserve those
2174     // results until we get here but it's likely not worth it.
2175     bool MemberOfUnknownSpecialization;
2176     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2177                        MemberOfUnknownSpecialization);
2178 
2179     if (MemberOfUnknownSpecialization ||
2180         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2181       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2182                                         IsAddressOfOperand, TemplateArgs);
2183   } else {
2184     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2185     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2186 
2187     // If the result might be in a dependent base class, this is a dependent
2188     // id-expression.
2189     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2190       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2191                                         IsAddressOfOperand, TemplateArgs);
2192 
2193     // If this reference is in an Objective-C method, then we need to do
2194     // some special Objective-C lookup, too.
2195     if (IvarLookupFollowUp) {
2196       ExprResult E(LookupInObjCMethod(R, S, II, true));
2197       if (E.isInvalid())
2198         return ExprError();
2199 
2200       if (Expr *Ex = E.getAs<Expr>())
2201         return Ex;
2202     }
2203   }
2204 
2205   if (R.isAmbiguous())
2206     return ExprError();
2207 
2208   // This could be an implicitly declared function reference (legal in C90,
2209   // extension in C99, forbidden in C++).
2210   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2211     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2212     if (D) R.addDecl(D);
2213   }
2214 
2215   // Determine whether this name might be a candidate for
2216   // argument-dependent lookup.
2217   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2218 
2219   if (R.empty() && !ADL) {
2220     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2221       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2222                                                    TemplateKWLoc, TemplateArgs))
2223         return E;
2224     }
2225 
2226     // Don't diagnose an empty lookup for inline assembly.
2227     if (IsInlineAsmIdentifier)
2228       return ExprError();
2229 
2230     // If this name wasn't predeclared and if this is not a function
2231     // call, diagnose the problem.
2232     TypoExpr *TE = nullptr;
2233     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2234         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2235     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2236     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2237            "Typo correction callback misconfigured");
2238     if (CCC) {
2239       // Make sure the callback knows what the typo being diagnosed is.
2240       CCC->setTypoName(II);
2241       if (SS.isValid())
2242         CCC->setTypoNNS(SS.getScopeRep());
2243     }
2244     if (DiagnoseEmptyLookup(S, SS, R,
2245                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2246                             nullptr, None, &TE)) {
2247       if (TE && KeywordReplacement) {
2248         auto &State = getTypoExprState(TE);
2249         auto BestTC = State.Consumer->getNextCorrection();
2250         if (BestTC.isKeyword()) {
2251           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2252           if (State.DiagHandler)
2253             State.DiagHandler(BestTC);
2254           KeywordReplacement->startToken();
2255           KeywordReplacement->setKind(II->getTokenID());
2256           KeywordReplacement->setIdentifierInfo(II);
2257           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2258           // Clean up the state associated with the TypoExpr, since it has
2259           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2260           clearDelayedTypo(TE);
2261           // Signal that a correction to a keyword was performed by returning a
2262           // valid-but-null ExprResult.
2263           return (Expr*)nullptr;
2264         }
2265         State.Consumer->resetCorrectionStream();
2266       }
2267       return TE ? TE : ExprError();
2268     }
2269 
2270     assert(!R.empty() &&
2271            "DiagnoseEmptyLookup returned false but added no results");
2272 
2273     // If we found an Objective-C instance variable, let
2274     // LookupInObjCMethod build the appropriate expression to
2275     // reference the ivar.
2276     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2277       R.clear();
2278       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2279       // In a hopelessly buggy code, Objective-C instance variable
2280       // lookup fails and no expression will be built to reference it.
2281       if (!E.isInvalid() && !E.get())
2282         return ExprError();
2283       return E;
2284     }
2285   }
2286 
2287   // This is guaranteed from this point on.
2288   assert(!R.empty() || ADL);
2289 
2290   // Check whether this might be a C++ implicit instance member access.
2291   // C++ [class.mfct.non-static]p3:
2292   //   When an id-expression that is not part of a class member access
2293   //   syntax and not used to form a pointer to member is used in the
2294   //   body of a non-static member function of class X, if name lookup
2295   //   resolves the name in the id-expression to a non-static non-type
2296   //   member of some class C, the id-expression is transformed into a
2297   //   class member access expression using (*this) as the
2298   //   postfix-expression to the left of the . operator.
2299   //
2300   // But we don't actually need to do this for '&' operands if R
2301   // resolved to a function or overloaded function set, because the
2302   // expression is ill-formed if it actually works out to be a
2303   // non-static member function:
2304   //
2305   // C++ [expr.ref]p4:
2306   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2307   //   [t]he expression can be used only as the left-hand operand of a
2308   //   member function call.
2309   //
2310   // There are other safeguards against such uses, but it's important
2311   // to get this right here so that we don't end up making a
2312   // spuriously dependent expression if we're inside a dependent
2313   // instance method.
2314   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2315     bool MightBeImplicitMember;
2316     if (!IsAddressOfOperand)
2317       MightBeImplicitMember = true;
2318     else if (!SS.isEmpty())
2319       MightBeImplicitMember = false;
2320     else if (R.isOverloadedResult())
2321       MightBeImplicitMember = false;
2322     else if (R.isUnresolvableResult())
2323       MightBeImplicitMember = true;
2324     else
2325       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2326                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2327                               isa<MSPropertyDecl>(R.getFoundDecl());
2328 
2329     if (MightBeImplicitMember)
2330       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2331                                              R, TemplateArgs, S);
2332   }
2333 
2334   if (TemplateArgs || TemplateKWLoc.isValid()) {
2335 
2336     // In C++1y, if this is a variable template id, then check it
2337     // in BuildTemplateIdExpr().
2338     // The single lookup result must be a variable template declaration.
2339     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2340         Id.TemplateId->Kind == TNK_Var_template) {
2341       assert(R.getAsSingle<VarTemplateDecl>() &&
2342              "There should only be one declaration found.");
2343     }
2344 
2345     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2346   }
2347 
2348   return BuildDeclarationNameExpr(SS, R, ADL);
2349 }
2350 
2351 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2352 /// declaration name, generally during template instantiation.
2353 /// There's a large number of things which don't need to be done along
2354 /// this path.
2355 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2356     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2357     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2358   DeclContext *DC = computeDeclContext(SS, false);
2359   if (!DC)
2360     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2361                                      NameInfo, /*TemplateArgs=*/nullptr);
2362 
2363   if (RequireCompleteDeclContext(SS, DC))
2364     return ExprError();
2365 
2366   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2367   LookupQualifiedName(R, DC);
2368 
2369   if (R.isAmbiguous())
2370     return ExprError();
2371 
2372   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2373     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2374                                      NameInfo, /*TemplateArgs=*/nullptr);
2375 
2376   if (R.empty()) {
2377     Diag(NameInfo.getLoc(), diag::err_no_member)
2378       << NameInfo.getName() << DC << SS.getRange();
2379     return ExprError();
2380   }
2381 
2382   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2383     // Diagnose a missing typename if this resolved unambiguously to a type in
2384     // a dependent context.  If we can recover with a type, downgrade this to
2385     // a warning in Microsoft compatibility mode.
2386     unsigned DiagID = diag::err_typename_missing;
2387     if (RecoveryTSI && getLangOpts().MSVCCompat)
2388       DiagID = diag::ext_typename_missing;
2389     SourceLocation Loc = SS.getBeginLoc();
2390     auto D = Diag(Loc, DiagID);
2391     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2392       << SourceRange(Loc, NameInfo.getEndLoc());
2393 
2394     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2395     // context.
2396     if (!RecoveryTSI)
2397       return ExprError();
2398 
2399     // Only issue the fixit if we're prepared to recover.
2400     D << FixItHint::CreateInsertion(Loc, "typename ");
2401 
2402     // Recover by pretending this was an elaborated type.
2403     QualType Ty = Context.getTypeDeclType(TD);
2404     TypeLocBuilder TLB;
2405     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2406 
2407     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2408     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2409     QTL.setElaboratedKeywordLoc(SourceLocation());
2410     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2411 
2412     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2413 
2414     return ExprEmpty();
2415   }
2416 
2417   // Defend against this resolving to an implicit member access. We usually
2418   // won't get here if this might be a legitimate a class member (we end up in
2419   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2420   // a pointer-to-member or in an unevaluated context in C++11.
2421   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2422     return BuildPossibleImplicitMemberExpr(SS,
2423                                            /*TemplateKWLoc=*/SourceLocation(),
2424                                            R, /*TemplateArgs=*/nullptr, S);
2425 
2426   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2427 }
2428 
2429 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2430 /// detected that we're currently inside an ObjC method.  Perform some
2431 /// additional lookup.
2432 ///
2433 /// Ideally, most of this would be done by lookup, but there's
2434 /// actually quite a lot of extra work involved.
2435 ///
2436 /// Returns a null sentinel to indicate trivial success.
2437 ExprResult
2438 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2439                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2440   SourceLocation Loc = Lookup.getNameLoc();
2441   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2442 
2443   // Check for error condition which is already reported.
2444   if (!CurMethod)
2445     return ExprError();
2446 
2447   // There are two cases to handle here.  1) scoped lookup could have failed,
2448   // in which case we should look for an ivar.  2) scoped lookup could have
2449   // found a decl, but that decl is outside the current instance method (i.e.
2450   // a global variable).  In these two cases, we do a lookup for an ivar with
2451   // this name, if the lookup sucedes, we replace it our current decl.
2452 
2453   // If we're in a class method, we don't normally want to look for
2454   // ivars.  But if we don't find anything else, and there's an
2455   // ivar, that's an error.
2456   bool IsClassMethod = CurMethod->isClassMethod();
2457 
2458   bool LookForIvars;
2459   if (Lookup.empty())
2460     LookForIvars = true;
2461   else if (IsClassMethod)
2462     LookForIvars = false;
2463   else
2464     LookForIvars = (Lookup.isSingleResult() &&
2465                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2466   ObjCInterfaceDecl *IFace = nullptr;
2467   if (LookForIvars) {
2468     IFace = CurMethod->getClassInterface();
2469     ObjCInterfaceDecl *ClassDeclared;
2470     ObjCIvarDecl *IV = nullptr;
2471     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2472       // Diagnose using an ivar in a class method.
2473       if (IsClassMethod)
2474         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2475                          << IV->getDeclName());
2476 
2477       // If we're referencing an invalid decl, just return this as a silent
2478       // error node.  The error diagnostic was already emitted on the decl.
2479       if (IV->isInvalidDecl())
2480         return ExprError();
2481 
2482       // Check if referencing a field with __attribute__((deprecated)).
2483       if (DiagnoseUseOfDecl(IV, Loc))
2484         return ExprError();
2485 
2486       // Diagnose the use of an ivar outside of the declaring class.
2487       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2488           !declaresSameEntity(ClassDeclared, IFace) &&
2489           !getLangOpts().DebuggerSupport)
2490         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2491 
2492       // FIXME: This should use a new expr for a direct reference, don't
2493       // turn this into Self->ivar, just return a BareIVarExpr or something.
2494       IdentifierInfo &II = Context.Idents.get("self");
2495       UnqualifiedId SelfName;
2496       SelfName.setIdentifier(&II, SourceLocation());
2497       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2498       CXXScopeSpec SelfScopeSpec;
2499       SourceLocation TemplateKWLoc;
2500       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2501                                               SelfName, false, false);
2502       if (SelfExpr.isInvalid())
2503         return ExprError();
2504 
2505       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2506       if (SelfExpr.isInvalid())
2507         return ExprError();
2508 
2509       MarkAnyDeclReferenced(Loc, IV, true);
2510 
2511       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2512       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2513           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2514         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2515 
2516       ObjCIvarRefExpr *Result = new (Context)
2517           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2518                           IV->getLocation(), SelfExpr.get(), true, true);
2519 
2520       if (getLangOpts().ObjCAutoRefCount) {
2521         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2522           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2523             recordUseOfEvaluatedWeak(Result);
2524         }
2525         if (CurContext->isClosure())
2526           Diag(Loc, diag::warn_implicitly_retains_self)
2527             << FixItHint::CreateInsertion(Loc, "self->");
2528       }
2529 
2530       return Result;
2531     }
2532   } else if (CurMethod->isInstanceMethod()) {
2533     // We should warn if a local variable hides an ivar.
2534     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2535       ObjCInterfaceDecl *ClassDeclared;
2536       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2537         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2538             declaresSameEntity(IFace, ClassDeclared))
2539           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2540       }
2541     }
2542   } else if (Lookup.isSingleResult() &&
2543              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2544     // If accessing a stand-alone ivar in a class method, this is an error.
2545     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2546       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2547                        << IV->getDeclName());
2548   }
2549 
2550   if (Lookup.empty() && II && AllowBuiltinCreation) {
2551     // FIXME. Consolidate this with similar code in LookupName.
2552     if (unsigned BuiltinID = II->getBuiltinID()) {
2553       if (!(getLangOpts().CPlusPlus &&
2554             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2555         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2556                                            S, Lookup.isForRedeclaration(),
2557                                            Lookup.getNameLoc());
2558         if (D) Lookup.addDecl(D);
2559       }
2560     }
2561   }
2562   // Sentinel value saying that we didn't do anything special.
2563   return ExprResult((Expr *)nullptr);
2564 }
2565 
2566 /// \brief Cast a base object to a member's actual type.
2567 ///
2568 /// Logically this happens in three phases:
2569 ///
2570 /// * First we cast from the base type to the naming class.
2571 ///   The naming class is the class into which we were looking
2572 ///   when we found the member;  it's the qualifier type if a
2573 ///   qualifier was provided, and otherwise it's the base type.
2574 ///
2575 /// * Next we cast from the naming class to the declaring class.
2576 ///   If the member we found was brought into a class's scope by
2577 ///   a using declaration, this is that class;  otherwise it's
2578 ///   the class declaring the member.
2579 ///
2580 /// * Finally we cast from the declaring class to the "true"
2581 ///   declaring class of the member.  This conversion does not
2582 ///   obey access control.
2583 ExprResult
2584 Sema::PerformObjectMemberConversion(Expr *From,
2585                                     NestedNameSpecifier *Qualifier,
2586                                     NamedDecl *FoundDecl,
2587                                     NamedDecl *Member) {
2588   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2589   if (!RD)
2590     return From;
2591 
2592   QualType DestRecordType;
2593   QualType DestType;
2594   QualType FromRecordType;
2595   QualType FromType = From->getType();
2596   bool PointerConversions = false;
2597   if (isa<FieldDecl>(Member)) {
2598     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2599 
2600     if (FromType->getAs<PointerType>()) {
2601       DestType = Context.getPointerType(DestRecordType);
2602       FromRecordType = FromType->getPointeeType();
2603       PointerConversions = true;
2604     } else {
2605       DestType = DestRecordType;
2606       FromRecordType = FromType;
2607     }
2608   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2609     if (Method->isStatic())
2610       return From;
2611 
2612     DestType = Method->getThisType(Context);
2613     DestRecordType = DestType->getPointeeType();
2614 
2615     if (FromType->getAs<PointerType>()) {
2616       FromRecordType = FromType->getPointeeType();
2617       PointerConversions = true;
2618     } else {
2619       FromRecordType = FromType;
2620       DestType = DestRecordType;
2621     }
2622   } else {
2623     // No conversion necessary.
2624     return From;
2625   }
2626 
2627   if (DestType->isDependentType() || FromType->isDependentType())
2628     return From;
2629 
2630   // If the unqualified types are the same, no conversion is necessary.
2631   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2632     return From;
2633 
2634   SourceRange FromRange = From->getSourceRange();
2635   SourceLocation FromLoc = FromRange.getBegin();
2636 
2637   ExprValueKind VK = From->getValueKind();
2638 
2639   // C++ [class.member.lookup]p8:
2640   //   [...] Ambiguities can often be resolved by qualifying a name with its
2641   //   class name.
2642   //
2643   // If the member was a qualified name and the qualified referred to a
2644   // specific base subobject type, we'll cast to that intermediate type
2645   // first and then to the object in which the member is declared. That allows
2646   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2647   //
2648   //   class Base { public: int x; };
2649   //   class Derived1 : public Base { };
2650   //   class Derived2 : public Base { };
2651   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2652   //
2653   //   void VeryDerived::f() {
2654   //     x = 17; // error: ambiguous base subobjects
2655   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2656   //   }
2657   if (Qualifier && Qualifier->getAsType()) {
2658     QualType QType = QualType(Qualifier->getAsType(), 0);
2659     assert(QType->isRecordType() && "lookup done with non-record type");
2660 
2661     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2662 
2663     // In C++98, the qualifier type doesn't actually have to be a base
2664     // type of the object type, in which case we just ignore it.
2665     // Otherwise build the appropriate casts.
2666     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2667       CXXCastPath BasePath;
2668       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2669                                        FromLoc, FromRange, &BasePath))
2670         return ExprError();
2671 
2672       if (PointerConversions)
2673         QType = Context.getPointerType(QType);
2674       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2675                                VK, &BasePath).get();
2676 
2677       FromType = QType;
2678       FromRecordType = QRecordType;
2679 
2680       // If the qualifier type was the same as the destination type,
2681       // we're done.
2682       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2683         return From;
2684     }
2685   }
2686 
2687   bool IgnoreAccess = false;
2688 
2689   // If we actually found the member through a using declaration, cast
2690   // down to the using declaration's type.
2691   //
2692   // Pointer equality is fine here because only one declaration of a
2693   // class ever has member declarations.
2694   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2695     assert(isa<UsingShadowDecl>(FoundDecl));
2696     QualType URecordType = Context.getTypeDeclType(
2697                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2698 
2699     // We only need to do this if the naming-class to declaring-class
2700     // conversion is non-trivial.
2701     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2702       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2703       CXXCastPath BasePath;
2704       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2705                                        FromLoc, FromRange, &BasePath))
2706         return ExprError();
2707 
2708       QualType UType = URecordType;
2709       if (PointerConversions)
2710         UType = Context.getPointerType(UType);
2711       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2712                                VK, &BasePath).get();
2713       FromType = UType;
2714       FromRecordType = URecordType;
2715     }
2716 
2717     // We don't do access control for the conversion from the
2718     // declaring class to the true declaring class.
2719     IgnoreAccess = true;
2720   }
2721 
2722   CXXCastPath BasePath;
2723   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2724                                    FromLoc, FromRange, &BasePath,
2725                                    IgnoreAccess))
2726     return ExprError();
2727 
2728   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2729                            VK, &BasePath);
2730 }
2731 
2732 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2733                                       const LookupResult &R,
2734                                       bool HasTrailingLParen) {
2735   // Only when used directly as the postfix-expression of a call.
2736   if (!HasTrailingLParen)
2737     return false;
2738 
2739   // Never if a scope specifier was provided.
2740   if (SS.isSet())
2741     return false;
2742 
2743   // Only in C++ or ObjC++.
2744   if (!getLangOpts().CPlusPlus)
2745     return false;
2746 
2747   // Turn off ADL when we find certain kinds of declarations during
2748   // normal lookup:
2749   for (NamedDecl *D : R) {
2750     // C++0x [basic.lookup.argdep]p3:
2751     //     -- a declaration of a class member
2752     // Since using decls preserve this property, we check this on the
2753     // original decl.
2754     if (D->isCXXClassMember())
2755       return false;
2756 
2757     // C++0x [basic.lookup.argdep]p3:
2758     //     -- a block-scope function declaration that is not a
2759     //        using-declaration
2760     // NOTE: we also trigger this for function templates (in fact, we
2761     // don't check the decl type at all, since all other decl types
2762     // turn off ADL anyway).
2763     if (isa<UsingShadowDecl>(D))
2764       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2765     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2766       return false;
2767 
2768     // C++0x [basic.lookup.argdep]p3:
2769     //     -- a declaration that is neither a function or a function
2770     //        template
2771     // And also for builtin functions.
2772     if (isa<FunctionDecl>(D)) {
2773       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2774 
2775       // But also builtin functions.
2776       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2777         return false;
2778     } else if (!isa<FunctionTemplateDecl>(D))
2779       return false;
2780   }
2781 
2782   return true;
2783 }
2784 
2785 
2786 /// Diagnoses obvious problems with the use of the given declaration
2787 /// as an expression.  This is only actually called for lookups that
2788 /// were not overloaded, and it doesn't promise that the declaration
2789 /// will in fact be used.
2790 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2791   if (D->isInvalidDecl())
2792     return true;
2793 
2794   if (isa<TypedefNameDecl>(D)) {
2795     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2796     return true;
2797   }
2798 
2799   if (isa<ObjCInterfaceDecl>(D)) {
2800     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2801     return true;
2802   }
2803 
2804   if (isa<NamespaceDecl>(D)) {
2805     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2806     return true;
2807   }
2808 
2809   return false;
2810 }
2811 
2812 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2813                                           LookupResult &R, bool NeedsADL,
2814                                           bool AcceptInvalidDecl) {
2815   // If this is a single, fully-resolved result and we don't need ADL,
2816   // just build an ordinary singleton decl ref.
2817   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2818     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2819                                     R.getRepresentativeDecl(), nullptr,
2820                                     AcceptInvalidDecl);
2821 
2822   // We only need to check the declaration if there's exactly one
2823   // result, because in the overloaded case the results can only be
2824   // functions and function templates.
2825   if (R.isSingleResult() &&
2826       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2827     return ExprError();
2828 
2829   // Otherwise, just build an unresolved lookup expression.  Suppress
2830   // any lookup-related diagnostics; we'll hash these out later, when
2831   // we've picked a target.
2832   R.suppressDiagnostics();
2833 
2834   UnresolvedLookupExpr *ULE
2835     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2836                                    SS.getWithLocInContext(Context),
2837                                    R.getLookupNameInfo(),
2838                                    NeedsADL, R.isOverloadedResult(),
2839                                    R.begin(), R.end());
2840 
2841   return ULE;
2842 }
2843 
2844 static void
2845 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2846                                    ValueDecl *var, DeclContext *DC);
2847 
2848 /// \brief Complete semantic analysis for a reference to the given declaration.
2849 ExprResult Sema::BuildDeclarationNameExpr(
2850     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2851     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2852     bool AcceptInvalidDecl) {
2853   assert(D && "Cannot refer to a NULL declaration");
2854   assert(!isa<FunctionTemplateDecl>(D) &&
2855          "Cannot refer unambiguously to a function template");
2856 
2857   SourceLocation Loc = NameInfo.getLoc();
2858   if (CheckDeclInExpr(*this, Loc, D))
2859     return ExprError();
2860 
2861   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2862     // Specifically diagnose references to class templates that are missing
2863     // a template argument list.
2864     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2865                                            << Template << SS.getRange();
2866     Diag(Template->getLocation(), diag::note_template_decl_here);
2867     return ExprError();
2868   }
2869 
2870   // Make sure that we're referring to a value.
2871   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2872   if (!VD) {
2873     Diag(Loc, diag::err_ref_non_value)
2874       << D << SS.getRange();
2875     Diag(D->getLocation(), diag::note_declared_at);
2876     return ExprError();
2877   }
2878 
2879   // Check whether this declaration can be used. Note that we suppress
2880   // this check when we're going to perform argument-dependent lookup
2881   // on this function name, because this might not be the function
2882   // that overload resolution actually selects.
2883   if (DiagnoseUseOfDecl(VD, Loc))
2884     return ExprError();
2885 
2886   // Only create DeclRefExpr's for valid Decl's.
2887   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2888     return ExprError();
2889 
2890   // Handle members of anonymous structs and unions.  If we got here,
2891   // and the reference is to a class member indirect field, then this
2892   // must be the subject of a pointer-to-member expression.
2893   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2894     if (!indirectField->isCXXClassMember())
2895       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2896                                                       indirectField);
2897 
2898   {
2899     QualType type = VD->getType();
2900     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2901       // C++ [except.spec]p17:
2902       //   An exception-specification is considered to be needed when:
2903       //   - in an expression, the function is the unique lookup result or
2904       //     the selected member of a set of overloaded functions.
2905       ResolveExceptionSpec(Loc, FPT);
2906       type = VD->getType();
2907     }
2908     ExprValueKind valueKind = VK_RValue;
2909 
2910     switch (D->getKind()) {
2911     // Ignore all the non-ValueDecl kinds.
2912 #define ABSTRACT_DECL(kind)
2913 #define VALUE(type, base)
2914 #define DECL(type, base) \
2915     case Decl::type:
2916 #include "clang/AST/DeclNodes.inc"
2917       llvm_unreachable("invalid value decl kind");
2918 
2919     // These shouldn't make it here.
2920     case Decl::ObjCAtDefsField:
2921     case Decl::ObjCIvar:
2922       llvm_unreachable("forming non-member reference to ivar?");
2923 
2924     // Enum constants are always r-values and never references.
2925     // Unresolved using declarations are dependent.
2926     case Decl::EnumConstant:
2927     case Decl::UnresolvedUsingValue:
2928     case Decl::OMPDeclareReduction:
2929       valueKind = VK_RValue;
2930       break;
2931 
2932     // Fields and indirect fields that got here must be for
2933     // pointer-to-member expressions; we just call them l-values for
2934     // internal consistency, because this subexpression doesn't really
2935     // exist in the high-level semantics.
2936     case Decl::Field:
2937     case Decl::IndirectField:
2938       assert(getLangOpts().CPlusPlus &&
2939              "building reference to field in C?");
2940 
2941       // These can't have reference type in well-formed programs, but
2942       // for internal consistency we do this anyway.
2943       type = type.getNonReferenceType();
2944       valueKind = VK_LValue;
2945       break;
2946 
2947     // Non-type template parameters are either l-values or r-values
2948     // depending on the type.
2949     case Decl::NonTypeTemplateParm: {
2950       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2951         type = reftype->getPointeeType();
2952         valueKind = VK_LValue; // even if the parameter is an r-value reference
2953         break;
2954       }
2955 
2956       // For non-references, we need to strip qualifiers just in case
2957       // the template parameter was declared as 'const int' or whatever.
2958       valueKind = VK_RValue;
2959       type = type.getUnqualifiedType();
2960       break;
2961     }
2962 
2963     case Decl::Var:
2964     case Decl::VarTemplateSpecialization:
2965     case Decl::VarTemplatePartialSpecialization:
2966     case Decl::Decomposition:
2967     case Decl::OMPCapturedExpr:
2968       // In C, "extern void blah;" is valid and is an r-value.
2969       if (!getLangOpts().CPlusPlus &&
2970           !type.hasQualifiers() &&
2971           type->isVoidType()) {
2972         valueKind = VK_RValue;
2973         break;
2974       }
2975       // fallthrough
2976 
2977     case Decl::ImplicitParam:
2978     case Decl::ParmVar: {
2979       // These are always l-values.
2980       valueKind = VK_LValue;
2981       type = type.getNonReferenceType();
2982 
2983       // FIXME: Does the addition of const really only apply in
2984       // potentially-evaluated contexts? Since the variable isn't actually
2985       // captured in an unevaluated context, it seems that the answer is no.
2986       if (!isUnevaluatedContext()) {
2987         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2988         if (!CapturedType.isNull())
2989           type = CapturedType;
2990       }
2991 
2992       break;
2993     }
2994 
2995     case Decl::Binding: {
2996       // These are always lvalues.
2997       valueKind = VK_LValue;
2998       type = type.getNonReferenceType();
2999       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3000       // decides how that's supposed to work.
3001       auto *BD = cast<BindingDecl>(VD);
3002       if (BD->getDeclContext()->isFunctionOrMethod() &&
3003           BD->getDeclContext() != CurContext)
3004         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3005       break;
3006     }
3007 
3008     case Decl::Function: {
3009       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3010         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3011           type = Context.BuiltinFnTy;
3012           valueKind = VK_RValue;
3013           break;
3014         }
3015       }
3016 
3017       const FunctionType *fty = type->castAs<FunctionType>();
3018 
3019       // If we're referring to a function with an __unknown_anytype
3020       // result type, make the entire expression __unknown_anytype.
3021       if (fty->getReturnType() == Context.UnknownAnyTy) {
3022         type = Context.UnknownAnyTy;
3023         valueKind = VK_RValue;
3024         break;
3025       }
3026 
3027       // Functions are l-values in C++.
3028       if (getLangOpts().CPlusPlus) {
3029         valueKind = VK_LValue;
3030         break;
3031       }
3032 
3033       // C99 DR 316 says that, if a function type comes from a
3034       // function definition (without a prototype), that type is only
3035       // used for checking compatibility. Therefore, when referencing
3036       // the function, we pretend that we don't have the full function
3037       // type.
3038       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3039           isa<FunctionProtoType>(fty))
3040         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3041                                               fty->getExtInfo());
3042 
3043       // Functions are r-values in C.
3044       valueKind = VK_RValue;
3045       break;
3046     }
3047 
3048     case Decl::MSProperty:
3049       valueKind = VK_LValue;
3050       break;
3051 
3052     case Decl::CXXMethod:
3053       // If we're referring to a method with an __unknown_anytype
3054       // result type, make the entire expression __unknown_anytype.
3055       // This should only be possible with a type written directly.
3056       if (const FunctionProtoType *proto
3057             = dyn_cast<FunctionProtoType>(VD->getType()))
3058         if (proto->getReturnType() == Context.UnknownAnyTy) {
3059           type = Context.UnknownAnyTy;
3060           valueKind = VK_RValue;
3061           break;
3062         }
3063 
3064       // C++ methods are l-values if static, r-values if non-static.
3065       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3066         valueKind = VK_LValue;
3067         break;
3068       }
3069       // fallthrough
3070 
3071     case Decl::CXXConversion:
3072     case Decl::CXXDestructor:
3073     case Decl::CXXConstructor:
3074       valueKind = VK_RValue;
3075       break;
3076     }
3077 
3078     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3079                             TemplateArgs);
3080   }
3081 }
3082 
3083 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3084                                     SmallString<32> &Target) {
3085   Target.resize(CharByteWidth * (Source.size() + 1));
3086   char *ResultPtr = &Target[0];
3087   const llvm::UTF8 *ErrorPtr;
3088   bool success =
3089       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3090   (void)success;
3091   assert(success);
3092   Target.resize(ResultPtr - &Target[0]);
3093 }
3094 
3095 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3096                                      PredefinedExpr::IdentType IT) {
3097   // Pick the current block, lambda, captured statement or function.
3098   Decl *currentDecl = nullptr;
3099   if (const BlockScopeInfo *BSI = getCurBlock())
3100     currentDecl = BSI->TheDecl;
3101   else if (const LambdaScopeInfo *LSI = getCurLambda())
3102     currentDecl = LSI->CallOperator;
3103   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3104     currentDecl = CSI->TheCapturedDecl;
3105   else
3106     currentDecl = getCurFunctionOrMethodDecl();
3107 
3108   if (!currentDecl) {
3109     Diag(Loc, diag::ext_predef_outside_function);
3110     currentDecl = Context.getTranslationUnitDecl();
3111   }
3112 
3113   QualType ResTy;
3114   StringLiteral *SL = nullptr;
3115   if (cast<DeclContext>(currentDecl)->isDependentContext())
3116     ResTy = Context.DependentTy;
3117   else {
3118     // Pre-defined identifiers are of type char[x], where x is the length of
3119     // the string.
3120     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3121     unsigned Length = Str.length();
3122 
3123     llvm::APInt LengthI(32, Length + 1);
3124     if (IT == PredefinedExpr::LFunction) {
3125       ResTy = Context.WideCharTy.withConst();
3126       SmallString<32> RawChars;
3127       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3128                               Str, RawChars);
3129       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3130                                            /*IndexTypeQuals*/ 0);
3131       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3132                                  /*Pascal*/ false, ResTy, Loc);
3133     } else {
3134       ResTy = Context.CharTy.withConst();
3135       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3136                                            /*IndexTypeQuals*/ 0);
3137       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3138                                  /*Pascal*/ false, ResTy, Loc);
3139     }
3140   }
3141 
3142   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3143 }
3144 
3145 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3146   PredefinedExpr::IdentType IT;
3147 
3148   switch (Kind) {
3149   default: llvm_unreachable("Unknown simple primary expr!");
3150   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3151   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3152   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3153   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3154   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3155   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3156   }
3157 
3158   return BuildPredefinedExpr(Loc, IT);
3159 }
3160 
3161 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3162   SmallString<16> CharBuffer;
3163   bool Invalid = false;
3164   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3165   if (Invalid)
3166     return ExprError();
3167 
3168   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3169                             PP, Tok.getKind());
3170   if (Literal.hadError())
3171     return ExprError();
3172 
3173   QualType Ty;
3174   if (Literal.isWide())
3175     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3176   else if (Literal.isUTF16())
3177     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3178   else if (Literal.isUTF32())
3179     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3180   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3181     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3182   else
3183     Ty = Context.CharTy;  // 'x' -> char in C++
3184 
3185   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3186   if (Literal.isWide())
3187     Kind = CharacterLiteral::Wide;
3188   else if (Literal.isUTF16())
3189     Kind = CharacterLiteral::UTF16;
3190   else if (Literal.isUTF32())
3191     Kind = CharacterLiteral::UTF32;
3192   else if (Literal.isUTF8())
3193     Kind = CharacterLiteral::UTF8;
3194 
3195   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3196                                              Tok.getLocation());
3197 
3198   if (Literal.getUDSuffix().empty())
3199     return Lit;
3200 
3201   // We're building a user-defined literal.
3202   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3203   SourceLocation UDSuffixLoc =
3204     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3205 
3206   // Make sure we're allowed user-defined literals here.
3207   if (!UDLScope)
3208     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3209 
3210   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3211   //   operator "" X (ch)
3212   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3213                                         Lit, Tok.getLocation());
3214 }
3215 
3216 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3217   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3218   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3219                                 Context.IntTy, Loc);
3220 }
3221 
3222 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3223                                   QualType Ty, SourceLocation Loc) {
3224   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3225 
3226   using llvm::APFloat;
3227   APFloat Val(Format);
3228 
3229   APFloat::opStatus result = Literal.GetFloatValue(Val);
3230 
3231   // Overflow is always an error, but underflow is only an error if
3232   // we underflowed to zero (APFloat reports denormals as underflow).
3233   if ((result & APFloat::opOverflow) ||
3234       ((result & APFloat::opUnderflow) && Val.isZero())) {
3235     unsigned diagnostic;
3236     SmallString<20> buffer;
3237     if (result & APFloat::opOverflow) {
3238       diagnostic = diag::warn_float_overflow;
3239       APFloat::getLargest(Format).toString(buffer);
3240     } else {
3241       diagnostic = diag::warn_float_underflow;
3242       APFloat::getSmallest(Format).toString(buffer);
3243     }
3244 
3245     S.Diag(Loc, diagnostic)
3246       << Ty
3247       << StringRef(buffer.data(), buffer.size());
3248   }
3249 
3250   bool isExact = (result == APFloat::opOK);
3251   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3252 }
3253 
3254 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3255   assert(E && "Invalid expression");
3256 
3257   if (E->isValueDependent())
3258     return false;
3259 
3260   QualType QT = E->getType();
3261   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3262     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3263     return true;
3264   }
3265 
3266   llvm::APSInt ValueAPS;
3267   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3268 
3269   if (R.isInvalid())
3270     return true;
3271 
3272   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3273   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3274     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3275         << ValueAPS.toString(10) << ValueIsPositive;
3276     return true;
3277   }
3278 
3279   return false;
3280 }
3281 
3282 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3283   // Fast path for a single digit (which is quite common).  A single digit
3284   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3285   if (Tok.getLength() == 1) {
3286     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3287     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3288   }
3289 
3290   SmallString<128> SpellingBuffer;
3291   // NumericLiteralParser wants to overread by one character.  Add padding to
3292   // the buffer in case the token is copied to the buffer.  If getSpelling()
3293   // returns a StringRef to the memory buffer, it should have a null char at
3294   // the EOF, so it is also safe.
3295   SpellingBuffer.resize(Tok.getLength() + 1);
3296 
3297   // Get the spelling of the token, which eliminates trigraphs, etc.
3298   bool Invalid = false;
3299   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3300   if (Invalid)
3301     return ExprError();
3302 
3303   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3304   if (Literal.hadError)
3305     return ExprError();
3306 
3307   if (Literal.hasUDSuffix()) {
3308     // We're building a user-defined literal.
3309     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3310     SourceLocation UDSuffixLoc =
3311       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3312 
3313     // Make sure we're allowed user-defined literals here.
3314     if (!UDLScope)
3315       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3316 
3317     QualType CookedTy;
3318     if (Literal.isFloatingLiteral()) {
3319       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3320       // long double, the literal is treated as a call of the form
3321       //   operator "" X (f L)
3322       CookedTy = Context.LongDoubleTy;
3323     } else {
3324       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3325       // unsigned long long, the literal is treated as a call of the form
3326       //   operator "" X (n ULL)
3327       CookedTy = Context.UnsignedLongLongTy;
3328     }
3329 
3330     DeclarationName OpName =
3331       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3332     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3333     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3334 
3335     SourceLocation TokLoc = Tok.getLocation();
3336 
3337     // Perform literal operator lookup to determine if we're building a raw
3338     // literal or a cooked one.
3339     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3340     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3341                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3342                                   /*AllowStringTemplate*/false)) {
3343     case LOLR_Error:
3344       return ExprError();
3345 
3346     case LOLR_Cooked: {
3347       Expr *Lit;
3348       if (Literal.isFloatingLiteral()) {
3349         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3350       } else {
3351         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3352         if (Literal.GetIntegerValue(ResultVal))
3353           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3354               << /* Unsigned */ 1;
3355         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3356                                      Tok.getLocation());
3357       }
3358       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3359     }
3360 
3361     case LOLR_Raw: {
3362       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3363       // literal is treated as a call of the form
3364       //   operator "" X ("n")
3365       unsigned Length = Literal.getUDSuffixOffset();
3366       QualType StrTy = Context.getConstantArrayType(
3367           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3368           ArrayType::Normal, 0);
3369       Expr *Lit = StringLiteral::Create(
3370           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3371           /*Pascal*/false, StrTy, &TokLoc, 1);
3372       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3373     }
3374 
3375     case LOLR_Template: {
3376       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3377       // template), L is treated as a call fo the form
3378       //   operator "" X <'c1', 'c2', ... 'ck'>()
3379       // where n is the source character sequence c1 c2 ... ck.
3380       TemplateArgumentListInfo ExplicitArgs;
3381       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3382       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3383       llvm::APSInt Value(CharBits, CharIsUnsigned);
3384       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3385         Value = TokSpelling[I];
3386         TemplateArgument Arg(Context, Value, Context.CharTy);
3387         TemplateArgumentLocInfo ArgInfo;
3388         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3389       }
3390       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3391                                       &ExplicitArgs);
3392     }
3393     case LOLR_StringTemplate:
3394       llvm_unreachable("unexpected literal operator lookup result");
3395     }
3396   }
3397 
3398   Expr *Res;
3399 
3400   if (Literal.isFloatingLiteral()) {
3401     QualType Ty;
3402     if (Literal.isHalf){
3403       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3404         Ty = Context.HalfTy;
3405       else {
3406         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3407         return ExprError();
3408       }
3409     } else if (Literal.isFloat)
3410       Ty = Context.FloatTy;
3411     else if (Literal.isLong)
3412       Ty = Context.LongDoubleTy;
3413     else if (Literal.isFloat128)
3414       Ty = Context.Float128Ty;
3415     else
3416       Ty = Context.DoubleTy;
3417 
3418     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3419 
3420     if (Ty == Context.DoubleTy) {
3421       if (getLangOpts().SinglePrecisionConstants) {
3422         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3423         if (BTy->getKind() != BuiltinType::Float) {
3424           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3425         }
3426       } else if (getLangOpts().OpenCL &&
3427                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3428         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3429         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3430         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3431       }
3432     }
3433   } else if (!Literal.isIntegerLiteral()) {
3434     return ExprError();
3435   } else {
3436     QualType Ty;
3437 
3438     // 'long long' is a C99 or C++11 feature.
3439     if (!getLangOpts().C99 && Literal.isLongLong) {
3440       if (getLangOpts().CPlusPlus)
3441         Diag(Tok.getLocation(),
3442              getLangOpts().CPlusPlus11 ?
3443              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3444       else
3445         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3446     }
3447 
3448     // Get the value in the widest-possible width.
3449     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3450     llvm::APInt ResultVal(MaxWidth, 0);
3451 
3452     if (Literal.GetIntegerValue(ResultVal)) {
3453       // If this value didn't fit into uintmax_t, error and force to ull.
3454       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3455           << /* Unsigned */ 1;
3456       Ty = Context.UnsignedLongLongTy;
3457       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3458              "long long is not intmax_t?");
3459     } else {
3460       // If this value fits into a ULL, try to figure out what else it fits into
3461       // according to the rules of C99 6.4.4.1p5.
3462 
3463       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3464       // be an unsigned int.
3465       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3466 
3467       // Check from smallest to largest, picking the smallest type we can.
3468       unsigned Width = 0;
3469 
3470       // Microsoft specific integer suffixes are explicitly sized.
3471       if (Literal.MicrosoftInteger) {
3472         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3473           Width = 8;
3474           Ty = Context.CharTy;
3475         } else {
3476           Width = Literal.MicrosoftInteger;
3477           Ty = Context.getIntTypeForBitwidth(Width,
3478                                              /*Signed=*/!Literal.isUnsigned);
3479         }
3480       }
3481 
3482       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3483         // Are int/unsigned possibilities?
3484         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3485 
3486         // Does it fit in a unsigned int?
3487         if (ResultVal.isIntN(IntSize)) {
3488           // Does it fit in a signed int?
3489           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3490             Ty = Context.IntTy;
3491           else if (AllowUnsigned)
3492             Ty = Context.UnsignedIntTy;
3493           Width = IntSize;
3494         }
3495       }
3496 
3497       // Are long/unsigned long possibilities?
3498       if (Ty.isNull() && !Literal.isLongLong) {
3499         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3500 
3501         // Does it fit in a unsigned long?
3502         if (ResultVal.isIntN(LongSize)) {
3503           // Does it fit in a signed long?
3504           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3505             Ty = Context.LongTy;
3506           else if (AllowUnsigned)
3507             Ty = Context.UnsignedLongTy;
3508           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3509           // is compatible.
3510           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3511             const unsigned LongLongSize =
3512                 Context.getTargetInfo().getLongLongWidth();
3513             Diag(Tok.getLocation(),
3514                  getLangOpts().CPlusPlus
3515                      ? Literal.isLong
3516                            ? diag::warn_old_implicitly_unsigned_long_cxx
3517                            : /*C++98 UB*/ diag::
3518                                  ext_old_implicitly_unsigned_long_cxx
3519                      : diag::warn_old_implicitly_unsigned_long)
3520                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3521                                             : /*will be ill-formed*/ 1);
3522             Ty = Context.UnsignedLongTy;
3523           }
3524           Width = LongSize;
3525         }
3526       }
3527 
3528       // Check long long if needed.
3529       if (Ty.isNull()) {
3530         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3531 
3532         // Does it fit in a unsigned long long?
3533         if (ResultVal.isIntN(LongLongSize)) {
3534           // Does it fit in a signed long long?
3535           // To be compatible with MSVC, hex integer literals ending with the
3536           // LL or i64 suffix are always signed in Microsoft mode.
3537           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3538               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3539             Ty = Context.LongLongTy;
3540           else if (AllowUnsigned)
3541             Ty = Context.UnsignedLongLongTy;
3542           Width = LongLongSize;
3543         }
3544       }
3545 
3546       // If we still couldn't decide a type, we probably have something that
3547       // does not fit in a signed long long, but has no U suffix.
3548       if (Ty.isNull()) {
3549         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3550         Ty = Context.UnsignedLongLongTy;
3551         Width = Context.getTargetInfo().getLongLongWidth();
3552       }
3553 
3554       if (ResultVal.getBitWidth() != Width)
3555         ResultVal = ResultVal.trunc(Width);
3556     }
3557     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3558   }
3559 
3560   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3561   if (Literal.isImaginary)
3562     Res = new (Context) ImaginaryLiteral(Res,
3563                                         Context.getComplexType(Res->getType()));
3564 
3565   return Res;
3566 }
3567 
3568 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3569   assert(E && "ActOnParenExpr() missing expr");
3570   return new (Context) ParenExpr(L, R, E);
3571 }
3572 
3573 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3574                                          SourceLocation Loc,
3575                                          SourceRange ArgRange) {
3576   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3577   // scalar or vector data type argument..."
3578   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3579   // type (C99 6.2.5p18) or void.
3580   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3581     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3582       << T << ArgRange;
3583     return true;
3584   }
3585 
3586   assert((T->isVoidType() || !T->isIncompleteType()) &&
3587          "Scalar types should always be complete");
3588   return false;
3589 }
3590 
3591 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3592                                            SourceLocation Loc,
3593                                            SourceRange ArgRange,
3594                                            UnaryExprOrTypeTrait TraitKind) {
3595   // Invalid types must be hard errors for SFINAE in C++.
3596   if (S.LangOpts.CPlusPlus)
3597     return true;
3598 
3599   // C99 6.5.3.4p1:
3600   if (T->isFunctionType() &&
3601       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3602     // sizeof(function)/alignof(function) is allowed as an extension.
3603     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3604       << TraitKind << ArgRange;
3605     return false;
3606   }
3607 
3608   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3609   // this is an error (OpenCL v1.1 s6.3.k)
3610   if (T->isVoidType()) {
3611     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3612                                         : diag::ext_sizeof_alignof_void_type;
3613     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3614     return false;
3615   }
3616 
3617   return true;
3618 }
3619 
3620 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3621                                              SourceLocation Loc,
3622                                              SourceRange ArgRange,
3623                                              UnaryExprOrTypeTrait TraitKind) {
3624   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3625   // runtime doesn't allow it.
3626   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3627     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3628       << T << (TraitKind == UETT_SizeOf)
3629       << ArgRange;
3630     return true;
3631   }
3632 
3633   return false;
3634 }
3635 
3636 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3637 /// pointer type is equal to T) and emit a warning if it is.
3638 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3639                                      Expr *E) {
3640   // Don't warn if the operation changed the type.
3641   if (T != E->getType())
3642     return;
3643 
3644   // Now look for array decays.
3645   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3646   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3647     return;
3648 
3649   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3650                                              << ICE->getType()
3651                                              << ICE->getSubExpr()->getType();
3652 }
3653 
3654 /// \brief Check the constraints on expression operands to unary type expression
3655 /// and type traits.
3656 ///
3657 /// Completes any types necessary and validates the constraints on the operand
3658 /// expression. The logic mostly mirrors the type-based overload, but may modify
3659 /// the expression as it completes the type for that expression through template
3660 /// instantiation, etc.
3661 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3662                                             UnaryExprOrTypeTrait ExprKind) {
3663   QualType ExprTy = E->getType();
3664   assert(!ExprTy->isReferenceType());
3665 
3666   if (ExprKind == UETT_VecStep)
3667     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3668                                         E->getSourceRange());
3669 
3670   // Whitelist some types as extensions
3671   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3672                                       E->getSourceRange(), ExprKind))
3673     return false;
3674 
3675   // 'alignof' applied to an expression only requires the base element type of
3676   // the expression to be complete. 'sizeof' requires the expression's type to
3677   // be complete (and will attempt to complete it if it's an array of unknown
3678   // bound).
3679   if (ExprKind == UETT_AlignOf) {
3680     if (RequireCompleteType(E->getExprLoc(),
3681                             Context.getBaseElementType(E->getType()),
3682                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3683                             E->getSourceRange()))
3684       return true;
3685   } else {
3686     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3687                                 ExprKind, E->getSourceRange()))
3688       return true;
3689   }
3690 
3691   // Completing the expression's type may have changed it.
3692   ExprTy = E->getType();
3693   assert(!ExprTy->isReferenceType());
3694 
3695   if (ExprTy->isFunctionType()) {
3696     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3697       << ExprKind << E->getSourceRange();
3698     return true;
3699   }
3700 
3701   // The operand for sizeof and alignof is in an unevaluated expression context,
3702   // so side effects could result in unintended consequences.
3703   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3704       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3705     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3706 
3707   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3708                                        E->getSourceRange(), ExprKind))
3709     return true;
3710 
3711   if (ExprKind == UETT_SizeOf) {
3712     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3713       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3714         QualType OType = PVD->getOriginalType();
3715         QualType Type = PVD->getType();
3716         if (Type->isPointerType() && OType->isArrayType()) {
3717           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3718             << Type << OType;
3719           Diag(PVD->getLocation(), diag::note_declared_at);
3720         }
3721       }
3722     }
3723 
3724     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3725     // decays into a pointer and returns an unintended result. This is most
3726     // likely a typo for "sizeof(array) op x".
3727     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3728       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3729                                BO->getLHS());
3730       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3731                                BO->getRHS());
3732     }
3733   }
3734 
3735   return false;
3736 }
3737 
3738 /// \brief Check the constraints on operands to unary expression and type
3739 /// traits.
3740 ///
3741 /// This will complete any types necessary, and validate the various constraints
3742 /// on those operands.
3743 ///
3744 /// The UsualUnaryConversions() function is *not* called by this routine.
3745 /// C99 6.3.2.1p[2-4] all state:
3746 ///   Except when it is the operand of the sizeof operator ...
3747 ///
3748 /// C++ [expr.sizeof]p4
3749 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3750 ///   standard conversions are not applied to the operand of sizeof.
3751 ///
3752 /// This policy is followed for all of the unary trait expressions.
3753 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3754                                             SourceLocation OpLoc,
3755                                             SourceRange ExprRange,
3756                                             UnaryExprOrTypeTrait ExprKind) {
3757   if (ExprType->isDependentType())
3758     return false;
3759 
3760   // C++ [expr.sizeof]p2:
3761   //     When applied to a reference or a reference type, the result
3762   //     is the size of the referenced type.
3763   // C++11 [expr.alignof]p3:
3764   //     When alignof is applied to a reference type, the result
3765   //     shall be the alignment of the referenced type.
3766   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3767     ExprType = Ref->getPointeeType();
3768 
3769   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3770   //   When alignof or _Alignof is applied to an array type, the result
3771   //   is the alignment of the element type.
3772   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3773     ExprType = Context.getBaseElementType(ExprType);
3774 
3775   if (ExprKind == UETT_VecStep)
3776     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3777 
3778   // Whitelist some types as extensions
3779   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3780                                       ExprKind))
3781     return false;
3782 
3783   if (RequireCompleteType(OpLoc, ExprType,
3784                           diag::err_sizeof_alignof_incomplete_type,
3785                           ExprKind, ExprRange))
3786     return true;
3787 
3788   if (ExprType->isFunctionType()) {
3789     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3790       << ExprKind << ExprRange;
3791     return true;
3792   }
3793 
3794   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3795                                        ExprKind))
3796     return true;
3797 
3798   return false;
3799 }
3800 
3801 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3802   E = E->IgnoreParens();
3803 
3804   // Cannot know anything else if the expression is dependent.
3805   if (E->isTypeDependent())
3806     return false;
3807 
3808   if (E->getObjectKind() == OK_BitField) {
3809     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3810        << 1 << E->getSourceRange();
3811     return true;
3812   }
3813 
3814   ValueDecl *D = nullptr;
3815   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3816     D = DRE->getDecl();
3817   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3818     D = ME->getMemberDecl();
3819   }
3820 
3821   // If it's a field, require the containing struct to have a
3822   // complete definition so that we can compute the layout.
3823   //
3824   // This can happen in C++11 onwards, either by naming the member
3825   // in a way that is not transformed into a member access expression
3826   // (in an unevaluated operand, for instance), or by naming the member
3827   // in a trailing-return-type.
3828   //
3829   // For the record, since __alignof__ on expressions is a GCC
3830   // extension, GCC seems to permit this but always gives the
3831   // nonsensical answer 0.
3832   //
3833   // We don't really need the layout here --- we could instead just
3834   // directly check for all the appropriate alignment-lowing
3835   // attributes --- but that would require duplicating a lot of
3836   // logic that just isn't worth duplicating for such a marginal
3837   // use-case.
3838   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3839     // Fast path this check, since we at least know the record has a
3840     // definition if we can find a member of it.
3841     if (!FD->getParent()->isCompleteDefinition()) {
3842       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3843         << E->getSourceRange();
3844       return true;
3845     }
3846 
3847     // Otherwise, if it's a field, and the field doesn't have
3848     // reference type, then it must have a complete type (or be a
3849     // flexible array member, which we explicitly want to
3850     // white-list anyway), which makes the following checks trivial.
3851     if (!FD->getType()->isReferenceType())
3852       return false;
3853   }
3854 
3855   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3856 }
3857 
3858 bool Sema::CheckVecStepExpr(Expr *E) {
3859   E = E->IgnoreParens();
3860 
3861   // Cannot know anything else if the expression is dependent.
3862   if (E->isTypeDependent())
3863     return false;
3864 
3865   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3866 }
3867 
3868 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3869                                         CapturingScopeInfo *CSI) {
3870   assert(T->isVariablyModifiedType());
3871   assert(CSI != nullptr);
3872 
3873   // We're going to walk down into the type and look for VLA expressions.
3874   do {
3875     const Type *Ty = T.getTypePtr();
3876     switch (Ty->getTypeClass()) {
3877 #define TYPE(Class, Base)
3878 #define ABSTRACT_TYPE(Class, Base)
3879 #define NON_CANONICAL_TYPE(Class, Base)
3880 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3881 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3882 #include "clang/AST/TypeNodes.def"
3883       T = QualType();
3884       break;
3885     // These types are never variably-modified.
3886     case Type::Builtin:
3887     case Type::Complex:
3888     case Type::Vector:
3889     case Type::ExtVector:
3890     case Type::Record:
3891     case Type::Enum:
3892     case Type::Elaborated:
3893     case Type::TemplateSpecialization:
3894     case Type::ObjCObject:
3895     case Type::ObjCInterface:
3896     case Type::ObjCObjectPointer:
3897     case Type::ObjCTypeParam:
3898     case Type::Pipe:
3899       llvm_unreachable("type class is never variably-modified!");
3900     case Type::Adjusted:
3901       T = cast<AdjustedType>(Ty)->getOriginalType();
3902       break;
3903     case Type::Decayed:
3904       T = cast<DecayedType>(Ty)->getPointeeType();
3905       break;
3906     case Type::Pointer:
3907       T = cast<PointerType>(Ty)->getPointeeType();
3908       break;
3909     case Type::BlockPointer:
3910       T = cast<BlockPointerType>(Ty)->getPointeeType();
3911       break;
3912     case Type::LValueReference:
3913     case Type::RValueReference:
3914       T = cast<ReferenceType>(Ty)->getPointeeType();
3915       break;
3916     case Type::MemberPointer:
3917       T = cast<MemberPointerType>(Ty)->getPointeeType();
3918       break;
3919     case Type::ConstantArray:
3920     case Type::IncompleteArray:
3921       // Losing element qualification here is fine.
3922       T = cast<ArrayType>(Ty)->getElementType();
3923       break;
3924     case Type::VariableArray: {
3925       // Losing element qualification here is fine.
3926       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3927 
3928       // Unknown size indication requires no size computation.
3929       // Otherwise, evaluate and record it.
3930       if (auto Size = VAT->getSizeExpr()) {
3931         if (!CSI->isVLATypeCaptured(VAT)) {
3932           RecordDecl *CapRecord = nullptr;
3933           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3934             CapRecord = LSI->Lambda;
3935           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3936             CapRecord = CRSI->TheRecordDecl;
3937           }
3938           if (CapRecord) {
3939             auto ExprLoc = Size->getExprLoc();
3940             auto SizeType = Context.getSizeType();
3941             // Build the non-static data member.
3942             auto Field =
3943                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3944                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3945                                   /*BW*/ nullptr, /*Mutable*/ false,
3946                                   /*InitStyle*/ ICIS_NoInit);
3947             Field->setImplicit(true);
3948             Field->setAccess(AS_private);
3949             Field->setCapturedVLAType(VAT);
3950             CapRecord->addDecl(Field);
3951 
3952             CSI->addVLATypeCapture(ExprLoc, SizeType);
3953           }
3954         }
3955       }
3956       T = VAT->getElementType();
3957       break;
3958     }
3959     case Type::FunctionProto:
3960     case Type::FunctionNoProto:
3961       T = cast<FunctionType>(Ty)->getReturnType();
3962       break;
3963     case Type::Paren:
3964     case Type::TypeOf:
3965     case Type::UnaryTransform:
3966     case Type::Attributed:
3967     case Type::SubstTemplateTypeParm:
3968     case Type::PackExpansion:
3969       // Keep walking after single level desugaring.
3970       T = T.getSingleStepDesugaredType(Context);
3971       break;
3972     case Type::Typedef:
3973       T = cast<TypedefType>(Ty)->desugar();
3974       break;
3975     case Type::Decltype:
3976       T = cast<DecltypeType>(Ty)->desugar();
3977       break;
3978     case Type::Auto:
3979       T = cast<AutoType>(Ty)->getDeducedType();
3980       break;
3981     case Type::TypeOfExpr:
3982       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3983       break;
3984     case Type::Atomic:
3985       T = cast<AtomicType>(Ty)->getValueType();
3986       break;
3987     }
3988   } while (!T.isNull() && T->isVariablyModifiedType());
3989 }
3990 
3991 /// \brief Build a sizeof or alignof expression given a type operand.
3992 ExprResult
3993 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3994                                      SourceLocation OpLoc,
3995                                      UnaryExprOrTypeTrait ExprKind,
3996                                      SourceRange R) {
3997   if (!TInfo)
3998     return ExprError();
3999 
4000   QualType T = TInfo->getType();
4001 
4002   if (!T->isDependentType() &&
4003       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4004     return ExprError();
4005 
4006   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4007     if (auto *TT = T->getAs<TypedefType>()) {
4008       for (auto I = FunctionScopes.rbegin(),
4009                 E = std::prev(FunctionScopes.rend());
4010            I != E; ++I) {
4011         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4012         if (CSI == nullptr)
4013           break;
4014         DeclContext *DC = nullptr;
4015         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4016           DC = LSI->CallOperator;
4017         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4018           DC = CRSI->TheCapturedDecl;
4019         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4020           DC = BSI->TheDecl;
4021         if (DC) {
4022           if (DC->containsDecl(TT->getDecl()))
4023             break;
4024           captureVariablyModifiedType(Context, T, CSI);
4025         }
4026       }
4027     }
4028   }
4029 
4030   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4031   return new (Context) UnaryExprOrTypeTraitExpr(
4032       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4033 }
4034 
4035 /// \brief Build a sizeof or alignof expression given an expression
4036 /// operand.
4037 ExprResult
4038 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4039                                      UnaryExprOrTypeTrait ExprKind) {
4040   ExprResult PE = CheckPlaceholderExpr(E);
4041   if (PE.isInvalid())
4042     return ExprError();
4043 
4044   E = PE.get();
4045 
4046   // Verify that the operand is valid.
4047   bool isInvalid = false;
4048   if (E->isTypeDependent()) {
4049     // Delay type-checking for type-dependent expressions.
4050   } else if (ExprKind == UETT_AlignOf) {
4051     isInvalid = CheckAlignOfExpr(*this, E);
4052   } else if (ExprKind == UETT_VecStep) {
4053     isInvalid = CheckVecStepExpr(E);
4054   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4055       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4056       isInvalid = true;
4057   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4058     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4059     isInvalid = true;
4060   } else {
4061     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4062   }
4063 
4064   if (isInvalid)
4065     return ExprError();
4066 
4067   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4068     PE = TransformToPotentiallyEvaluated(E);
4069     if (PE.isInvalid()) return ExprError();
4070     E = PE.get();
4071   }
4072 
4073   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4074   return new (Context) UnaryExprOrTypeTraitExpr(
4075       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4076 }
4077 
4078 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4079 /// expr and the same for @c alignof and @c __alignof
4080 /// Note that the ArgRange is invalid if isType is false.
4081 ExprResult
4082 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4083                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4084                                     void *TyOrEx, SourceRange ArgRange) {
4085   // If error parsing type, ignore.
4086   if (!TyOrEx) return ExprError();
4087 
4088   if (IsType) {
4089     TypeSourceInfo *TInfo;
4090     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4091     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4092   }
4093 
4094   Expr *ArgEx = (Expr *)TyOrEx;
4095   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4096   return Result;
4097 }
4098 
4099 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4100                                      bool IsReal) {
4101   if (V.get()->isTypeDependent())
4102     return S.Context.DependentTy;
4103 
4104   // _Real and _Imag are only l-values for normal l-values.
4105   if (V.get()->getObjectKind() != OK_Ordinary) {
4106     V = S.DefaultLvalueConversion(V.get());
4107     if (V.isInvalid())
4108       return QualType();
4109   }
4110 
4111   // These operators return the element type of a complex type.
4112   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4113     return CT->getElementType();
4114 
4115   // Otherwise they pass through real integer and floating point types here.
4116   if (V.get()->getType()->isArithmeticType())
4117     return V.get()->getType();
4118 
4119   // Test for placeholders.
4120   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4121   if (PR.isInvalid()) return QualType();
4122   if (PR.get() != V.get()) {
4123     V = PR;
4124     return CheckRealImagOperand(S, V, Loc, IsReal);
4125   }
4126 
4127   // Reject anything else.
4128   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4129     << (IsReal ? "__real" : "__imag");
4130   return QualType();
4131 }
4132 
4133 
4134 
4135 ExprResult
4136 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4137                           tok::TokenKind Kind, Expr *Input) {
4138   UnaryOperatorKind Opc;
4139   switch (Kind) {
4140   default: llvm_unreachable("Unknown unary op!");
4141   case tok::plusplus:   Opc = UO_PostInc; break;
4142   case tok::minusminus: Opc = UO_PostDec; break;
4143   }
4144 
4145   // Since this might is a postfix expression, get rid of ParenListExprs.
4146   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4147   if (Result.isInvalid()) return ExprError();
4148   Input = Result.get();
4149 
4150   return BuildUnaryOp(S, OpLoc, Opc, Input);
4151 }
4152 
4153 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4154 ///
4155 /// \return true on error
4156 static bool checkArithmeticOnObjCPointer(Sema &S,
4157                                          SourceLocation opLoc,
4158                                          Expr *op) {
4159   assert(op->getType()->isObjCObjectPointerType());
4160   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4161       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4162     return false;
4163 
4164   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4165     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4166     << op->getSourceRange();
4167   return true;
4168 }
4169 
4170 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4171   auto *BaseNoParens = Base->IgnoreParens();
4172   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4173     return MSProp->getPropertyDecl()->getType()->isArrayType();
4174   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4175 }
4176 
4177 ExprResult
4178 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4179                               Expr *idx, SourceLocation rbLoc) {
4180   if (base && !base->getType().isNull() &&
4181       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4182     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4183                                     /*Length=*/nullptr, rbLoc);
4184 
4185   // Since this might be a postfix expression, get rid of ParenListExprs.
4186   if (isa<ParenListExpr>(base)) {
4187     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4188     if (result.isInvalid()) return ExprError();
4189     base = result.get();
4190   }
4191 
4192   // Handle any non-overload placeholder types in the base and index
4193   // expressions.  We can't handle overloads here because the other
4194   // operand might be an overloadable type, in which case the overload
4195   // resolution for the operator overload should get the first crack
4196   // at the overload.
4197   bool IsMSPropertySubscript = false;
4198   if (base->getType()->isNonOverloadPlaceholderType()) {
4199     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4200     if (!IsMSPropertySubscript) {
4201       ExprResult result = CheckPlaceholderExpr(base);
4202       if (result.isInvalid())
4203         return ExprError();
4204       base = result.get();
4205     }
4206   }
4207   if (idx->getType()->isNonOverloadPlaceholderType()) {
4208     ExprResult result = CheckPlaceholderExpr(idx);
4209     if (result.isInvalid()) return ExprError();
4210     idx = result.get();
4211   }
4212 
4213   // Build an unanalyzed expression if either operand is type-dependent.
4214   if (getLangOpts().CPlusPlus &&
4215       (base->isTypeDependent() || idx->isTypeDependent())) {
4216     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4217                                             VK_LValue, OK_Ordinary, rbLoc);
4218   }
4219 
4220   // MSDN, property (C++)
4221   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4222   // This attribute can also be used in the declaration of an empty array in a
4223   // class or structure definition. For example:
4224   // __declspec(property(get=GetX, put=PutX)) int x[];
4225   // The above statement indicates that x[] can be used with one or more array
4226   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4227   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4228   if (IsMSPropertySubscript) {
4229     // Build MS property subscript expression if base is MS property reference
4230     // or MS property subscript.
4231     return new (Context) MSPropertySubscriptExpr(
4232         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4233   }
4234 
4235   // Use C++ overloaded-operator rules if either operand has record
4236   // type.  The spec says to do this if either type is *overloadable*,
4237   // but enum types can't declare subscript operators or conversion
4238   // operators, so there's nothing interesting for overload resolution
4239   // to do if there aren't any record types involved.
4240   //
4241   // ObjC pointers have their own subscripting logic that is not tied
4242   // to overload resolution and so should not take this path.
4243   if (getLangOpts().CPlusPlus &&
4244       (base->getType()->isRecordType() ||
4245        (!base->getType()->isObjCObjectPointerType() &&
4246         idx->getType()->isRecordType()))) {
4247     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4248   }
4249 
4250   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4251 }
4252 
4253 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4254                                           Expr *LowerBound,
4255                                           SourceLocation ColonLoc, Expr *Length,
4256                                           SourceLocation RBLoc) {
4257   if (Base->getType()->isPlaceholderType() &&
4258       !Base->getType()->isSpecificPlaceholderType(
4259           BuiltinType::OMPArraySection)) {
4260     ExprResult Result = CheckPlaceholderExpr(Base);
4261     if (Result.isInvalid())
4262       return ExprError();
4263     Base = Result.get();
4264   }
4265   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4266     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4267     if (Result.isInvalid())
4268       return ExprError();
4269     Result = DefaultLvalueConversion(Result.get());
4270     if (Result.isInvalid())
4271       return ExprError();
4272     LowerBound = Result.get();
4273   }
4274   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4275     ExprResult Result = CheckPlaceholderExpr(Length);
4276     if (Result.isInvalid())
4277       return ExprError();
4278     Result = DefaultLvalueConversion(Result.get());
4279     if (Result.isInvalid())
4280       return ExprError();
4281     Length = Result.get();
4282   }
4283 
4284   // Build an unanalyzed expression if either operand is type-dependent.
4285   if (Base->isTypeDependent() ||
4286       (LowerBound &&
4287        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4288       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4289     return new (Context)
4290         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4291                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4292   }
4293 
4294   // Perform default conversions.
4295   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4296   QualType ResultTy;
4297   if (OriginalTy->isAnyPointerType()) {
4298     ResultTy = OriginalTy->getPointeeType();
4299   } else if (OriginalTy->isArrayType()) {
4300     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4301   } else {
4302     return ExprError(
4303         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4304         << Base->getSourceRange());
4305   }
4306   // C99 6.5.2.1p1
4307   if (LowerBound) {
4308     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4309                                                       LowerBound);
4310     if (Res.isInvalid())
4311       return ExprError(Diag(LowerBound->getExprLoc(),
4312                             diag::err_omp_typecheck_section_not_integer)
4313                        << 0 << LowerBound->getSourceRange());
4314     LowerBound = Res.get();
4315 
4316     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4317         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4318       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4319           << 0 << LowerBound->getSourceRange();
4320   }
4321   if (Length) {
4322     auto Res =
4323         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4324     if (Res.isInvalid())
4325       return ExprError(Diag(Length->getExprLoc(),
4326                             diag::err_omp_typecheck_section_not_integer)
4327                        << 1 << Length->getSourceRange());
4328     Length = Res.get();
4329 
4330     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4331         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4332       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4333           << 1 << Length->getSourceRange();
4334   }
4335 
4336   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4337   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4338   // type. Note that functions are not objects, and that (in C99 parlance)
4339   // incomplete types are not object types.
4340   if (ResultTy->isFunctionType()) {
4341     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4342         << ResultTy << Base->getSourceRange();
4343     return ExprError();
4344   }
4345 
4346   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4347                           diag::err_omp_section_incomplete_type, Base))
4348     return ExprError();
4349 
4350   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4351     llvm::APSInt LowerBoundValue;
4352     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4353       // OpenMP 4.5, [2.4 Array Sections]
4354       // The array section must be a subset of the original array.
4355       if (LowerBoundValue.isNegative()) {
4356         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4357             << LowerBound->getSourceRange();
4358         return ExprError();
4359       }
4360     }
4361   }
4362 
4363   if (Length) {
4364     llvm::APSInt LengthValue;
4365     if (Length->EvaluateAsInt(LengthValue, Context)) {
4366       // OpenMP 4.5, [2.4 Array Sections]
4367       // The length must evaluate to non-negative integers.
4368       if (LengthValue.isNegative()) {
4369         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4370             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4371             << Length->getSourceRange();
4372         return ExprError();
4373       }
4374     }
4375   } else if (ColonLoc.isValid() &&
4376              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4377                                       !OriginalTy->isVariableArrayType()))) {
4378     // OpenMP 4.5, [2.4 Array Sections]
4379     // When the size of the array dimension is not known, the length must be
4380     // specified explicitly.
4381     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4382         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4383     return ExprError();
4384   }
4385 
4386   if (!Base->getType()->isSpecificPlaceholderType(
4387           BuiltinType::OMPArraySection)) {
4388     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4389     if (Result.isInvalid())
4390       return ExprError();
4391     Base = Result.get();
4392   }
4393   return new (Context)
4394       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4395                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4396 }
4397 
4398 ExprResult
4399 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4400                                       Expr *Idx, SourceLocation RLoc) {
4401   Expr *LHSExp = Base;
4402   Expr *RHSExp = Idx;
4403 
4404   ExprValueKind VK = VK_LValue;
4405   ExprObjectKind OK = OK_Ordinary;
4406 
4407   // Per C++ core issue 1213, the result is an xvalue if either operand is
4408   // a non-lvalue array, and an lvalue otherwise.
4409   if (getLangOpts().CPlusPlus11 &&
4410       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4411        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4412     VK = VK_XValue;
4413 
4414   // Perform default conversions.
4415   if (!LHSExp->getType()->getAs<VectorType>()) {
4416     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4417     if (Result.isInvalid())
4418       return ExprError();
4419     LHSExp = Result.get();
4420   }
4421   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4422   if (Result.isInvalid())
4423     return ExprError();
4424   RHSExp = Result.get();
4425 
4426   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4427 
4428   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4429   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4430   // in the subscript position. As a result, we need to derive the array base
4431   // and index from the expression types.
4432   Expr *BaseExpr, *IndexExpr;
4433   QualType ResultType;
4434   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4435     BaseExpr = LHSExp;
4436     IndexExpr = RHSExp;
4437     ResultType = Context.DependentTy;
4438   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4439     BaseExpr = LHSExp;
4440     IndexExpr = RHSExp;
4441     ResultType = PTy->getPointeeType();
4442   } else if (const ObjCObjectPointerType *PTy =
4443                LHSTy->getAs<ObjCObjectPointerType>()) {
4444     BaseExpr = LHSExp;
4445     IndexExpr = RHSExp;
4446 
4447     // Use custom logic if this should be the pseudo-object subscript
4448     // expression.
4449     if (!LangOpts.isSubscriptPointerArithmetic())
4450       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4451                                           nullptr);
4452 
4453     ResultType = PTy->getPointeeType();
4454   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4455      // Handle the uncommon case of "123[Ptr]".
4456     BaseExpr = RHSExp;
4457     IndexExpr = LHSExp;
4458     ResultType = PTy->getPointeeType();
4459   } else if (const ObjCObjectPointerType *PTy =
4460                RHSTy->getAs<ObjCObjectPointerType>()) {
4461      // Handle the uncommon case of "123[Ptr]".
4462     BaseExpr = RHSExp;
4463     IndexExpr = LHSExp;
4464     ResultType = PTy->getPointeeType();
4465     if (!LangOpts.isSubscriptPointerArithmetic()) {
4466       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4467         << ResultType << BaseExpr->getSourceRange();
4468       return ExprError();
4469     }
4470   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4471     BaseExpr = LHSExp;    // vectors: V[123]
4472     IndexExpr = RHSExp;
4473     VK = LHSExp->getValueKind();
4474     if (VK != VK_RValue)
4475       OK = OK_VectorComponent;
4476 
4477     // FIXME: need to deal with const...
4478     ResultType = VTy->getElementType();
4479   } else if (LHSTy->isArrayType()) {
4480     // If we see an array that wasn't promoted by
4481     // DefaultFunctionArrayLvalueConversion, it must be an array that
4482     // wasn't promoted because of the C90 rule that doesn't
4483     // allow promoting non-lvalue arrays.  Warn, then
4484     // force the promotion here.
4485     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4486         LHSExp->getSourceRange();
4487     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4488                                CK_ArrayToPointerDecay).get();
4489     LHSTy = LHSExp->getType();
4490 
4491     BaseExpr = LHSExp;
4492     IndexExpr = RHSExp;
4493     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4494   } else if (RHSTy->isArrayType()) {
4495     // Same as previous, except for 123[f().a] case
4496     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4497         RHSExp->getSourceRange();
4498     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4499                                CK_ArrayToPointerDecay).get();
4500     RHSTy = RHSExp->getType();
4501 
4502     BaseExpr = RHSExp;
4503     IndexExpr = LHSExp;
4504     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4505   } else {
4506     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4507        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4508   }
4509   // C99 6.5.2.1p1
4510   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4511     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4512                      << IndexExpr->getSourceRange());
4513 
4514   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4515        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4516          && !IndexExpr->isTypeDependent())
4517     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4518 
4519   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4520   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4521   // type. Note that Functions are not objects, and that (in C99 parlance)
4522   // incomplete types are not object types.
4523   if (ResultType->isFunctionType()) {
4524     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4525       << ResultType << BaseExpr->getSourceRange();
4526     return ExprError();
4527   }
4528 
4529   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4530     // GNU extension: subscripting on pointer to void
4531     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4532       << BaseExpr->getSourceRange();
4533 
4534     // C forbids expressions of unqualified void type from being l-values.
4535     // See IsCForbiddenLValueType.
4536     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4537   } else if (!ResultType->isDependentType() &&
4538       RequireCompleteType(LLoc, ResultType,
4539                           diag::err_subscript_incomplete_type, BaseExpr))
4540     return ExprError();
4541 
4542   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4543          !ResultType.isCForbiddenLValueType());
4544 
4545   return new (Context)
4546       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4547 }
4548 
4549 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4550                                   ParmVarDecl *Param) {
4551   if (Param->hasUnparsedDefaultArg()) {
4552     Diag(CallLoc,
4553          diag::err_use_of_default_argument_to_function_declared_later) <<
4554       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4555     Diag(UnparsedDefaultArgLocs[Param],
4556          diag::note_default_argument_declared_here);
4557     return true;
4558   }
4559 
4560   if (Param->hasUninstantiatedDefaultArg()) {
4561     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4562 
4563     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4564                                                  Param);
4565 
4566     // Instantiate the expression.
4567     MultiLevelTemplateArgumentList MutiLevelArgList
4568       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4569 
4570     InstantiatingTemplate Inst(*this, CallLoc, Param,
4571                                MutiLevelArgList.getInnermost());
4572     if (Inst.isInvalid())
4573       return true;
4574     if (Inst.isAlreadyInstantiating()) {
4575       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4576       Param->setInvalidDecl();
4577       return true;
4578     }
4579 
4580     ExprResult Result;
4581     {
4582       // C++ [dcl.fct.default]p5:
4583       //   The names in the [default argument] expression are bound, and
4584       //   the semantic constraints are checked, at the point where the
4585       //   default argument expression appears.
4586       ContextRAII SavedContext(*this, FD);
4587       LocalInstantiationScope Local(*this);
4588       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4589                                 /*DirectInit*/false);
4590     }
4591     if (Result.isInvalid())
4592       return true;
4593 
4594     // Check the expression as an initializer for the parameter.
4595     InitializedEntity Entity
4596       = InitializedEntity::InitializeParameter(Context, Param);
4597     InitializationKind Kind
4598       = InitializationKind::CreateCopy(Param->getLocation(),
4599              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4600     Expr *ResultE = Result.getAs<Expr>();
4601 
4602     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4603     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4604     if (Result.isInvalid())
4605       return true;
4606 
4607     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4608                                  Param->getOuterLocStart());
4609     if (Result.isInvalid())
4610       return true;
4611 
4612     // Remember the instantiated default argument.
4613     Param->setDefaultArg(Result.getAs<Expr>());
4614     if (ASTMutationListener *L = getASTMutationListener()) {
4615       L->DefaultArgumentInstantiated(Param);
4616     }
4617   }
4618 
4619   // If the default argument expression is not set yet, we are building it now.
4620   if (!Param->hasInit()) {
4621     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4622     Param->setInvalidDecl();
4623     return true;
4624   }
4625 
4626   // If the default expression creates temporaries, we need to
4627   // push them to the current stack of expression temporaries so they'll
4628   // be properly destroyed.
4629   // FIXME: We should really be rebuilding the default argument with new
4630   // bound temporaries; see the comment in PR5810.
4631   // We don't need to do that with block decls, though, because
4632   // blocks in default argument expression can never capture anything.
4633   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4634     // Set the "needs cleanups" bit regardless of whether there are
4635     // any explicit objects.
4636     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4637 
4638     // Append all the objects to the cleanup list.  Right now, this
4639     // should always be a no-op, because blocks in default argument
4640     // expressions should never be able to capture anything.
4641     assert(!Init->getNumObjects() &&
4642            "default argument expression has capturing blocks?");
4643   }
4644 
4645   // We already type-checked the argument, so we know it works.
4646   // Just mark all of the declarations in this potentially-evaluated expression
4647   // as being "referenced".
4648   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4649                                    /*SkipLocalVariables=*/true);
4650   return false;
4651 }
4652 
4653 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4654                                         FunctionDecl *FD, ParmVarDecl *Param) {
4655   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4656     return ExprError();
4657   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4658 }
4659 
4660 Sema::VariadicCallType
4661 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4662                           Expr *Fn) {
4663   if (Proto && Proto->isVariadic()) {
4664     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4665       return VariadicConstructor;
4666     else if (Fn && Fn->getType()->isBlockPointerType())
4667       return VariadicBlock;
4668     else if (FDecl) {
4669       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4670         if (Method->isInstance())
4671           return VariadicMethod;
4672     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4673       return VariadicMethod;
4674     return VariadicFunction;
4675   }
4676   return VariadicDoesNotApply;
4677 }
4678 
4679 namespace {
4680 class FunctionCallCCC : public FunctionCallFilterCCC {
4681 public:
4682   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4683                   unsigned NumArgs, MemberExpr *ME)
4684       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4685         FunctionName(FuncName) {}
4686 
4687   bool ValidateCandidate(const TypoCorrection &candidate) override {
4688     if (!candidate.getCorrectionSpecifier() ||
4689         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4690       return false;
4691     }
4692 
4693     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4694   }
4695 
4696 private:
4697   const IdentifierInfo *const FunctionName;
4698 };
4699 }
4700 
4701 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4702                                                FunctionDecl *FDecl,
4703                                                ArrayRef<Expr *> Args) {
4704   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4705   DeclarationName FuncName = FDecl->getDeclName();
4706   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4707 
4708   if (TypoCorrection Corrected = S.CorrectTypo(
4709           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4710           S.getScopeForContext(S.CurContext), nullptr,
4711           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4712                                              Args.size(), ME),
4713           Sema::CTK_ErrorRecovery)) {
4714     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4715       if (Corrected.isOverloaded()) {
4716         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4717         OverloadCandidateSet::iterator Best;
4718         for (NamedDecl *CD : Corrected) {
4719           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4720             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4721                                    OCS);
4722         }
4723         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4724         case OR_Success:
4725           ND = Best->FoundDecl;
4726           Corrected.setCorrectionDecl(ND);
4727           break;
4728         default:
4729           break;
4730         }
4731       }
4732       ND = ND->getUnderlyingDecl();
4733       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4734         return Corrected;
4735     }
4736   }
4737   return TypoCorrection();
4738 }
4739 
4740 /// ConvertArgumentsForCall - Converts the arguments specified in
4741 /// Args/NumArgs to the parameter types of the function FDecl with
4742 /// function prototype Proto. Call is the call expression itself, and
4743 /// Fn is the function expression. For a C++ member function, this
4744 /// routine does not attempt to convert the object argument. Returns
4745 /// true if the call is ill-formed.
4746 bool
4747 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4748                               FunctionDecl *FDecl,
4749                               const FunctionProtoType *Proto,
4750                               ArrayRef<Expr *> Args,
4751                               SourceLocation RParenLoc,
4752                               bool IsExecConfig) {
4753   // Bail out early if calling a builtin with custom typechecking.
4754   if (FDecl)
4755     if (unsigned ID = FDecl->getBuiltinID())
4756       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4757         return false;
4758 
4759   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4760   // assignment, to the types of the corresponding parameter, ...
4761   unsigned NumParams = Proto->getNumParams();
4762   bool Invalid = false;
4763   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4764   unsigned FnKind = Fn->getType()->isBlockPointerType()
4765                        ? 1 /* block */
4766                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4767                                        : 0 /* function */);
4768 
4769   // If too few arguments are available (and we don't have default
4770   // arguments for the remaining parameters), don't make the call.
4771   if (Args.size() < NumParams) {
4772     if (Args.size() < MinArgs) {
4773       TypoCorrection TC;
4774       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4775         unsigned diag_id =
4776             MinArgs == NumParams && !Proto->isVariadic()
4777                 ? diag::err_typecheck_call_too_few_args_suggest
4778                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4779         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4780                                         << static_cast<unsigned>(Args.size())
4781                                         << TC.getCorrectionRange());
4782       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4783         Diag(RParenLoc,
4784              MinArgs == NumParams && !Proto->isVariadic()
4785                  ? diag::err_typecheck_call_too_few_args_one
4786                  : diag::err_typecheck_call_too_few_args_at_least_one)
4787             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4788       else
4789         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4790                             ? diag::err_typecheck_call_too_few_args
4791                             : diag::err_typecheck_call_too_few_args_at_least)
4792             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4793             << Fn->getSourceRange();
4794 
4795       // Emit the location of the prototype.
4796       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4797         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4798           << FDecl;
4799 
4800       return true;
4801     }
4802     Call->setNumArgs(Context, NumParams);
4803   }
4804 
4805   // If too many are passed and not variadic, error on the extras and drop
4806   // them.
4807   if (Args.size() > NumParams) {
4808     if (!Proto->isVariadic()) {
4809       TypoCorrection TC;
4810       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4811         unsigned diag_id =
4812             MinArgs == NumParams && !Proto->isVariadic()
4813                 ? diag::err_typecheck_call_too_many_args_suggest
4814                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4815         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4816                                         << static_cast<unsigned>(Args.size())
4817                                         << TC.getCorrectionRange());
4818       } else if (NumParams == 1 && FDecl &&
4819                  FDecl->getParamDecl(0)->getDeclName())
4820         Diag(Args[NumParams]->getLocStart(),
4821              MinArgs == NumParams
4822                  ? diag::err_typecheck_call_too_many_args_one
4823                  : diag::err_typecheck_call_too_many_args_at_most_one)
4824             << FnKind << FDecl->getParamDecl(0)
4825             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4826             << SourceRange(Args[NumParams]->getLocStart(),
4827                            Args.back()->getLocEnd());
4828       else
4829         Diag(Args[NumParams]->getLocStart(),
4830              MinArgs == NumParams
4831                  ? diag::err_typecheck_call_too_many_args
4832                  : diag::err_typecheck_call_too_many_args_at_most)
4833             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4834             << Fn->getSourceRange()
4835             << SourceRange(Args[NumParams]->getLocStart(),
4836                            Args.back()->getLocEnd());
4837 
4838       // Emit the location of the prototype.
4839       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4840         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4841           << FDecl;
4842 
4843       // This deletes the extra arguments.
4844       Call->setNumArgs(Context, NumParams);
4845       return true;
4846     }
4847   }
4848   SmallVector<Expr *, 8> AllArgs;
4849   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4850 
4851   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4852                                    Proto, 0, Args, AllArgs, CallType);
4853   if (Invalid)
4854     return true;
4855   unsigned TotalNumArgs = AllArgs.size();
4856   for (unsigned i = 0; i < TotalNumArgs; ++i)
4857     Call->setArg(i, AllArgs[i]);
4858 
4859   return false;
4860 }
4861 
4862 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4863                                   const FunctionProtoType *Proto,
4864                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4865                                   SmallVectorImpl<Expr *> &AllArgs,
4866                                   VariadicCallType CallType, bool AllowExplicit,
4867                                   bool IsListInitialization) {
4868   unsigned NumParams = Proto->getNumParams();
4869   bool Invalid = false;
4870   size_t ArgIx = 0;
4871   // Continue to check argument types (even if we have too few/many args).
4872   for (unsigned i = FirstParam; i < NumParams; i++) {
4873     QualType ProtoArgType = Proto->getParamType(i);
4874 
4875     Expr *Arg;
4876     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4877     if (ArgIx < Args.size()) {
4878       Arg = Args[ArgIx++];
4879 
4880       if (RequireCompleteType(Arg->getLocStart(),
4881                               ProtoArgType,
4882                               diag::err_call_incomplete_argument, Arg))
4883         return true;
4884 
4885       // Strip the unbridged-cast placeholder expression off, if applicable.
4886       bool CFAudited = false;
4887       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4888           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4889           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4890         Arg = stripARCUnbridgedCast(Arg);
4891       else if (getLangOpts().ObjCAutoRefCount &&
4892                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4893                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4894         CFAudited = true;
4895 
4896       InitializedEntity Entity =
4897           Param ? InitializedEntity::InitializeParameter(Context, Param,
4898                                                          ProtoArgType)
4899                 : InitializedEntity::InitializeParameter(
4900                       Context, ProtoArgType, Proto->isParamConsumed(i));
4901 
4902       // Remember that parameter belongs to a CF audited API.
4903       if (CFAudited)
4904         Entity.setParameterCFAudited();
4905 
4906       ExprResult ArgE = PerformCopyInitialization(
4907           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4908       if (ArgE.isInvalid())
4909         return true;
4910 
4911       Arg = ArgE.getAs<Expr>();
4912     } else {
4913       assert(Param && "can't use default arguments without a known callee");
4914 
4915       ExprResult ArgExpr =
4916         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4917       if (ArgExpr.isInvalid())
4918         return true;
4919 
4920       Arg = ArgExpr.getAs<Expr>();
4921     }
4922 
4923     // Check for array bounds violations for each argument to the call. This
4924     // check only triggers warnings when the argument isn't a more complex Expr
4925     // with its own checking, such as a BinaryOperator.
4926     CheckArrayAccess(Arg);
4927 
4928     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4929     CheckStaticArrayArgument(CallLoc, Param, Arg);
4930 
4931     AllArgs.push_back(Arg);
4932   }
4933 
4934   // If this is a variadic call, handle args passed through "...".
4935   if (CallType != VariadicDoesNotApply) {
4936     // Assume that extern "C" functions with variadic arguments that
4937     // return __unknown_anytype aren't *really* variadic.
4938     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4939         FDecl->isExternC()) {
4940       for (Expr *A : Args.slice(ArgIx)) {
4941         QualType paramType; // ignored
4942         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4943         Invalid |= arg.isInvalid();
4944         AllArgs.push_back(arg.get());
4945       }
4946 
4947     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4948     } else {
4949       for (Expr *A : Args.slice(ArgIx)) {
4950         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4951         Invalid |= Arg.isInvalid();
4952         AllArgs.push_back(Arg.get());
4953       }
4954     }
4955 
4956     // Check for array bounds violations.
4957     for (Expr *A : Args.slice(ArgIx))
4958       CheckArrayAccess(A);
4959   }
4960   return Invalid;
4961 }
4962 
4963 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4964   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4965   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4966     TL = DTL.getOriginalLoc();
4967   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4968     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4969       << ATL.getLocalSourceRange();
4970 }
4971 
4972 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4973 /// array parameter, check that it is non-null, and that if it is formed by
4974 /// array-to-pointer decay, the underlying array is sufficiently large.
4975 ///
4976 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4977 /// array type derivation, then for each call to the function, the value of the
4978 /// corresponding actual argument shall provide access to the first element of
4979 /// an array with at least as many elements as specified by the size expression.
4980 void
4981 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4982                                ParmVarDecl *Param,
4983                                const Expr *ArgExpr) {
4984   // Static array parameters are not supported in C++.
4985   if (!Param || getLangOpts().CPlusPlus)
4986     return;
4987 
4988   QualType OrigTy = Param->getOriginalType();
4989 
4990   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4991   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4992     return;
4993 
4994   if (ArgExpr->isNullPointerConstant(Context,
4995                                      Expr::NPC_NeverValueDependent)) {
4996     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4997     DiagnoseCalleeStaticArrayParam(*this, Param);
4998     return;
4999   }
5000 
5001   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5002   if (!CAT)
5003     return;
5004 
5005   const ConstantArrayType *ArgCAT =
5006     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5007   if (!ArgCAT)
5008     return;
5009 
5010   if (ArgCAT->getSize().ult(CAT->getSize())) {
5011     Diag(CallLoc, diag::warn_static_array_too_small)
5012       << ArgExpr->getSourceRange()
5013       << (unsigned) ArgCAT->getSize().getZExtValue()
5014       << (unsigned) CAT->getSize().getZExtValue();
5015     DiagnoseCalleeStaticArrayParam(*this, Param);
5016   }
5017 }
5018 
5019 /// Given a function expression of unknown-any type, try to rebuild it
5020 /// to have a function type.
5021 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5022 
5023 /// Is the given type a placeholder that we need to lower out
5024 /// immediately during argument processing?
5025 static bool isPlaceholderToRemoveAsArg(QualType type) {
5026   // Placeholders are never sugared.
5027   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5028   if (!placeholder) return false;
5029 
5030   switch (placeholder->getKind()) {
5031   // Ignore all the non-placeholder types.
5032 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5033   case BuiltinType::Id:
5034 #include "clang/Basic/OpenCLImageTypes.def"
5035 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5036 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5037 #include "clang/AST/BuiltinTypes.def"
5038     return false;
5039 
5040   // We cannot lower out overload sets; they might validly be resolved
5041   // by the call machinery.
5042   case BuiltinType::Overload:
5043     return false;
5044 
5045   // Unbridged casts in ARC can be handled in some call positions and
5046   // should be left in place.
5047   case BuiltinType::ARCUnbridgedCast:
5048     return false;
5049 
5050   // Pseudo-objects should be converted as soon as possible.
5051   case BuiltinType::PseudoObject:
5052     return true;
5053 
5054   // The debugger mode could theoretically but currently does not try
5055   // to resolve unknown-typed arguments based on known parameter types.
5056   case BuiltinType::UnknownAny:
5057     return true;
5058 
5059   // These are always invalid as call arguments and should be reported.
5060   case BuiltinType::BoundMember:
5061   case BuiltinType::BuiltinFn:
5062   case BuiltinType::OMPArraySection:
5063     return true;
5064 
5065   }
5066   llvm_unreachable("bad builtin type kind");
5067 }
5068 
5069 /// Check an argument list for placeholders that we won't try to
5070 /// handle later.
5071 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5072   // Apply this processing to all the arguments at once instead of
5073   // dying at the first failure.
5074   bool hasInvalid = false;
5075   for (size_t i = 0, e = args.size(); i != e; i++) {
5076     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5077       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5078       if (result.isInvalid()) hasInvalid = true;
5079       else args[i] = result.get();
5080     } else if (hasInvalid) {
5081       (void)S.CorrectDelayedTyposInExpr(args[i]);
5082     }
5083   }
5084   return hasInvalid;
5085 }
5086 
5087 /// If a builtin function has a pointer argument with no explicit address
5088 /// space, then it should be able to accept a pointer to any address
5089 /// space as input.  In order to do this, we need to replace the
5090 /// standard builtin declaration with one that uses the same address space
5091 /// as the call.
5092 ///
5093 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5094 ///                  it does not contain any pointer arguments without
5095 ///                  an address space qualifer.  Otherwise the rewritten
5096 ///                  FunctionDecl is returned.
5097 /// TODO: Handle pointer return types.
5098 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5099                                                 const FunctionDecl *FDecl,
5100                                                 MultiExprArg ArgExprs) {
5101 
5102   QualType DeclType = FDecl->getType();
5103   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5104 
5105   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5106       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5107     return nullptr;
5108 
5109   bool NeedsNewDecl = false;
5110   unsigned i = 0;
5111   SmallVector<QualType, 8> OverloadParams;
5112 
5113   for (QualType ParamType : FT->param_types()) {
5114 
5115     // Convert array arguments to pointer to simplify type lookup.
5116     ExprResult ArgRes =
5117         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5118     if (ArgRes.isInvalid())
5119       return nullptr;
5120     Expr *Arg = ArgRes.get();
5121     QualType ArgType = Arg->getType();
5122     if (!ParamType->isPointerType() ||
5123         ParamType.getQualifiers().hasAddressSpace() ||
5124         !ArgType->isPointerType() ||
5125         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5126       OverloadParams.push_back(ParamType);
5127       continue;
5128     }
5129 
5130     NeedsNewDecl = true;
5131     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5132 
5133     QualType PointeeType = ParamType->getPointeeType();
5134     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5135     OverloadParams.push_back(Context.getPointerType(PointeeType));
5136   }
5137 
5138   if (!NeedsNewDecl)
5139     return nullptr;
5140 
5141   FunctionProtoType::ExtProtoInfo EPI;
5142   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5143                                                 OverloadParams, EPI);
5144   DeclContext *Parent = Context.getTranslationUnitDecl();
5145   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5146                                                     FDecl->getLocation(),
5147                                                     FDecl->getLocation(),
5148                                                     FDecl->getIdentifier(),
5149                                                     OverloadTy,
5150                                                     /*TInfo=*/nullptr,
5151                                                     SC_Extern, false,
5152                                                     /*hasPrototype=*/true);
5153   SmallVector<ParmVarDecl*, 16> Params;
5154   FT = cast<FunctionProtoType>(OverloadTy);
5155   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5156     QualType ParamType = FT->getParamType(i);
5157     ParmVarDecl *Parm =
5158         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5159                                 SourceLocation(), nullptr, ParamType,
5160                                 /*TInfo=*/nullptr, SC_None, nullptr);
5161     Parm->setScopeInfo(0, i);
5162     Params.push_back(Parm);
5163   }
5164   OverloadDecl->setParams(Params);
5165   return OverloadDecl;
5166 }
5167 
5168 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5169                                     FunctionDecl *Callee,
5170                                     MultiExprArg ArgExprs) {
5171   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5172   // similar attributes) really don't like it when functions are called with an
5173   // invalid number of args.
5174   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5175                          /*PartialOverloading=*/false) &&
5176       !Callee->isVariadic())
5177     return;
5178   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5179     return;
5180 
5181   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5182     S.Diag(Fn->getLocStart(),
5183            isa<CXXMethodDecl>(Callee)
5184                ? diag::err_ovl_no_viable_member_function_in_call
5185                : diag::err_ovl_no_viable_function_in_call)
5186         << Callee << Callee->getSourceRange();
5187     S.Diag(Callee->getLocation(),
5188            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5189         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5190     return;
5191   }
5192 
5193   SmallVector<DiagnoseIfAttr *, 4> Nonfatal;
5194   if (const DiagnoseIfAttr *Attr = S.checkArgDependentDiagnoseIf(
5195           Callee, ArgExprs, Nonfatal, /*MissingImplicitThis=*/true)) {
5196     S.emitDiagnoseIfDiagnostic(Fn->getLocStart(), Attr);
5197     return;
5198   }
5199 
5200   for (const auto *W : Nonfatal)
5201     S.emitDiagnoseIfDiagnostic(Fn->getLocStart(), W);
5202 }
5203 
5204 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5205 /// This provides the location of the left/right parens and a list of comma
5206 /// locations.
5207 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5208                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5209                                Expr *ExecConfig, bool IsExecConfig) {
5210   // Since this might be a postfix expression, get rid of ParenListExprs.
5211   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5212   if (Result.isInvalid()) return ExprError();
5213   Fn = Result.get();
5214 
5215   if (checkArgsForPlaceholders(*this, ArgExprs))
5216     return ExprError();
5217 
5218   if (getLangOpts().CPlusPlus) {
5219     // If this is a pseudo-destructor expression, build the call immediately.
5220     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5221       if (!ArgExprs.empty()) {
5222         // Pseudo-destructor calls should not have any arguments.
5223         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5224             << FixItHint::CreateRemoval(
5225                    SourceRange(ArgExprs.front()->getLocStart(),
5226                                ArgExprs.back()->getLocEnd()));
5227       }
5228 
5229       return new (Context)
5230           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5231     }
5232     if (Fn->getType() == Context.PseudoObjectTy) {
5233       ExprResult result = CheckPlaceholderExpr(Fn);
5234       if (result.isInvalid()) return ExprError();
5235       Fn = result.get();
5236     }
5237 
5238     // Determine whether this is a dependent call inside a C++ template,
5239     // in which case we won't do any semantic analysis now.
5240     bool Dependent = false;
5241     if (Fn->isTypeDependent())
5242       Dependent = true;
5243     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5244       Dependent = true;
5245 
5246     if (Dependent) {
5247       if (ExecConfig) {
5248         return new (Context) CUDAKernelCallExpr(
5249             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5250             Context.DependentTy, VK_RValue, RParenLoc);
5251       } else {
5252         return new (Context) CallExpr(
5253             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5254       }
5255     }
5256 
5257     // Determine whether this is a call to an object (C++ [over.call.object]).
5258     if (Fn->getType()->isRecordType())
5259       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5260                                           RParenLoc);
5261 
5262     if (Fn->getType() == Context.UnknownAnyTy) {
5263       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5264       if (result.isInvalid()) return ExprError();
5265       Fn = result.get();
5266     }
5267 
5268     if (Fn->getType() == Context.BoundMemberTy) {
5269       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5270                                        RParenLoc);
5271     }
5272   }
5273 
5274   // Check for overloaded calls.  This can happen even in C due to extensions.
5275   if (Fn->getType() == Context.OverloadTy) {
5276     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5277 
5278     // We aren't supposed to apply this logic for if there'Scope an '&'
5279     // involved.
5280     if (!find.HasFormOfMemberPointer) {
5281       OverloadExpr *ovl = find.Expression;
5282       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5283         return BuildOverloadedCallExpr(
5284             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5285             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5286       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5287                                        RParenLoc);
5288     }
5289   }
5290 
5291   // If we're directly calling a function, get the appropriate declaration.
5292   if (Fn->getType() == Context.UnknownAnyTy) {
5293     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5294     if (result.isInvalid()) return ExprError();
5295     Fn = result.get();
5296   }
5297 
5298   Expr *NakedFn = Fn->IgnoreParens();
5299 
5300   bool CallingNDeclIndirectly = false;
5301   NamedDecl *NDecl = nullptr;
5302   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5303     if (UnOp->getOpcode() == UO_AddrOf) {
5304       CallingNDeclIndirectly = true;
5305       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5306     }
5307   }
5308 
5309   if (isa<DeclRefExpr>(NakedFn)) {
5310     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5311 
5312     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5313     if (FDecl && FDecl->getBuiltinID()) {
5314       // Rewrite the function decl for this builtin by replacing parameters
5315       // with no explicit address space with the address space of the arguments
5316       // in ArgExprs.
5317       if ((FDecl =
5318                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5319         NDecl = FDecl;
5320         Fn = DeclRefExpr::Create(
5321             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5322             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5323       }
5324     }
5325   } else if (isa<MemberExpr>(NakedFn))
5326     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5327 
5328   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5329     if (CallingNDeclIndirectly &&
5330         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5331                                            Fn->getLocStart()))
5332       return ExprError();
5333 
5334     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5335       return ExprError();
5336 
5337     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5338   }
5339 
5340   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5341                                ExecConfig, IsExecConfig);
5342 }
5343 
5344 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5345 ///
5346 /// __builtin_astype( value, dst type )
5347 ///
5348 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5349                                  SourceLocation BuiltinLoc,
5350                                  SourceLocation RParenLoc) {
5351   ExprValueKind VK = VK_RValue;
5352   ExprObjectKind OK = OK_Ordinary;
5353   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5354   QualType SrcTy = E->getType();
5355   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5356     return ExprError(Diag(BuiltinLoc,
5357                           diag::err_invalid_astype_of_different_size)
5358                      << DstTy
5359                      << SrcTy
5360                      << E->getSourceRange());
5361   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5362 }
5363 
5364 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5365 /// provided arguments.
5366 ///
5367 /// __builtin_convertvector( value, dst type )
5368 ///
5369 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5370                                         SourceLocation BuiltinLoc,
5371                                         SourceLocation RParenLoc) {
5372   TypeSourceInfo *TInfo;
5373   GetTypeFromParser(ParsedDestTy, &TInfo);
5374   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5375 }
5376 
5377 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5378 /// i.e. an expression not of \p OverloadTy.  The expression should
5379 /// unary-convert to an expression of function-pointer or
5380 /// block-pointer type.
5381 ///
5382 /// \param NDecl the declaration being called, if available
5383 ExprResult
5384 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5385                             SourceLocation LParenLoc,
5386                             ArrayRef<Expr *> Args,
5387                             SourceLocation RParenLoc,
5388                             Expr *Config, bool IsExecConfig) {
5389   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5390   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5391 
5392   // Functions with 'interrupt' attribute cannot be called directly.
5393   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5394     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5395     return ExprError();
5396   }
5397 
5398   // Promote the function operand.
5399   // We special-case function promotion here because we only allow promoting
5400   // builtin functions to function pointers in the callee of a call.
5401   ExprResult Result;
5402   if (BuiltinID &&
5403       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5404     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5405                                CK_BuiltinFnToFnPtr).get();
5406   } else {
5407     Result = CallExprUnaryConversions(Fn);
5408   }
5409   if (Result.isInvalid())
5410     return ExprError();
5411   Fn = Result.get();
5412 
5413   // Make the call expr early, before semantic checks.  This guarantees cleanup
5414   // of arguments and function on error.
5415   CallExpr *TheCall;
5416   if (Config)
5417     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5418                                                cast<CallExpr>(Config), Args,
5419                                                Context.BoolTy, VK_RValue,
5420                                                RParenLoc);
5421   else
5422     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5423                                      VK_RValue, RParenLoc);
5424 
5425   if (!getLangOpts().CPlusPlus) {
5426     // C cannot always handle TypoExpr nodes in builtin calls and direct
5427     // function calls as their argument checking don't necessarily handle
5428     // dependent types properly, so make sure any TypoExprs have been
5429     // dealt with.
5430     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5431     if (!Result.isUsable()) return ExprError();
5432     TheCall = dyn_cast<CallExpr>(Result.get());
5433     if (!TheCall) return Result;
5434     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5435   }
5436 
5437   // Bail out early if calling a builtin with custom typechecking.
5438   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5439     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5440 
5441  retry:
5442   const FunctionType *FuncT;
5443   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5444     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5445     // have type pointer to function".
5446     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5447     if (!FuncT)
5448       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5449                          << Fn->getType() << Fn->getSourceRange());
5450   } else if (const BlockPointerType *BPT =
5451                Fn->getType()->getAs<BlockPointerType>()) {
5452     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5453   } else {
5454     // Handle calls to expressions of unknown-any type.
5455     if (Fn->getType() == Context.UnknownAnyTy) {
5456       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5457       if (rewrite.isInvalid()) return ExprError();
5458       Fn = rewrite.get();
5459       TheCall->setCallee(Fn);
5460       goto retry;
5461     }
5462 
5463     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5464       << Fn->getType() << Fn->getSourceRange());
5465   }
5466 
5467   if (getLangOpts().CUDA) {
5468     if (Config) {
5469       // CUDA: Kernel calls must be to global functions
5470       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5471         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5472             << FDecl->getName() << Fn->getSourceRange());
5473 
5474       // CUDA: Kernel function must have 'void' return type
5475       if (!FuncT->getReturnType()->isVoidType())
5476         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5477             << Fn->getType() << Fn->getSourceRange());
5478     } else {
5479       // CUDA: Calls to global functions must be configured
5480       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5481         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5482             << FDecl->getName() << Fn->getSourceRange());
5483     }
5484   }
5485 
5486   // Check for a valid return type
5487   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5488                           FDecl))
5489     return ExprError();
5490 
5491   // We know the result type of the call, set it.
5492   TheCall->setType(FuncT->getCallResultType(Context));
5493   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5494 
5495   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5496   if (Proto) {
5497     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5498                                 IsExecConfig))
5499       return ExprError();
5500   } else {
5501     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5502 
5503     if (FDecl) {
5504       // Check if we have too few/too many template arguments, based
5505       // on our knowledge of the function definition.
5506       const FunctionDecl *Def = nullptr;
5507       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5508         Proto = Def->getType()->getAs<FunctionProtoType>();
5509        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5510           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5511           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5512       }
5513 
5514       // If the function we're calling isn't a function prototype, but we have
5515       // a function prototype from a prior declaratiom, use that prototype.
5516       if (!FDecl->hasPrototype())
5517         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5518     }
5519 
5520     // Promote the arguments (C99 6.5.2.2p6).
5521     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5522       Expr *Arg = Args[i];
5523 
5524       if (Proto && i < Proto->getNumParams()) {
5525         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5526             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5527         ExprResult ArgE =
5528             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5529         if (ArgE.isInvalid())
5530           return true;
5531 
5532         Arg = ArgE.getAs<Expr>();
5533 
5534       } else {
5535         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5536 
5537         if (ArgE.isInvalid())
5538           return true;
5539 
5540         Arg = ArgE.getAs<Expr>();
5541       }
5542 
5543       if (RequireCompleteType(Arg->getLocStart(),
5544                               Arg->getType(),
5545                               diag::err_call_incomplete_argument, Arg))
5546         return ExprError();
5547 
5548       TheCall->setArg(i, Arg);
5549     }
5550   }
5551 
5552   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5553     if (!Method->isStatic())
5554       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5555         << Fn->getSourceRange());
5556 
5557   // Check for sentinels
5558   if (NDecl)
5559     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5560 
5561   // Do special checking on direct calls to functions.
5562   if (FDecl) {
5563     if (CheckFunctionCall(FDecl, TheCall, Proto))
5564       return ExprError();
5565 
5566     if (BuiltinID)
5567       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5568   } else if (NDecl) {
5569     if (CheckPointerCall(NDecl, TheCall, Proto))
5570       return ExprError();
5571   } else {
5572     if (CheckOtherCall(TheCall, Proto))
5573       return ExprError();
5574   }
5575 
5576   return MaybeBindToTemporary(TheCall);
5577 }
5578 
5579 ExprResult
5580 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5581                            SourceLocation RParenLoc, Expr *InitExpr) {
5582   assert(Ty && "ActOnCompoundLiteral(): missing type");
5583   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5584 
5585   TypeSourceInfo *TInfo;
5586   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5587   if (!TInfo)
5588     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5589 
5590   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5591 }
5592 
5593 ExprResult
5594 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5595                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5596   QualType literalType = TInfo->getType();
5597 
5598   if (literalType->isArrayType()) {
5599     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5600           diag::err_illegal_decl_array_incomplete_type,
5601           SourceRange(LParenLoc,
5602                       LiteralExpr->getSourceRange().getEnd())))
5603       return ExprError();
5604     if (literalType->isVariableArrayType())
5605       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5606         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5607   } else if (!literalType->isDependentType() &&
5608              RequireCompleteType(LParenLoc, literalType,
5609                diag::err_typecheck_decl_incomplete_type,
5610                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5611     return ExprError();
5612 
5613   InitializedEntity Entity
5614     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5615   InitializationKind Kind
5616     = InitializationKind::CreateCStyleCast(LParenLoc,
5617                                            SourceRange(LParenLoc, RParenLoc),
5618                                            /*InitList=*/true);
5619   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5620   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5621                                       &literalType);
5622   if (Result.isInvalid())
5623     return ExprError();
5624   LiteralExpr = Result.get();
5625 
5626   bool isFileScope = !CurContext->isFunctionOrMethod();
5627   if (isFileScope &&
5628       !LiteralExpr->isTypeDependent() &&
5629       !LiteralExpr->isValueDependent() &&
5630       !literalType->isDependentType()) { // 6.5.2.5p3
5631     if (CheckForConstantInitializer(LiteralExpr, literalType))
5632       return ExprError();
5633   }
5634 
5635   // In C, compound literals are l-values for some reason.
5636   // For GCC compatibility, in C++, file-scope array compound literals with
5637   // constant initializers are also l-values, and compound literals are
5638   // otherwise prvalues.
5639   //
5640   // (GCC also treats C++ list-initialized file-scope array prvalues with
5641   // constant initializers as l-values, but that's non-conforming, so we don't
5642   // follow it there.)
5643   //
5644   // FIXME: It would be better to handle the lvalue cases as materializing and
5645   // lifetime-extending a temporary object, but our materialized temporaries
5646   // representation only supports lifetime extension from a variable, not "out
5647   // of thin air".
5648   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5649   // is bound to the result of applying array-to-pointer decay to the compound
5650   // literal.
5651   // FIXME: GCC supports compound literals of reference type, which should
5652   // obviously have a value kind derived from the kind of reference involved.
5653   ExprValueKind VK =
5654       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5655           ? VK_RValue
5656           : VK_LValue;
5657 
5658   return MaybeBindToTemporary(
5659       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5660                                         VK, LiteralExpr, isFileScope));
5661 }
5662 
5663 ExprResult
5664 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5665                     SourceLocation RBraceLoc) {
5666   // Immediately handle non-overload placeholders.  Overloads can be
5667   // resolved contextually, but everything else here can't.
5668   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5669     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5670       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5671 
5672       // Ignore failures; dropping the entire initializer list because
5673       // of one failure would be terrible for indexing/etc.
5674       if (result.isInvalid()) continue;
5675 
5676       InitArgList[I] = result.get();
5677     }
5678   }
5679 
5680   // Semantic analysis for initializers is done by ActOnDeclarator() and
5681   // CheckInitializer() - it requires knowledge of the object being intialized.
5682 
5683   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5684                                                RBraceLoc);
5685   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5686   return E;
5687 }
5688 
5689 /// Do an explicit extend of the given block pointer if we're in ARC.
5690 void Sema::maybeExtendBlockObject(ExprResult &E) {
5691   assert(E.get()->getType()->isBlockPointerType());
5692   assert(E.get()->isRValue());
5693 
5694   // Only do this in an r-value context.
5695   if (!getLangOpts().ObjCAutoRefCount) return;
5696 
5697   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5698                                CK_ARCExtendBlockObject, E.get(),
5699                                /*base path*/ nullptr, VK_RValue);
5700   Cleanup.setExprNeedsCleanups(true);
5701 }
5702 
5703 /// Prepare a conversion of the given expression to an ObjC object
5704 /// pointer type.
5705 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5706   QualType type = E.get()->getType();
5707   if (type->isObjCObjectPointerType()) {
5708     return CK_BitCast;
5709   } else if (type->isBlockPointerType()) {
5710     maybeExtendBlockObject(E);
5711     return CK_BlockPointerToObjCPointerCast;
5712   } else {
5713     assert(type->isPointerType());
5714     return CK_CPointerToObjCPointerCast;
5715   }
5716 }
5717 
5718 /// Prepares for a scalar cast, performing all the necessary stages
5719 /// except the final cast and returning the kind required.
5720 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5721   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5722   // Also, callers should have filtered out the invalid cases with
5723   // pointers.  Everything else should be possible.
5724 
5725   QualType SrcTy = Src.get()->getType();
5726   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5727     return CK_NoOp;
5728 
5729   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5730   case Type::STK_MemberPointer:
5731     llvm_unreachable("member pointer type in C");
5732 
5733   case Type::STK_CPointer:
5734   case Type::STK_BlockPointer:
5735   case Type::STK_ObjCObjectPointer:
5736     switch (DestTy->getScalarTypeKind()) {
5737     case Type::STK_CPointer: {
5738       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5739       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5740       if (SrcAS != DestAS)
5741         return CK_AddressSpaceConversion;
5742       return CK_BitCast;
5743     }
5744     case Type::STK_BlockPointer:
5745       return (SrcKind == Type::STK_BlockPointer
5746                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5747     case Type::STK_ObjCObjectPointer:
5748       if (SrcKind == Type::STK_ObjCObjectPointer)
5749         return CK_BitCast;
5750       if (SrcKind == Type::STK_CPointer)
5751         return CK_CPointerToObjCPointerCast;
5752       maybeExtendBlockObject(Src);
5753       return CK_BlockPointerToObjCPointerCast;
5754     case Type::STK_Bool:
5755       return CK_PointerToBoolean;
5756     case Type::STK_Integral:
5757       return CK_PointerToIntegral;
5758     case Type::STK_Floating:
5759     case Type::STK_FloatingComplex:
5760     case Type::STK_IntegralComplex:
5761     case Type::STK_MemberPointer:
5762       llvm_unreachable("illegal cast from pointer");
5763     }
5764     llvm_unreachable("Should have returned before this");
5765 
5766   case Type::STK_Bool: // casting from bool is like casting from an integer
5767   case Type::STK_Integral:
5768     switch (DestTy->getScalarTypeKind()) {
5769     case Type::STK_CPointer:
5770     case Type::STK_ObjCObjectPointer:
5771     case Type::STK_BlockPointer:
5772       if (Src.get()->isNullPointerConstant(Context,
5773                                            Expr::NPC_ValueDependentIsNull))
5774         return CK_NullToPointer;
5775       return CK_IntegralToPointer;
5776     case Type::STK_Bool:
5777       return CK_IntegralToBoolean;
5778     case Type::STK_Integral:
5779       return CK_IntegralCast;
5780     case Type::STK_Floating:
5781       return CK_IntegralToFloating;
5782     case Type::STK_IntegralComplex:
5783       Src = ImpCastExprToType(Src.get(),
5784                       DestTy->castAs<ComplexType>()->getElementType(),
5785                       CK_IntegralCast);
5786       return CK_IntegralRealToComplex;
5787     case Type::STK_FloatingComplex:
5788       Src = ImpCastExprToType(Src.get(),
5789                       DestTy->castAs<ComplexType>()->getElementType(),
5790                       CK_IntegralToFloating);
5791       return CK_FloatingRealToComplex;
5792     case Type::STK_MemberPointer:
5793       llvm_unreachable("member pointer type in C");
5794     }
5795     llvm_unreachable("Should have returned before this");
5796 
5797   case Type::STK_Floating:
5798     switch (DestTy->getScalarTypeKind()) {
5799     case Type::STK_Floating:
5800       return CK_FloatingCast;
5801     case Type::STK_Bool:
5802       return CK_FloatingToBoolean;
5803     case Type::STK_Integral:
5804       return CK_FloatingToIntegral;
5805     case Type::STK_FloatingComplex:
5806       Src = ImpCastExprToType(Src.get(),
5807                               DestTy->castAs<ComplexType>()->getElementType(),
5808                               CK_FloatingCast);
5809       return CK_FloatingRealToComplex;
5810     case Type::STK_IntegralComplex:
5811       Src = ImpCastExprToType(Src.get(),
5812                               DestTy->castAs<ComplexType>()->getElementType(),
5813                               CK_FloatingToIntegral);
5814       return CK_IntegralRealToComplex;
5815     case Type::STK_CPointer:
5816     case Type::STK_ObjCObjectPointer:
5817     case Type::STK_BlockPointer:
5818       llvm_unreachable("valid float->pointer cast?");
5819     case Type::STK_MemberPointer:
5820       llvm_unreachable("member pointer type in C");
5821     }
5822     llvm_unreachable("Should have returned before this");
5823 
5824   case Type::STK_FloatingComplex:
5825     switch (DestTy->getScalarTypeKind()) {
5826     case Type::STK_FloatingComplex:
5827       return CK_FloatingComplexCast;
5828     case Type::STK_IntegralComplex:
5829       return CK_FloatingComplexToIntegralComplex;
5830     case Type::STK_Floating: {
5831       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5832       if (Context.hasSameType(ET, DestTy))
5833         return CK_FloatingComplexToReal;
5834       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5835       return CK_FloatingCast;
5836     }
5837     case Type::STK_Bool:
5838       return CK_FloatingComplexToBoolean;
5839     case Type::STK_Integral:
5840       Src = ImpCastExprToType(Src.get(),
5841                               SrcTy->castAs<ComplexType>()->getElementType(),
5842                               CK_FloatingComplexToReal);
5843       return CK_FloatingToIntegral;
5844     case Type::STK_CPointer:
5845     case Type::STK_ObjCObjectPointer:
5846     case Type::STK_BlockPointer:
5847       llvm_unreachable("valid complex float->pointer cast?");
5848     case Type::STK_MemberPointer:
5849       llvm_unreachable("member pointer type in C");
5850     }
5851     llvm_unreachable("Should have returned before this");
5852 
5853   case Type::STK_IntegralComplex:
5854     switch (DestTy->getScalarTypeKind()) {
5855     case Type::STK_FloatingComplex:
5856       return CK_IntegralComplexToFloatingComplex;
5857     case Type::STK_IntegralComplex:
5858       return CK_IntegralComplexCast;
5859     case Type::STK_Integral: {
5860       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5861       if (Context.hasSameType(ET, DestTy))
5862         return CK_IntegralComplexToReal;
5863       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5864       return CK_IntegralCast;
5865     }
5866     case Type::STK_Bool:
5867       return CK_IntegralComplexToBoolean;
5868     case Type::STK_Floating:
5869       Src = ImpCastExprToType(Src.get(),
5870                               SrcTy->castAs<ComplexType>()->getElementType(),
5871                               CK_IntegralComplexToReal);
5872       return CK_IntegralToFloating;
5873     case Type::STK_CPointer:
5874     case Type::STK_ObjCObjectPointer:
5875     case Type::STK_BlockPointer:
5876       llvm_unreachable("valid complex int->pointer cast?");
5877     case Type::STK_MemberPointer:
5878       llvm_unreachable("member pointer type in C");
5879     }
5880     llvm_unreachable("Should have returned before this");
5881   }
5882 
5883   llvm_unreachable("Unhandled scalar cast");
5884 }
5885 
5886 static bool breakDownVectorType(QualType type, uint64_t &len,
5887                                 QualType &eltType) {
5888   // Vectors are simple.
5889   if (const VectorType *vecType = type->getAs<VectorType>()) {
5890     len = vecType->getNumElements();
5891     eltType = vecType->getElementType();
5892     assert(eltType->isScalarType());
5893     return true;
5894   }
5895 
5896   // We allow lax conversion to and from non-vector types, but only if
5897   // they're real types (i.e. non-complex, non-pointer scalar types).
5898   if (!type->isRealType()) return false;
5899 
5900   len = 1;
5901   eltType = type;
5902   return true;
5903 }
5904 
5905 /// Are the two types lax-compatible vector types?  That is, given
5906 /// that one of them is a vector, do they have equal storage sizes,
5907 /// where the storage size is the number of elements times the element
5908 /// size?
5909 ///
5910 /// This will also return false if either of the types is neither a
5911 /// vector nor a real type.
5912 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5913   assert(destTy->isVectorType() || srcTy->isVectorType());
5914 
5915   // Disallow lax conversions between scalars and ExtVectors (these
5916   // conversions are allowed for other vector types because common headers
5917   // depend on them).  Most scalar OP ExtVector cases are handled by the
5918   // splat path anyway, which does what we want (convert, not bitcast).
5919   // What this rules out for ExtVectors is crazy things like char4*float.
5920   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5921   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5922 
5923   uint64_t srcLen, destLen;
5924   QualType srcEltTy, destEltTy;
5925   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5926   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5927 
5928   // ASTContext::getTypeSize will return the size rounded up to a
5929   // power of 2, so instead of using that, we need to use the raw
5930   // element size multiplied by the element count.
5931   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5932   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5933 
5934   return (srcLen * srcEltSize == destLen * destEltSize);
5935 }
5936 
5937 /// Is this a legal conversion between two types, one of which is
5938 /// known to be a vector type?
5939 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5940   assert(destTy->isVectorType() || srcTy->isVectorType());
5941 
5942   if (!Context.getLangOpts().LaxVectorConversions)
5943     return false;
5944   return areLaxCompatibleVectorTypes(srcTy, destTy);
5945 }
5946 
5947 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5948                            CastKind &Kind) {
5949   assert(VectorTy->isVectorType() && "Not a vector type!");
5950 
5951   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5952     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5953       return Diag(R.getBegin(),
5954                   Ty->isVectorType() ?
5955                   diag::err_invalid_conversion_between_vectors :
5956                   diag::err_invalid_conversion_between_vector_and_integer)
5957         << VectorTy << Ty << R;
5958   } else
5959     return Diag(R.getBegin(),
5960                 diag::err_invalid_conversion_between_vector_and_scalar)
5961       << VectorTy << Ty << R;
5962 
5963   Kind = CK_BitCast;
5964   return false;
5965 }
5966 
5967 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5968   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5969 
5970   if (DestElemTy == SplattedExpr->getType())
5971     return SplattedExpr;
5972 
5973   assert(DestElemTy->isFloatingType() ||
5974          DestElemTy->isIntegralOrEnumerationType());
5975 
5976   CastKind CK;
5977   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5978     // OpenCL requires that we convert `true` boolean expressions to -1, but
5979     // only when splatting vectors.
5980     if (DestElemTy->isFloatingType()) {
5981       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5982       // in two steps: boolean to signed integral, then to floating.
5983       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5984                                                  CK_BooleanToSignedIntegral);
5985       SplattedExpr = CastExprRes.get();
5986       CK = CK_IntegralToFloating;
5987     } else {
5988       CK = CK_BooleanToSignedIntegral;
5989     }
5990   } else {
5991     ExprResult CastExprRes = SplattedExpr;
5992     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5993     if (CastExprRes.isInvalid())
5994       return ExprError();
5995     SplattedExpr = CastExprRes.get();
5996   }
5997   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5998 }
5999 
6000 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6001                                     Expr *CastExpr, CastKind &Kind) {
6002   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6003 
6004   QualType SrcTy = CastExpr->getType();
6005 
6006   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6007   // an ExtVectorType.
6008   // In OpenCL, casts between vectors of different types are not allowed.
6009   // (See OpenCL 6.2).
6010   if (SrcTy->isVectorType()) {
6011     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6012         || (getLangOpts().OpenCL &&
6013             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6014       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6015         << DestTy << SrcTy << R;
6016       return ExprError();
6017     }
6018     Kind = CK_BitCast;
6019     return CastExpr;
6020   }
6021 
6022   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6023   // conversion will take place first from scalar to elt type, and then
6024   // splat from elt type to vector.
6025   if (SrcTy->isPointerType())
6026     return Diag(R.getBegin(),
6027                 diag::err_invalid_conversion_between_vector_and_scalar)
6028       << DestTy << SrcTy << R;
6029 
6030   Kind = CK_VectorSplat;
6031   return prepareVectorSplat(DestTy, CastExpr);
6032 }
6033 
6034 ExprResult
6035 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6036                     Declarator &D, ParsedType &Ty,
6037                     SourceLocation RParenLoc, Expr *CastExpr) {
6038   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6039          "ActOnCastExpr(): missing type or expr");
6040 
6041   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6042   if (D.isInvalidType())
6043     return ExprError();
6044 
6045   if (getLangOpts().CPlusPlus) {
6046     // Check that there are no default arguments (C++ only).
6047     CheckExtraCXXDefaultArguments(D);
6048   } else {
6049     // Make sure any TypoExprs have been dealt with.
6050     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6051     if (!Res.isUsable())
6052       return ExprError();
6053     CastExpr = Res.get();
6054   }
6055 
6056   checkUnusedDeclAttributes(D);
6057 
6058   QualType castType = castTInfo->getType();
6059   Ty = CreateParsedType(castType, castTInfo);
6060 
6061   bool isVectorLiteral = false;
6062 
6063   // Check for an altivec or OpenCL literal,
6064   // i.e. all the elements are integer constants.
6065   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6066   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6067   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6068        && castType->isVectorType() && (PE || PLE)) {
6069     if (PLE && PLE->getNumExprs() == 0) {
6070       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6071       return ExprError();
6072     }
6073     if (PE || PLE->getNumExprs() == 1) {
6074       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6075       if (!E->getType()->isVectorType())
6076         isVectorLiteral = true;
6077     }
6078     else
6079       isVectorLiteral = true;
6080   }
6081 
6082   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6083   // then handle it as such.
6084   if (isVectorLiteral)
6085     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6086 
6087   // If the Expr being casted is a ParenListExpr, handle it specially.
6088   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6089   // sequence of BinOp comma operators.
6090   if (isa<ParenListExpr>(CastExpr)) {
6091     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6092     if (Result.isInvalid()) return ExprError();
6093     CastExpr = Result.get();
6094   }
6095 
6096   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6097       !getSourceManager().isInSystemMacro(LParenLoc))
6098     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6099 
6100   CheckTollFreeBridgeCast(castType, CastExpr);
6101 
6102   CheckObjCBridgeRelatedCast(castType, CastExpr);
6103 
6104   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6105 
6106   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6107 }
6108 
6109 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6110                                     SourceLocation RParenLoc, Expr *E,
6111                                     TypeSourceInfo *TInfo) {
6112   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6113          "Expected paren or paren list expression");
6114 
6115   Expr **exprs;
6116   unsigned numExprs;
6117   Expr *subExpr;
6118   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6119   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6120     LiteralLParenLoc = PE->getLParenLoc();
6121     LiteralRParenLoc = PE->getRParenLoc();
6122     exprs = PE->getExprs();
6123     numExprs = PE->getNumExprs();
6124   } else { // isa<ParenExpr> by assertion at function entrance
6125     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6126     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6127     subExpr = cast<ParenExpr>(E)->getSubExpr();
6128     exprs = &subExpr;
6129     numExprs = 1;
6130   }
6131 
6132   QualType Ty = TInfo->getType();
6133   assert(Ty->isVectorType() && "Expected vector type");
6134 
6135   SmallVector<Expr *, 8> initExprs;
6136   const VectorType *VTy = Ty->getAs<VectorType>();
6137   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6138 
6139   // '(...)' form of vector initialization in AltiVec: the number of
6140   // initializers must be one or must match the size of the vector.
6141   // If a single value is specified in the initializer then it will be
6142   // replicated to all the components of the vector
6143   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6144     // The number of initializers must be one or must match the size of the
6145     // vector. If a single value is specified in the initializer then it will
6146     // be replicated to all the components of the vector
6147     if (numExprs == 1) {
6148       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6149       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6150       if (Literal.isInvalid())
6151         return ExprError();
6152       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6153                                   PrepareScalarCast(Literal, ElemTy));
6154       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6155     }
6156     else if (numExprs < numElems) {
6157       Diag(E->getExprLoc(),
6158            diag::err_incorrect_number_of_vector_initializers);
6159       return ExprError();
6160     }
6161     else
6162       initExprs.append(exprs, exprs + numExprs);
6163   }
6164   else {
6165     // For OpenCL, when the number of initializers is a single value,
6166     // it will be replicated to all components of the vector.
6167     if (getLangOpts().OpenCL &&
6168         VTy->getVectorKind() == VectorType::GenericVector &&
6169         numExprs == 1) {
6170         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6171         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6172         if (Literal.isInvalid())
6173           return ExprError();
6174         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6175                                     PrepareScalarCast(Literal, ElemTy));
6176         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6177     }
6178 
6179     initExprs.append(exprs, exprs + numExprs);
6180   }
6181   // FIXME: This means that pretty-printing the final AST will produce curly
6182   // braces instead of the original commas.
6183   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6184                                                    initExprs, LiteralRParenLoc);
6185   initE->setType(Ty);
6186   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6187 }
6188 
6189 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6190 /// the ParenListExpr into a sequence of comma binary operators.
6191 ExprResult
6192 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6193   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6194   if (!E)
6195     return OrigExpr;
6196 
6197   ExprResult Result(E->getExpr(0));
6198 
6199   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6200     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6201                         E->getExpr(i));
6202 
6203   if (Result.isInvalid()) return ExprError();
6204 
6205   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6206 }
6207 
6208 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6209                                     SourceLocation R,
6210                                     MultiExprArg Val) {
6211   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6212   return expr;
6213 }
6214 
6215 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6216 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6217 /// emitted.
6218 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6219                                       SourceLocation QuestionLoc) {
6220   Expr *NullExpr = LHSExpr;
6221   Expr *NonPointerExpr = RHSExpr;
6222   Expr::NullPointerConstantKind NullKind =
6223       NullExpr->isNullPointerConstant(Context,
6224                                       Expr::NPC_ValueDependentIsNotNull);
6225 
6226   if (NullKind == Expr::NPCK_NotNull) {
6227     NullExpr = RHSExpr;
6228     NonPointerExpr = LHSExpr;
6229     NullKind =
6230         NullExpr->isNullPointerConstant(Context,
6231                                         Expr::NPC_ValueDependentIsNotNull);
6232   }
6233 
6234   if (NullKind == Expr::NPCK_NotNull)
6235     return false;
6236 
6237   if (NullKind == Expr::NPCK_ZeroExpression)
6238     return false;
6239 
6240   if (NullKind == Expr::NPCK_ZeroLiteral) {
6241     // In this case, check to make sure that we got here from a "NULL"
6242     // string in the source code.
6243     NullExpr = NullExpr->IgnoreParenImpCasts();
6244     SourceLocation loc = NullExpr->getExprLoc();
6245     if (!findMacroSpelling(loc, "NULL"))
6246       return false;
6247   }
6248 
6249   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6250   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6251       << NonPointerExpr->getType() << DiagType
6252       << NonPointerExpr->getSourceRange();
6253   return true;
6254 }
6255 
6256 /// \brief Return false if the condition expression is valid, true otherwise.
6257 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6258   QualType CondTy = Cond->getType();
6259 
6260   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6261   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6262     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6263       << CondTy << Cond->getSourceRange();
6264     return true;
6265   }
6266 
6267   // C99 6.5.15p2
6268   if (CondTy->isScalarType()) return false;
6269 
6270   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6271     << CondTy << Cond->getSourceRange();
6272   return true;
6273 }
6274 
6275 /// \brief Handle when one or both operands are void type.
6276 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6277                                          ExprResult &RHS) {
6278     Expr *LHSExpr = LHS.get();
6279     Expr *RHSExpr = RHS.get();
6280 
6281     if (!LHSExpr->getType()->isVoidType())
6282       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6283         << RHSExpr->getSourceRange();
6284     if (!RHSExpr->getType()->isVoidType())
6285       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6286         << LHSExpr->getSourceRange();
6287     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6288     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6289     return S.Context.VoidTy;
6290 }
6291 
6292 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6293 /// true otherwise.
6294 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6295                                         QualType PointerTy) {
6296   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6297       !NullExpr.get()->isNullPointerConstant(S.Context,
6298                                             Expr::NPC_ValueDependentIsNull))
6299     return true;
6300 
6301   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6302   return false;
6303 }
6304 
6305 /// \brief Checks compatibility between two pointers and return the resulting
6306 /// type.
6307 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6308                                                      ExprResult &RHS,
6309                                                      SourceLocation Loc) {
6310   QualType LHSTy = LHS.get()->getType();
6311   QualType RHSTy = RHS.get()->getType();
6312 
6313   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6314     // Two identical pointers types are always compatible.
6315     return LHSTy;
6316   }
6317 
6318   QualType lhptee, rhptee;
6319 
6320   // Get the pointee types.
6321   bool IsBlockPointer = false;
6322   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6323     lhptee = LHSBTy->getPointeeType();
6324     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6325     IsBlockPointer = true;
6326   } else {
6327     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6328     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6329   }
6330 
6331   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6332   // differently qualified versions of compatible types, the result type is
6333   // a pointer to an appropriately qualified version of the composite
6334   // type.
6335 
6336   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6337   // clause doesn't make sense for our extensions. E.g. address space 2 should
6338   // be incompatible with address space 3: they may live on different devices or
6339   // anything.
6340   Qualifiers lhQual = lhptee.getQualifiers();
6341   Qualifiers rhQual = rhptee.getQualifiers();
6342 
6343   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6344   lhQual.removeCVRQualifiers();
6345   rhQual.removeCVRQualifiers();
6346 
6347   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6348   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6349 
6350   // For OpenCL:
6351   // 1. If LHS and RHS types match exactly and:
6352   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6353   //  (b) AS overlap => generate addrspacecast
6354   //  (c) AS don't overlap => give an error
6355   // 2. if LHS and RHS types don't match:
6356   //  (a) AS match => use standard C rules, generate bitcast
6357   //  (b) AS overlap => generate addrspacecast instead of bitcast
6358   //  (c) AS don't overlap => give an error
6359 
6360   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6361   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6362 
6363   // OpenCL cases 1c, 2a, 2b, and 2c.
6364   if (CompositeTy.isNull()) {
6365     // In this situation, we assume void* type. No especially good
6366     // reason, but this is what gcc does, and we do have to pick
6367     // to get a consistent AST.
6368     QualType incompatTy;
6369     if (S.getLangOpts().OpenCL) {
6370       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6371       // spaces is disallowed.
6372       unsigned ResultAddrSpace;
6373       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6374         // Cases 2a and 2b.
6375         ResultAddrSpace = lhQual.getAddressSpace();
6376       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6377         // Cases 2a and 2b.
6378         ResultAddrSpace = rhQual.getAddressSpace();
6379       } else {
6380         // Cases 1c and 2c.
6381         S.Diag(Loc,
6382                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6383             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6384             << RHS.get()->getSourceRange();
6385         return QualType();
6386       }
6387 
6388       // Continue handling cases 2a and 2b.
6389       incompatTy = S.Context.getPointerType(
6390           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6391       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6392                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6393                                     ? CK_AddressSpaceConversion /* 2b */
6394                                     : CK_BitCast /* 2a */);
6395       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6396                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6397                                     ? CK_AddressSpaceConversion /* 2b */
6398                                     : CK_BitCast /* 2a */);
6399     } else {
6400       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6401           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6402           << RHS.get()->getSourceRange();
6403       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6404       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6405       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6406     }
6407     return incompatTy;
6408   }
6409 
6410   // The pointer types are compatible.
6411   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6412   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6413   if (IsBlockPointer)
6414     ResultTy = S.Context.getBlockPointerType(ResultTy);
6415   else {
6416     // Cases 1a and 1b for OpenCL.
6417     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6418     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6419                       ? CK_BitCast /* 1a */
6420                       : CK_AddressSpaceConversion /* 1b */;
6421     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6422                       ? CK_BitCast /* 1a */
6423                       : CK_AddressSpaceConversion /* 1b */;
6424     ResultTy = S.Context.getPointerType(ResultTy);
6425   }
6426 
6427   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6428   // if the target type does not change.
6429   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6430   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6431   return ResultTy;
6432 }
6433 
6434 /// \brief Return the resulting type when the operands are both block pointers.
6435 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6436                                                           ExprResult &LHS,
6437                                                           ExprResult &RHS,
6438                                                           SourceLocation Loc) {
6439   QualType LHSTy = LHS.get()->getType();
6440   QualType RHSTy = RHS.get()->getType();
6441 
6442   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6443     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6444       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6445       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6446       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6447       return destType;
6448     }
6449     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6450       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6451       << RHS.get()->getSourceRange();
6452     return QualType();
6453   }
6454 
6455   // We have 2 block pointer types.
6456   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6457 }
6458 
6459 /// \brief Return the resulting type when the operands are both pointers.
6460 static QualType
6461 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6462                                             ExprResult &RHS,
6463                                             SourceLocation Loc) {
6464   // get the pointer types
6465   QualType LHSTy = LHS.get()->getType();
6466   QualType RHSTy = RHS.get()->getType();
6467 
6468   // get the "pointed to" types
6469   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6470   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6471 
6472   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6473   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6474     // Figure out necessary qualifiers (C99 6.5.15p6)
6475     QualType destPointee
6476       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6477     QualType destType = S.Context.getPointerType(destPointee);
6478     // Add qualifiers if necessary.
6479     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6480     // Promote to void*.
6481     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6482     return destType;
6483   }
6484   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6485     QualType destPointee
6486       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6487     QualType destType = S.Context.getPointerType(destPointee);
6488     // Add qualifiers if necessary.
6489     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6490     // Promote to void*.
6491     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6492     return destType;
6493   }
6494 
6495   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6496 }
6497 
6498 /// \brief Return false if the first expression is not an integer and the second
6499 /// expression is not a pointer, true otherwise.
6500 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6501                                         Expr* PointerExpr, SourceLocation Loc,
6502                                         bool IsIntFirstExpr) {
6503   if (!PointerExpr->getType()->isPointerType() ||
6504       !Int.get()->getType()->isIntegerType())
6505     return false;
6506 
6507   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6508   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6509 
6510   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6511     << Expr1->getType() << Expr2->getType()
6512     << Expr1->getSourceRange() << Expr2->getSourceRange();
6513   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6514                             CK_IntegralToPointer);
6515   return true;
6516 }
6517 
6518 /// \brief Simple conversion between integer and floating point types.
6519 ///
6520 /// Used when handling the OpenCL conditional operator where the
6521 /// condition is a vector while the other operands are scalar.
6522 ///
6523 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6524 /// types are either integer or floating type. Between the two
6525 /// operands, the type with the higher rank is defined as the "result
6526 /// type". The other operand needs to be promoted to the same type. No
6527 /// other type promotion is allowed. We cannot use
6528 /// UsualArithmeticConversions() for this purpose, since it always
6529 /// promotes promotable types.
6530 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6531                                             ExprResult &RHS,
6532                                             SourceLocation QuestionLoc) {
6533   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6534   if (LHS.isInvalid())
6535     return QualType();
6536   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6537   if (RHS.isInvalid())
6538     return QualType();
6539 
6540   // For conversion purposes, we ignore any qualifiers.
6541   // For example, "const float" and "float" are equivalent.
6542   QualType LHSType =
6543     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6544   QualType RHSType =
6545     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6546 
6547   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6548     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6549       << LHSType << LHS.get()->getSourceRange();
6550     return QualType();
6551   }
6552 
6553   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6554     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6555       << RHSType << RHS.get()->getSourceRange();
6556     return QualType();
6557   }
6558 
6559   // If both types are identical, no conversion is needed.
6560   if (LHSType == RHSType)
6561     return LHSType;
6562 
6563   // Now handle "real" floating types (i.e. float, double, long double).
6564   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6565     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6566                                  /*IsCompAssign = */ false);
6567 
6568   // Finally, we have two differing integer types.
6569   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6570   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6571 }
6572 
6573 /// \brief Convert scalar operands to a vector that matches the
6574 ///        condition in length.
6575 ///
6576 /// Used when handling the OpenCL conditional operator where the
6577 /// condition is a vector while the other operands are scalar.
6578 ///
6579 /// We first compute the "result type" for the scalar operands
6580 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6581 /// into a vector of that type where the length matches the condition
6582 /// vector type. s6.11.6 requires that the element types of the result
6583 /// and the condition must have the same number of bits.
6584 static QualType
6585 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6586                               QualType CondTy, SourceLocation QuestionLoc) {
6587   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6588   if (ResTy.isNull()) return QualType();
6589 
6590   const VectorType *CV = CondTy->getAs<VectorType>();
6591   assert(CV);
6592 
6593   // Determine the vector result type
6594   unsigned NumElements = CV->getNumElements();
6595   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6596 
6597   // Ensure that all types have the same number of bits
6598   if (S.Context.getTypeSize(CV->getElementType())
6599       != S.Context.getTypeSize(ResTy)) {
6600     // Since VectorTy is created internally, it does not pretty print
6601     // with an OpenCL name. Instead, we just print a description.
6602     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6603     SmallString<64> Str;
6604     llvm::raw_svector_ostream OS(Str);
6605     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6606     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6607       << CondTy << OS.str();
6608     return QualType();
6609   }
6610 
6611   // Convert operands to the vector result type
6612   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6613   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6614 
6615   return VectorTy;
6616 }
6617 
6618 /// \brief Return false if this is a valid OpenCL condition vector
6619 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6620                                        SourceLocation QuestionLoc) {
6621   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6622   // integral type.
6623   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6624   assert(CondTy);
6625   QualType EleTy = CondTy->getElementType();
6626   if (EleTy->isIntegerType()) return false;
6627 
6628   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6629     << Cond->getType() << Cond->getSourceRange();
6630   return true;
6631 }
6632 
6633 /// \brief Return false if the vector condition type and the vector
6634 ///        result type are compatible.
6635 ///
6636 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6637 /// number of elements, and their element types have the same number
6638 /// of bits.
6639 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6640                               SourceLocation QuestionLoc) {
6641   const VectorType *CV = CondTy->getAs<VectorType>();
6642   const VectorType *RV = VecResTy->getAs<VectorType>();
6643   assert(CV && RV);
6644 
6645   if (CV->getNumElements() != RV->getNumElements()) {
6646     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6647       << CondTy << VecResTy;
6648     return true;
6649   }
6650 
6651   QualType CVE = CV->getElementType();
6652   QualType RVE = RV->getElementType();
6653 
6654   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6655     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6656       << CondTy << VecResTy;
6657     return true;
6658   }
6659 
6660   return false;
6661 }
6662 
6663 /// \brief Return the resulting type for the conditional operator in
6664 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6665 ///        s6.3.i) when the condition is a vector type.
6666 static QualType
6667 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6668                              ExprResult &LHS, ExprResult &RHS,
6669                              SourceLocation QuestionLoc) {
6670   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6671   if (Cond.isInvalid())
6672     return QualType();
6673   QualType CondTy = Cond.get()->getType();
6674 
6675   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6676     return QualType();
6677 
6678   // If either operand is a vector then find the vector type of the
6679   // result as specified in OpenCL v1.1 s6.3.i.
6680   if (LHS.get()->getType()->isVectorType() ||
6681       RHS.get()->getType()->isVectorType()) {
6682     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6683                                               /*isCompAssign*/false,
6684                                               /*AllowBothBool*/true,
6685                                               /*AllowBoolConversions*/false);
6686     if (VecResTy.isNull()) return QualType();
6687     // The result type must match the condition type as specified in
6688     // OpenCL v1.1 s6.11.6.
6689     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6690       return QualType();
6691     return VecResTy;
6692   }
6693 
6694   // Both operands are scalar.
6695   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6696 }
6697 
6698 /// \brief Return true if the Expr is block type
6699 static bool checkBlockType(Sema &S, const Expr *E) {
6700   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6701     QualType Ty = CE->getCallee()->getType();
6702     if (Ty->isBlockPointerType()) {
6703       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6704       return true;
6705     }
6706   }
6707   return false;
6708 }
6709 
6710 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6711 /// In that case, LHS = cond.
6712 /// C99 6.5.15
6713 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6714                                         ExprResult &RHS, ExprValueKind &VK,
6715                                         ExprObjectKind &OK,
6716                                         SourceLocation QuestionLoc) {
6717 
6718   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6719   if (!LHSResult.isUsable()) return QualType();
6720   LHS = LHSResult;
6721 
6722   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6723   if (!RHSResult.isUsable()) return QualType();
6724   RHS = RHSResult;
6725 
6726   // C++ is sufficiently different to merit its own checker.
6727   if (getLangOpts().CPlusPlus)
6728     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6729 
6730   VK = VK_RValue;
6731   OK = OK_Ordinary;
6732 
6733   // The OpenCL operator with a vector condition is sufficiently
6734   // different to merit its own checker.
6735   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6736     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6737 
6738   // First, check the condition.
6739   Cond = UsualUnaryConversions(Cond.get());
6740   if (Cond.isInvalid())
6741     return QualType();
6742   if (checkCondition(*this, Cond.get(), QuestionLoc))
6743     return QualType();
6744 
6745   // Now check the two expressions.
6746   if (LHS.get()->getType()->isVectorType() ||
6747       RHS.get()->getType()->isVectorType())
6748     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6749                                /*AllowBothBool*/true,
6750                                /*AllowBoolConversions*/false);
6751 
6752   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6753   if (LHS.isInvalid() || RHS.isInvalid())
6754     return QualType();
6755 
6756   QualType LHSTy = LHS.get()->getType();
6757   QualType RHSTy = RHS.get()->getType();
6758 
6759   // Diagnose attempts to convert between __float128 and long double where
6760   // such conversions currently can't be handled.
6761   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6762     Diag(QuestionLoc,
6763          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6764       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6765     return QualType();
6766   }
6767 
6768   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6769   // selection operator (?:).
6770   if (getLangOpts().OpenCL &&
6771       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6772     return QualType();
6773   }
6774 
6775   // If both operands have arithmetic type, do the usual arithmetic conversions
6776   // to find a common type: C99 6.5.15p3,5.
6777   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6778     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6779     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6780 
6781     return ResTy;
6782   }
6783 
6784   // If both operands are the same structure or union type, the result is that
6785   // type.
6786   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6787     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6788       if (LHSRT->getDecl() == RHSRT->getDecl())
6789         // "If both the operands have structure or union type, the result has
6790         // that type."  This implies that CV qualifiers are dropped.
6791         return LHSTy.getUnqualifiedType();
6792     // FIXME: Type of conditional expression must be complete in C mode.
6793   }
6794 
6795   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6796   // The following || allows only one side to be void (a GCC-ism).
6797   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6798     return checkConditionalVoidType(*this, LHS, RHS);
6799   }
6800 
6801   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6802   // the type of the other operand."
6803   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6804   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6805 
6806   // All objective-c pointer type analysis is done here.
6807   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6808                                                         QuestionLoc);
6809   if (LHS.isInvalid() || RHS.isInvalid())
6810     return QualType();
6811   if (!compositeType.isNull())
6812     return compositeType;
6813 
6814 
6815   // Handle block pointer types.
6816   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6817     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6818                                                      QuestionLoc);
6819 
6820   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6821   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6822     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6823                                                        QuestionLoc);
6824 
6825   // GCC compatibility: soften pointer/integer mismatch.  Note that
6826   // null pointers have been filtered out by this point.
6827   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6828       /*isIntFirstExpr=*/true))
6829     return RHSTy;
6830   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6831       /*isIntFirstExpr=*/false))
6832     return LHSTy;
6833 
6834   // Emit a better diagnostic if one of the expressions is a null pointer
6835   // constant and the other is not a pointer type. In this case, the user most
6836   // likely forgot to take the address of the other expression.
6837   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6838     return QualType();
6839 
6840   // Otherwise, the operands are not compatible.
6841   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6842     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6843     << RHS.get()->getSourceRange();
6844   return QualType();
6845 }
6846 
6847 /// FindCompositeObjCPointerType - Helper method to find composite type of
6848 /// two objective-c pointer types of the two input expressions.
6849 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6850                                             SourceLocation QuestionLoc) {
6851   QualType LHSTy = LHS.get()->getType();
6852   QualType RHSTy = RHS.get()->getType();
6853 
6854   // Handle things like Class and struct objc_class*.  Here we case the result
6855   // to the pseudo-builtin, because that will be implicitly cast back to the
6856   // redefinition type if an attempt is made to access its fields.
6857   if (LHSTy->isObjCClassType() &&
6858       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6859     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6860     return LHSTy;
6861   }
6862   if (RHSTy->isObjCClassType() &&
6863       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6864     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6865     return RHSTy;
6866   }
6867   // And the same for struct objc_object* / id
6868   if (LHSTy->isObjCIdType() &&
6869       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6870     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6871     return LHSTy;
6872   }
6873   if (RHSTy->isObjCIdType() &&
6874       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6875     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6876     return RHSTy;
6877   }
6878   // And the same for struct objc_selector* / SEL
6879   if (Context.isObjCSelType(LHSTy) &&
6880       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6881     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6882     return LHSTy;
6883   }
6884   if (Context.isObjCSelType(RHSTy) &&
6885       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6886     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6887     return RHSTy;
6888   }
6889   // Check constraints for Objective-C object pointers types.
6890   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6891 
6892     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6893       // Two identical object pointer types are always compatible.
6894       return LHSTy;
6895     }
6896     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6897     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6898     QualType compositeType = LHSTy;
6899 
6900     // If both operands are interfaces and either operand can be
6901     // assigned to the other, use that type as the composite
6902     // type. This allows
6903     //   xxx ? (A*) a : (B*) b
6904     // where B is a subclass of A.
6905     //
6906     // Additionally, as for assignment, if either type is 'id'
6907     // allow silent coercion. Finally, if the types are
6908     // incompatible then make sure to use 'id' as the composite
6909     // type so the result is acceptable for sending messages to.
6910 
6911     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6912     // It could return the composite type.
6913     if (!(compositeType =
6914           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6915       // Nothing more to do.
6916     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6917       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6918     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6919       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6920     } else if ((LHSTy->isObjCQualifiedIdType() ||
6921                 RHSTy->isObjCQualifiedIdType()) &&
6922                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6923       // Need to handle "id<xx>" explicitly.
6924       // GCC allows qualified id and any Objective-C type to devolve to
6925       // id. Currently localizing to here until clear this should be
6926       // part of ObjCQualifiedIdTypesAreCompatible.
6927       compositeType = Context.getObjCIdType();
6928     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6929       compositeType = Context.getObjCIdType();
6930     } else {
6931       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6932       << LHSTy << RHSTy
6933       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6934       QualType incompatTy = Context.getObjCIdType();
6935       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6936       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6937       return incompatTy;
6938     }
6939     // The object pointer types are compatible.
6940     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6941     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6942     return compositeType;
6943   }
6944   // Check Objective-C object pointer types and 'void *'
6945   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6946     if (getLangOpts().ObjCAutoRefCount) {
6947       // ARC forbids the implicit conversion of object pointers to 'void *',
6948       // so these types are not compatible.
6949       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6950           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6951       LHS = RHS = true;
6952       return QualType();
6953     }
6954     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6955     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6956     QualType destPointee
6957     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6958     QualType destType = Context.getPointerType(destPointee);
6959     // Add qualifiers if necessary.
6960     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6961     // Promote to void*.
6962     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6963     return destType;
6964   }
6965   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6966     if (getLangOpts().ObjCAutoRefCount) {
6967       // ARC forbids the implicit conversion of object pointers to 'void *',
6968       // so these types are not compatible.
6969       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6970           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6971       LHS = RHS = true;
6972       return QualType();
6973     }
6974     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6975     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6976     QualType destPointee
6977     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6978     QualType destType = Context.getPointerType(destPointee);
6979     // Add qualifiers if necessary.
6980     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6981     // Promote to void*.
6982     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6983     return destType;
6984   }
6985   return QualType();
6986 }
6987 
6988 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6989 /// ParenRange in parentheses.
6990 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6991                                const PartialDiagnostic &Note,
6992                                SourceRange ParenRange) {
6993   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6994   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6995       EndLoc.isValid()) {
6996     Self.Diag(Loc, Note)
6997       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6998       << FixItHint::CreateInsertion(EndLoc, ")");
6999   } else {
7000     // We can't display the parentheses, so just show the bare note.
7001     Self.Diag(Loc, Note) << ParenRange;
7002   }
7003 }
7004 
7005 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7006   return BinaryOperator::isAdditiveOp(Opc) ||
7007          BinaryOperator::isMultiplicativeOp(Opc) ||
7008          BinaryOperator::isShiftOp(Opc);
7009 }
7010 
7011 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7012 /// expression, either using a built-in or overloaded operator,
7013 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7014 /// expression.
7015 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7016                                    Expr **RHSExprs) {
7017   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7018   E = E->IgnoreImpCasts();
7019   E = E->IgnoreConversionOperator();
7020   E = E->IgnoreImpCasts();
7021 
7022   // Built-in binary operator.
7023   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7024     if (IsArithmeticOp(OP->getOpcode())) {
7025       *Opcode = OP->getOpcode();
7026       *RHSExprs = OP->getRHS();
7027       return true;
7028     }
7029   }
7030 
7031   // Overloaded operator.
7032   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7033     if (Call->getNumArgs() != 2)
7034       return false;
7035 
7036     // Make sure this is really a binary operator that is safe to pass into
7037     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7038     OverloadedOperatorKind OO = Call->getOperator();
7039     if (OO < OO_Plus || OO > OO_Arrow ||
7040         OO == OO_PlusPlus || OO == OO_MinusMinus)
7041       return false;
7042 
7043     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7044     if (IsArithmeticOp(OpKind)) {
7045       *Opcode = OpKind;
7046       *RHSExprs = Call->getArg(1);
7047       return true;
7048     }
7049   }
7050 
7051   return false;
7052 }
7053 
7054 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7055 /// or is a logical expression such as (x==y) which has int type, but is
7056 /// commonly interpreted as boolean.
7057 static bool ExprLooksBoolean(Expr *E) {
7058   E = E->IgnoreParenImpCasts();
7059 
7060   if (E->getType()->isBooleanType())
7061     return true;
7062   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7063     return OP->isComparisonOp() || OP->isLogicalOp();
7064   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7065     return OP->getOpcode() == UO_LNot;
7066   if (E->getType()->isPointerType())
7067     return true;
7068 
7069   return false;
7070 }
7071 
7072 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7073 /// and binary operator are mixed in a way that suggests the programmer assumed
7074 /// the conditional operator has higher precedence, for example:
7075 /// "int x = a + someBinaryCondition ? 1 : 2".
7076 static void DiagnoseConditionalPrecedence(Sema &Self,
7077                                           SourceLocation OpLoc,
7078                                           Expr *Condition,
7079                                           Expr *LHSExpr,
7080                                           Expr *RHSExpr) {
7081   BinaryOperatorKind CondOpcode;
7082   Expr *CondRHS;
7083 
7084   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7085     return;
7086   if (!ExprLooksBoolean(CondRHS))
7087     return;
7088 
7089   // The condition is an arithmetic binary expression, with a right-
7090   // hand side that looks boolean, so warn.
7091 
7092   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7093       << Condition->getSourceRange()
7094       << BinaryOperator::getOpcodeStr(CondOpcode);
7095 
7096   SuggestParentheses(Self, OpLoc,
7097     Self.PDiag(diag::note_precedence_silence)
7098       << BinaryOperator::getOpcodeStr(CondOpcode),
7099     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7100 
7101   SuggestParentheses(Self, OpLoc,
7102     Self.PDiag(diag::note_precedence_conditional_first),
7103     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7104 }
7105 
7106 /// Compute the nullability of a conditional expression.
7107 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7108                                               QualType LHSTy, QualType RHSTy,
7109                                               ASTContext &Ctx) {
7110   if (!ResTy->isAnyPointerType())
7111     return ResTy;
7112 
7113   auto GetNullability = [&Ctx](QualType Ty) {
7114     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7115     if (Kind)
7116       return *Kind;
7117     return NullabilityKind::Unspecified;
7118   };
7119 
7120   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7121   NullabilityKind MergedKind;
7122 
7123   // Compute nullability of a binary conditional expression.
7124   if (IsBin) {
7125     if (LHSKind == NullabilityKind::NonNull)
7126       MergedKind = NullabilityKind::NonNull;
7127     else
7128       MergedKind = RHSKind;
7129   // Compute nullability of a normal conditional expression.
7130   } else {
7131     if (LHSKind == NullabilityKind::Nullable ||
7132         RHSKind == NullabilityKind::Nullable)
7133       MergedKind = NullabilityKind::Nullable;
7134     else if (LHSKind == NullabilityKind::NonNull)
7135       MergedKind = RHSKind;
7136     else if (RHSKind == NullabilityKind::NonNull)
7137       MergedKind = LHSKind;
7138     else
7139       MergedKind = NullabilityKind::Unspecified;
7140   }
7141 
7142   // Return if ResTy already has the correct nullability.
7143   if (GetNullability(ResTy) == MergedKind)
7144     return ResTy;
7145 
7146   // Strip all nullability from ResTy.
7147   while (ResTy->getNullability(Ctx))
7148     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7149 
7150   // Create a new AttributedType with the new nullability kind.
7151   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7152   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7153 }
7154 
7155 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7156 /// in the case of a the GNU conditional expr extension.
7157 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7158                                     SourceLocation ColonLoc,
7159                                     Expr *CondExpr, Expr *LHSExpr,
7160                                     Expr *RHSExpr) {
7161   if (!getLangOpts().CPlusPlus) {
7162     // C cannot handle TypoExpr nodes in the condition because it
7163     // doesn't handle dependent types properly, so make sure any TypoExprs have
7164     // been dealt with before checking the operands.
7165     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7166     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7167     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7168 
7169     if (!CondResult.isUsable())
7170       return ExprError();
7171 
7172     if (LHSExpr) {
7173       if (!LHSResult.isUsable())
7174         return ExprError();
7175     }
7176 
7177     if (!RHSResult.isUsable())
7178       return ExprError();
7179 
7180     CondExpr = CondResult.get();
7181     LHSExpr = LHSResult.get();
7182     RHSExpr = RHSResult.get();
7183   }
7184 
7185   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7186   // was the condition.
7187   OpaqueValueExpr *opaqueValue = nullptr;
7188   Expr *commonExpr = nullptr;
7189   if (!LHSExpr) {
7190     commonExpr = CondExpr;
7191     // Lower out placeholder types first.  This is important so that we don't
7192     // try to capture a placeholder. This happens in few cases in C++; such
7193     // as Objective-C++'s dictionary subscripting syntax.
7194     if (commonExpr->hasPlaceholderType()) {
7195       ExprResult result = CheckPlaceholderExpr(commonExpr);
7196       if (!result.isUsable()) return ExprError();
7197       commonExpr = result.get();
7198     }
7199     // We usually want to apply unary conversions *before* saving, except
7200     // in the special case of a C++ l-value conditional.
7201     if (!(getLangOpts().CPlusPlus
7202           && !commonExpr->isTypeDependent()
7203           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7204           && commonExpr->isGLValue()
7205           && commonExpr->isOrdinaryOrBitFieldObject()
7206           && RHSExpr->isOrdinaryOrBitFieldObject()
7207           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7208       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7209       if (commonRes.isInvalid())
7210         return ExprError();
7211       commonExpr = commonRes.get();
7212     }
7213 
7214     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7215                                                 commonExpr->getType(),
7216                                                 commonExpr->getValueKind(),
7217                                                 commonExpr->getObjectKind(),
7218                                                 commonExpr);
7219     LHSExpr = CondExpr = opaqueValue;
7220   }
7221 
7222   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7223   ExprValueKind VK = VK_RValue;
7224   ExprObjectKind OK = OK_Ordinary;
7225   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7226   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7227                                              VK, OK, QuestionLoc);
7228   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7229       RHS.isInvalid())
7230     return ExprError();
7231 
7232   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7233                                 RHS.get());
7234 
7235   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7236 
7237   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7238                                          Context);
7239 
7240   if (!commonExpr)
7241     return new (Context)
7242         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7243                             RHS.get(), result, VK, OK);
7244 
7245   return new (Context) BinaryConditionalOperator(
7246       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7247       ColonLoc, result, VK, OK);
7248 }
7249 
7250 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7251 // being closely modeled after the C99 spec:-). The odd characteristic of this
7252 // routine is it effectively iqnores the qualifiers on the top level pointee.
7253 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7254 // FIXME: add a couple examples in this comment.
7255 static Sema::AssignConvertType
7256 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7257   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7258   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7259 
7260   // get the "pointed to" type (ignoring qualifiers at the top level)
7261   const Type *lhptee, *rhptee;
7262   Qualifiers lhq, rhq;
7263   std::tie(lhptee, lhq) =
7264       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7265   std::tie(rhptee, rhq) =
7266       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7267 
7268   Sema::AssignConvertType ConvTy = Sema::Compatible;
7269 
7270   // C99 6.5.16.1p1: This following citation is common to constraints
7271   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7272   // qualifiers of the type *pointed to* by the right;
7273 
7274   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7275   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7276       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7277     // Ignore lifetime for further calculation.
7278     lhq.removeObjCLifetime();
7279     rhq.removeObjCLifetime();
7280   }
7281 
7282   if (!lhq.compatiblyIncludes(rhq)) {
7283     // Treat address-space mismatches as fatal.  TODO: address subspaces
7284     if (!lhq.isAddressSpaceSupersetOf(rhq))
7285       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7286 
7287     // It's okay to add or remove GC or lifetime qualifiers when converting to
7288     // and from void*.
7289     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7290                         .compatiblyIncludes(
7291                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7292              && (lhptee->isVoidType() || rhptee->isVoidType()))
7293       ; // keep old
7294 
7295     // Treat lifetime mismatches as fatal.
7296     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7297       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7298 
7299     // For GCC/MS compatibility, other qualifier mismatches are treated
7300     // as still compatible in C.
7301     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7302   }
7303 
7304   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7305   // incomplete type and the other is a pointer to a qualified or unqualified
7306   // version of void...
7307   if (lhptee->isVoidType()) {
7308     if (rhptee->isIncompleteOrObjectType())
7309       return ConvTy;
7310 
7311     // As an extension, we allow cast to/from void* to function pointer.
7312     assert(rhptee->isFunctionType());
7313     return Sema::FunctionVoidPointer;
7314   }
7315 
7316   if (rhptee->isVoidType()) {
7317     if (lhptee->isIncompleteOrObjectType())
7318       return ConvTy;
7319 
7320     // As an extension, we allow cast to/from void* to function pointer.
7321     assert(lhptee->isFunctionType());
7322     return Sema::FunctionVoidPointer;
7323   }
7324 
7325   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7326   // unqualified versions of compatible types, ...
7327   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7328   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7329     // Check if the pointee types are compatible ignoring the sign.
7330     // We explicitly check for char so that we catch "char" vs
7331     // "unsigned char" on systems where "char" is unsigned.
7332     if (lhptee->isCharType())
7333       ltrans = S.Context.UnsignedCharTy;
7334     else if (lhptee->hasSignedIntegerRepresentation())
7335       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7336 
7337     if (rhptee->isCharType())
7338       rtrans = S.Context.UnsignedCharTy;
7339     else if (rhptee->hasSignedIntegerRepresentation())
7340       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7341 
7342     if (ltrans == rtrans) {
7343       // Types are compatible ignoring the sign. Qualifier incompatibility
7344       // takes priority over sign incompatibility because the sign
7345       // warning can be disabled.
7346       if (ConvTy != Sema::Compatible)
7347         return ConvTy;
7348 
7349       return Sema::IncompatiblePointerSign;
7350     }
7351 
7352     // If we are a multi-level pointer, it's possible that our issue is simply
7353     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7354     // the eventual target type is the same and the pointers have the same
7355     // level of indirection, this must be the issue.
7356     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7357       do {
7358         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7359         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7360       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7361 
7362       if (lhptee == rhptee)
7363         return Sema::IncompatibleNestedPointerQualifiers;
7364     }
7365 
7366     // General pointer incompatibility takes priority over qualifiers.
7367     return Sema::IncompatiblePointer;
7368   }
7369   if (!S.getLangOpts().CPlusPlus &&
7370       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7371     return Sema::IncompatiblePointer;
7372   return ConvTy;
7373 }
7374 
7375 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7376 /// block pointer types are compatible or whether a block and normal pointer
7377 /// are compatible. It is more restrict than comparing two function pointer
7378 // types.
7379 static Sema::AssignConvertType
7380 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7381                                     QualType RHSType) {
7382   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7383   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7384 
7385   QualType lhptee, rhptee;
7386 
7387   // get the "pointed to" type (ignoring qualifiers at the top level)
7388   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7389   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7390 
7391   // In C++, the types have to match exactly.
7392   if (S.getLangOpts().CPlusPlus)
7393     return Sema::IncompatibleBlockPointer;
7394 
7395   Sema::AssignConvertType ConvTy = Sema::Compatible;
7396 
7397   // For blocks we enforce that qualifiers are identical.
7398   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7399     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7400 
7401   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7402     return Sema::IncompatibleBlockPointer;
7403 
7404   return ConvTy;
7405 }
7406 
7407 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7408 /// for assignment compatibility.
7409 static Sema::AssignConvertType
7410 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7411                                    QualType RHSType) {
7412   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7413   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7414 
7415   if (LHSType->isObjCBuiltinType()) {
7416     // Class is not compatible with ObjC object pointers.
7417     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7418         !RHSType->isObjCQualifiedClassType())
7419       return Sema::IncompatiblePointer;
7420     return Sema::Compatible;
7421   }
7422   if (RHSType->isObjCBuiltinType()) {
7423     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7424         !LHSType->isObjCQualifiedClassType())
7425       return Sema::IncompatiblePointer;
7426     return Sema::Compatible;
7427   }
7428   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7429   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7430 
7431   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7432       // make an exception for id<P>
7433       !LHSType->isObjCQualifiedIdType())
7434     return Sema::CompatiblePointerDiscardsQualifiers;
7435 
7436   if (S.Context.typesAreCompatible(LHSType, RHSType))
7437     return Sema::Compatible;
7438   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7439     return Sema::IncompatibleObjCQualifiedId;
7440   return Sema::IncompatiblePointer;
7441 }
7442 
7443 Sema::AssignConvertType
7444 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7445                                  QualType LHSType, QualType RHSType) {
7446   // Fake up an opaque expression.  We don't actually care about what
7447   // cast operations are required, so if CheckAssignmentConstraints
7448   // adds casts to this they'll be wasted, but fortunately that doesn't
7449   // usually happen on valid code.
7450   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7451   ExprResult RHSPtr = &RHSExpr;
7452   CastKind K = CK_Invalid;
7453 
7454   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7455 }
7456 
7457 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7458 /// has code to accommodate several GCC extensions when type checking
7459 /// pointers. Here are some objectionable examples that GCC considers warnings:
7460 ///
7461 ///  int a, *pint;
7462 ///  short *pshort;
7463 ///  struct foo *pfoo;
7464 ///
7465 ///  pint = pshort; // warning: assignment from incompatible pointer type
7466 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7467 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7468 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7469 ///
7470 /// As a result, the code for dealing with pointers is more complex than the
7471 /// C99 spec dictates.
7472 ///
7473 /// Sets 'Kind' for any result kind except Incompatible.
7474 Sema::AssignConvertType
7475 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7476                                  CastKind &Kind, bool ConvertRHS) {
7477   QualType RHSType = RHS.get()->getType();
7478   QualType OrigLHSType = LHSType;
7479 
7480   // Get canonical types.  We're not formatting these types, just comparing
7481   // them.
7482   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7483   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7484 
7485   // Common case: no conversion required.
7486   if (LHSType == RHSType) {
7487     Kind = CK_NoOp;
7488     return Compatible;
7489   }
7490 
7491   // If we have an atomic type, try a non-atomic assignment, then just add an
7492   // atomic qualification step.
7493   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7494     Sema::AssignConvertType result =
7495       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7496     if (result != Compatible)
7497       return result;
7498     if (Kind != CK_NoOp && ConvertRHS)
7499       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7500     Kind = CK_NonAtomicToAtomic;
7501     return Compatible;
7502   }
7503 
7504   // If the left-hand side is a reference type, then we are in a
7505   // (rare!) case where we've allowed the use of references in C,
7506   // e.g., as a parameter type in a built-in function. In this case,
7507   // just make sure that the type referenced is compatible with the
7508   // right-hand side type. The caller is responsible for adjusting
7509   // LHSType so that the resulting expression does not have reference
7510   // type.
7511   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7512     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7513       Kind = CK_LValueBitCast;
7514       return Compatible;
7515     }
7516     return Incompatible;
7517   }
7518 
7519   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7520   // to the same ExtVector type.
7521   if (LHSType->isExtVectorType()) {
7522     if (RHSType->isExtVectorType())
7523       return Incompatible;
7524     if (RHSType->isArithmeticType()) {
7525       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7526       if (ConvertRHS)
7527         RHS = prepareVectorSplat(LHSType, RHS.get());
7528       Kind = CK_VectorSplat;
7529       return Compatible;
7530     }
7531   }
7532 
7533   // Conversions to or from vector type.
7534   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7535     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7536       // Allow assignments of an AltiVec vector type to an equivalent GCC
7537       // vector type and vice versa
7538       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7539         Kind = CK_BitCast;
7540         return Compatible;
7541       }
7542 
7543       // If we are allowing lax vector conversions, and LHS and RHS are both
7544       // vectors, the total size only needs to be the same. This is a bitcast;
7545       // no bits are changed but the result type is different.
7546       if (isLaxVectorConversion(RHSType, LHSType)) {
7547         Kind = CK_BitCast;
7548         return IncompatibleVectors;
7549       }
7550     }
7551 
7552     // When the RHS comes from another lax conversion (e.g. binops between
7553     // scalars and vectors) the result is canonicalized as a vector. When the
7554     // LHS is also a vector, the lax is allowed by the condition above. Handle
7555     // the case where LHS is a scalar.
7556     if (LHSType->isScalarType()) {
7557       const VectorType *VecType = RHSType->getAs<VectorType>();
7558       if (VecType && VecType->getNumElements() == 1 &&
7559           isLaxVectorConversion(RHSType, LHSType)) {
7560         ExprResult *VecExpr = &RHS;
7561         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7562         Kind = CK_BitCast;
7563         return Compatible;
7564       }
7565     }
7566 
7567     return Incompatible;
7568   }
7569 
7570   // Diagnose attempts to convert between __float128 and long double where
7571   // such conversions currently can't be handled.
7572   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7573     return Incompatible;
7574 
7575   // Arithmetic conversions.
7576   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7577       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7578     if (ConvertRHS)
7579       Kind = PrepareScalarCast(RHS, LHSType);
7580     return Compatible;
7581   }
7582 
7583   // Conversions to normal pointers.
7584   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7585     // U* -> T*
7586     if (isa<PointerType>(RHSType)) {
7587       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7588       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7589       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7590       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7591     }
7592 
7593     // int -> T*
7594     if (RHSType->isIntegerType()) {
7595       Kind = CK_IntegralToPointer; // FIXME: null?
7596       return IntToPointer;
7597     }
7598 
7599     // C pointers are not compatible with ObjC object pointers,
7600     // with two exceptions:
7601     if (isa<ObjCObjectPointerType>(RHSType)) {
7602       //  - conversions to void*
7603       if (LHSPointer->getPointeeType()->isVoidType()) {
7604         Kind = CK_BitCast;
7605         return Compatible;
7606       }
7607 
7608       //  - conversions from 'Class' to the redefinition type
7609       if (RHSType->isObjCClassType() &&
7610           Context.hasSameType(LHSType,
7611                               Context.getObjCClassRedefinitionType())) {
7612         Kind = CK_BitCast;
7613         return Compatible;
7614       }
7615 
7616       Kind = CK_BitCast;
7617       return IncompatiblePointer;
7618     }
7619 
7620     // U^ -> void*
7621     if (RHSType->getAs<BlockPointerType>()) {
7622       if (LHSPointer->getPointeeType()->isVoidType()) {
7623         Kind = CK_BitCast;
7624         return Compatible;
7625       }
7626     }
7627 
7628     return Incompatible;
7629   }
7630 
7631   // Conversions to block pointers.
7632   if (isa<BlockPointerType>(LHSType)) {
7633     // U^ -> T^
7634     if (RHSType->isBlockPointerType()) {
7635       Kind = CK_BitCast;
7636       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7637     }
7638 
7639     // int or null -> T^
7640     if (RHSType->isIntegerType()) {
7641       Kind = CK_IntegralToPointer; // FIXME: null
7642       return IntToBlockPointer;
7643     }
7644 
7645     // id -> T^
7646     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7647       Kind = CK_AnyPointerToBlockPointerCast;
7648       return Compatible;
7649     }
7650 
7651     // void* -> T^
7652     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7653       if (RHSPT->getPointeeType()->isVoidType()) {
7654         Kind = CK_AnyPointerToBlockPointerCast;
7655         return Compatible;
7656       }
7657 
7658     return Incompatible;
7659   }
7660 
7661   // Conversions to Objective-C pointers.
7662   if (isa<ObjCObjectPointerType>(LHSType)) {
7663     // A* -> B*
7664     if (RHSType->isObjCObjectPointerType()) {
7665       Kind = CK_BitCast;
7666       Sema::AssignConvertType result =
7667         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7668       if (getLangOpts().ObjCAutoRefCount &&
7669           result == Compatible &&
7670           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7671         result = IncompatibleObjCWeakRef;
7672       return result;
7673     }
7674 
7675     // int or null -> A*
7676     if (RHSType->isIntegerType()) {
7677       Kind = CK_IntegralToPointer; // FIXME: null
7678       return IntToPointer;
7679     }
7680 
7681     // In general, C pointers are not compatible with ObjC object pointers,
7682     // with two exceptions:
7683     if (isa<PointerType>(RHSType)) {
7684       Kind = CK_CPointerToObjCPointerCast;
7685 
7686       //  - conversions from 'void*'
7687       if (RHSType->isVoidPointerType()) {
7688         return Compatible;
7689       }
7690 
7691       //  - conversions to 'Class' from its redefinition type
7692       if (LHSType->isObjCClassType() &&
7693           Context.hasSameType(RHSType,
7694                               Context.getObjCClassRedefinitionType())) {
7695         return Compatible;
7696       }
7697 
7698       return IncompatiblePointer;
7699     }
7700 
7701     // Only under strict condition T^ is compatible with an Objective-C pointer.
7702     if (RHSType->isBlockPointerType() &&
7703         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7704       if (ConvertRHS)
7705         maybeExtendBlockObject(RHS);
7706       Kind = CK_BlockPointerToObjCPointerCast;
7707       return Compatible;
7708     }
7709 
7710     return Incompatible;
7711   }
7712 
7713   // Conversions from pointers that are not covered by the above.
7714   if (isa<PointerType>(RHSType)) {
7715     // T* -> _Bool
7716     if (LHSType == Context.BoolTy) {
7717       Kind = CK_PointerToBoolean;
7718       return Compatible;
7719     }
7720 
7721     // T* -> int
7722     if (LHSType->isIntegerType()) {
7723       Kind = CK_PointerToIntegral;
7724       return PointerToInt;
7725     }
7726 
7727     return Incompatible;
7728   }
7729 
7730   // Conversions from Objective-C pointers that are not covered by the above.
7731   if (isa<ObjCObjectPointerType>(RHSType)) {
7732     // T* -> _Bool
7733     if (LHSType == Context.BoolTy) {
7734       Kind = CK_PointerToBoolean;
7735       return Compatible;
7736     }
7737 
7738     // T* -> int
7739     if (LHSType->isIntegerType()) {
7740       Kind = CK_PointerToIntegral;
7741       return PointerToInt;
7742     }
7743 
7744     return Incompatible;
7745   }
7746 
7747   // struct A -> struct B
7748   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7749     if (Context.typesAreCompatible(LHSType, RHSType)) {
7750       Kind = CK_NoOp;
7751       return Compatible;
7752     }
7753   }
7754 
7755   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7756     Kind = CK_IntToOCLSampler;
7757     return Compatible;
7758   }
7759 
7760   return Incompatible;
7761 }
7762 
7763 /// \brief Constructs a transparent union from an expression that is
7764 /// used to initialize the transparent union.
7765 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7766                                       ExprResult &EResult, QualType UnionType,
7767                                       FieldDecl *Field) {
7768   // Build an initializer list that designates the appropriate member
7769   // of the transparent union.
7770   Expr *E = EResult.get();
7771   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7772                                                    E, SourceLocation());
7773   Initializer->setType(UnionType);
7774   Initializer->setInitializedFieldInUnion(Field);
7775 
7776   // Build a compound literal constructing a value of the transparent
7777   // union type from this initializer list.
7778   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7779   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7780                                         VK_RValue, Initializer, false);
7781 }
7782 
7783 Sema::AssignConvertType
7784 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7785                                                ExprResult &RHS) {
7786   QualType RHSType = RHS.get()->getType();
7787 
7788   // If the ArgType is a Union type, we want to handle a potential
7789   // transparent_union GCC extension.
7790   const RecordType *UT = ArgType->getAsUnionType();
7791   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7792     return Incompatible;
7793 
7794   // The field to initialize within the transparent union.
7795   RecordDecl *UD = UT->getDecl();
7796   FieldDecl *InitField = nullptr;
7797   // It's compatible if the expression matches any of the fields.
7798   for (auto *it : UD->fields()) {
7799     if (it->getType()->isPointerType()) {
7800       // If the transparent union contains a pointer type, we allow:
7801       // 1) void pointer
7802       // 2) null pointer constant
7803       if (RHSType->isPointerType())
7804         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7805           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7806           InitField = it;
7807           break;
7808         }
7809 
7810       if (RHS.get()->isNullPointerConstant(Context,
7811                                            Expr::NPC_ValueDependentIsNull)) {
7812         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7813                                 CK_NullToPointer);
7814         InitField = it;
7815         break;
7816       }
7817     }
7818 
7819     CastKind Kind = CK_Invalid;
7820     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7821           == Compatible) {
7822       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7823       InitField = it;
7824       break;
7825     }
7826   }
7827 
7828   if (!InitField)
7829     return Incompatible;
7830 
7831   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7832   return Compatible;
7833 }
7834 
7835 Sema::AssignConvertType
7836 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7837                                        bool Diagnose,
7838                                        bool DiagnoseCFAudited,
7839                                        bool ConvertRHS) {
7840   // We need to be able to tell the caller whether we diagnosed a problem, if
7841   // they ask us to issue diagnostics.
7842   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7843 
7844   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7845   // we can't avoid *all* modifications at the moment, so we need some somewhere
7846   // to put the updated value.
7847   ExprResult LocalRHS = CallerRHS;
7848   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7849 
7850   if (getLangOpts().CPlusPlus) {
7851     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7852       // C++ 5.17p3: If the left operand is not of class type, the
7853       // expression is implicitly converted (C++ 4) to the
7854       // cv-unqualified type of the left operand.
7855       QualType RHSType = RHS.get()->getType();
7856       if (Diagnose) {
7857         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7858                                         AA_Assigning);
7859       } else {
7860         ImplicitConversionSequence ICS =
7861             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7862                                   /*SuppressUserConversions=*/false,
7863                                   /*AllowExplicit=*/false,
7864                                   /*InOverloadResolution=*/false,
7865                                   /*CStyle=*/false,
7866                                   /*AllowObjCWritebackConversion=*/false);
7867         if (ICS.isFailure())
7868           return Incompatible;
7869         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7870                                         ICS, AA_Assigning);
7871       }
7872       if (RHS.isInvalid())
7873         return Incompatible;
7874       Sema::AssignConvertType result = Compatible;
7875       if (getLangOpts().ObjCAutoRefCount &&
7876           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7877         result = IncompatibleObjCWeakRef;
7878       return result;
7879     }
7880 
7881     // FIXME: Currently, we fall through and treat C++ classes like C
7882     // structures.
7883     // FIXME: We also fall through for atomics; not sure what should
7884     // happen there, though.
7885   } else if (RHS.get()->getType() == Context.OverloadTy) {
7886     // As a set of extensions to C, we support overloading on functions. These
7887     // functions need to be resolved here.
7888     DeclAccessPair DAP;
7889     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7890             RHS.get(), LHSType, /*Complain=*/false, DAP))
7891       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7892     else
7893       return Incompatible;
7894   }
7895 
7896   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7897   // a null pointer constant.
7898   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7899        LHSType->isBlockPointerType()) &&
7900       RHS.get()->isNullPointerConstant(Context,
7901                                        Expr::NPC_ValueDependentIsNull)) {
7902     if (Diagnose || ConvertRHS) {
7903       CastKind Kind;
7904       CXXCastPath Path;
7905       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7906                              /*IgnoreBaseAccess=*/false, Diagnose);
7907       if (ConvertRHS)
7908         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7909     }
7910     return Compatible;
7911   }
7912 
7913   // This check seems unnatural, however it is necessary to ensure the proper
7914   // conversion of functions/arrays. If the conversion were done for all
7915   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7916   // expressions that suppress this implicit conversion (&, sizeof).
7917   //
7918   // Suppress this for references: C++ 8.5.3p5.
7919   if (!LHSType->isReferenceType()) {
7920     // FIXME: We potentially allocate here even if ConvertRHS is false.
7921     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7922     if (RHS.isInvalid())
7923       return Incompatible;
7924   }
7925 
7926   Expr *PRE = RHS.get()->IgnoreParenCasts();
7927   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7928     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7929     if (PDecl && !PDecl->hasDefinition()) {
7930       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7931       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7932     }
7933   }
7934 
7935   CastKind Kind = CK_Invalid;
7936   Sema::AssignConvertType result =
7937     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7938 
7939   // C99 6.5.16.1p2: The value of the right operand is converted to the
7940   // type of the assignment expression.
7941   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7942   // so that we can use references in built-in functions even in C.
7943   // The getNonReferenceType() call makes sure that the resulting expression
7944   // does not have reference type.
7945   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7946     QualType Ty = LHSType.getNonLValueExprType(Context);
7947     Expr *E = RHS.get();
7948 
7949     // Check for various Objective-C errors. If we are not reporting
7950     // diagnostics and just checking for errors, e.g., during overload
7951     // resolution, return Incompatible to indicate the failure.
7952     if (getLangOpts().ObjCAutoRefCount &&
7953         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7954                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7955       if (!Diagnose)
7956         return Incompatible;
7957     }
7958     if (getLangOpts().ObjC1 &&
7959         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7960                                            E->getType(), E, Diagnose) ||
7961          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7962       if (!Diagnose)
7963         return Incompatible;
7964       // Replace the expression with a corrected version and continue so we
7965       // can find further errors.
7966       RHS = E;
7967       return Compatible;
7968     }
7969 
7970     if (ConvertRHS)
7971       RHS = ImpCastExprToType(E, Ty, Kind);
7972   }
7973   return result;
7974 }
7975 
7976 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7977                                ExprResult &RHS) {
7978   Diag(Loc, diag::err_typecheck_invalid_operands)
7979     << LHS.get()->getType() << RHS.get()->getType()
7980     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7981   return QualType();
7982 }
7983 
7984 /// Try to convert a value of non-vector type to a vector type by converting
7985 /// the type to the element type of the vector and then performing a splat.
7986 /// If the language is OpenCL, we only use conversions that promote scalar
7987 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7988 /// for float->int.
7989 ///
7990 /// \param scalar - if non-null, actually perform the conversions
7991 /// \return true if the operation fails (but without diagnosing the failure)
7992 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7993                                      QualType scalarTy,
7994                                      QualType vectorEltTy,
7995                                      QualType vectorTy) {
7996   // The conversion to apply to the scalar before splatting it,
7997   // if necessary.
7998   CastKind scalarCast = CK_Invalid;
7999 
8000   if (vectorEltTy->isIntegralType(S.Context)) {
8001     if (!scalarTy->isIntegralType(S.Context))
8002       return true;
8003     if (S.getLangOpts().OpenCL &&
8004         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8005       return true;
8006     scalarCast = CK_IntegralCast;
8007   } else if (vectorEltTy->isRealFloatingType()) {
8008     if (scalarTy->isRealFloatingType()) {
8009       if (S.getLangOpts().OpenCL &&
8010           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8011         return true;
8012       scalarCast = CK_FloatingCast;
8013     }
8014     else if (scalarTy->isIntegralType(S.Context))
8015       scalarCast = CK_IntegralToFloating;
8016     else
8017       return true;
8018   } else {
8019     return true;
8020   }
8021 
8022   // Adjust scalar if desired.
8023   if (scalar) {
8024     if (scalarCast != CK_Invalid)
8025       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8026     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8027   }
8028   return false;
8029 }
8030 
8031 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8032                                    SourceLocation Loc, bool IsCompAssign,
8033                                    bool AllowBothBool,
8034                                    bool AllowBoolConversions) {
8035   if (!IsCompAssign) {
8036     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8037     if (LHS.isInvalid())
8038       return QualType();
8039   }
8040   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8041   if (RHS.isInvalid())
8042     return QualType();
8043 
8044   // For conversion purposes, we ignore any qualifiers.
8045   // For example, "const float" and "float" are equivalent.
8046   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8047   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8048 
8049   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8050   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8051   assert(LHSVecType || RHSVecType);
8052 
8053   // AltiVec-style "vector bool op vector bool" combinations are allowed
8054   // for some operators but not others.
8055   if (!AllowBothBool &&
8056       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8057       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8058     return InvalidOperands(Loc, LHS, RHS);
8059 
8060   // If the vector types are identical, return.
8061   if (Context.hasSameType(LHSType, RHSType))
8062     return LHSType;
8063 
8064   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8065   if (LHSVecType && RHSVecType &&
8066       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8067     if (isa<ExtVectorType>(LHSVecType)) {
8068       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8069       return LHSType;
8070     }
8071 
8072     if (!IsCompAssign)
8073       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8074     return RHSType;
8075   }
8076 
8077   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8078   // can be mixed, with the result being the non-bool type.  The non-bool
8079   // operand must have integer element type.
8080   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8081       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8082       (Context.getTypeSize(LHSVecType->getElementType()) ==
8083        Context.getTypeSize(RHSVecType->getElementType()))) {
8084     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8085         LHSVecType->getElementType()->isIntegerType() &&
8086         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8087       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8088       return LHSType;
8089     }
8090     if (!IsCompAssign &&
8091         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8092         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8093         RHSVecType->getElementType()->isIntegerType()) {
8094       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8095       return RHSType;
8096     }
8097   }
8098 
8099   // If there's an ext-vector type and a scalar, try to convert the scalar to
8100   // the vector element type and splat.
8101   // FIXME: this should also work for regular vector types as supported in GCC.
8102   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8103     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8104                                   LHSVecType->getElementType(), LHSType))
8105       return LHSType;
8106   }
8107   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8108     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8109                                   LHSType, RHSVecType->getElementType(),
8110                                   RHSType))
8111       return RHSType;
8112   }
8113 
8114   // FIXME: The code below also handles convertion between vectors and
8115   // non-scalars, we should break this down into fine grained specific checks
8116   // and emit proper diagnostics.
8117   QualType VecType = LHSVecType ? LHSType : RHSType;
8118   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8119   QualType OtherType = LHSVecType ? RHSType : LHSType;
8120   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8121   if (isLaxVectorConversion(OtherType, VecType)) {
8122     // If we're allowing lax vector conversions, only the total (data) size
8123     // needs to be the same. For non compound assignment, if one of the types is
8124     // scalar, the result is always the vector type.
8125     if (!IsCompAssign) {
8126       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8127       return VecType;
8128     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8129     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8130     // type. Note that this is already done by non-compound assignments in
8131     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8132     // <1 x T> -> T. The result is also a vector type.
8133     } else if (OtherType->isExtVectorType() ||
8134                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8135       ExprResult *RHSExpr = &RHS;
8136       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8137       return VecType;
8138     }
8139   }
8140 
8141   // Okay, the expression is invalid.
8142 
8143   // If there's a non-vector, non-real operand, diagnose that.
8144   if ((!RHSVecType && !RHSType->isRealType()) ||
8145       (!LHSVecType && !LHSType->isRealType())) {
8146     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8147       << LHSType << RHSType
8148       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8149     return QualType();
8150   }
8151 
8152   // OpenCL V1.1 6.2.6.p1:
8153   // If the operands are of more than one vector type, then an error shall
8154   // occur. Implicit conversions between vector types are not permitted, per
8155   // section 6.2.1.
8156   if (getLangOpts().OpenCL &&
8157       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8158       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8159     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8160                                                            << RHSType;
8161     return QualType();
8162   }
8163 
8164   // Otherwise, use the generic diagnostic.
8165   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8166     << LHSType << RHSType
8167     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8168   return QualType();
8169 }
8170 
8171 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8172 // expression.  These are mainly cases where the null pointer is used as an
8173 // integer instead of a pointer.
8174 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8175                                 SourceLocation Loc, bool IsCompare) {
8176   // The canonical way to check for a GNU null is with isNullPointerConstant,
8177   // but we use a bit of a hack here for speed; this is a relatively
8178   // hot path, and isNullPointerConstant is slow.
8179   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8180   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8181 
8182   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8183 
8184   // Avoid analyzing cases where the result will either be invalid (and
8185   // diagnosed as such) or entirely valid and not something to warn about.
8186   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8187       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8188     return;
8189 
8190   // Comparison operations would not make sense with a null pointer no matter
8191   // what the other expression is.
8192   if (!IsCompare) {
8193     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8194         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8195         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8196     return;
8197   }
8198 
8199   // The rest of the operations only make sense with a null pointer
8200   // if the other expression is a pointer.
8201   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8202       NonNullType->canDecayToPointerType())
8203     return;
8204 
8205   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8206       << LHSNull /* LHS is NULL */ << NonNullType
8207       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8208 }
8209 
8210 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8211                                                ExprResult &RHS,
8212                                                SourceLocation Loc, bool IsDiv) {
8213   // Check for division/remainder by zero.
8214   llvm::APSInt RHSValue;
8215   if (!RHS.get()->isValueDependent() &&
8216       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8217     S.DiagRuntimeBehavior(Loc, RHS.get(),
8218                           S.PDiag(diag::warn_remainder_division_by_zero)
8219                             << IsDiv << RHS.get()->getSourceRange());
8220 }
8221 
8222 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8223                                            SourceLocation Loc,
8224                                            bool IsCompAssign, bool IsDiv) {
8225   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8226 
8227   if (LHS.get()->getType()->isVectorType() ||
8228       RHS.get()->getType()->isVectorType())
8229     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8230                                /*AllowBothBool*/getLangOpts().AltiVec,
8231                                /*AllowBoolConversions*/false);
8232 
8233   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8234   if (LHS.isInvalid() || RHS.isInvalid())
8235     return QualType();
8236 
8237 
8238   if (compType.isNull() || !compType->isArithmeticType())
8239     return InvalidOperands(Loc, LHS, RHS);
8240   if (IsDiv)
8241     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8242   return compType;
8243 }
8244 
8245 QualType Sema::CheckRemainderOperands(
8246   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8247   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8248 
8249   if (LHS.get()->getType()->isVectorType() ||
8250       RHS.get()->getType()->isVectorType()) {
8251     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8252         RHS.get()->getType()->hasIntegerRepresentation())
8253       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8254                                  /*AllowBothBool*/getLangOpts().AltiVec,
8255                                  /*AllowBoolConversions*/false);
8256     return InvalidOperands(Loc, LHS, RHS);
8257   }
8258 
8259   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8260   if (LHS.isInvalid() || RHS.isInvalid())
8261     return QualType();
8262 
8263   if (compType.isNull() || !compType->isIntegerType())
8264     return InvalidOperands(Loc, LHS, RHS);
8265   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8266   return compType;
8267 }
8268 
8269 /// \brief Diagnose invalid arithmetic on two void pointers.
8270 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8271                                                 Expr *LHSExpr, Expr *RHSExpr) {
8272   S.Diag(Loc, S.getLangOpts().CPlusPlus
8273                 ? diag::err_typecheck_pointer_arith_void_type
8274                 : diag::ext_gnu_void_ptr)
8275     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8276                             << RHSExpr->getSourceRange();
8277 }
8278 
8279 /// \brief Diagnose invalid arithmetic on a void pointer.
8280 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8281                                             Expr *Pointer) {
8282   S.Diag(Loc, S.getLangOpts().CPlusPlus
8283                 ? diag::err_typecheck_pointer_arith_void_type
8284                 : diag::ext_gnu_void_ptr)
8285     << 0 /* one pointer */ << Pointer->getSourceRange();
8286 }
8287 
8288 /// \brief Diagnose invalid arithmetic on two function pointers.
8289 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8290                                                     Expr *LHS, Expr *RHS) {
8291   assert(LHS->getType()->isAnyPointerType());
8292   assert(RHS->getType()->isAnyPointerType());
8293   S.Diag(Loc, S.getLangOpts().CPlusPlus
8294                 ? diag::err_typecheck_pointer_arith_function_type
8295                 : diag::ext_gnu_ptr_func_arith)
8296     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8297     // We only show the second type if it differs from the first.
8298     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8299                                                    RHS->getType())
8300     << RHS->getType()->getPointeeType()
8301     << LHS->getSourceRange() << RHS->getSourceRange();
8302 }
8303 
8304 /// \brief Diagnose invalid arithmetic on a function pointer.
8305 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8306                                                 Expr *Pointer) {
8307   assert(Pointer->getType()->isAnyPointerType());
8308   S.Diag(Loc, S.getLangOpts().CPlusPlus
8309                 ? diag::err_typecheck_pointer_arith_function_type
8310                 : diag::ext_gnu_ptr_func_arith)
8311     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8312     << 0 /* one pointer, so only one type */
8313     << Pointer->getSourceRange();
8314 }
8315 
8316 /// \brief Emit error if Operand is incomplete pointer type
8317 ///
8318 /// \returns True if pointer has incomplete type
8319 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8320                                                  Expr *Operand) {
8321   QualType ResType = Operand->getType();
8322   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8323     ResType = ResAtomicType->getValueType();
8324 
8325   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8326   QualType PointeeTy = ResType->getPointeeType();
8327   return S.RequireCompleteType(Loc, PointeeTy,
8328                                diag::err_typecheck_arithmetic_incomplete_type,
8329                                PointeeTy, Operand->getSourceRange());
8330 }
8331 
8332 /// \brief Check the validity of an arithmetic pointer operand.
8333 ///
8334 /// If the operand has pointer type, this code will check for pointer types
8335 /// which are invalid in arithmetic operations. These will be diagnosed
8336 /// appropriately, including whether or not the use is supported as an
8337 /// extension.
8338 ///
8339 /// \returns True when the operand is valid to use (even if as an extension).
8340 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8341                                             Expr *Operand) {
8342   QualType ResType = Operand->getType();
8343   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8344     ResType = ResAtomicType->getValueType();
8345 
8346   if (!ResType->isAnyPointerType()) return true;
8347 
8348   QualType PointeeTy = ResType->getPointeeType();
8349   if (PointeeTy->isVoidType()) {
8350     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8351     return !S.getLangOpts().CPlusPlus;
8352   }
8353   if (PointeeTy->isFunctionType()) {
8354     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8355     return !S.getLangOpts().CPlusPlus;
8356   }
8357 
8358   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8359 
8360   return true;
8361 }
8362 
8363 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8364 /// operands.
8365 ///
8366 /// This routine will diagnose any invalid arithmetic on pointer operands much
8367 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8368 /// for emitting a single diagnostic even for operations where both LHS and RHS
8369 /// are (potentially problematic) pointers.
8370 ///
8371 /// \returns True when the operand is valid to use (even if as an extension).
8372 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8373                                                 Expr *LHSExpr, Expr *RHSExpr) {
8374   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8375   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8376   if (!isLHSPointer && !isRHSPointer) return true;
8377 
8378   QualType LHSPointeeTy, RHSPointeeTy;
8379   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8380   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8381 
8382   // if both are pointers check if operation is valid wrt address spaces
8383   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8384     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8385     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8386     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8387       S.Diag(Loc,
8388              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8389           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8390           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8391       return false;
8392     }
8393   }
8394 
8395   // Check for arithmetic on pointers to incomplete types.
8396   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8397   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8398   if (isLHSVoidPtr || isRHSVoidPtr) {
8399     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8400     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8401     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8402 
8403     return !S.getLangOpts().CPlusPlus;
8404   }
8405 
8406   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8407   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8408   if (isLHSFuncPtr || isRHSFuncPtr) {
8409     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8410     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8411                                                                 RHSExpr);
8412     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8413 
8414     return !S.getLangOpts().CPlusPlus;
8415   }
8416 
8417   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8418     return false;
8419   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8420     return false;
8421 
8422   return true;
8423 }
8424 
8425 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8426 /// literal.
8427 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8428                                   Expr *LHSExpr, Expr *RHSExpr) {
8429   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8430   Expr* IndexExpr = RHSExpr;
8431   if (!StrExpr) {
8432     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8433     IndexExpr = LHSExpr;
8434   }
8435 
8436   bool IsStringPlusInt = StrExpr &&
8437       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8438   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8439     return;
8440 
8441   llvm::APSInt index;
8442   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8443     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8444     if (index.isNonNegative() &&
8445         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8446                               index.isUnsigned()))
8447       return;
8448   }
8449 
8450   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8451   Self.Diag(OpLoc, diag::warn_string_plus_int)
8452       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8453 
8454   // Only print a fixit for "str" + int, not for int + "str".
8455   if (IndexExpr == RHSExpr) {
8456     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8457     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8458         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8459         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8460         << FixItHint::CreateInsertion(EndLoc, "]");
8461   } else
8462     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8463 }
8464 
8465 /// \brief Emit a warning when adding a char literal to a string.
8466 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8467                                    Expr *LHSExpr, Expr *RHSExpr) {
8468   const Expr *StringRefExpr = LHSExpr;
8469   const CharacterLiteral *CharExpr =
8470       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8471 
8472   if (!CharExpr) {
8473     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8474     StringRefExpr = RHSExpr;
8475   }
8476 
8477   if (!CharExpr || !StringRefExpr)
8478     return;
8479 
8480   const QualType StringType = StringRefExpr->getType();
8481 
8482   // Return if not a PointerType.
8483   if (!StringType->isAnyPointerType())
8484     return;
8485 
8486   // Return if not a CharacterType.
8487   if (!StringType->getPointeeType()->isAnyCharacterType())
8488     return;
8489 
8490   ASTContext &Ctx = Self.getASTContext();
8491   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8492 
8493   const QualType CharType = CharExpr->getType();
8494   if (!CharType->isAnyCharacterType() &&
8495       CharType->isIntegerType() &&
8496       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8497     Self.Diag(OpLoc, diag::warn_string_plus_char)
8498         << DiagRange << Ctx.CharTy;
8499   } else {
8500     Self.Diag(OpLoc, diag::warn_string_plus_char)
8501         << DiagRange << CharExpr->getType();
8502   }
8503 
8504   // Only print a fixit for str + char, not for char + str.
8505   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8506     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8507     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8508         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8509         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8510         << FixItHint::CreateInsertion(EndLoc, "]");
8511   } else {
8512     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8513   }
8514 }
8515 
8516 /// \brief Emit error when two pointers are incompatible.
8517 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8518                                            Expr *LHSExpr, Expr *RHSExpr) {
8519   assert(LHSExpr->getType()->isAnyPointerType());
8520   assert(RHSExpr->getType()->isAnyPointerType());
8521   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8522     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8523     << RHSExpr->getSourceRange();
8524 }
8525 
8526 // C99 6.5.6
8527 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8528                                      SourceLocation Loc, BinaryOperatorKind Opc,
8529                                      QualType* CompLHSTy) {
8530   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8531 
8532   if (LHS.get()->getType()->isVectorType() ||
8533       RHS.get()->getType()->isVectorType()) {
8534     QualType compType = CheckVectorOperands(
8535         LHS, RHS, Loc, CompLHSTy,
8536         /*AllowBothBool*/getLangOpts().AltiVec,
8537         /*AllowBoolConversions*/getLangOpts().ZVector);
8538     if (CompLHSTy) *CompLHSTy = compType;
8539     return compType;
8540   }
8541 
8542   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8543   if (LHS.isInvalid() || RHS.isInvalid())
8544     return QualType();
8545 
8546   // Diagnose "string literal" '+' int and string '+' "char literal".
8547   if (Opc == BO_Add) {
8548     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8549     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8550   }
8551 
8552   // handle the common case first (both operands are arithmetic).
8553   if (!compType.isNull() && compType->isArithmeticType()) {
8554     if (CompLHSTy) *CompLHSTy = compType;
8555     return compType;
8556   }
8557 
8558   // Type-checking.  Ultimately the pointer's going to be in PExp;
8559   // note that we bias towards the LHS being the pointer.
8560   Expr *PExp = LHS.get(), *IExp = RHS.get();
8561 
8562   bool isObjCPointer;
8563   if (PExp->getType()->isPointerType()) {
8564     isObjCPointer = false;
8565   } else if (PExp->getType()->isObjCObjectPointerType()) {
8566     isObjCPointer = true;
8567   } else {
8568     std::swap(PExp, IExp);
8569     if (PExp->getType()->isPointerType()) {
8570       isObjCPointer = false;
8571     } else if (PExp->getType()->isObjCObjectPointerType()) {
8572       isObjCPointer = true;
8573     } else {
8574       return InvalidOperands(Loc, LHS, RHS);
8575     }
8576   }
8577   assert(PExp->getType()->isAnyPointerType());
8578 
8579   if (!IExp->getType()->isIntegerType())
8580     return InvalidOperands(Loc, LHS, RHS);
8581 
8582   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8583     return QualType();
8584 
8585   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8586     return QualType();
8587 
8588   // Check array bounds for pointer arithemtic
8589   CheckArrayAccess(PExp, IExp);
8590 
8591   if (CompLHSTy) {
8592     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8593     if (LHSTy.isNull()) {
8594       LHSTy = LHS.get()->getType();
8595       if (LHSTy->isPromotableIntegerType())
8596         LHSTy = Context.getPromotedIntegerType(LHSTy);
8597     }
8598     *CompLHSTy = LHSTy;
8599   }
8600 
8601   return PExp->getType();
8602 }
8603 
8604 // C99 6.5.6
8605 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8606                                         SourceLocation Loc,
8607                                         QualType* CompLHSTy) {
8608   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8609 
8610   if (LHS.get()->getType()->isVectorType() ||
8611       RHS.get()->getType()->isVectorType()) {
8612     QualType compType = CheckVectorOperands(
8613         LHS, RHS, Loc, CompLHSTy,
8614         /*AllowBothBool*/getLangOpts().AltiVec,
8615         /*AllowBoolConversions*/getLangOpts().ZVector);
8616     if (CompLHSTy) *CompLHSTy = compType;
8617     return compType;
8618   }
8619 
8620   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8621   if (LHS.isInvalid() || RHS.isInvalid())
8622     return QualType();
8623 
8624   // Enforce type constraints: C99 6.5.6p3.
8625 
8626   // Handle the common case first (both operands are arithmetic).
8627   if (!compType.isNull() && compType->isArithmeticType()) {
8628     if (CompLHSTy) *CompLHSTy = compType;
8629     return compType;
8630   }
8631 
8632   // Either ptr - int   or   ptr - ptr.
8633   if (LHS.get()->getType()->isAnyPointerType()) {
8634     QualType lpointee = LHS.get()->getType()->getPointeeType();
8635 
8636     // Diagnose bad cases where we step over interface counts.
8637     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8638         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8639       return QualType();
8640 
8641     // The result type of a pointer-int computation is the pointer type.
8642     if (RHS.get()->getType()->isIntegerType()) {
8643       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8644         return QualType();
8645 
8646       // Check array bounds for pointer arithemtic
8647       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8648                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8649 
8650       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8651       return LHS.get()->getType();
8652     }
8653 
8654     // Handle pointer-pointer subtractions.
8655     if (const PointerType *RHSPTy
8656           = RHS.get()->getType()->getAs<PointerType>()) {
8657       QualType rpointee = RHSPTy->getPointeeType();
8658 
8659       if (getLangOpts().CPlusPlus) {
8660         // Pointee types must be the same: C++ [expr.add]
8661         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8662           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8663         }
8664       } else {
8665         // Pointee types must be compatible C99 6.5.6p3
8666         if (!Context.typesAreCompatible(
8667                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8668                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8669           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8670           return QualType();
8671         }
8672       }
8673 
8674       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8675                                                LHS.get(), RHS.get()))
8676         return QualType();
8677 
8678       // The pointee type may have zero size.  As an extension, a structure or
8679       // union may have zero size or an array may have zero length.  In this
8680       // case subtraction does not make sense.
8681       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8682         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8683         if (ElementSize.isZero()) {
8684           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8685             << rpointee.getUnqualifiedType()
8686             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8687         }
8688       }
8689 
8690       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8691       return Context.getPointerDiffType();
8692     }
8693   }
8694 
8695   return InvalidOperands(Loc, LHS, RHS);
8696 }
8697 
8698 static bool isScopedEnumerationType(QualType T) {
8699   if (const EnumType *ET = T->getAs<EnumType>())
8700     return ET->getDecl()->isScoped();
8701   return false;
8702 }
8703 
8704 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8705                                    SourceLocation Loc, BinaryOperatorKind Opc,
8706                                    QualType LHSType) {
8707   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8708   // so skip remaining warnings as we don't want to modify values within Sema.
8709   if (S.getLangOpts().OpenCL)
8710     return;
8711 
8712   llvm::APSInt Right;
8713   // Check right/shifter operand
8714   if (RHS.get()->isValueDependent() ||
8715       !RHS.get()->EvaluateAsInt(Right, S.Context))
8716     return;
8717 
8718   if (Right.isNegative()) {
8719     S.DiagRuntimeBehavior(Loc, RHS.get(),
8720                           S.PDiag(diag::warn_shift_negative)
8721                             << RHS.get()->getSourceRange());
8722     return;
8723   }
8724   llvm::APInt LeftBits(Right.getBitWidth(),
8725                        S.Context.getTypeSize(LHS.get()->getType()));
8726   if (Right.uge(LeftBits)) {
8727     S.DiagRuntimeBehavior(Loc, RHS.get(),
8728                           S.PDiag(diag::warn_shift_gt_typewidth)
8729                             << RHS.get()->getSourceRange());
8730     return;
8731   }
8732   if (Opc != BO_Shl)
8733     return;
8734 
8735   // When left shifting an ICE which is signed, we can check for overflow which
8736   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8737   // integers have defined behavior modulo one more than the maximum value
8738   // representable in the result type, so never warn for those.
8739   llvm::APSInt Left;
8740   if (LHS.get()->isValueDependent() ||
8741       LHSType->hasUnsignedIntegerRepresentation() ||
8742       !LHS.get()->EvaluateAsInt(Left, S.Context))
8743     return;
8744 
8745   // If LHS does not have a signed type and non-negative value
8746   // then, the behavior is undefined. Warn about it.
8747   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8748     S.DiagRuntimeBehavior(Loc, LHS.get(),
8749                           S.PDiag(diag::warn_shift_lhs_negative)
8750                             << LHS.get()->getSourceRange());
8751     return;
8752   }
8753 
8754   llvm::APInt ResultBits =
8755       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8756   if (LeftBits.uge(ResultBits))
8757     return;
8758   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8759   Result = Result.shl(Right);
8760 
8761   // Print the bit representation of the signed integer as an unsigned
8762   // hexadecimal number.
8763   SmallString<40> HexResult;
8764   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8765 
8766   // If we are only missing a sign bit, this is less likely to result in actual
8767   // bugs -- if the result is cast back to an unsigned type, it will have the
8768   // expected value. Thus we place this behind a different warning that can be
8769   // turned off separately if needed.
8770   if (LeftBits == ResultBits - 1) {
8771     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8772         << HexResult << LHSType
8773         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8774     return;
8775   }
8776 
8777   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8778     << HexResult.str() << Result.getMinSignedBits() << LHSType
8779     << Left.getBitWidth() << LHS.get()->getSourceRange()
8780     << RHS.get()->getSourceRange();
8781 }
8782 
8783 /// \brief Return the resulting type when a vector is shifted
8784 ///        by a scalar or vector shift amount.
8785 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8786                                  SourceLocation Loc, bool IsCompAssign) {
8787   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8788   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8789       !LHS.get()->getType()->isVectorType()) {
8790     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8791       << RHS.get()->getType() << LHS.get()->getType()
8792       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8793     return QualType();
8794   }
8795 
8796   if (!IsCompAssign) {
8797     LHS = S.UsualUnaryConversions(LHS.get());
8798     if (LHS.isInvalid()) return QualType();
8799   }
8800 
8801   RHS = S.UsualUnaryConversions(RHS.get());
8802   if (RHS.isInvalid()) return QualType();
8803 
8804   QualType LHSType = LHS.get()->getType();
8805   // Note that LHS might be a scalar because the routine calls not only in
8806   // OpenCL case.
8807   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8808   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8809 
8810   // Note that RHS might not be a vector.
8811   QualType RHSType = RHS.get()->getType();
8812   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8813   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8814 
8815   // The operands need to be integers.
8816   if (!LHSEleType->isIntegerType()) {
8817     S.Diag(Loc, diag::err_typecheck_expect_int)
8818       << LHS.get()->getType() << LHS.get()->getSourceRange();
8819     return QualType();
8820   }
8821 
8822   if (!RHSEleType->isIntegerType()) {
8823     S.Diag(Loc, diag::err_typecheck_expect_int)
8824       << RHS.get()->getType() << RHS.get()->getSourceRange();
8825     return QualType();
8826   }
8827 
8828   if (!LHSVecTy) {
8829     assert(RHSVecTy);
8830     if (IsCompAssign)
8831       return RHSType;
8832     if (LHSEleType != RHSEleType) {
8833       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8834       LHSEleType = RHSEleType;
8835     }
8836     QualType VecTy =
8837         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8838     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8839     LHSType = VecTy;
8840   } else if (RHSVecTy) {
8841     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8842     // are applied component-wise. So if RHS is a vector, then ensure
8843     // that the number of elements is the same as LHS...
8844     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8845       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8846         << LHS.get()->getType() << RHS.get()->getType()
8847         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8848       return QualType();
8849     }
8850     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8851       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8852       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8853       if (LHSBT != RHSBT &&
8854           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8855         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8856             << LHS.get()->getType() << RHS.get()->getType()
8857             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8858       }
8859     }
8860   } else {
8861     // ...else expand RHS to match the number of elements in LHS.
8862     QualType VecTy =
8863       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8864     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8865   }
8866 
8867   return LHSType;
8868 }
8869 
8870 // C99 6.5.7
8871 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8872                                   SourceLocation Loc, BinaryOperatorKind Opc,
8873                                   bool IsCompAssign) {
8874   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8875 
8876   // Vector shifts promote their scalar inputs to vector type.
8877   if (LHS.get()->getType()->isVectorType() ||
8878       RHS.get()->getType()->isVectorType()) {
8879     if (LangOpts.ZVector) {
8880       // The shift operators for the z vector extensions work basically
8881       // like general shifts, except that neither the LHS nor the RHS is
8882       // allowed to be a "vector bool".
8883       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8884         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8885           return InvalidOperands(Loc, LHS, RHS);
8886       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8887         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8888           return InvalidOperands(Loc, LHS, RHS);
8889     }
8890     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8891   }
8892 
8893   // Shifts don't perform usual arithmetic conversions, they just do integer
8894   // promotions on each operand. C99 6.5.7p3
8895 
8896   // For the LHS, do usual unary conversions, but then reset them away
8897   // if this is a compound assignment.
8898   ExprResult OldLHS = LHS;
8899   LHS = UsualUnaryConversions(LHS.get());
8900   if (LHS.isInvalid())
8901     return QualType();
8902   QualType LHSType = LHS.get()->getType();
8903   if (IsCompAssign) LHS = OldLHS;
8904 
8905   // The RHS is simpler.
8906   RHS = UsualUnaryConversions(RHS.get());
8907   if (RHS.isInvalid())
8908     return QualType();
8909   QualType RHSType = RHS.get()->getType();
8910 
8911   // C99 6.5.7p2: Each of the operands shall have integer type.
8912   if (!LHSType->hasIntegerRepresentation() ||
8913       !RHSType->hasIntegerRepresentation())
8914     return InvalidOperands(Loc, LHS, RHS);
8915 
8916   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8917   // hasIntegerRepresentation() above instead of this.
8918   if (isScopedEnumerationType(LHSType) ||
8919       isScopedEnumerationType(RHSType)) {
8920     return InvalidOperands(Loc, LHS, RHS);
8921   }
8922   // Sanity-check shift operands
8923   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8924 
8925   // "The type of the result is that of the promoted left operand."
8926   return LHSType;
8927 }
8928 
8929 static bool IsWithinTemplateSpecialization(Decl *D) {
8930   if (DeclContext *DC = D->getDeclContext()) {
8931     if (isa<ClassTemplateSpecializationDecl>(DC))
8932       return true;
8933     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8934       return FD->isFunctionTemplateSpecialization();
8935   }
8936   return false;
8937 }
8938 
8939 /// If two different enums are compared, raise a warning.
8940 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8941                                 Expr *RHS) {
8942   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8943   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8944 
8945   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8946   if (!LHSEnumType)
8947     return;
8948   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8949   if (!RHSEnumType)
8950     return;
8951 
8952   // Ignore anonymous enums.
8953   if (!LHSEnumType->getDecl()->getIdentifier())
8954     return;
8955   if (!RHSEnumType->getDecl()->getIdentifier())
8956     return;
8957 
8958   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8959     return;
8960 
8961   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8962       << LHSStrippedType << RHSStrippedType
8963       << LHS->getSourceRange() << RHS->getSourceRange();
8964 }
8965 
8966 /// \brief Diagnose bad pointer comparisons.
8967 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8968                                               ExprResult &LHS, ExprResult &RHS,
8969                                               bool IsError) {
8970   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8971                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8972     << LHS.get()->getType() << RHS.get()->getType()
8973     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8974 }
8975 
8976 /// \brief Returns false if the pointers are converted to a composite type,
8977 /// true otherwise.
8978 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8979                                            ExprResult &LHS, ExprResult &RHS) {
8980   // C++ [expr.rel]p2:
8981   //   [...] Pointer conversions (4.10) and qualification
8982   //   conversions (4.4) are performed on pointer operands (or on
8983   //   a pointer operand and a null pointer constant) to bring
8984   //   them to their composite pointer type. [...]
8985   //
8986   // C++ [expr.eq]p1 uses the same notion for (in)equality
8987   // comparisons of pointers.
8988 
8989   QualType LHSType = LHS.get()->getType();
8990   QualType RHSType = RHS.get()->getType();
8991   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8992          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
8993 
8994   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
8995   if (T.isNull()) {
8996     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8997         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8998       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8999     else
9000       S.InvalidOperands(Loc, LHS, RHS);
9001     return true;
9002   }
9003 
9004   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9005   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9006   return false;
9007 }
9008 
9009 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9010                                                     ExprResult &LHS,
9011                                                     ExprResult &RHS,
9012                                                     bool IsError) {
9013   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9014                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9015     << LHS.get()->getType() << RHS.get()->getType()
9016     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9017 }
9018 
9019 static bool isObjCObjectLiteral(ExprResult &E) {
9020   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9021   case Stmt::ObjCArrayLiteralClass:
9022   case Stmt::ObjCDictionaryLiteralClass:
9023   case Stmt::ObjCStringLiteralClass:
9024   case Stmt::ObjCBoxedExprClass:
9025     return true;
9026   default:
9027     // Note that ObjCBoolLiteral is NOT an object literal!
9028     return false;
9029   }
9030 }
9031 
9032 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9033   const ObjCObjectPointerType *Type =
9034     LHS->getType()->getAs<ObjCObjectPointerType>();
9035 
9036   // If this is not actually an Objective-C object, bail out.
9037   if (!Type)
9038     return false;
9039 
9040   // Get the LHS object's interface type.
9041   QualType InterfaceType = Type->getPointeeType();
9042 
9043   // If the RHS isn't an Objective-C object, bail out.
9044   if (!RHS->getType()->isObjCObjectPointerType())
9045     return false;
9046 
9047   // Try to find the -isEqual: method.
9048   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9049   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9050                                                       InterfaceType,
9051                                                       /*instance=*/true);
9052   if (!Method) {
9053     if (Type->isObjCIdType()) {
9054       // For 'id', just check the global pool.
9055       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9056                                                   /*receiverId=*/true);
9057     } else {
9058       // Check protocols.
9059       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9060                                              /*instance=*/true);
9061     }
9062   }
9063 
9064   if (!Method)
9065     return false;
9066 
9067   QualType T = Method->parameters()[0]->getType();
9068   if (!T->isObjCObjectPointerType())
9069     return false;
9070 
9071   QualType R = Method->getReturnType();
9072   if (!R->isScalarType())
9073     return false;
9074 
9075   return true;
9076 }
9077 
9078 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9079   FromE = FromE->IgnoreParenImpCasts();
9080   switch (FromE->getStmtClass()) {
9081     default:
9082       break;
9083     case Stmt::ObjCStringLiteralClass:
9084       // "string literal"
9085       return LK_String;
9086     case Stmt::ObjCArrayLiteralClass:
9087       // "array literal"
9088       return LK_Array;
9089     case Stmt::ObjCDictionaryLiteralClass:
9090       // "dictionary literal"
9091       return LK_Dictionary;
9092     case Stmt::BlockExprClass:
9093       return LK_Block;
9094     case Stmt::ObjCBoxedExprClass: {
9095       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9096       switch (Inner->getStmtClass()) {
9097         case Stmt::IntegerLiteralClass:
9098         case Stmt::FloatingLiteralClass:
9099         case Stmt::CharacterLiteralClass:
9100         case Stmt::ObjCBoolLiteralExprClass:
9101         case Stmt::CXXBoolLiteralExprClass:
9102           // "numeric literal"
9103           return LK_Numeric;
9104         case Stmt::ImplicitCastExprClass: {
9105           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9106           // Boolean literals can be represented by implicit casts.
9107           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9108             return LK_Numeric;
9109           break;
9110         }
9111         default:
9112           break;
9113       }
9114       return LK_Boxed;
9115     }
9116   }
9117   return LK_None;
9118 }
9119 
9120 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9121                                           ExprResult &LHS, ExprResult &RHS,
9122                                           BinaryOperator::Opcode Opc){
9123   Expr *Literal;
9124   Expr *Other;
9125   if (isObjCObjectLiteral(LHS)) {
9126     Literal = LHS.get();
9127     Other = RHS.get();
9128   } else {
9129     Literal = RHS.get();
9130     Other = LHS.get();
9131   }
9132 
9133   // Don't warn on comparisons against nil.
9134   Other = Other->IgnoreParenCasts();
9135   if (Other->isNullPointerConstant(S.getASTContext(),
9136                                    Expr::NPC_ValueDependentIsNotNull))
9137     return;
9138 
9139   // This should be kept in sync with warn_objc_literal_comparison.
9140   // LK_String should always be after the other literals, since it has its own
9141   // warning flag.
9142   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9143   assert(LiteralKind != Sema::LK_Block);
9144   if (LiteralKind == Sema::LK_None) {
9145     llvm_unreachable("Unknown Objective-C object literal kind");
9146   }
9147 
9148   if (LiteralKind == Sema::LK_String)
9149     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9150       << Literal->getSourceRange();
9151   else
9152     S.Diag(Loc, diag::warn_objc_literal_comparison)
9153       << LiteralKind << Literal->getSourceRange();
9154 
9155   if (BinaryOperator::isEqualityOp(Opc) &&
9156       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9157     SourceLocation Start = LHS.get()->getLocStart();
9158     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9159     CharSourceRange OpRange =
9160       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9161 
9162     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9163       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9164       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9165       << FixItHint::CreateInsertion(End, "]");
9166   }
9167 }
9168 
9169 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9170 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9171                                            ExprResult &RHS, SourceLocation Loc,
9172                                            BinaryOperatorKind Opc) {
9173   // Check that left hand side is !something.
9174   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9175   if (!UO || UO->getOpcode() != UO_LNot) return;
9176 
9177   // Only check if the right hand side is non-bool arithmetic type.
9178   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9179 
9180   // Make sure that the something in !something is not bool.
9181   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9182   if (SubExpr->isKnownToHaveBooleanValue()) return;
9183 
9184   // Emit warning.
9185   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9186   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9187       << Loc << IsBitwiseOp;
9188 
9189   // First note suggest !(x < y)
9190   SourceLocation FirstOpen = SubExpr->getLocStart();
9191   SourceLocation FirstClose = RHS.get()->getLocEnd();
9192   FirstClose = S.getLocForEndOfToken(FirstClose);
9193   if (FirstClose.isInvalid())
9194     FirstOpen = SourceLocation();
9195   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9196       << IsBitwiseOp
9197       << FixItHint::CreateInsertion(FirstOpen, "(")
9198       << FixItHint::CreateInsertion(FirstClose, ")");
9199 
9200   // Second note suggests (!x) < y
9201   SourceLocation SecondOpen = LHS.get()->getLocStart();
9202   SourceLocation SecondClose = LHS.get()->getLocEnd();
9203   SecondClose = S.getLocForEndOfToken(SecondClose);
9204   if (SecondClose.isInvalid())
9205     SecondOpen = SourceLocation();
9206   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9207       << FixItHint::CreateInsertion(SecondOpen, "(")
9208       << FixItHint::CreateInsertion(SecondClose, ")");
9209 }
9210 
9211 // Get the decl for a simple expression: a reference to a variable,
9212 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9213 static ValueDecl *getCompareDecl(Expr *E) {
9214   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9215     return DR->getDecl();
9216   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9217     if (Ivar->isFreeIvar())
9218       return Ivar->getDecl();
9219   }
9220   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9221     if (Mem->isImplicitAccess())
9222       return Mem->getMemberDecl();
9223   }
9224   return nullptr;
9225 }
9226 
9227 // C99 6.5.8, C++ [expr.rel]
9228 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9229                                     SourceLocation Loc, BinaryOperatorKind Opc,
9230                                     bool IsRelational) {
9231   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9232 
9233   // Handle vector comparisons separately.
9234   if (LHS.get()->getType()->isVectorType() ||
9235       RHS.get()->getType()->isVectorType())
9236     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9237 
9238   QualType LHSType = LHS.get()->getType();
9239   QualType RHSType = RHS.get()->getType();
9240 
9241   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9242   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9243 
9244   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9245   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9246 
9247   if (!LHSType->hasFloatingRepresentation() &&
9248       !(LHSType->isBlockPointerType() && IsRelational) &&
9249       !LHS.get()->getLocStart().isMacroID() &&
9250       !RHS.get()->getLocStart().isMacroID() &&
9251       ActiveTemplateInstantiations.empty()) {
9252     // For non-floating point types, check for self-comparisons of the form
9253     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9254     // often indicate logic errors in the program.
9255     //
9256     // NOTE: Don't warn about comparison expressions resulting from macro
9257     // expansion. Also don't warn about comparisons which are only self
9258     // comparisons within a template specialization. The warnings should catch
9259     // obvious cases in the definition of the template anyways. The idea is to
9260     // warn when the typed comparison operator will always evaluate to the same
9261     // result.
9262     ValueDecl *DL = getCompareDecl(LHSStripped);
9263     ValueDecl *DR = getCompareDecl(RHSStripped);
9264     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9265       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9266                           << 0 // self-
9267                           << (Opc == BO_EQ
9268                               || Opc == BO_LE
9269                               || Opc == BO_GE));
9270     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9271                !DL->getType()->isReferenceType() &&
9272                !DR->getType()->isReferenceType()) {
9273         // what is it always going to eval to?
9274         char always_evals_to;
9275         switch(Opc) {
9276         case BO_EQ: // e.g. array1 == array2
9277           always_evals_to = 0; // false
9278           break;
9279         case BO_NE: // e.g. array1 != array2
9280           always_evals_to = 1; // true
9281           break;
9282         default:
9283           // best we can say is 'a constant'
9284           always_evals_to = 2; // e.g. array1 <= array2
9285           break;
9286         }
9287         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9288                             << 1 // array
9289                             << always_evals_to);
9290     }
9291 
9292     if (isa<CastExpr>(LHSStripped))
9293       LHSStripped = LHSStripped->IgnoreParenCasts();
9294     if (isa<CastExpr>(RHSStripped))
9295       RHSStripped = RHSStripped->IgnoreParenCasts();
9296 
9297     // Warn about comparisons against a string constant (unless the other
9298     // operand is null), the user probably wants strcmp.
9299     Expr *literalString = nullptr;
9300     Expr *literalStringStripped = nullptr;
9301     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9302         !RHSStripped->isNullPointerConstant(Context,
9303                                             Expr::NPC_ValueDependentIsNull)) {
9304       literalString = LHS.get();
9305       literalStringStripped = LHSStripped;
9306     } else if ((isa<StringLiteral>(RHSStripped) ||
9307                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9308                !LHSStripped->isNullPointerConstant(Context,
9309                                             Expr::NPC_ValueDependentIsNull)) {
9310       literalString = RHS.get();
9311       literalStringStripped = RHSStripped;
9312     }
9313 
9314     if (literalString) {
9315       DiagRuntimeBehavior(Loc, nullptr,
9316         PDiag(diag::warn_stringcompare)
9317           << isa<ObjCEncodeExpr>(literalStringStripped)
9318           << literalString->getSourceRange());
9319     }
9320   }
9321 
9322   // C99 6.5.8p3 / C99 6.5.9p4
9323   UsualArithmeticConversions(LHS, RHS);
9324   if (LHS.isInvalid() || RHS.isInvalid())
9325     return QualType();
9326 
9327   LHSType = LHS.get()->getType();
9328   RHSType = RHS.get()->getType();
9329 
9330   // The result of comparisons is 'bool' in C++, 'int' in C.
9331   QualType ResultTy = Context.getLogicalOperationType();
9332 
9333   if (IsRelational) {
9334     if (LHSType->isRealType() && RHSType->isRealType())
9335       return ResultTy;
9336   } else {
9337     // Check for comparisons of floating point operands using != and ==.
9338     if (LHSType->hasFloatingRepresentation())
9339       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9340 
9341     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9342       return ResultTy;
9343   }
9344 
9345   const Expr::NullPointerConstantKind LHSNullKind =
9346       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9347   const Expr::NullPointerConstantKind RHSNullKind =
9348       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9349   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9350   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9351 
9352   if (!IsRelational && LHSIsNull != RHSIsNull) {
9353     bool IsEquality = Opc == BO_EQ;
9354     if (RHSIsNull)
9355       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9356                                    RHS.get()->getSourceRange());
9357     else
9358       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9359                                    LHS.get()->getSourceRange());
9360   }
9361 
9362   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9363       (RHSType->isIntegerType() && !RHSIsNull)) {
9364     // Skip normal pointer conversion checks in this case; we have better
9365     // diagnostics for this below.
9366   } else if (getLangOpts().CPlusPlus) {
9367     // Equality comparison of a function pointer to a void pointer is invalid,
9368     // but we allow it as an extension.
9369     // FIXME: If we really want to allow this, should it be part of composite
9370     // pointer type computation so it works in conditionals too?
9371     if (!IsRelational &&
9372         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9373          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9374       // This is a gcc extension compatibility comparison.
9375       // In a SFINAE context, we treat this as a hard error to maintain
9376       // conformance with the C++ standard.
9377       diagnoseFunctionPointerToVoidComparison(
9378           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9379 
9380       if (isSFINAEContext())
9381         return QualType();
9382 
9383       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9384       return ResultTy;
9385     }
9386 
9387     // C++ [expr.eq]p2:
9388     //   If at least one operand is a pointer [...] bring them to their
9389     //   composite pointer type.
9390     // C++ [expr.rel]p2:
9391     //   If both operands are pointers, [...] bring them to their composite
9392     //   pointer type.
9393     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9394         (IsRelational ? 2 : 1)) {
9395       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9396         return QualType();
9397       else
9398         return ResultTy;
9399     }
9400   } else if (LHSType->isPointerType() &&
9401              RHSType->isPointerType()) { // C99 6.5.8p2
9402     // All of the following pointer-related warnings are GCC extensions, except
9403     // when handling null pointer constants.
9404     QualType LCanPointeeTy =
9405       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9406     QualType RCanPointeeTy =
9407       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9408 
9409     // C99 6.5.9p2 and C99 6.5.8p2
9410     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9411                                    RCanPointeeTy.getUnqualifiedType())) {
9412       // Valid unless a relational comparison of function pointers
9413       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9414         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9415           << LHSType << RHSType << LHS.get()->getSourceRange()
9416           << RHS.get()->getSourceRange();
9417       }
9418     } else if (!IsRelational &&
9419                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9420       // Valid unless comparison between non-null pointer and function pointer
9421       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9422           && !LHSIsNull && !RHSIsNull)
9423         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9424                                                 /*isError*/false);
9425     } else {
9426       // Invalid
9427       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9428     }
9429     if (LCanPointeeTy != RCanPointeeTy) {
9430       // Treat NULL constant as a special case in OpenCL.
9431       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9432         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9433         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9434           Diag(Loc,
9435                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9436               << LHSType << RHSType << 0 /* comparison */
9437               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9438         }
9439       }
9440       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9441       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9442       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9443                                                : CK_BitCast;
9444       if (LHSIsNull && !RHSIsNull)
9445         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9446       else
9447         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9448     }
9449     return ResultTy;
9450   }
9451 
9452   if (getLangOpts().CPlusPlus) {
9453     // C++ [expr.eq]p4:
9454     //   Two operands of type std::nullptr_t or one operand of type
9455     //   std::nullptr_t and the other a null pointer constant compare equal.
9456     if (!IsRelational && LHSIsNull && RHSIsNull) {
9457       if (LHSType->isNullPtrType()) {
9458         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9459         return ResultTy;
9460       }
9461       if (RHSType->isNullPtrType()) {
9462         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9463         return ResultTy;
9464       }
9465     }
9466 
9467     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9468     // These aren't covered by the composite pointer type rules.
9469     if (!IsRelational && RHSType->isNullPtrType() &&
9470         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9471       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9472       return ResultTy;
9473     }
9474     if (!IsRelational && LHSType->isNullPtrType() &&
9475         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9476       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9477       return ResultTy;
9478     }
9479 
9480     if (IsRelational &&
9481         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9482          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9483       // HACK: Relational comparison of nullptr_t against a pointer type is
9484       // invalid per DR583, but we allow it within std::less<> and friends,
9485       // since otherwise common uses of it break.
9486       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9487       // friends to have std::nullptr_t overload candidates.
9488       DeclContext *DC = CurContext;
9489       if (isa<FunctionDecl>(DC))
9490         DC = DC->getParent();
9491       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9492         if (CTSD->isInStdNamespace() &&
9493             llvm::StringSwitch<bool>(CTSD->getName())
9494                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9495                 .Default(false)) {
9496           if (RHSType->isNullPtrType())
9497             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9498           else
9499             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9500           return ResultTy;
9501         }
9502       }
9503     }
9504 
9505     // C++ [expr.eq]p2:
9506     //   If at least one operand is a pointer to member, [...] bring them to
9507     //   their composite pointer type.
9508     if (!IsRelational &&
9509         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9510       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9511         return QualType();
9512       else
9513         return ResultTy;
9514     }
9515 
9516     // Handle scoped enumeration types specifically, since they don't promote
9517     // to integers.
9518     if (LHS.get()->getType()->isEnumeralType() &&
9519         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9520                                        RHS.get()->getType()))
9521       return ResultTy;
9522   }
9523 
9524   // Handle block pointer types.
9525   if (!IsRelational && LHSType->isBlockPointerType() &&
9526       RHSType->isBlockPointerType()) {
9527     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9528     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9529 
9530     if (!LHSIsNull && !RHSIsNull &&
9531         !Context.typesAreCompatible(lpointee, rpointee)) {
9532       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9533         << LHSType << RHSType << LHS.get()->getSourceRange()
9534         << RHS.get()->getSourceRange();
9535     }
9536     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9537     return ResultTy;
9538   }
9539 
9540   // Allow block pointers to be compared with null pointer constants.
9541   if (!IsRelational
9542       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9543           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9544     if (!LHSIsNull && !RHSIsNull) {
9545       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9546              ->getPointeeType()->isVoidType())
9547             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9548                 ->getPointeeType()->isVoidType())))
9549         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9550           << LHSType << RHSType << LHS.get()->getSourceRange()
9551           << RHS.get()->getSourceRange();
9552     }
9553     if (LHSIsNull && !RHSIsNull)
9554       LHS = ImpCastExprToType(LHS.get(), RHSType,
9555                               RHSType->isPointerType() ? CK_BitCast
9556                                 : CK_AnyPointerToBlockPointerCast);
9557     else
9558       RHS = ImpCastExprToType(RHS.get(), LHSType,
9559                               LHSType->isPointerType() ? CK_BitCast
9560                                 : CK_AnyPointerToBlockPointerCast);
9561     return ResultTy;
9562   }
9563 
9564   if (LHSType->isObjCObjectPointerType() ||
9565       RHSType->isObjCObjectPointerType()) {
9566     const PointerType *LPT = LHSType->getAs<PointerType>();
9567     const PointerType *RPT = RHSType->getAs<PointerType>();
9568     if (LPT || RPT) {
9569       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9570       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9571 
9572       if (!LPtrToVoid && !RPtrToVoid &&
9573           !Context.typesAreCompatible(LHSType, RHSType)) {
9574         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9575                                           /*isError*/false);
9576       }
9577       if (LHSIsNull && !RHSIsNull) {
9578         Expr *E = LHS.get();
9579         if (getLangOpts().ObjCAutoRefCount)
9580           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9581         LHS = ImpCastExprToType(E, RHSType,
9582                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9583       }
9584       else {
9585         Expr *E = RHS.get();
9586         if (getLangOpts().ObjCAutoRefCount)
9587           CheckObjCARCConversion(SourceRange(), LHSType, E,
9588                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9589                                  /*DiagnoseCFAudited=*/false, Opc);
9590         RHS = ImpCastExprToType(E, LHSType,
9591                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9592       }
9593       return ResultTy;
9594     }
9595     if (LHSType->isObjCObjectPointerType() &&
9596         RHSType->isObjCObjectPointerType()) {
9597       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9598         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9599                                           /*isError*/false);
9600       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9601         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9602 
9603       if (LHSIsNull && !RHSIsNull)
9604         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9605       else
9606         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9607       return ResultTy;
9608     }
9609   }
9610   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9611       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9612     unsigned DiagID = 0;
9613     bool isError = false;
9614     if (LangOpts.DebuggerSupport) {
9615       // Under a debugger, allow the comparison of pointers to integers,
9616       // since users tend to want to compare addresses.
9617     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9618                (RHSIsNull && RHSType->isIntegerType())) {
9619       if (IsRelational) {
9620         isError = getLangOpts().CPlusPlus;
9621         DiagID =
9622           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9623                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9624       }
9625     } else if (getLangOpts().CPlusPlus) {
9626       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9627       isError = true;
9628     } else if (IsRelational)
9629       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9630     else
9631       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9632 
9633     if (DiagID) {
9634       Diag(Loc, DiagID)
9635         << LHSType << RHSType << LHS.get()->getSourceRange()
9636         << RHS.get()->getSourceRange();
9637       if (isError)
9638         return QualType();
9639     }
9640 
9641     if (LHSType->isIntegerType())
9642       LHS = ImpCastExprToType(LHS.get(), RHSType,
9643                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9644     else
9645       RHS = ImpCastExprToType(RHS.get(), LHSType,
9646                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9647     return ResultTy;
9648   }
9649 
9650   // Handle block pointers.
9651   if (!IsRelational && RHSIsNull
9652       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9653     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9654     return ResultTy;
9655   }
9656   if (!IsRelational && LHSIsNull
9657       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9658     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9659     return ResultTy;
9660   }
9661 
9662   if (getLangOpts().OpenCLVersion >= 200) {
9663     if (LHSIsNull && RHSType->isQueueT()) {
9664       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9665       return ResultTy;
9666     }
9667 
9668     if (LHSType->isQueueT() && RHSIsNull) {
9669       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9670       return ResultTy;
9671     }
9672   }
9673 
9674   return InvalidOperands(Loc, LHS, RHS);
9675 }
9676 
9677 
9678 // Return a signed type that is of identical size and number of elements.
9679 // For floating point vectors, return an integer type of identical size
9680 // and number of elements.
9681 QualType Sema::GetSignedVectorType(QualType V) {
9682   const VectorType *VTy = V->getAs<VectorType>();
9683   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9684   if (TypeSize == Context.getTypeSize(Context.CharTy))
9685     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9686   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9687     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9688   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9689     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9690   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9691     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9692   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9693          "Unhandled vector element size in vector compare");
9694   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9695 }
9696 
9697 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9698 /// operates on extended vector types.  Instead of producing an IntTy result,
9699 /// like a scalar comparison, a vector comparison produces a vector of integer
9700 /// types.
9701 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9702                                           SourceLocation Loc,
9703                                           bool IsRelational) {
9704   // Check to make sure we're operating on vectors of the same type and width,
9705   // Allowing one side to be a scalar of element type.
9706   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9707                               /*AllowBothBool*/true,
9708                               /*AllowBoolConversions*/getLangOpts().ZVector);
9709   if (vType.isNull())
9710     return vType;
9711 
9712   QualType LHSType = LHS.get()->getType();
9713 
9714   // If AltiVec, the comparison results in a numeric type, i.e.
9715   // bool for C++, int for C
9716   if (getLangOpts().AltiVec &&
9717       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9718     return Context.getLogicalOperationType();
9719 
9720   // For non-floating point types, check for self-comparisons of the form
9721   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9722   // often indicate logic errors in the program.
9723   if (!LHSType->hasFloatingRepresentation() &&
9724       ActiveTemplateInstantiations.empty()) {
9725     if (DeclRefExpr* DRL
9726           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9727       if (DeclRefExpr* DRR
9728             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9729         if (DRL->getDecl() == DRR->getDecl())
9730           DiagRuntimeBehavior(Loc, nullptr,
9731                               PDiag(diag::warn_comparison_always)
9732                                 << 0 // self-
9733                                 << 2 // "a constant"
9734                               );
9735   }
9736 
9737   // Check for comparisons of floating point operands using != and ==.
9738   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9739     assert (RHS.get()->getType()->hasFloatingRepresentation());
9740     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9741   }
9742 
9743   // Return a signed type for the vector.
9744   return GetSignedVectorType(vType);
9745 }
9746 
9747 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9748                                           SourceLocation Loc) {
9749   // Ensure that either both operands are of the same vector type, or
9750   // one operand is of a vector type and the other is of its element type.
9751   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9752                                        /*AllowBothBool*/true,
9753                                        /*AllowBoolConversions*/false);
9754   if (vType.isNull())
9755     return InvalidOperands(Loc, LHS, RHS);
9756   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9757       vType->hasFloatingRepresentation())
9758     return InvalidOperands(Loc, LHS, RHS);
9759 
9760   return GetSignedVectorType(LHS.get()->getType());
9761 }
9762 
9763 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9764                                            SourceLocation Loc,
9765                                            BinaryOperatorKind Opc) {
9766   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9767 
9768   bool IsCompAssign =
9769       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9770 
9771   if (LHS.get()->getType()->isVectorType() ||
9772       RHS.get()->getType()->isVectorType()) {
9773     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9774         RHS.get()->getType()->hasIntegerRepresentation())
9775       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9776                         /*AllowBothBool*/true,
9777                         /*AllowBoolConversions*/getLangOpts().ZVector);
9778     return InvalidOperands(Loc, LHS, RHS);
9779   }
9780 
9781   if (Opc == BO_And)
9782     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9783 
9784   ExprResult LHSResult = LHS, RHSResult = RHS;
9785   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9786                                                  IsCompAssign);
9787   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9788     return QualType();
9789   LHS = LHSResult.get();
9790   RHS = RHSResult.get();
9791 
9792   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9793     return compType;
9794   return InvalidOperands(Loc, LHS, RHS);
9795 }
9796 
9797 // C99 6.5.[13,14]
9798 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9799                                            SourceLocation Loc,
9800                                            BinaryOperatorKind Opc) {
9801   // Check vector operands differently.
9802   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9803     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9804 
9805   // Diagnose cases where the user write a logical and/or but probably meant a
9806   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9807   // is a constant.
9808   if (LHS.get()->getType()->isIntegerType() &&
9809       !LHS.get()->getType()->isBooleanType() &&
9810       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9811       // Don't warn in macros or template instantiations.
9812       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9813     // If the RHS can be constant folded, and if it constant folds to something
9814     // that isn't 0 or 1 (which indicate a potential logical operation that
9815     // happened to fold to true/false) then warn.
9816     // Parens on the RHS are ignored.
9817     llvm::APSInt Result;
9818     if (RHS.get()->EvaluateAsInt(Result, Context))
9819       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9820            !RHS.get()->getExprLoc().isMacroID()) ||
9821           (Result != 0 && Result != 1)) {
9822         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9823           << RHS.get()->getSourceRange()
9824           << (Opc == BO_LAnd ? "&&" : "||");
9825         // Suggest replacing the logical operator with the bitwise version
9826         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9827             << (Opc == BO_LAnd ? "&" : "|")
9828             << FixItHint::CreateReplacement(SourceRange(
9829                                                  Loc, getLocForEndOfToken(Loc)),
9830                                             Opc == BO_LAnd ? "&" : "|");
9831         if (Opc == BO_LAnd)
9832           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9833           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9834               << FixItHint::CreateRemoval(
9835                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9836                               RHS.get()->getLocEnd()));
9837       }
9838   }
9839 
9840   if (!Context.getLangOpts().CPlusPlus) {
9841     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9842     // not operate on the built-in scalar and vector float types.
9843     if (Context.getLangOpts().OpenCL &&
9844         Context.getLangOpts().OpenCLVersion < 120) {
9845       if (LHS.get()->getType()->isFloatingType() ||
9846           RHS.get()->getType()->isFloatingType())
9847         return InvalidOperands(Loc, LHS, RHS);
9848     }
9849 
9850     LHS = UsualUnaryConversions(LHS.get());
9851     if (LHS.isInvalid())
9852       return QualType();
9853 
9854     RHS = UsualUnaryConversions(RHS.get());
9855     if (RHS.isInvalid())
9856       return QualType();
9857 
9858     if (!LHS.get()->getType()->isScalarType() ||
9859         !RHS.get()->getType()->isScalarType())
9860       return InvalidOperands(Loc, LHS, RHS);
9861 
9862     return Context.IntTy;
9863   }
9864 
9865   // The following is safe because we only use this method for
9866   // non-overloadable operands.
9867 
9868   // C++ [expr.log.and]p1
9869   // C++ [expr.log.or]p1
9870   // The operands are both contextually converted to type bool.
9871   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9872   if (LHSRes.isInvalid())
9873     return InvalidOperands(Loc, LHS, RHS);
9874   LHS = LHSRes;
9875 
9876   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9877   if (RHSRes.isInvalid())
9878     return InvalidOperands(Loc, LHS, RHS);
9879   RHS = RHSRes;
9880 
9881   // C++ [expr.log.and]p2
9882   // C++ [expr.log.or]p2
9883   // The result is a bool.
9884   return Context.BoolTy;
9885 }
9886 
9887 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9888   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9889   if (!ME) return false;
9890   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9891   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9892       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9893   if (!Base) return false;
9894   return Base->getMethodDecl() != nullptr;
9895 }
9896 
9897 /// Is the given expression (which must be 'const') a reference to a
9898 /// variable which was originally non-const, but which has become
9899 /// 'const' due to being captured within a block?
9900 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9901 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9902   assert(E->isLValue() && E->getType().isConstQualified());
9903   E = E->IgnoreParens();
9904 
9905   // Must be a reference to a declaration from an enclosing scope.
9906   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9907   if (!DRE) return NCCK_None;
9908   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9909 
9910   // The declaration must be a variable which is not declared 'const'.
9911   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9912   if (!var) return NCCK_None;
9913   if (var->getType().isConstQualified()) return NCCK_None;
9914   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9915 
9916   // Decide whether the first capture was for a block or a lambda.
9917   DeclContext *DC = S.CurContext, *Prev = nullptr;
9918   // Decide whether the first capture was for a block or a lambda.
9919   while (DC) {
9920     // For init-capture, it is possible that the variable belongs to the
9921     // template pattern of the current context.
9922     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9923       if (var->isInitCapture() &&
9924           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9925         break;
9926     if (DC == var->getDeclContext())
9927       break;
9928     Prev = DC;
9929     DC = DC->getParent();
9930   }
9931   // Unless we have an init-capture, we've gone one step too far.
9932   if (!var->isInitCapture())
9933     DC = Prev;
9934   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9935 }
9936 
9937 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9938   Ty = Ty.getNonReferenceType();
9939   if (IsDereference && Ty->isPointerType())
9940     Ty = Ty->getPointeeType();
9941   return !Ty.isConstQualified();
9942 }
9943 
9944 /// Emit the "read-only variable not assignable" error and print notes to give
9945 /// more information about why the variable is not assignable, such as pointing
9946 /// to the declaration of a const variable, showing that a method is const, or
9947 /// that the function is returning a const reference.
9948 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9949                                     SourceLocation Loc) {
9950   // Update err_typecheck_assign_const and note_typecheck_assign_const
9951   // when this enum is changed.
9952   enum {
9953     ConstFunction,
9954     ConstVariable,
9955     ConstMember,
9956     ConstMethod,
9957     ConstUnknown,  // Keep as last element
9958   };
9959 
9960   SourceRange ExprRange = E->getSourceRange();
9961 
9962   // Only emit one error on the first const found.  All other consts will emit
9963   // a note to the error.
9964   bool DiagnosticEmitted = false;
9965 
9966   // Track if the current expression is the result of a dereference, and if the
9967   // next checked expression is the result of a dereference.
9968   bool IsDereference = false;
9969   bool NextIsDereference = false;
9970 
9971   // Loop to process MemberExpr chains.
9972   while (true) {
9973     IsDereference = NextIsDereference;
9974 
9975     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9976     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9977       NextIsDereference = ME->isArrow();
9978       const ValueDecl *VD = ME->getMemberDecl();
9979       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9980         // Mutable fields can be modified even if the class is const.
9981         if (Field->isMutable()) {
9982           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9983           break;
9984         }
9985 
9986         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9987           if (!DiagnosticEmitted) {
9988             S.Diag(Loc, diag::err_typecheck_assign_const)
9989                 << ExprRange << ConstMember << false /*static*/ << Field
9990                 << Field->getType();
9991             DiagnosticEmitted = true;
9992           }
9993           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9994               << ConstMember << false /*static*/ << Field << Field->getType()
9995               << Field->getSourceRange();
9996         }
9997         E = ME->getBase();
9998         continue;
9999       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10000         if (VDecl->getType().isConstQualified()) {
10001           if (!DiagnosticEmitted) {
10002             S.Diag(Loc, diag::err_typecheck_assign_const)
10003                 << ExprRange << ConstMember << true /*static*/ << VDecl
10004                 << VDecl->getType();
10005             DiagnosticEmitted = true;
10006           }
10007           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10008               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10009               << VDecl->getSourceRange();
10010         }
10011         // Static fields do not inherit constness from parents.
10012         break;
10013       }
10014       break;
10015     } // End MemberExpr
10016     break;
10017   }
10018 
10019   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10020     // Function calls
10021     const FunctionDecl *FD = CE->getDirectCallee();
10022     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10023       if (!DiagnosticEmitted) {
10024         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10025                                                       << ConstFunction << FD;
10026         DiagnosticEmitted = true;
10027       }
10028       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10029              diag::note_typecheck_assign_const)
10030           << ConstFunction << FD << FD->getReturnType()
10031           << FD->getReturnTypeSourceRange();
10032     }
10033   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10034     // Point to variable declaration.
10035     if (const ValueDecl *VD = DRE->getDecl()) {
10036       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10037         if (!DiagnosticEmitted) {
10038           S.Diag(Loc, diag::err_typecheck_assign_const)
10039               << ExprRange << ConstVariable << VD << VD->getType();
10040           DiagnosticEmitted = true;
10041         }
10042         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10043             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10044       }
10045     }
10046   } else if (isa<CXXThisExpr>(E)) {
10047     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10048       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10049         if (MD->isConst()) {
10050           if (!DiagnosticEmitted) {
10051             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10052                                                           << ConstMethod << MD;
10053             DiagnosticEmitted = true;
10054           }
10055           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10056               << ConstMethod << MD << MD->getSourceRange();
10057         }
10058       }
10059     }
10060   }
10061 
10062   if (DiagnosticEmitted)
10063     return;
10064 
10065   // Can't determine a more specific message, so display the generic error.
10066   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10067 }
10068 
10069 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10070 /// emit an error and return true.  If so, return false.
10071 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10072   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10073 
10074   S.CheckShadowingDeclModification(E, Loc);
10075 
10076   SourceLocation OrigLoc = Loc;
10077   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10078                                                               &Loc);
10079   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10080     IsLV = Expr::MLV_InvalidMessageExpression;
10081   if (IsLV == Expr::MLV_Valid)
10082     return false;
10083 
10084   unsigned DiagID = 0;
10085   bool NeedType = false;
10086   switch (IsLV) { // C99 6.5.16p2
10087   case Expr::MLV_ConstQualified:
10088     // Use a specialized diagnostic when we're assigning to an object
10089     // from an enclosing function or block.
10090     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10091       if (NCCK == NCCK_Block)
10092         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10093       else
10094         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10095       break;
10096     }
10097 
10098     // In ARC, use some specialized diagnostics for occasions where we
10099     // infer 'const'.  These are always pseudo-strong variables.
10100     if (S.getLangOpts().ObjCAutoRefCount) {
10101       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10102       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10103         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10104 
10105         // Use the normal diagnostic if it's pseudo-__strong but the
10106         // user actually wrote 'const'.
10107         if (var->isARCPseudoStrong() &&
10108             (!var->getTypeSourceInfo() ||
10109              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10110           // There are two pseudo-strong cases:
10111           //  - self
10112           ObjCMethodDecl *method = S.getCurMethodDecl();
10113           if (method && var == method->getSelfDecl())
10114             DiagID = method->isClassMethod()
10115               ? diag::err_typecheck_arc_assign_self_class_method
10116               : diag::err_typecheck_arc_assign_self;
10117 
10118           //  - fast enumeration variables
10119           else
10120             DiagID = diag::err_typecheck_arr_assign_enumeration;
10121 
10122           SourceRange Assign;
10123           if (Loc != OrigLoc)
10124             Assign = SourceRange(OrigLoc, OrigLoc);
10125           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10126           // We need to preserve the AST regardless, so migration tool
10127           // can do its job.
10128           return false;
10129         }
10130       }
10131     }
10132 
10133     // If none of the special cases above are triggered, then this is a
10134     // simple const assignment.
10135     if (DiagID == 0) {
10136       DiagnoseConstAssignment(S, E, Loc);
10137       return true;
10138     }
10139 
10140     break;
10141   case Expr::MLV_ConstAddrSpace:
10142     DiagnoseConstAssignment(S, E, Loc);
10143     return true;
10144   case Expr::MLV_ArrayType:
10145   case Expr::MLV_ArrayTemporary:
10146     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10147     NeedType = true;
10148     break;
10149   case Expr::MLV_NotObjectType:
10150     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10151     NeedType = true;
10152     break;
10153   case Expr::MLV_LValueCast:
10154     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10155     break;
10156   case Expr::MLV_Valid:
10157     llvm_unreachable("did not take early return for MLV_Valid");
10158   case Expr::MLV_InvalidExpression:
10159   case Expr::MLV_MemberFunction:
10160   case Expr::MLV_ClassTemporary:
10161     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10162     break;
10163   case Expr::MLV_IncompleteType:
10164   case Expr::MLV_IncompleteVoidType:
10165     return S.RequireCompleteType(Loc, E->getType(),
10166              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10167   case Expr::MLV_DuplicateVectorComponents:
10168     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10169     break;
10170   case Expr::MLV_NoSetterProperty:
10171     llvm_unreachable("readonly properties should be processed differently");
10172   case Expr::MLV_InvalidMessageExpression:
10173     DiagID = diag::err_readonly_message_assignment;
10174     break;
10175   case Expr::MLV_SubObjCPropertySetting:
10176     DiagID = diag::err_no_subobject_property_setting;
10177     break;
10178   }
10179 
10180   SourceRange Assign;
10181   if (Loc != OrigLoc)
10182     Assign = SourceRange(OrigLoc, OrigLoc);
10183   if (NeedType)
10184     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10185   else
10186     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10187   return true;
10188 }
10189 
10190 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10191                                          SourceLocation Loc,
10192                                          Sema &Sema) {
10193   // C / C++ fields
10194   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10195   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10196   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10197     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10198       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10199   }
10200 
10201   // Objective-C instance variables
10202   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10203   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10204   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10205     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10206     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10207     if (RL && RR && RL->getDecl() == RR->getDecl())
10208       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10209   }
10210 }
10211 
10212 // C99 6.5.16.1
10213 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10214                                        SourceLocation Loc,
10215                                        QualType CompoundType) {
10216   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10217 
10218   // Verify that LHS is a modifiable lvalue, and emit error if not.
10219   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10220     return QualType();
10221 
10222   QualType LHSType = LHSExpr->getType();
10223   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10224                                              CompoundType;
10225   // OpenCL v1.2 s6.1.1.1 p2:
10226   // The half data type can only be used to declare a pointer to a buffer that
10227   // contains half values
10228   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10229     LHSType->isHalfType()) {
10230     Diag(Loc, diag::err_opencl_half_load_store) << 1
10231         << LHSType.getUnqualifiedType();
10232     return QualType();
10233   }
10234 
10235   AssignConvertType ConvTy;
10236   if (CompoundType.isNull()) {
10237     Expr *RHSCheck = RHS.get();
10238 
10239     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10240 
10241     QualType LHSTy(LHSType);
10242     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10243     if (RHS.isInvalid())
10244       return QualType();
10245     // Special case of NSObject attributes on c-style pointer types.
10246     if (ConvTy == IncompatiblePointer &&
10247         ((Context.isObjCNSObjectType(LHSType) &&
10248           RHSType->isObjCObjectPointerType()) ||
10249          (Context.isObjCNSObjectType(RHSType) &&
10250           LHSType->isObjCObjectPointerType())))
10251       ConvTy = Compatible;
10252 
10253     if (ConvTy == Compatible &&
10254         LHSType->isObjCObjectType())
10255         Diag(Loc, diag::err_objc_object_assignment)
10256           << LHSType;
10257 
10258     // If the RHS is a unary plus or minus, check to see if they = and + are
10259     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10260     // instead of "x += 4".
10261     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10262       RHSCheck = ICE->getSubExpr();
10263     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10264       if ((UO->getOpcode() == UO_Plus ||
10265            UO->getOpcode() == UO_Minus) &&
10266           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10267           // Only if the two operators are exactly adjacent.
10268           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10269           // And there is a space or other character before the subexpr of the
10270           // unary +/-.  We don't want to warn on "x=-1".
10271           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10272           UO->getSubExpr()->getLocStart().isFileID()) {
10273         Diag(Loc, diag::warn_not_compound_assign)
10274           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10275           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10276       }
10277     }
10278 
10279     if (ConvTy == Compatible) {
10280       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10281         // Warn about retain cycles where a block captures the LHS, but
10282         // not if the LHS is a simple variable into which the block is
10283         // being stored...unless that variable can be captured by reference!
10284         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10285         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10286         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10287           checkRetainCycles(LHSExpr, RHS.get());
10288 
10289         // It is safe to assign a weak reference into a strong variable.
10290         // Although this code can still have problems:
10291         //   id x = self.weakProp;
10292         //   id y = self.weakProp;
10293         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10294         // paths through the function. This should be revisited if
10295         // -Wrepeated-use-of-weak is made flow-sensitive.
10296         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10297                              RHS.get()->getLocStart()))
10298           getCurFunction()->markSafeWeakUse(RHS.get());
10299 
10300       } else if (getLangOpts().ObjCAutoRefCount) {
10301         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10302       }
10303     }
10304   } else {
10305     // Compound assignment "x += y"
10306     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10307   }
10308 
10309   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10310                                RHS.get(), AA_Assigning))
10311     return QualType();
10312 
10313   CheckForNullPointerDereference(*this, LHSExpr);
10314 
10315   // C99 6.5.16p3: The type of an assignment expression is the type of the
10316   // left operand unless the left operand has qualified type, in which case
10317   // it is the unqualified version of the type of the left operand.
10318   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10319   // is converted to the type of the assignment expression (above).
10320   // C++ 5.17p1: the type of the assignment expression is that of its left
10321   // operand.
10322   return (getLangOpts().CPlusPlus
10323           ? LHSType : LHSType.getUnqualifiedType());
10324 }
10325 
10326 // Only ignore explicit casts to void.
10327 static bool IgnoreCommaOperand(const Expr *E) {
10328   E = E->IgnoreParens();
10329 
10330   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10331     if (CE->getCastKind() == CK_ToVoid) {
10332       return true;
10333     }
10334   }
10335 
10336   return false;
10337 }
10338 
10339 // Look for instances where it is likely the comma operator is confused with
10340 // another operator.  There is a whitelist of acceptable expressions for the
10341 // left hand side of the comma operator, otherwise emit a warning.
10342 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10343   // No warnings in macros
10344   if (Loc.isMacroID())
10345     return;
10346 
10347   // Don't warn in template instantiations.
10348   if (!ActiveTemplateInstantiations.empty())
10349     return;
10350 
10351   // Scope isn't fine-grained enough to whitelist the specific cases, so
10352   // instead, skip more than needed, then call back into here with the
10353   // CommaVisitor in SemaStmt.cpp.
10354   // The whitelisted locations are the initialization and increment portions
10355   // of a for loop.  The additional checks are on the condition of
10356   // if statements, do/while loops, and for loops.
10357   const unsigned ForIncrementFlags =
10358       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10359   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10360   const unsigned ScopeFlags = getCurScope()->getFlags();
10361   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10362       (ScopeFlags & ForInitFlags) == ForInitFlags)
10363     return;
10364 
10365   // If there are multiple comma operators used together, get the RHS of the
10366   // of the comma operator as the LHS.
10367   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10368     if (BO->getOpcode() != BO_Comma)
10369       break;
10370     LHS = BO->getRHS();
10371   }
10372 
10373   // Only allow some expressions on LHS to not warn.
10374   if (IgnoreCommaOperand(LHS))
10375     return;
10376 
10377   Diag(Loc, diag::warn_comma_operator);
10378   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10379       << LHS->getSourceRange()
10380       << FixItHint::CreateInsertion(LHS->getLocStart(),
10381                                     LangOpts.CPlusPlus ? "static_cast<void>("
10382                                                        : "(void)(")
10383       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10384                                     ")");
10385 }
10386 
10387 // C99 6.5.17
10388 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10389                                    SourceLocation Loc) {
10390   LHS = S.CheckPlaceholderExpr(LHS.get());
10391   RHS = S.CheckPlaceholderExpr(RHS.get());
10392   if (LHS.isInvalid() || RHS.isInvalid())
10393     return QualType();
10394 
10395   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10396   // operands, but not unary promotions.
10397   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10398 
10399   // So we treat the LHS as a ignored value, and in C++ we allow the
10400   // containing site to determine what should be done with the RHS.
10401   LHS = S.IgnoredValueConversions(LHS.get());
10402   if (LHS.isInvalid())
10403     return QualType();
10404 
10405   S.DiagnoseUnusedExprResult(LHS.get());
10406 
10407   if (!S.getLangOpts().CPlusPlus) {
10408     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10409     if (RHS.isInvalid())
10410       return QualType();
10411     if (!RHS.get()->getType()->isVoidType())
10412       S.RequireCompleteType(Loc, RHS.get()->getType(),
10413                             diag::err_incomplete_type);
10414   }
10415 
10416   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10417     S.DiagnoseCommaOperator(LHS.get(), Loc);
10418 
10419   return RHS.get()->getType();
10420 }
10421 
10422 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10423 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10424 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10425                                                ExprValueKind &VK,
10426                                                ExprObjectKind &OK,
10427                                                SourceLocation OpLoc,
10428                                                bool IsInc, bool IsPrefix) {
10429   if (Op->isTypeDependent())
10430     return S.Context.DependentTy;
10431 
10432   QualType ResType = Op->getType();
10433   // Atomic types can be used for increment / decrement where the non-atomic
10434   // versions can, so ignore the _Atomic() specifier for the purpose of
10435   // checking.
10436   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10437     ResType = ResAtomicType->getValueType();
10438 
10439   assert(!ResType.isNull() && "no type for increment/decrement expression");
10440 
10441   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10442     // Decrement of bool is not allowed.
10443     if (!IsInc) {
10444       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10445       return QualType();
10446     }
10447     // Increment of bool sets it to true, but is deprecated.
10448     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10449                                               : diag::warn_increment_bool)
10450       << Op->getSourceRange();
10451   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10452     // Error on enum increments and decrements in C++ mode
10453     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10454     return QualType();
10455   } else if (ResType->isRealType()) {
10456     // OK!
10457   } else if (ResType->isPointerType()) {
10458     // C99 6.5.2.4p2, 6.5.6p2
10459     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10460       return QualType();
10461   } else if (ResType->isObjCObjectPointerType()) {
10462     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10463     // Otherwise, we just need a complete type.
10464     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10465         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10466       return QualType();
10467   } else if (ResType->isAnyComplexType()) {
10468     // C99 does not support ++/-- on complex types, we allow as an extension.
10469     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10470       << ResType << Op->getSourceRange();
10471   } else if (ResType->isPlaceholderType()) {
10472     ExprResult PR = S.CheckPlaceholderExpr(Op);
10473     if (PR.isInvalid()) return QualType();
10474     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10475                                           IsInc, IsPrefix);
10476   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10477     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10478   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10479              (ResType->getAs<VectorType>()->getVectorKind() !=
10480               VectorType::AltiVecBool)) {
10481     // The z vector extensions allow ++ and -- for non-bool vectors.
10482   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10483             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10484     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10485   } else {
10486     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10487       << ResType << int(IsInc) << Op->getSourceRange();
10488     return QualType();
10489   }
10490   // At this point, we know we have a real, complex or pointer type.
10491   // Now make sure the operand is a modifiable lvalue.
10492   if (CheckForModifiableLvalue(Op, OpLoc, S))
10493     return QualType();
10494   // In C++, a prefix increment is the same type as the operand. Otherwise
10495   // (in C or with postfix), the increment is the unqualified type of the
10496   // operand.
10497   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10498     VK = VK_LValue;
10499     OK = Op->getObjectKind();
10500     return ResType;
10501   } else {
10502     VK = VK_RValue;
10503     return ResType.getUnqualifiedType();
10504   }
10505 }
10506 
10507 
10508 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10509 /// This routine allows us to typecheck complex/recursive expressions
10510 /// where the declaration is needed for type checking. We only need to
10511 /// handle cases when the expression references a function designator
10512 /// or is an lvalue. Here are some examples:
10513 ///  - &(x) => x
10514 ///  - &*****f => f for f a function designator.
10515 ///  - &s.xx => s
10516 ///  - &s.zz[1].yy -> s, if zz is an array
10517 ///  - *(x + 1) -> x, if x is an array
10518 ///  - &"123"[2] -> 0
10519 ///  - & __real__ x -> x
10520 static ValueDecl *getPrimaryDecl(Expr *E) {
10521   switch (E->getStmtClass()) {
10522   case Stmt::DeclRefExprClass:
10523     return cast<DeclRefExpr>(E)->getDecl();
10524   case Stmt::MemberExprClass:
10525     // If this is an arrow operator, the address is an offset from
10526     // the base's value, so the object the base refers to is
10527     // irrelevant.
10528     if (cast<MemberExpr>(E)->isArrow())
10529       return nullptr;
10530     // Otherwise, the expression refers to a part of the base
10531     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10532   case Stmt::ArraySubscriptExprClass: {
10533     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10534     // promotion of register arrays earlier.
10535     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10536     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10537       if (ICE->getSubExpr()->getType()->isArrayType())
10538         return getPrimaryDecl(ICE->getSubExpr());
10539     }
10540     return nullptr;
10541   }
10542   case Stmt::UnaryOperatorClass: {
10543     UnaryOperator *UO = cast<UnaryOperator>(E);
10544 
10545     switch(UO->getOpcode()) {
10546     case UO_Real:
10547     case UO_Imag:
10548     case UO_Extension:
10549       return getPrimaryDecl(UO->getSubExpr());
10550     default:
10551       return nullptr;
10552     }
10553   }
10554   case Stmt::ParenExprClass:
10555     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10556   case Stmt::ImplicitCastExprClass:
10557     // If the result of an implicit cast is an l-value, we care about
10558     // the sub-expression; otherwise, the result here doesn't matter.
10559     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10560   default:
10561     return nullptr;
10562   }
10563 }
10564 
10565 namespace {
10566   enum {
10567     AO_Bit_Field = 0,
10568     AO_Vector_Element = 1,
10569     AO_Property_Expansion = 2,
10570     AO_Register_Variable = 3,
10571     AO_No_Error = 4
10572   };
10573 }
10574 /// \brief Diagnose invalid operand for address of operations.
10575 ///
10576 /// \param Type The type of operand which cannot have its address taken.
10577 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10578                                          Expr *E, unsigned Type) {
10579   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10580 }
10581 
10582 /// CheckAddressOfOperand - The operand of & must be either a function
10583 /// designator or an lvalue designating an object. If it is an lvalue, the
10584 /// object cannot be declared with storage class register or be a bit field.
10585 /// Note: The usual conversions are *not* applied to the operand of the &
10586 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10587 /// In C++, the operand might be an overloaded function name, in which case
10588 /// we allow the '&' but retain the overloaded-function type.
10589 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10590   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10591     if (PTy->getKind() == BuiltinType::Overload) {
10592       Expr *E = OrigOp.get()->IgnoreParens();
10593       if (!isa<OverloadExpr>(E)) {
10594         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10595         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10596           << OrigOp.get()->getSourceRange();
10597         return QualType();
10598       }
10599 
10600       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10601       if (isa<UnresolvedMemberExpr>(Ovl))
10602         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10603           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10604             << OrigOp.get()->getSourceRange();
10605           return QualType();
10606         }
10607 
10608       return Context.OverloadTy;
10609     }
10610 
10611     if (PTy->getKind() == BuiltinType::UnknownAny)
10612       return Context.UnknownAnyTy;
10613 
10614     if (PTy->getKind() == BuiltinType::BoundMember) {
10615       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10616         << OrigOp.get()->getSourceRange();
10617       return QualType();
10618     }
10619 
10620     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10621     if (OrigOp.isInvalid()) return QualType();
10622   }
10623 
10624   if (OrigOp.get()->isTypeDependent())
10625     return Context.DependentTy;
10626 
10627   assert(!OrigOp.get()->getType()->isPlaceholderType());
10628 
10629   // Make sure to ignore parentheses in subsequent checks
10630   Expr *op = OrigOp.get()->IgnoreParens();
10631 
10632   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10633   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10634     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10635     return QualType();
10636   }
10637 
10638   if (getLangOpts().C99) {
10639     // Implement C99-only parts of addressof rules.
10640     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10641       if (uOp->getOpcode() == UO_Deref)
10642         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10643         // (assuming the deref expression is valid).
10644         return uOp->getSubExpr()->getType();
10645     }
10646     // Technically, there should be a check for array subscript
10647     // expressions here, but the result of one is always an lvalue anyway.
10648   }
10649   ValueDecl *dcl = getPrimaryDecl(op);
10650 
10651   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10652     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10653                                            op->getLocStart()))
10654       return QualType();
10655 
10656   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10657   unsigned AddressOfError = AO_No_Error;
10658 
10659   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10660     bool sfinae = (bool)isSFINAEContext();
10661     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10662                                   : diag::ext_typecheck_addrof_temporary)
10663       << op->getType() << op->getSourceRange();
10664     if (sfinae)
10665       return QualType();
10666     // Materialize the temporary as an lvalue so that we can take its address.
10667     OrigOp = op =
10668         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10669   } else if (isa<ObjCSelectorExpr>(op)) {
10670     return Context.getPointerType(op->getType());
10671   } else if (lval == Expr::LV_MemberFunction) {
10672     // If it's an instance method, make a member pointer.
10673     // The expression must have exactly the form &A::foo.
10674 
10675     // If the underlying expression isn't a decl ref, give up.
10676     if (!isa<DeclRefExpr>(op)) {
10677       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10678         << OrigOp.get()->getSourceRange();
10679       return QualType();
10680     }
10681     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10682     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10683 
10684     // The id-expression was parenthesized.
10685     if (OrigOp.get() != DRE) {
10686       Diag(OpLoc, diag::err_parens_pointer_member_function)
10687         << OrigOp.get()->getSourceRange();
10688 
10689     // The method was named without a qualifier.
10690     } else if (!DRE->getQualifier()) {
10691       if (MD->getParent()->getName().empty())
10692         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10693           << op->getSourceRange();
10694       else {
10695         SmallString<32> Str;
10696         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10697         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10698           << op->getSourceRange()
10699           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10700       }
10701     }
10702 
10703     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10704     if (isa<CXXDestructorDecl>(MD))
10705       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10706 
10707     QualType MPTy = Context.getMemberPointerType(
10708         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10709     // Under the MS ABI, lock down the inheritance model now.
10710     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10711       (void)isCompleteType(OpLoc, MPTy);
10712     return MPTy;
10713   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10714     // C99 6.5.3.2p1
10715     // The operand must be either an l-value or a function designator
10716     if (!op->getType()->isFunctionType()) {
10717       // Use a special diagnostic for loads from property references.
10718       if (isa<PseudoObjectExpr>(op)) {
10719         AddressOfError = AO_Property_Expansion;
10720       } else {
10721         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10722           << op->getType() << op->getSourceRange();
10723         return QualType();
10724       }
10725     }
10726   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10727     // The operand cannot be a bit-field
10728     AddressOfError = AO_Bit_Field;
10729   } else if (op->getObjectKind() == OK_VectorComponent) {
10730     // The operand cannot be an element of a vector
10731     AddressOfError = AO_Vector_Element;
10732   } else if (dcl) { // C99 6.5.3.2p1
10733     // We have an lvalue with a decl. Make sure the decl is not declared
10734     // with the register storage-class specifier.
10735     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10736       // in C++ it is not error to take address of a register
10737       // variable (c++03 7.1.1P3)
10738       if (vd->getStorageClass() == SC_Register &&
10739           !getLangOpts().CPlusPlus) {
10740         AddressOfError = AO_Register_Variable;
10741       }
10742     } else if (isa<MSPropertyDecl>(dcl)) {
10743       AddressOfError = AO_Property_Expansion;
10744     } else if (isa<FunctionTemplateDecl>(dcl)) {
10745       return Context.OverloadTy;
10746     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10747       // Okay: we can take the address of a field.
10748       // Could be a pointer to member, though, if there is an explicit
10749       // scope qualifier for the class.
10750       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10751         DeclContext *Ctx = dcl->getDeclContext();
10752         if (Ctx && Ctx->isRecord()) {
10753           if (dcl->getType()->isReferenceType()) {
10754             Diag(OpLoc,
10755                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10756               << dcl->getDeclName() << dcl->getType();
10757             return QualType();
10758           }
10759 
10760           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10761             Ctx = Ctx->getParent();
10762 
10763           QualType MPTy = Context.getMemberPointerType(
10764               op->getType(),
10765               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10766           // Under the MS ABI, lock down the inheritance model now.
10767           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10768             (void)isCompleteType(OpLoc, MPTy);
10769           return MPTy;
10770         }
10771       }
10772     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10773                !isa<BindingDecl>(dcl))
10774       llvm_unreachable("Unknown/unexpected decl type");
10775   }
10776 
10777   if (AddressOfError != AO_No_Error) {
10778     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10779     return QualType();
10780   }
10781 
10782   if (lval == Expr::LV_IncompleteVoidType) {
10783     // Taking the address of a void variable is technically illegal, but we
10784     // allow it in cases which are otherwise valid.
10785     // Example: "extern void x; void* y = &x;".
10786     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10787   }
10788 
10789   // If the operand has type "type", the result has type "pointer to type".
10790   if (op->getType()->isObjCObjectType())
10791     return Context.getObjCObjectPointerType(op->getType());
10792 
10793   CheckAddressOfPackedMember(op);
10794 
10795   return Context.getPointerType(op->getType());
10796 }
10797 
10798 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10799   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10800   if (!DRE)
10801     return;
10802   const Decl *D = DRE->getDecl();
10803   if (!D)
10804     return;
10805   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10806   if (!Param)
10807     return;
10808   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10809     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10810       return;
10811   if (FunctionScopeInfo *FD = S.getCurFunction())
10812     if (!FD->ModifiedNonNullParams.count(Param))
10813       FD->ModifiedNonNullParams.insert(Param);
10814 }
10815 
10816 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10817 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10818                                         SourceLocation OpLoc) {
10819   if (Op->isTypeDependent())
10820     return S.Context.DependentTy;
10821 
10822   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10823   if (ConvResult.isInvalid())
10824     return QualType();
10825   Op = ConvResult.get();
10826   QualType OpTy = Op->getType();
10827   QualType Result;
10828 
10829   if (isa<CXXReinterpretCastExpr>(Op)) {
10830     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10831     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10832                                      Op->getSourceRange());
10833   }
10834 
10835   if (const PointerType *PT = OpTy->getAs<PointerType>())
10836   {
10837     Result = PT->getPointeeType();
10838   }
10839   else if (const ObjCObjectPointerType *OPT =
10840              OpTy->getAs<ObjCObjectPointerType>())
10841     Result = OPT->getPointeeType();
10842   else {
10843     ExprResult PR = S.CheckPlaceholderExpr(Op);
10844     if (PR.isInvalid()) return QualType();
10845     if (PR.get() != Op)
10846       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10847   }
10848 
10849   if (Result.isNull()) {
10850     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10851       << OpTy << Op->getSourceRange();
10852     return QualType();
10853   }
10854 
10855   // Note that per both C89 and C99, indirection is always legal, even if Result
10856   // is an incomplete type or void.  It would be possible to warn about
10857   // dereferencing a void pointer, but it's completely well-defined, and such a
10858   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10859   // for pointers to 'void' but is fine for any other pointer type:
10860   //
10861   // C++ [expr.unary.op]p1:
10862   //   [...] the expression to which [the unary * operator] is applied shall
10863   //   be a pointer to an object type, or a pointer to a function type
10864   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10865     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10866       << OpTy << Op->getSourceRange();
10867 
10868   // Dereferences are usually l-values...
10869   VK = VK_LValue;
10870 
10871   // ...except that certain expressions are never l-values in C.
10872   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10873     VK = VK_RValue;
10874 
10875   return Result;
10876 }
10877 
10878 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10879   BinaryOperatorKind Opc;
10880   switch (Kind) {
10881   default: llvm_unreachable("Unknown binop!");
10882   case tok::periodstar:           Opc = BO_PtrMemD; break;
10883   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10884   case tok::star:                 Opc = BO_Mul; break;
10885   case tok::slash:                Opc = BO_Div; break;
10886   case tok::percent:              Opc = BO_Rem; break;
10887   case tok::plus:                 Opc = BO_Add; break;
10888   case tok::minus:                Opc = BO_Sub; break;
10889   case tok::lessless:             Opc = BO_Shl; break;
10890   case tok::greatergreater:       Opc = BO_Shr; break;
10891   case tok::lessequal:            Opc = BO_LE; break;
10892   case tok::less:                 Opc = BO_LT; break;
10893   case tok::greaterequal:         Opc = BO_GE; break;
10894   case tok::greater:              Opc = BO_GT; break;
10895   case tok::exclaimequal:         Opc = BO_NE; break;
10896   case tok::equalequal:           Opc = BO_EQ; break;
10897   case tok::amp:                  Opc = BO_And; break;
10898   case tok::caret:                Opc = BO_Xor; break;
10899   case tok::pipe:                 Opc = BO_Or; break;
10900   case tok::ampamp:               Opc = BO_LAnd; break;
10901   case tok::pipepipe:             Opc = BO_LOr; break;
10902   case tok::equal:                Opc = BO_Assign; break;
10903   case tok::starequal:            Opc = BO_MulAssign; break;
10904   case tok::slashequal:           Opc = BO_DivAssign; break;
10905   case tok::percentequal:         Opc = BO_RemAssign; break;
10906   case tok::plusequal:            Opc = BO_AddAssign; break;
10907   case tok::minusequal:           Opc = BO_SubAssign; break;
10908   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10909   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10910   case tok::ampequal:             Opc = BO_AndAssign; break;
10911   case tok::caretequal:           Opc = BO_XorAssign; break;
10912   case tok::pipeequal:            Opc = BO_OrAssign; break;
10913   case tok::comma:                Opc = BO_Comma; break;
10914   }
10915   return Opc;
10916 }
10917 
10918 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10919   tok::TokenKind Kind) {
10920   UnaryOperatorKind Opc;
10921   switch (Kind) {
10922   default: llvm_unreachable("Unknown unary op!");
10923   case tok::plusplus:     Opc = UO_PreInc; break;
10924   case tok::minusminus:   Opc = UO_PreDec; break;
10925   case tok::amp:          Opc = UO_AddrOf; break;
10926   case tok::star:         Opc = UO_Deref; break;
10927   case tok::plus:         Opc = UO_Plus; break;
10928   case tok::minus:        Opc = UO_Minus; break;
10929   case tok::tilde:        Opc = UO_Not; break;
10930   case tok::exclaim:      Opc = UO_LNot; break;
10931   case tok::kw___real:    Opc = UO_Real; break;
10932   case tok::kw___imag:    Opc = UO_Imag; break;
10933   case tok::kw___extension__: Opc = UO_Extension; break;
10934   }
10935   return Opc;
10936 }
10937 
10938 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10939 /// This warning is only emitted for builtin assignment operations. It is also
10940 /// suppressed in the event of macro expansions.
10941 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10942                                    SourceLocation OpLoc) {
10943   if (!S.ActiveTemplateInstantiations.empty())
10944     return;
10945   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10946     return;
10947   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10948   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10949   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10950   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10951   if (!LHSDeclRef || !RHSDeclRef ||
10952       LHSDeclRef->getLocation().isMacroID() ||
10953       RHSDeclRef->getLocation().isMacroID())
10954     return;
10955   const ValueDecl *LHSDecl =
10956     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10957   const ValueDecl *RHSDecl =
10958     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10959   if (LHSDecl != RHSDecl)
10960     return;
10961   if (LHSDecl->getType().isVolatileQualified())
10962     return;
10963   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10964     if (RefTy->getPointeeType().isVolatileQualified())
10965       return;
10966 
10967   S.Diag(OpLoc, diag::warn_self_assignment)
10968       << LHSDeclRef->getType()
10969       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10970 }
10971 
10972 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10973 /// is usually indicative of introspection within the Objective-C pointer.
10974 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10975                                           SourceLocation OpLoc) {
10976   if (!S.getLangOpts().ObjC1)
10977     return;
10978 
10979   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10980   const Expr *LHS = L.get();
10981   const Expr *RHS = R.get();
10982 
10983   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10984     ObjCPointerExpr = LHS;
10985     OtherExpr = RHS;
10986   }
10987   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10988     ObjCPointerExpr = RHS;
10989     OtherExpr = LHS;
10990   }
10991 
10992   // This warning is deliberately made very specific to reduce false
10993   // positives with logic that uses '&' for hashing.  This logic mainly
10994   // looks for code trying to introspect into tagged pointers, which
10995   // code should generally never do.
10996   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10997     unsigned Diag = diag::warn_objc_pointer_masking;
10998     // Determine if we are introspecting the result of performSelectorXXX.
10999     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11000     // Special case messages to -performSelector and friends, which
11001     // can return non-pointer values boxed in a pointer value.
11002     // Some clients may wish to silence warnings in this subcase.
11003     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11004       Selector S = ME->getSelector();
11005       StringRef SelArg0 = S.getNameForSlot(0);
11006       if (SelArg0.startswith("performSelector"))
11007         Diag = diag::warn_objc_pointer_masking_performSelector;
11008     }
11009 
11010     S.Diag(OpLoc, Diag)
11011       << ObjCPointerExpr->getSourceRange();
11012   }
11013 }
11014 
11015 static NamedDecl *getDeclFromExpr(Expr *E) {
11016   if (!E)
11017     return nullptr;
11018   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11019     return DRE->getDecl();
11020   if (auto *ME = dyn_cast<MemberExpr>(E))
11021     return ME->getMemberDecl();
11022   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11023     return IRE->getDecl();
11024   return nullptr;
11025 }
11026 
11027 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11028 /// operator @p Opc at location @c TokLoc. This routine only supports
11029 /// built-in operations; ActOnBinOp handles overloaded operators.
11030 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11031                                     BinaryOperatorKind Opc,
11032                                     Expr *LHSExpr, Expr *RHSExpr) {
11033   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11034     // The syntax only allows initializer lists on the RHS of assignment,
11035     // so we don't need to worry about accepting invalid code for
11036     // non-assignment operators.
11037     // C++11 5.17p9:
11038     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11039     //   of x = {} is x = T().
11040     InitializationKind Kind =
11041         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11042     InitializedEntity Entity =
11043         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11044     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11045     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11046     if (Init.isInvalid())
11047       return Init;
11048     RHSExpr = Init.get();
11049   }
11050 
11051   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11052   QualType ResultTy;     // Result type of the binary operator.
11053   // The following two variables are used for compound assignment operators
11054   QualType CompLHSTy;    // Type of LHS after promotions for computation
11055   QualType CompResultTy; // Type of computation result
11056   ExprValueKind VK = VK_RValue;
11057   ExprObjectKind OK = OK_Ordinary;
11058 
11059   if (!getLangOpts().CPlusPlus) {
11060     // C cannot handle TypoExpr nodes on either side of a binop because it
11061     // doesn't handle dependent types properly, so make sure any TypoExprs have
11062     // been dealt with before checking the operands.
11063     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11064     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11065       if (Opc != BO_Assign)
11066         return ExprResult(E);
11067       // Avoid correcting the RHS to the same Expr as the LHS.
11068       Decl *D = getDeclFromExpr(E);
11069       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11070     });
11071     if (!LHS.isUsable() || !RHS.isUsable())
11072       return ExprError();
11073   }
11074 
11075   if (getLangOpts().OpenCL) {
11076     QualType LHSTy = LHSExpr->getType();
11077     QualType RHSTy = RHSExpr->getType();
11078     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11079     // the ATOMIC_VAR_INIT macro.
11080     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11081       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11082       if (BO_Assign == Opc)
11083         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11084       else
11085         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11086       return ExprError();
11087     }
11088 
11089     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11090     // only with a builtin functions and therefore should be disallowed here.
11091     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11092         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11093         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11094         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11095       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11096       return ExprError();
11097     }
11098   }
11099 
11100   switch (Opc) {
11101   case BO_Assign:
11102     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11103     if (getLangOpts().CPlusPlus &&
11104         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11105       VK = LHS.get()->getValueKind();
11106       OK = LHS.get()->getObjectKind();
11107     }
11108     if (!ResultTy.isNull()) {
11109       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11110       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11111     }
11112     RecordModifiableNonNullParam(*this, LHS.get());
11113     break;
11114   case BO_PtrMemD:
11115   case BO_PtrMemI:
11116     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11117                                             Opc == BO_PtrMemI);
11118     break;
11119   case BO_Mul:
11120   case BO_Div:
11121     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11122                                            Opc == BO_Div);
11123     break;
11124   case BO_Rem:
11125     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11126     break;
11127   case BO_Add:
11128     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11129     break;
11130   case BO_Sub:
11131     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11132     break;
11133   case BO_Shl:
11134   case BO_Shr:
11135     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11136     break;
11137   case BO_LE:
11138   case BO_LT:
11139   case BO_GE:
11140   case BO_GT:
11141     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11142     break;
11143   case BO_EQ:
11144   case BO_NE:
11145     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11146     break;
11147   case BO_And:
11148     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11149   case BO_Xor:
11150   case BO_Or:
11151     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11152     break;
11153   case BO_LAnd:
11154   case BO_LOr:
11155     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11156     break;
11157   case BO_MulAssign:
11158   case BO_DivAssign:
11159     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11160                                                Opc == BO_DivAssign);
11161     CompLHSTy = CompResultTy;
11162     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11163       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11164     break;
11165   case BO_RemAssign:
11166     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11167     CompLHSTy = CompResultTy;
11168     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11169       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11170     break;
11171   case BO_AddAssign:
11172     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11173     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11174       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11175     break;
11176   case BO_SubAssign:
11177     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11178     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11179       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11180     break;
11181   case BO_ShlAssign:
11182   case BO_ShrAssign:
11183     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11184     CompLHSTy = CompResultTy;
11185     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11186       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11187     break;
11188   case BO_AndAssign:
11189   case BO_OrAssign: // fallthrough
11190     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11191   case BO_XorAssign:
11192     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11193     CompLHSTy = CompResultTy;
11194     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11195       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11196     break;
11197   case BO_Comma:
11198     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11199     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11200       VK = RHS.get()->getValueKind();
11201       OK = RHS.get()->getObjectKind();
11202     }
11203     break;
11204   }
11205   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11206     return ExprError();
11207 
11208   // Check for array bounds violations for both sides of the BinaryOperator
11209   CheckArrayAccess(LHS.get());
11210   CheckArrayAccess(RHS.get());
11211 
11212   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11213     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11214                                                  &Context.Idents.get("object_setClass"),
11215                                                  SourceLocation(), LookupOrdinaryName);
11216     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11217       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11218       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11219       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11220       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11221       FixItHint::CreateInsertion(RHSLocEnd, ")");
11222     }
11223     else
11224       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11225   }
11226   else if (const ObjCIvarRefExpr *OIRE =
11227            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11228     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11229 
11230   if (CompResultTy.isNull())
11231     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11232                                         OK, OpLoc, FPFeatures.fp_contract);
11233   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11234       OK_ObjCProperty) {
11235     VK = VK_LValue;
11236     OK = LHS.get()->getObjectKind();
11237   }
11238   return new (Context) CompoundAssignOperator(
11239       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11240       OpLoc, FPFeatures.fp_contract);
11241 }
11242 
11243 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11244 /// operators are mixed in a way that suggests that the programmer forgot that
11245 /// comparison operators have higher precedence. The most typical example of
11246 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11247 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11248                                       SourceLocation OpLoc, Expr *LHSExpr,
11249                                       Expr *RHSExpr) {
11250   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11251   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11252 
11253   // Check that one of the sides is a comparison operator and the other isn't.
11254   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11255   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11256   if (isLeftComp == isRightComp)
11257     return;
11258 
11259   // Bitwise operations are sometimes used as eager logical ops.
11260   // Don't diagnose this.
11261   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11262   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11263   if (isLeftBitwise || isRightBitwise)
11264     return;
11265 
11266   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11267                                                    OpLoc)
11268                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11269   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11270   SourceRange ParensRange = isLeftComp ?
11271       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11272     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11273 
11274   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11275     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11276   SuggestParentheses(Self, OpLoc,
11277     Self.PDiag(diag::note_precedence_silence) << OpStr,
11278     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11279   SuggestParentheses(Self, OpLoc,
11280     Self.PDiag(diag::note_precedence_bitwise_first)
11281       << BinaryOperator::getOpcodeStr(Opc),
11282     ParensRange);
11283 }
11284 
11285 /// \brief It accepts a '&&' expr that is inside a '||' one.
11286 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11287 /// in parentheses.
11288 static void
11289 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11290                                        BinaryOperator *Bop) {
11291   assert(Bop->getOpcode() == BO_LAnd);
11292   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11293       << Bop->getSourceRange() << OpLoc;
11294   SuggestParentheses(Self, Bop->getOperatorLoc(),
11295     Self.PDiag(diag::note_precedence_silence)
11296       << Bop->getOpcodeStr(),
11297     Bop->getSourceRange());
11298 }
11299 
11300 /// \brief Returns true if the given expression can be evaluated as a constant
11301 /// 'true'.
11302 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11303   bool Res;
11304   return !E->isValueDependent() &&
11305          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11306 }
11307 
11308 /// \brief Returns true if the given expression can be evaluated as a constant
11309 /// 'false'.
11310 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11311   bool Res;
11312   return !E->isValueDependent() &&
11313          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11314 }
11315 
11316 /// \brief Look for '&&' in the left hand of a '||' expr.
11317 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11318                                              Expr *LHSExpr, Expr *RHSExpr) {
11319   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11320     if (Bop->getOpcode() == BO_LAnd) {
11321       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11322       if (EvaluatesAsFalse(S, RHSExpr))
11323         return;
11324       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11325       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11326         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11327     } else if (Bop->getOpcode() == BO_LOr) {
11328       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11329         // If it's "a || b && 1 || c" we didn't warn earlier for
11330         // "a || b && 1", but warn now.
11331         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11332           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11333       }
11334     }
11335   }
11336 }
11337 
11338 /// \brief Look for '&&' in the right hand of a '||' expr.
11339 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11340                                              Expr *LHSExpr, Expr *RHSExpr) {
11341   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11342     if (Bop->getOpcode() == BO_LAnd) {
11343       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11344       if (EvaluatesAsFalse(S, LHSExpr))
11345         return;
11346       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11347       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11348         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11349     }
11350   }
11351 }
11352 
11353 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11354 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11355 /// the '&' expression in parentheses.
11356 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11357                                          SourceLocation OpLoc, Expr *SubExpr) {
11358   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11359     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11360       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11361         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11362         << Bop->getSourceRange() << OpLoc;
11363       SuggestParentheses(S, Bop->getOperatorLoc(),
11364         S.PDiag(diag::note_precedence_silence)
11365           << Bop->getOpcodeStr(),
11366         Bop->getSourceRange());
11367     }
11368   }
11369 }
11370 
11371 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11372                                     Expr *SubExpr, StringRef Shift) {
11373   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11374     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11375       StringRef Op = Bop->getOpcodeStr();
11376       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11377           << Bop->getSourceRange() << OpLoc << Shift << Op;
11378       SuggestParentheses(S, Bop->getOperatorLoc(),
11379           S.PDiag(diag::note_precedence_silence) << Op,
11380           Bop->getSourceRange());
11381     }
11382   }
11383 }
11384 
11385 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11386                                  Expr *LHSExpr, Expr *RHSExpr) {
11387   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11388   if (!OCE)
11389     return;
11390 
11391   FunctionDecl *FD = OCE->getDirectCallee();
11392   if (!FD || !FD->isOverloadedOperator())
11393     return;
11394 
11395   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11396   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11397     return;
11398 
11399   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11400       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11401       << (Kind == OO_LessLess);
11402   SuggestParentheses(S, OCE->getOperatorLoc(),
11403                      S.PDiag(diag::note_precedence_silence)
11404                          << (Kind == OO_LessLess ? "<<" : ">>"),
11405                      OCE->getSourceRange());
11406   SuggestParentheses(S, OpLoc,
11407                      S.PDiag(diag::note_evaluate_comparison_first),
11408                      SourceRange(OCE->getArg(1)->getLocStart(),
11409                                  RHSExpr->getLocEnd()));
11410 }
11411 
11412 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11413 /// precedence.
11414 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11415                                     SourceLocation OpLoc, Expr *LHSExpr,
11416                                     Expr *RHSExpr){
11417   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11418   if (BinaryOperator::isBitwiseOp(Opc))
11419     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11420 
11421   // Diagnose "arg1 & arg2 | arg3"
11422   if ((Opc == BO_Or || Opc == BO_Xor) &&
11423       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11424     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11425     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11426   }
11427 
11428   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11429   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11430   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11431     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11432     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11433   }
11434 
11435   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11436       || Opc == BO_Shr) {
11437     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11438     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11439     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11440   }
11441 
11442   // Warn on overloaded shift operators and comparisons, such as:
11443   // cout << 5 == 4;
11444   if (BinaryOperator::isComparisonOp(Opc))
11445     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11446 }
11447 
11448 // Binary Operators.  'Tok' is the token for the operator.
11449 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11450                             tok::TokenKind Kind,
11451                             Expr *LHSExpr, Expr *RHSExpr) {
11452   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11453   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11454   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11455 
11456   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11457   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11458 
11459   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11460 }
11461 
11462 /// Build an overloaded binary operator expression in the given scope.
11463 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11464                                        BinaryOperatorKind Opc,
11465                                        Expr *LHS, Expr *RHS) {
11466   // Find all of the overloaded operators visible from this
11467   // point. We perform both an operator-name lookup from the local
11468   // scope and an argument-dependent lookup based on the types of
11469   // the arguments.
11470   UnresolvedSet<16> Functions;
11471   OverloadedOperatorKind OverOp
11472     = BinaryOperator::getOverloadedOperator(Opc);
11473   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11474     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11475                                    RHS->getType(), Functions);
11476 
11477   // Build the (potentially-overloaded, potentially-dependent)
11478   // binary operation.
11479   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11480 }
11481 
11482 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11483                             BinaryOperatorKind Opc,
11484                             Expr *LHSExpr, Expr *RHSExpr) {
11485   // We want to end up calling one of checkPseudoObjectAssignment
11486   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11487   // both expressions are overloadable or either is type-dependent),
11488   // or CreateBuiltinBinOp (in any other case).  We also want to get
11489   // any placeholder types out of the way.
11490 
11491   // Handle pseudo-objects in the LHS.
11492   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11493     // Assignments with a pseudo-object l-value need special analysis.
11494     if (pty->getKind() == BuiltinType::PseudoObject &&
11495         BinaryOperator::isAssignmentOp(Opc))
11496       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11497 
11498     // Don't resolve overloads if the other type is overloadable.
11499     if (pty->getKind() == BuiltinType::Overload) {
11500       // We can't actually test that if we still have a placeholder,
11501       // though.  Fortunately, none of the exceptions we see in that
11502       // code below are valid when the LHS is an overload set.  Note
11503       // that an overload set can be dependently-typed, but it never
11504       // instantiates to having an overloadable type.
11505       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11506       if (resolvedRHS.isInvalid()) return ExprError();
11507       RHSExpr = resolvedRHS.get();
11508 
11509       if (RHSExpr->isTypeDependent() ||
11510           RHSExpr->getType()->isOverloadableType())
11511         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11512     }
11513 
11514     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11515     if (LHS.isInvalid()) return ExprError();
11516     LHSExpr = LHS.get();
11517   }
11518 
11519   // Handle pseudo-objects in the RHS.
11520   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11521     // An overload in the RHS can potentially be resolved by the type
11522     // being assigned to.
11523     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11524       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11525         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11526 
11527       if (LHSExpr->getType()->isOverloadableType())
11528         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11529 
11530       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11531     }
11532 
11533     // Don't resolve overloads if the other type is overloadable.
11534     if (pty->getKind() == BuiltinType::Overload &&
11535         LHSExpr->getType()->isOverloadableType())
11536       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11537 
11538     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11539     if (!resolvedRHS.isUsable()) return ExprError();
11540     RHSExpr = resolvedRHS.get();
11541   }
11542 
11543   if (getLangOpts().CPlusPlus) {
11544     // If either expression is type-dependent, always build an
11545     // overloaded op.
11546     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11547       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11548 
11549     // Otherwise, build an overloaded op if either expression has an
11550     // overloadable type.
11551     if (LHSExpr->getType()->isOverloadableType() ||
11552         RHSExpr->getType()->isOverloadableType())
11553       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11554   }
11555 
11556   // Build a built-in binary operation.
11557   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11558 }
11559 
11560 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11561                                       UnaryOperatorKind Opc,
11562                                       Expr *InputExpr) {
11563   ExprResult Input = InputExpr;
11564   ExprValueKind VK = VK_RValue;
11565   ExprObjectKind OK = OK_Ordinary;
11566   QualType resultType;
11567   if (getLangOpts().OpenCL) {
11568     QualType Ty = InputExpr->getType();
11569     // The only legal unary operation for atomics is '&'.
11570     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11571     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11572     // only with a builtin functions and therefore should be disallowed here.
11573         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11574         || Ty->isBlockPointerType())) {
11575       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11576                        << InputExpr->getType()
11577                        << Input.get()->getSourceRange());
11578     }
11579   }
11580   switch (Opc) {
11581   case UO_PreInc:
11582   case UO_PreDec:
11583   case UO_PostInc:
11584   case UO_PostDec:
11585     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11586                                                 OpLoc,
11587                                                 Opc == UO_PreInc ||
11588                                                 Opc == UO_PostInc,
11589                                                 Opc == UO_PreInc ||
11590                                                 Opc == UO_PreDec);
11591     break;
11592   case UO_AddrOf:
11593     resultType = CheckAddressOfOperand(Input, OpLoc);
11594     RecordModifiableNonNullParam(*this, InputExpr);
11595     break;
11596   case UO_Deref: {
11597     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11598     if (Input.isInvalid()) return ExprError();
11599     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11600     break;
11601   }
11602   case UO_Plus:
11603   case UO_Minus:
11604     Input = UsualUnaryConversions(Input.get());
11605     if (Input.isInvalid()) return ExprError();
11606     resultType = Input.get()->getType();
11607     if (resultType->isDependentType())
11608       break;
11609     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11610       break;
11611     else if (resultType->isVectorType() &&
11612              // The z vector extensions don't allow + or - with bool vectors.
11613              (!Context.getLangOpts().ZVector ||
11614               resultType->getAs<VectorType>()->getVectorKind() !=
11615               VectorType::AltiVecBool))
11616       break;
11617     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11618              Opc == UO_Plus &&
11619              resultType->isPointerType())
11620       break;
11621 
11622     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11623       << resultType << Input.get()->getSourceRange());
11624 
11625   case UO_Not: // bitwise complement
11626     Input = UsualUnaryConversions(Input.get());
11627     if (Input.isInvalid())
11628       return ExprError();
11629     resultType = Input.get()->getType();
11630     if (resultType->isDependentType())
11631       break;
11632     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11633     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11634       // C99 does not support '~' for complex conjugation.
11635       Diag(OpLoc, diag::ext_integer_complement_complex)
11636           << resultType << Input.get()->getSourceRange();
11637     else if (resultType->hasIntegerRepresentation())
11638       break;
11639     else if (resultType->isExtVectorType()) {
11640       if (Context.getLangOpts().OpenCL) {
11641         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11642         // on vector float types.
11643         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11644         if (!T->isIntegerType())
11645           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11646                            << resultType << Input.get()->getSourceRange());
11647       }
11648       break;
11649     } else {
11650       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11651                        << resultType << Input.get()->getSourceRange());
11652     }
11653     break;
11654 
11655   case UO_LNot: // logical negation
11656     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11657     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11658     if (Input.isInvalid()) return ExprError();
11659     resultType = Input.get()->getType();
11660 
11661     // Though we still have to promote half FP to float...
11662     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11663       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11664       resultType = Context.FloatTy;
11665     }
11666 
11667     if (resultType->isDependentType())
11668       break;
11669     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11670       // C99 6.5.3.3p1: ok, fallthrough;
11671       if (Context.getLangOpts().CPlusPlus) {
11672         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11673         // operand contextually converted to bool.
11674         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11675                                   ScalarTypeToBooleanCastKind(resultType));
11676       } else if (Context.getLangOpts().OpenCL &&
11677                  Context.getLangOpts().OpenCLVersion < 120) {
11678         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11679         // operate on scalar float types.
11680         if (!resultType->isIntegerType())
11681           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11682                            << resultType << Input.get()->getSourceRange());
11683       }
11684     } else if (resultType->isExtVectorType()) {
11685       if (Context.getLangOpts().OpenCL &&
11686           Context.getLangOpts().OpenCLVersion < 120) {
11687         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11688         // operate on vector float types.
11689         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11690         if (!T->isIntegerType())
11691           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11692                            << resultType << Input.get()->getSourceRange());
11693       }
11694       // Vector logical not returns the signed variant of the operand type.
11695       resultType = GetSignedVectorType(resultType);
11696       break;
11697     } else {
11698       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11699         << resultType << Input.get()->getSourceRange());
11700     }
11701 
11702     // LNot always has type int. C99 6.5.3.3p5.
11703     // In C++, it's bool. C++ 5.3.1p8
11704     resultType = Context.getLogicalOperationType();
11705     break;
11706   case UO_Real:
11707   case UO_Imag:
11708     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11709     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11710     // complex l-values to ordinary l-values and all other values to r-values.
11711     if (Input.isInvalid()) return ExprError();
11712     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11713       if (Input.get()->getValueKind() != VK_RValue &&
11714           Input.get()->getObjectKind() == OK_Ordinary)
11715         VK = Input.get()->getValueKind();
11716     } else if (!getLangOpts().CPlusPlus) {
11717       // In C, a volatile scalar is read by __imag. In C++, it is not.
11718       Input = DefaultLvalueConversion(Input.get());
11719     }
11720     break;
11721   case UO_Extension:
11722   case UO_Coawait:
11723     resultType = Input.get()->getType();
11724     VK = Input.get()->getValueKind();
11725     OK = Input.get()->getObjectKind();
11726     break;
11727   }
11728   if (resultType.isNull() || Input.isInvalid())
11729     return ExprError();
11730 
11731   // Check for array bounds violations in the operand of the UnaryOperator,
11732   // except for the '*' and '&' operators that have to be handled specially
11733   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11734   // that are explicitly defined as valid by the standard).
11735   if (Opc != UO_AddrOf && Opc != UO_Deref)
11736     CheckArrayAccess(Input.get());
11737 
11738   return new (Context)
11739       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11740 }
11741 
11742 /// \brief Determine whether the given expression is a qualified member
11743 /// access expression, of a form that could be turned into a pointer to member
11744 /// with the address-of operator.
11745 static bool isQualifiedMemberAccess(Expr *E) {
11746   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11747     if (!DRE->getQualifier())
11748       return false;
11749 
11750     ValueDecl *VD = DRE->getDecl();
11751     if (!VD->isCXXClassMember())
11752       return false;
11753 
11754     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11755       return true;
11756     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11757       return Method->isInstance();
11758 
11759     return false;
11760   }
11761 
11762   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11763     if (!ULE->getQualifier())
11764       return false;
11765 
11766     for (NamedDecl *D : ULE->decls()) {
11767       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11768         if (Method->isInstance())
11769           return true;
11770       } else {
11771         // Overload set does not contain methods.
11772         break;
11773       }
11774     }
11775 
11776     return false;
11777   }
11778 
11779   return false;
11780 }
11781 
11782 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11783                               UnaryOperatorKind Opc, Expr *Input) {
11784   // First things first: handle placeholders so that the
11785   // overloaded-operator check considers the right type.
11786   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11787     // Increment and decrement of pseudo-object references.
11788     if (pty->getKind() == BuiltinType::PseudoObject &&
11789         UnaryOperator::isIncrementDecrementOp(Opc))
11790       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11791 
11792     // extension is always a builtin operator.
11793     if (Opc == UO_Extension)
11794       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11795 
11796     // & gets special logic for several kinds of placeholder.
11797     // The builtin code knows what to do.
11798     if (Opc == UO_AddrOf &&
11799         (pty->getKind() == BuiltinType::Overload ||
11800          pty->getKind() == BuiltinType::UnknownAny ||
11801          pty->getKind() == BuiltinType::BoundMember))
11802       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11803 
11804     // Anything else needs to be handled now.
11805     ExprResult Result = CheckPlaceholderExpr(Input);
11806     if (Result.isInvalid()) return ExprError();
11807     Input = Result.get();
11808   }
11809 
11810   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11811       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11812       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11813     // Find all of the overloaded operators visible from this
11814     // point. We perform both an operator-name lookup from the local
11815     // scope and an argument-dependent lookup based on the types of
11816     // the arguments.
11817     UnresolvedSet<16> Functions;
11818     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11819     if (S && OverOp != OO_None)
11820       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11821                                    Functions);
11822 
11823     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11824   }
11825 
11826   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11827 }
11828 
11829 // Unary Operators.  'Tok' is the token for the operator.
11830 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11831                               tok::TokenKind Op, Expr *Input) {
11832   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11833 }
11834 
11835 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11836 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11837                                 LabelDecl *TheDecl) {
11838   TheDecl->markUsed(Context);
11839   // Create the AST node.  The address of a label always has type 'void*'.
11840   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11841                                      Context.getPointerType(Context.VoidTy));
11842 }
11843 
11844 /// Given the last statement in a statement-expression, check whether
11845 /// the result is a producing expression (like a call to an
11846 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11847 /// release out of the full-expression.  Otherwise, return null.
11848 /// Cannot fail.
11849 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11850   // Should always be wrapped with one of these.
11851   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11852   if (!cleanups) return nullptr;
11853 
11854   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11855   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11856     return nullptr;
11857 
11858   // Splice out the cast.  This shouldn't modify any interesting
11859   // features of the statement.
11860   Expr *producer = cast->getSubExpr();
11861   assert(producer->getType() == cast->getType());
11862   assert(producer->getValueKind() == cast->getValueKind());
11863   cleanups->setSubExpr(producer);
11864   return cleanups;
11865 }
11866 
11867 void Sema::ActOnStartStmtExpr() {
11868   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11869 }
11870 
11871 void Sema::ActOnStmtExprError() {
11872   // Note that function is also called by TreeTransform when leaving a
11873   // StmtExpr scope without rebuilding anything.
11874 
11875   DiscardCleanupsInEvaluationContext();
11876   PopExpressionEvaluationContext();
11877 }
11878 
11879 ExprResult
11880 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11881                     SourceLocation RPLoc) { // "({..})"
11882   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11883   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11884 
11885   if (hasAnyUnrecoverableErrorsInThisFunction())
11886     DiscardCleanupsInEvaluationContext();
11887   assert(!Cleanup.exprNeedsCleanups() &&
11888          "cleanups within StmtExpr not correctly bound!");
11889   PopExpressionEvaluationContext();
11890 
11891   // FIXME: there are a variety of strange constraints to enforce here, for
11892   // example, it is not possible to goto into a stmt expression apparently.
11893   // More semantic analysis is needed.
11894 
11895   // If there are sub-stmts in the compound stmt, take the type of the last one
11896   // as the type of the stmtexpr.
11897   QualType Ty = Context.VoidTy;
11898   bool StmtExprMayBindToTemp = false;
11899   if (!Compound->body_empty()) {
11900     Stmt *LastStmt = Compound->body_back();
11901     LabelStmt *LastLabelStmt = nullptr;
11902     // If LastStmt is a label, skip down through into the body.
11903     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11904       LastLabelStmt = Label;
11905       LastStmt = Label->getSubStmt();
11906     }
11907 
11908     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11909       // Do function/array conversion on the last expression, but not
11910       // lvalue-to-rvalue.  However, initialize an unqualified type.
11911       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11912       if (LastExpr.isInvalid())
11913         return ExprError();
11914       Ty = LastExpr.get()->getType().getUnqualifiedType();
11915 
11916       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11917         // In ARC, if the final expression ends in a consume, splice
11918         // the consume out and bind it later.  In the alternate case
11919         // (when dealing with a retainable type), the result
11920         // initialization will create a produce.  In both cases the
11921         // result will be +1, and we'll need to balance that out with
11922         // a bind.
11923         if (Expr *rebuiltLastStmt
11924               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11925           LastExpr = rebuiltLastStmt;
11926         } else {
11927           LastExpr = PerformCopyInitialization(
11928                             InitializedEntity::InitializeResult(LPLoc,
11929                                                                 Ty,
11930                                                                 false),
11931                                                    SourceLocation(),
11932                                                LastExpr);
11933         }
11934 
11935         if (LastExpr.isInvalid())
11936           return ExprError();
11937         if (LastExpr.get() != nullptr) {
11938           if (!LastLabelStmt)
11939             Compound->setLastStmt(LastExpr.get());
11940           else
11941             LastLabelStmt->setSubStmt(LastExpr.get());
11942           StmtExprMayBindToTemp = true;
11943         }
11944       }
11945     }
11946   }
11947 
11948   // FIXME: Check that expression type is complete/non-abstract; statement
11949   // expressions are not lvalues.
11950   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11951   if (StmtExprMayBindToTemp)
11952     return MaybeBindToTemporary(ResStmtExpr);
11953   return ResStmtExpr;
11954 }
11955 
11956 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11957                                       TypeSourceInfo *TInfo,
11958                                       ArrayRef<OffsetOfComponent> Components,
11959                                       SourceLocation RParenLoc) {
11960   QualType ArgTy = TInfo->getType();
11961   bool Dependent = ArgTy->isDependentType();
11962   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11963 
11964   // We must have at least one component that refers to the type, and the first
11965   // one is known to be a field designator.  Verify that the ArgTy represents
11966   // a struct/union/class.
11967   if (!Dependent && !ArgTy->isRecordType())
11968     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11969                        << ArgTy << TypeRange);
11970 
11971   // Type must be complete per C99 7.17p3 because a declaring a variable
11972   // with an incomplete type would be ill-formed.
11973   if (!Dependent
11974       && RequireCompleteType(BuiltinLoc, ArgTy,
11975                              diag::err_offsetof_incomplete_type, TypeRange))
11976     return ExprError();
11977 
11978   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11979   // GCC extension, diagnose them.
11980   // FIXME: This diagnostic isn't actually visible because the location is in
11981   // a system header!
11982   if (Components.size() != 1)
11983     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11984       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11985 
11986   bool DidWarnAboutNonPOD = false;
11987   QualType CurrentType = ArgTy;
11988   SmallVector<OffsetOfNode, 4> Comps;
11989   SmallVector<Expr*, 4> Exprs;
11990   for (const OffsetOfComponent &OC : Components) {
11991     if (OC.isBrackets) {
11992       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11993       if (!CurrentType->isDependentType()) {
11994         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11995         if(!AT)
11996           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11997                            << CurrentType);
11998         CurrentType = AT->getElementType();
11999       } else
12000         CurrentType = Context.DependentTy;
12001 
12002       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12003       if (IdxRval.isInvalid())
12004         return ExprError();
12005       Expr *Idx = IdxRval.get();
12006 
12007       // The expression must be an integral expression.
12008       // FIXME: An integral constant expression?
12009       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12010           !Idx->getType()->isIntegerType())
12011         return ExprError(Diag(Idx->getLocStart(),
12012                               diag::err_typecheck_subscript_not_integer)
12013                          << Idx->getSourceRange());
12014 
12015       // Record this array index.
12016       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12017       Exprs.push_back(Idx);
12018       continue;
12019     }
12020 
12021     // Offset of a field.
12022     if (CurrentType->isDependentType()) {
12023       // We have the offset of a field, but we can't look into the dependent
12024       // type. Just record the identifier of the field.
12025       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12026       CurrentType = Context.DependentTy;
12027       continue;
12028     }
12029 
12030     // We need to have a complete type to look into.
12031     if (RequireCompleteType(OC.LocStart, CurrentType,
12032                             diag::err_offsetof_incomplete_type))
12033       return ExprError();
12034 
12035     // Look for the designated field.
12036     const RecordType *RC = CurrentType->getAs<RecordType>();
12037     if (!RC)
12038       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12039                        << CurrentType);
12040     RecordDecl *RD = RC->getDecl();
12041 
12042     // C++ [lib.support.types]p5:
12043     //   The macro offsetof accepts a restricted set of type arguments in this
12044     //   International Standard. type shall be a POD structure or a POD union
12045     //   (clause 9).
12046     // C++11 [support.types]p4:
12047     //   If type is not a standard-layout class (Clause 9), the results are
12048     //   undefined.
12049     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12050       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12051       unsigned DiagID =
12052         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12053                             : diag::ext_offsetof_non_pod_type;
12054 
12055       if (!IsSafe && !DidWarnAboutNonPOD &&
12056           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12057                               PDiag(DiagID)
12058                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12059                               << CurrentType))
12060         DidWarnAboutNonPOD = true;
12061     }
12062 
12063     // Look for the field.
12064     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12065     LookupQualifiedName(R, RD);
12066     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12067     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12068     if (!MemberDecl) {
12069       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12070         MemberDecl = IndirectMemberDecl->getAnonField();
12071     }
12072 
12073     if (!MemberDecl)
12074       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12075                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12076                                                               OC.LocEnd));
12077 
12078     // C99 7.17p3:
12079     //   (If the specified member is a bit-field, the behavior is undefined.)
12080     //
12081     // We diagnose this as an error.
12082     if (MemberDecl->isBitField()) {
12083       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12084         << MemberDecl->getDeclName()
12085         << SourceRange(BuiltinLoc, RParenLoc);
12086       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12087       return ExprError();
12088     }
12089 
12090     RecordDecl *Parent = MemberDecl->getParent();
12091     if (IndirectMemberDecl)
12092       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12093 
12094     // If the member was found in a base class, introduce OffsetOfNodes for
12095     // the base class indirections.
12096     CXXBasePaths Paths;
12097     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12098                       Paths)) {
12099       if (Paths.getDetectedVirtual()) {
12100         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12101           << MemberDecl->getDeclName()
12102           << SourceRange(BuiltinLoc, RParenLoc);
12103         return ExprError();
12104       }
12105 
12106       CXXBasePath &Path = Paths.front();
12107       for (const CXXBasePathElement &B : Path)
12108         Comps.push_back(OffsetOfNode(B.Base));
12109     }
12110 
12111     if (IndirectMemberDecl) {
12112       for (auto *FI : IndirectMemberDecl->chain()) {
12113         assert(isa<FieldDecl>(FI));
12114         Comps.push_back(OffsetOfNode(OC.LocStart,
12115                                      cast<FieldDecl>(FI), OC.LocEnd));
12116       }
12117     } else
12118       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12119 
12120     CurrentType = MemberDecl->getType().getNonReferenceType();
12121   }
12122 
12123   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12124                               Comps, Exprs, RParenLoc);
12125 }
12126 
12127 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12128                                       SourceLocation BuiltinLoc,
12129                                       SourceLocation TypeLoc,
12130                                       ParsedType ParsedArgTy,
12131                                       ArrayRef<OffsetOfComponent> Components,
12132                                       SourceLocation RParenLoc) {
12133 
12134   TypeSourceInfo *ArgTInfo;
12135   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12136   if (ArgTy.isNull())
12137     return ExprError();
12138 
12139   if (!ArgTInfo)
12140     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12141 
12142   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12143 }
12144 
12145 
12146 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12147                                  Expr *CondExpr,
12148                                  Expr *LHSExpr, Expr *RHSExpr,
12149                                  SourceLocation RPLoc) {
12150   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12151 
12152   ExprValueKind VK = VK_RValue;
12153   ExprObjectKind OK = OK_Ordinary;
12154   QualType resType;
12155   bool ValueDependent = false;
12156   bool CondIsTrue = false;
12157   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12158     resType = Context.DependentTy;
12159     ValueDependent = true;
12160   } else {
12161     // The conditional expression is required to be a constant expression.
12162     llvm::APSInt condEval(32);
12163     ExprResult CondICE
12164       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12165           diag::err_typecheck_choose_expr_requires_constant, false);
12166     if (CondICE.isInvalid())
12167       return ExprError();
12168     CondExpr = CondICE.get();
12169     CondIsTrue = condEval.getZExtValue();
12170 
12171     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12172     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12173 
12174     resType = ActiveExpr->getType();
12175     ValueDependent = ActiveExpr->isValueDependent();
12176     VK = ActiveExpr->getValueKind();
12177     OK = ActiveExpr->getObjectKind();
12178   }
12179 
12180   return new (Context)
12181       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12182                  CondIsTrue, resType->isDependentType(), ValueDependent);
12183 }
12184 
12185 //===----------------------------------------------------------------------===//
12186 // Clang Extensions.
12187 //===----------------------------------------------------------------------===//
12188 
12189 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12190 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12191   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12192 
12193   if (LangOpts.CPlusPlus) {
12194     Decl *ManglingContextDecl;
12195     if (MangleNumberingContext *MCtx =
12196             getCurrentMangleNumberContext(Block->getDeclContext(),
12197                                           ManglingContextDecl)) {
12198       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12199       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12200     }
12201   }
12202 
12203   PushBlockScope(CurScope, Block);
12204   CurContext->addDecl(Block);
12205   if (CurScope)
12206     PushDeclContext(CurScope, Block);
12207   else
12208     CurContext = Block;
12209 
12210   getCurBlock()->HasImplicitReturnType = true;
12211 
12212   // Enter a new evaluation context to insulate the block from any
12213   // cleanups from the enclosing full-expression.
12214   PushExpressionEvaluationContext(PotentiallyEvaluated);
12215 }
12216 
12217 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12218                                Scope *CurScope) {
12219   assert(ParamInfo.getIdentifier() == nullptr &&
12220          "block-id should have no identifier!");
12221   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12222   BlockScopeInfo *CurBlock = getCurBlock();
12223 
12224   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12225   QualType T = Sig->getType();
12226 
12227   // FIXME: We should allow unexpanded parameter packs here, but that would,
12228   // in turn, make the block expression contain unexpanded parameter packs.
12229   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12230     // Drop the parameters.
12231     FunctionProtoType::ExtProtoInfo EPI;
12232     EPI.HasTrailingReturn = false;
12233     EPI.TypeQuals |= DeclSpec::TQ_const;
12234     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12235     Sig = Context.getTrivialTypeSourceInfo(T);
12236   }
12237 
12238   // GetTypeForDeclarator always produces a function type for a block
12239   // literal signature.  Furthermore, it is always a FunctionProtoType
12240   // unless the function was written with a typedef.
12241   assert(T->isFunctionType() &&
12242          "GetTypeForDeclarator made a non-function block signature");
12243 
12244   // Look for an explicit signature in that function type.
12245   FunctionProtoTypeLoc ExplicitSignature;
12246 
12247   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12248   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12249 
12250     // Check whether that explicit signature was synthesized by
12251     // GetTypeForDeclarator.  If so, don't save that as part of the
12252     // written signature.
12253     if (ExplicitSignature.getLocalRangeBegin() ==
12254         ExplicitSignature.getLocalRangeEnd()) {
12255       // This would be much cheaper if we stored TypeLocs instead of
12256       // TypeSourceInfos.
12257       TypeLoc Result = ExplicitSignature.getReturnLoc();
12258       unsigned Size = Result.getFullDataSize();
12259       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12260       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12261 
12262       ExplicitSignature = FunctionProtoTypeLoc();
12263     }
12264   }
12265 
12266   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12267   CurBlock->FunctionType = T;
12268 
12269   const FunctionType *Fn = T->getAs<FunctionType>();
12270   QualType RetTy = Fn->getReturnType();
12271   bool isVariadic =
12272     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12273 
12274   CurBlock->TheDecl->setIsVariadic(isVariadic);
12275 
12276   // Context.DependentTy is used as a placeholder for a missing block
12277   // return type.  TODO:  what should we do with declarators like:
12278   //   ^ * { ... }
12279   // If the answer is "apply template argument deduction"....
12280   if (RetTy != Context.DependentTy) {
12281     CurBlock->ReturnType = RetTy;
12282     CurBlock->TheDecl->setBlockMissingReturnType(false);
12283     CurBlock->HasImplicitReturnType = false;
12284   }
12285 
12286   // Push block parameters from the declarator if we had them.
12287   SmallVector<ParmVarDecl*, 8> Params;
12288   if (ExplicitSignature) {
12289     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12290       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12291       if (Param->getIdentifier() == nullptr &&
12292           !Param->isImplicit() &&
12293           !Param->isInvalidDecl() &&
12294           !getLangOpts().CPlusPlus)
12295         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12296       Params.push_back(Param);
12297     }
12298 
12299   // Fake up parameter variables if we have a typedef, like
12300   //   ^ fntype { ... }
12301   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12302     for (const auto &I : Fn->param_types()) {
12303       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12304           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12305       Params.push_back(Param);
12306     }
12307   }
12308 
12309   // Set the parameters on the block decl.
12310   if (!Params.empty()) {
12311     CurBlock->TheDecl->setParams(Params);
12312     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12313                              /*CheckParameterNames=*/false);
12314   }
12315 
12316   // Finally we can process decl attributes.
12317   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12318 
12319   // Put the parameter variables in scope.
12320   for (auto AI : CurBlock->TheDecl->parameters()) {
12321     AI->setOwningFunction(CurBlock->TheDecl);
12322 
12323     // If this has an identifier, add it to the scope stack.
12324     if (AI->getIdentifier()) {
12325       CheckShadow(CurBlock->TheScope, AI);
12326 
12327       PushOnScopeChains(AI, CurBlock->TheScope);
12328     }
12329   }
12330 }
12331 
12332 /// ActOnBlockError - If there is an error parsing a block, this callback
12333 /// is invoked to pop the information about the block from the action impl.
12334 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12335   // Leave the expression-evaluation context.
12336   DiscardCleanupsInEvaluationContext();
12337   PopExpressionEvaluationContext();
12338 
12339   // Pop off CurBlock, handle nested blocks.
12340   PopDeclContext();
12341   PopFunctionScopeInfo();
12342 }
12343 
12344 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12345 /// literal was successfully completed.  ^(int x){...}
12346 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12347                                     Stmt *Body, Scope *CurScope) {
12348   // If blocks are disabled, emit an error.
12349   if (!LangOpts.Blocks)
12350     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12351 
12352   // Leave the expression-evaluation context.
12353   if (hasAnyUnrecoverableErrorsInThisFunction())
12354     DiscardCleanupsInEvaluationContext();
12355   assert(!Cleanup.exprNeedsCleanups() &&
12356          "cleanups within block not correctly bound!");
12357   PopExpressionEvaluationContext();
12358 
12359   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12360 
12361   if (BSI->HasImplicitReturnType)
12362     deduceClosureReturnType(*BSI);
12363 
12364   PopDeclContext();
12365 
12366   QualType RetTy = Context.VoidTy;
12367   if (!BSI->ReturnType.isNull())
12368     RetTy = BSI->ReturnType;
12369 
12370   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12371   QualType BlockTy;
12372 
12373   // Set the captured variables on the block.
12374   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12375   SmallVector<BlockDecl::Capture, 4> Captures;
12376   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12377     if (Cap.isThisCapture())
12378       continue;
12379     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12380                               Cap.isNested(), Cap.getInitExpr());
12381     Captures.push_back(NewCap);
12382   }
12383   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12384 
12385   // If the user wrote a function type in some form, try to use that.
12386   if (!BSI->FunctionType.isNull()) {
12387     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12388 
12389     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12390     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12391 
12392     // Turn protoless block types into nullary block types.
12393     if (isa<FunctionNoProtoType>(FTy)) {
12394       FunctionProtoType::ExtProtoInfo EPI;
12395       EPI.ExtInfo = Ext;
12396       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12397 
12398     // Otherwise, if we don't need to change anything about the function type,
12399     // preserve its sugar structure.
12400     } else if (FTy->getReturnType() == RetTy &&
12401                (!NoReturn || FTy->getNoReturnAttr())) {
12402       BlockTy = BSI->FunctionType;
12403 
12404     // Otherwise, make the minimal modifications to the function type.
12405     } else {
12406       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12407       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12408       EPI.TypeQuals = 0; // FIXME: silently?
12409       EPI.ExtInfo = Ext;
12410       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12411     }
12412 
12413   // If we don't have a function type, just build one from nothing.
12414   } else {
12415     FunctionProtoType::ExtProtoInfo EPI;
12416     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12417     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12418   }
12419 
12420   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12421   BlockTy = Context.getBlockPointerType(BlockTy);
12422 
12423   // If needed, diagnose invalid gotos and switches in the block.
12424   if (getCurFunction()->NeedsScopeChecking() &&
12425       !PP.isCodeCompletionEnabled())
12426     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12427 
12428   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12429 
12430   // Try to apply the named return value optimization. We have to check again
12431   // if we can do this, though, because blocks keep return statements around
12432   // to deduce an implicit return type.
12433   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12434       !BSI->TheDecl->isDependentContext())
12435     computeNRVO(Body, BSI);
12436 
12437   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12438   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12439   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12440 
12441   // If the block isn't obviously global, i.e. it captures anything at
12442   // all, then we need to do a few things in the surrounding context:
12443   if (Result->getBlockDecl()->hasCaptures()) {
12444     // First, this expression has a new cleanup object.
12445     ExprCleanupObjects.push_back(Result->getBlockDecl());
12446     Cleanup.setExprNeedsCleanups(true);
12447 
12448     // It also gets a branch-protected scope if any of the captured
12449     // variables needs destruction.
12450     for (const auto &CI : Result->getBlockDecl()->captures()) {
12451       const VarDecl *var = CI.getVariable();
12452       if (var->getType().isDestructedType() != QualType::DK_none) {
12453         getCurFunction()->setHasBranchProtectedScope();
12454         break;
12455       }
12456     }
12457   }
12458 
12459   return Result;
12460 }
12461 
12462 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12463                             SourceLocation RPLoc) {
12464   TypeSourceInfo *TInfo;
12465   GetTypeFromParser(Ty, &TInfo);
12466   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12467 }
12468 
12469 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12470                                 Expr *E, TypeSourceInfo *TInfo,
12471                                 SourceLocation RPLoc) {
12472   Expr *OrigExpr = E;
12473   bool IsMS = false;
12474 
12475   // CUDA device code does not support varargs.
12476   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12477     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12478       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12479       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12480         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12481     }
12482   }
12483 
12484   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12485   // as Microsoft ABI on an actual Microsoft platform, where
12486   // __builtin_ms_va_list and __builtin_va_list are the same.)
12487   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12488       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12489     QualType MSVaListType = Context.getBuiltinMSVaListType();
12490     if (Context.hasSameType(MSVaListType, E->getType())) {
12491       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12492         return ExprError();
12493       IsMS = true;
12494     }
12495   }
12496 
12497   // Get the va_list type
12498   QualType VaListType = Context.getBuiltinVaListType();
12499   if (!IsMS) {
12500     if (VaListType->isArrayType()) {
12501       // Deal with implicit array decay; for example, on x86-64,
12502       // va_list is an array, but it's supposed to decay to
12503       // a pointer for va_arg.
12504       VaListType = Context.getArrayDecayedType(VaListType);
12505       // Make sure the input expression also decays appropriately.
12506       ExprResult Result = UsualUnaryConversions(E);
12507       if (Result.isInvalid())
12508         return ExprError();
12509       E = Result.get();
12510     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12511       // If va_list is a record type and we are compiling in C++ mode,
12512       // check the argument using reference binding.
12513       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12514           Context, Context.getLValueReferenceType(VaListType), false);
12515       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12516       if (Init.isInvalid())
12517         return ExprError();
12518       E = Init.getAs<Expr>();
12519     } else {
12520       // Otherwise, the va_list argument must be an l-value because
12521       // it is modified by va_arg.
12522       if (!E->isTypeDependent() &&
12523           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12524         return ExprError();
12525     }
12526   }
12527 
12528   if (!IsMS && !E->isTypeDependent() &&
12529       !Context.hasSameType(VaListType, E->getType()))
12530     return ExprError(Diag(E->getLocStart(),
12531                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12532       << OrigExpr->getType() << E->getSourceRange());
12533 
12534   if (!TInfo->getType()->isDependentType()) {
12535     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12536                             diag::err_second_parameter_to_va_arg_incomplete,
12537                             TInfo->getTypeLoc()))
12538       return ExprError();
12539 
12540     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12541                                TInfo->getType(),
12542                                diag::err_second_parameter_to_va_arg_abstract,
12543                                TInfo->getTypeLoc()))
12544       return ExprError();
12545 
12546     if (!TInfo->getType().isPODType(Context)) {
12547       Diag(TInfo->getTypeLoc().getBeginLoc(),
12548            TInfo->getType()->isObjCLifetimeType()
12549              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12550              : diag::warn_second_parameter_to_va_arg_not_pod)
12551         << TInfo->getType()
12552         << TInfo->getTypeLoc().getSourceRange();
12553     }
12554 
12555     // Check for va_arg where arguments of the given type will be promoted
12556     // (i.e. this va_arg is guaranteed to have undefined behavior).
12557     QualType PromoteType;
12558     if (TInfo->getType()->isPromotableIntegerType()) {
12559       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12560       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12561         PromoteType = QualType();
12562     }
12563     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12564       PromoteType = Context.DoubleTy;
12565     if (!PromoteType.isNull())
12566       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12567                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12568                           << TInfo->getType()
12569                           << PromoteType
12570                           << TInfo->getTypeLoc().getSourceRange());
12571   }
12572 
12573   QualType T = TInfo->getType().getNonLValueExprType(Context);
12574   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12575 }
12576 
12577 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12578   // The type of __null will be int or long, depending on the size of
12579   // pointers on the target.
12580   QualType Ty;
12581   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12582   if (pw == Context.getTargetInfo().getIntWidth())
12583     Ty = Context.IntTy;
12584   else if (pw == Context.getTargetInfo().getLongWidth())
12585     Ty = Context.LongTy;
12586   else if (pw == Context.getTargetInfo().getLongLongWidth())
12587     Ty = Context.LongLongTy;
12588   else {
12589     llvm_unreachable("I don't know size of pointer!");
12590   }
12591 
12592   return new (Context) GNUNullExpr(Ty, TokenLoc);
12593 }
12594 
12595 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12596                                               bool Diagnose) {
12597   if (!getLangOpts().ObjC1)
12598     return false;
12599 
12600   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12601   if (!PT)
12602     return false;
12603 
12604   if (!PT->isObjCIdType()) {
12605     // Check if the destination is the 'NSString' interface.
12606     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12607     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12608       return false;
12609   }
12610 
12611   // Ignore any parens, implicit casts (should only be
12612   // array-to-pointer decays), and not-so-opaque values.  The last is
12613   // important for making this trigger for property assignments.
12614   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12615   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12616     if (OV->getSourceExpr())
12617       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12618 
12619   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12620   if (!SL || !SL->isAscii())
12621     return false;
12622   if (Diagnose) {
12623     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12624       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12625     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12626   }
12627   return true;
12628 }
12629 
12630 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12631                                               const Expr *SrcExpr) {
12632   if (!DstType->isFunctionPointerType() ||
12633       !SrcExpr->getType()->isFunctionType())
12634     return false;
12635 
12636   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12637   if (!DRE)
12638     return false;
12639 
12640   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12641   if (!FD)
12642     return false;
12643 
12644   return !S.checkAddressOfFunctionIsAvailable(FD,
12645                                               /*Complain=*/true,
12646                                               SrcExpr->getLocStart());
12647 }
12648 
12649 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12650                                     SourceLocation Loc,
12651                                     QualType DstType, QualType SrcType,
12652                                     Expr *SrcExpr, AssignmentAction Action,
12653                                     bool *Complained) {
12654   if (Complained)
12655     *Complained = false;
12656 
12657   // Decode the result (notice that AST's are still created for extensions).
12658   bool CheckInferredResultType = false;
12659   bool isInvalid = false;
12660   unsigned DiagKind = 0;
12661   FixItHint Hint;
12662   ConversionFixItGenerator ConvHints;
12663   bool MayHaveConvFixit = false;
12664   bool MayHaveFunctionDiff = false;
12665   const ObjCInterfaceDecl *IFace = nullptr;
12666   const ObjCProtocolDecl *PDecl = nullptr;
12667 
12668   switch (ConvTy) {
12669   case Compatible:
12670       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12671       return false;
12672 
12673   case PointerToInt:
12674     DiagKind = diag::ext_typecheck_convert_pointer_int;
12675     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12676     MayHaveConvFixit = true;
12677     break;
12678   case IntToPointer:
12679     DiagKind = diag::ext_typecheck_convert_int_pointer;
12680     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12681     MayHaveConvFixit = true;
12682     break;
12683   case IncompatiblePointer:
12684     if (Action == AA_Passing_CFAudited)
12685       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12686     else if (SrcType->isFunctionPointerType() &&
12687              DstType->isFunctionPointerType())
12688       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12689     else
12690       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12691 
12692     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12693       SrcType->isObjCObjectPointerType();
12694     if (Hint.isNull() && !CheckInferredResultType) {
12695       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12696     }
12697     else if (CheckInferredResultType) {
12698       SrcType = SrcType.getUnqualifiedType();
12699       DstType = DstType.getUnqualifiedType();
12700     }
12701     MayHaveConvFixit = true;
12702     break;
12703   case IncompatiblePointerSign:
12704     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12705     break;
12706   case FunctionVoidPointer:
12707     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12708     break;
12709   case IncompatiblePointerDiscardsQualifiers: {
12710     // Perform array-to-pointer decay if necessary.
12711     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12712 
12713     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12714     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12715     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12716       DiagKind = diag::err_typecheck_incompatible_address_space;
12717       break;
12718 
12719 
12720     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12721       DiagKind = diag::err_typecheck_incompatible_ownership;
12722       break;
12723     }
12724 
12725     llvm_unreachable("unknown error case for discarding qualifiers!");
12726     // fallthrough
12727   }
12728   case CompatiblePointerDiscardsQualifiers:
12729     // If the qualifiers lost were because we were applying the
12730     // (deprecated) C++ conversion from a string literal to a char*
12731     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12732     // Ideally, this check would be performed in
12733     // checkPointerTypesForAssignment. However, that would require a
12734     // bit of refactoring (so that the second argument is an
12735     // expression, rather than a type), which should be done as part
12736     // of a larger effort to fix checkPointerTypesForAssignment for
12737     // C++ semantics.
12738     if (getLangOpts().CPlusPlus &&
12739         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12740       return false;
12741     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12742     break;
12743   case IncompatibleNestedPointerQualifiers:
12744     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12745     break;
12746   case IntToBlockPointer:
12747     DiagKind = diag::err_int_to_block_pointer;
12748     break;
12749   case IncompatibleBlockPointer:
12750     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12751     break;
12752   case IncompatibleObjCQualifiedId: {
12753     if (SrcType->isObjCQualifiedIdType()) {
12754       const ObjCObjectPointerType *srcOPT =
12755                 SrcType->getAs<ObjCObjectPointerType>();
12756       for (auto *srcProto : srcOPT->quals()) {
12757         PDecl = srcProto;
12758         break;
12759       }
12760       if (const ObjCInterfaceType *IFaceT =
12761             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12762         IFace = IFaceT->getDecl();
12763     }
12764     else if (DstType->isObjCQualifiedIdType()) {
12765       const ObjCObjectPointerType *dstOPT =
12766         DstType->getAs<ObjCObjectPointerType>();
12767       for (auto *dstProto : dstOPT->quals()) {
12768         PDecl = dstProto;
12769         break;
12770       }
12771       if (const ObjCInterfaceType *IFaceT =
12772             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12773         IFace = IFaceT->getDecl();
12774     }
12775     DiagKind = diag::warn_incompatible_qualified_id;
12776     break;
12777   }
12778   case IncompatibleVectors:
12779     DiagKind = diag::warn_incompatible_vectors;
12780     break;
12781   case IncompatibleObjCWeakRef:
12782     DiagKind = diag::err_arc_weak_unavailable_assign;
12783     break;
12784   case Incompatible:
12785     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12786       if (Complained)
12787         *Complained = true;
12788       return true;
12789     }
12790 
12791     DiagKind = diag::err_typecheck_convert_incompatible;
12792     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12793     MayHaveConvFixit = true;
12794     isInvalid = true;
12795     MayHaveFunctionDiff = true;
12796     break;
12797   }
12798 
12799   QualType FirstType, SecondType;
12800   switch (Action) {
12801   case AA_Assigning:
12802   case AA_Initializing:
12803     // The destination type comes first.
12804     FirstType = DstType;
12805     SecondType = SrcType;
12806     break;
12807 
12808   case AA_Returning:
12809   case AA_Passing:
12810   case AA_Passing_CFAudited:
12811   case AA_Converting:
12812   case AA_Sending:
12813   case AA_Casting:
12814     // The source type comes first.
12815     FirstType = SrcType;
12816     SecondType = DstType;
12817     break;
12818   }
12819 
12820   PartialDiagnostic FDiag = PDiag(DiagKind);
12821   if (Action == AA_Passing_CFAudited)
12822     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12823   else
12824     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12825 
12826   // If we can fix the conversion, suggest the FixIts.
12827   assert(ConvHints.isNull() || Hint.isNull());
12828   if (!ConvHints.isNull()) {
12829     for (FixItHint &H : ConvHints.Hints)
12830       FDiag << H;
12831   } else {
12832     FDiag << Hint;
12833   }
12834   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12835 
12836   if (MayHaveFunctionDiff)
12837     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12838 
12839   Diag(Loc, FDiag);
12840   if (DiagKind == diag::warn_incompatible_qualified_id &&
12841       PDecl && IFace && !IFace->hasDefinition())
12842       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12843         << IFace->getName() << PDecl->getName();
12844 
12845   if (SecondType == Context.OverloadTy)
12846     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12847                               FirstType, /*TakingAddress=*/true);
12848 
12849   if (CheckInferredResultType)
12850     EmitRelatedResultTypeNote(SrcExpr);
12851 
12852   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12853     EmitRelatedResultTypeNoteForReturn(DstType);
12854 
12855   if (Complained)
12856     *Complained = true;
12857   return isInvalid;
12858 }
12859 
12860 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12861                                                  llvm::APSInt *Result) {
12862   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12863   public:
12864     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12865       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12866     }
12867   } Diagnoser;
12868 
12869   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12870 }
12871 
12872 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12873                                                  llvm::APSInt *Result,
12874                                                  unsigned DiagID,
12875                                                  bool AllowFold) {
12876   class IDDiagnoser : public VerifyICEDiagnoser {
12877     unsigned DiagID;
12878 
12879   public:
12880     IDDiagnoser(unsigned DiagID)
12881       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12882 
12883     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12884       S.Diag(Loc, DiagID) << SR;
12885     }
12886   } Diagnoser(DiagID);
12887 
12888   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12889 }
12890 
12891 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12892                                             SourceRange SR) {
12893   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12894 }
12895 
12896 ExprResult
12897 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12898                                       VerifyICEDiagnoser &Diagnoser,
12899                                       bool AllowFold) {
12900   SourceLocation DiagLoc = E->getLocStart();
12901 
12902   if (getLangOpts().CPlusPlus11) {
12903     // C++11 [expr.const]p5:
12904     //   If an expression of literal class type is used in a context where an
12905     //   integral constant expression is required, then that class type shall
12906     //   have a single non-explicit conversion function to an integral or
12907     //   unscoped enumeration type
12908     ExprResult Converted;
12909     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12910     public:
12911       CXX11ConvertDiagnoser(bool Silent)
12912           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12913                                 Silent, true) {}
12914 
12915       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12916                                            QualType T) override {
12917         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12918       }
12919 
12920       SemaDiagnosticBuilder diagnoseIncomplete(
12921           Sema &S, SourceLocation Loc, QualType T) override {
12922         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12923       }
12924 
12925       SemaDiagnosticBuilder diagnoseExplicitConv(
12926           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12927         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12928       }
12929 
12930       SemaDiagnosticBuilder noteExplicitConv(
12931           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12932         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12933                  << ConvTy->isEnumeralType() << ConvTy;
12934       }
12935 
12936       SemaDiagnosticBuilder diagnoseAmbiguous(
12937           Sema &S, SourceLocation Loc, QualType T) override {
12938         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12939       }
12940 
12941       SemaDiagnosticBuilder noteAmbiguous(
12942           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12943         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12944                  << ConvTy->isEnumeralType() << ConvTy;
12945       }
12946 
12947       SemaDiagnosticBuilder diagnoseConversion(
12948           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12949         llvm_unreachable("conversion functions are permitted");
12950       }
12951     } ConvertDiagnoser(Diagnoser.Suppress);
12952 
12953     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12954                                                     ConvertDiagnoser);
12955     if (Converted.isInvalid())
12956       return Converted;
12957     E = Converted.get();
12958     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12959       return ExprError();
12960   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12961     // An ICE must be of integral or unscoped enumeration type.
12962     if (!Diagnoser.Suppress)
12963       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12964     return ExprError();
12965   }
12966 
12967   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12968   // in the non-ICE case.
12969   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12970     if (Result)
12971       *Result = E->EvaluateKnownConstInt(Context);
12972     return E;
12973   }
12974 
12975   Expr::EvalResult EvalResult;
12976   SmallVector<PartialDiagnosticAt, 8> Notes;
12977   EvalResult.Diag = &Notes;
12978 
12979   // Try to evaluate the expression, and produce diagnostics explaining why it's
12980   // not a constant expression as a side-effect.
12981   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12982                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12983 
12984   // In C++11, we can rely on diagnostics being produced for any expression
12985   // which is not a constant expression. If no diagnostics were produced, then
12986   // this is a constant expression.
12987   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12988     if (Result)
12989       *Result = EvalResult.Val.getInt();
12990     return E;
12991   }
12992 
12993   // If our only note is the usual "invalid subexpression" note, just point
12994   // the caret at its location rather than producing an essentially
12995   // redundant note.
12996   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12997         diag::note_invalid_subexpr_in_const_expr) {
12998     DiagLoc = Notes[0].first;
12999     Notes.clear();
13000   }
13001 
13002   if (!Folded || !AllowFold) {
13003     if (!Diagnoser.Suppress) {
13004       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13005       for (const PartialDiagnosticAt &Note : Notes)
13006         Diag(Note.first, Note.second);
13007     }
13008 
13009     return ExprError();
13010   }
13011 
13012   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13013   for (const PartialDiagnosticAt &Note : Notes)
13014     Diag(Note.first, Note.second);
13015 
13016   if (Result)
13017     *Result = EvalResult.Val.getInt();
13018   return E;
13019 }
13020 
13021 namespace {
13022   // Handle the case where we conclude a expression which we speculatively
13023   // considered to be unevaluated is actually evaluated.
13024   class TransformToPE : public TreeTransform<TransformToPE> {
13025     typedef TreeTransform<TransformToPE> BaseTransform;
13026 
13027   public:
13028     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13029 
13030     // Make sure we redo semantic analysis
13031     bool AlwaysRebuild() { return true; }
13032 
13033     // Make sure we handle LabelStmts correctly.
13034     // FIXME: This does the right thing, but maybe we need a more general
13035     // fix to TreeTransform?
13036     StmtResult TransformLabelStmt(LabelStmt *S) {
13037       S->getDecl()->setStmt(nullptr);
13038       return BaseTransform::TransformLabelStmt(S);
13039     }
13040 
13041     // We need to special-case DeclRefExprs referring to FieldDecls which
13042     // are not part of a member pointer formation; normal TreeTransforming
13043     // doesn't catch this case because of the way we represent them in the AST.
13044     // FIXME: This is a bit ugly; is it really the best way to handle this
13045     // case?
13046     //
13047     // Error on DeclRefExprs referring to FieldDecls.
13048     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13049       if (isa<FieldDecl>(E->getDecl()) &&
13050           !SemaRef.isUnevaluatedContext())
13051         return SemaRef.Diag(E->getLocation(),
13052                             diag::err_invalid_non_static_member_use)
13053             << E->getDecl() << E->getSourceRange();
13054 
13055       return BaseTransform::TransformDeclRefExpr(E);
13056     }
13057 
13058     // Exception: filter out member pointer formation
13059     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13060       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13061         return E;
13062 
13063       return BaseTransform::TransformUnaryOperator(E);
13064     }
13065 
13066     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13067       // Lambdas never need to be transformed.
13068       return E;
13069     }
13070   };
13071 }
13072 
13073 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13074   assert(isUnevaluatedContext() &&
13075          "Should only transform unevaluated expressions");
13076   ExprEvalContexts.back().Context =
13077       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13078   if (isUnevaluatedContext())
13079     return E;
13080   return TransformToPE(*this).TransformExpr(E);
13081 }
13082 
13083 void
13084 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13085                                       Decl *LambdaContextDecl,
13086                                       bool IsDecltype) {
13087   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13088                                 LambdaContextDecl, IsDecltype);
13089   Cleanup.reset();
13090   if (!MaybeODRUseExprs.empty())
13091     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13092 }
13093 
13094 void
13095 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13096                                       ReuseLambdaContextDecl_t,
13097                                       bool IsDecltype) {
13098   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13099   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13100 }
13101 
13102 void Sema::PopExpressionEvaluationContext() {
13103   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13104   unsigned NumTypos = Rec.NumTypos;
13105 
13106   if (!Rec.Lambdas.empty()) {
13107     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13108       unsigned D;
13109       if (Rec.isUnevaluated()) {
13110         // C++11 [expr.prim.lambda]p2:
13111         //   A lambda-expression shall not appear in an unevaluated operand
13112         //   (Clause 5).
13113         D = diag::err_lambda_unevaluated_operand;
13114       } else {
13115         // C++1y [expr.const]p2:
13116         //   A conditional-expression e is a core constant expression unless the
13117         //   evaluation of e, following the rules of the abstract machine, would
13118         //   evaluate [...] a lambda-expression.
13119         D = diag::err_lambda_in_constant_expression;
13120       }
13121 
13122       // C++1z allows lambda expressions as core constant expressions.
13123       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13124       // 1607) from appearing within template-arguments and array-bounds that
13125       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13126       // unevaluated contexts) might lift some of these restrictions in a
13127       // future version.
13128       if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z)
13129         for (const auto *L : Rec.Lambdas)
13130           Diag(L->getLocStart(), D);
13131     } else {
13132       // Mark the capture expressions odr-used. This was deferred
13133       // during lambda expression creation.
13134       for (auto *Lambda : Rec.Lambdas) {
13135         for (auto *C : Lambda->capture_inits())
13136           MarkDeclarationsReferencedInExpr(C);
13137       }
13138     }
13139   }
13140 
13141   // When are coming out of an unevaluated context, clear out any
13142   // temporaries that we may have created as part of the evaluation of
13143   // the expression in that context: they aren't relevant because they
13144   // will never be constructed.
13145   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13146     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13147                              ExprCleanupObjects.end());
13148     Cleanup = Rec.ParentCleanup;
13149     CleanupVarDeclMarking();
13150     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13151   // Otherwise, merge the contexts together.
13152   } else {
13153     Cleanup.mergeFrom(Rec.ParentCleanup);
13154     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13155                             Rec.SavedMaybeODRUseExprs.end());
13156   }
13157 
13158   // Pop the current expression evaluation context off the stack.
13159   ExprEvalContexts.pop_back();
13160 
13161   if (!ExprEvalContexts.empty())
13162     ExprEvalContexts.back().NumTypos += NumTypos;
13163   else
13164     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13165                             "last ExpressionEvaluationContextRecord");
13166 }
13167 
13168 void Sema::DiscardCleanupsInEvaluationContext() {
13169   ExprCleanupObjects.erase(
13170          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13171          ExprCleanupObjects.end());
13172   Cleanup.reset();
13173   MaybeODRUseExprs.clear();
13174 }
13175 
13176 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13177   if (!E->getType()->isVariablyModifiedType())
13178     return E;
13179   return TransformToPotentiallyEvaluated(E);
13180 }
13181 
13182 /// Are we within a context in which some evaluation could be performed (be it
13183 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13184 /// captured by C++'s idea of an "unevaluated context".
13185 static bool isEvaluatableContext(Sema &SemaRef) {
13186   switch (SemaRef.ExprEvalContexts.back().Context) {
13187     case Sema::Unevaluated:
13188     case Sema::UnevaluatedAbstract:
13189     case Sema::DiscardedStatement:
13190       // Expressions in this context are never evaluated.
13191       return false;
13192 
13193     case Sema::UnevaluatedList:
13194     case Sema::ConstantEvaluated:
13195     case Sema::PotentiallyEvaluated:
13196       // Expressions in this context could be evaluated.
13197       return true;
13198 
13199     case Sema::PotentiallyEvaluatedIfUsed:
13200       // Referenced declarations will only be used if the construct in the
13201       // containing expression is used, at which point we'll be given another
13202       // turn to mark them.
13203       return false;
13204   }
13205   llvm_unreachable("Invalid context");
13206 }
13207 
13208 /// Are we within a context in which references to resolved functions or to
13209 /// variables result in odr-use?
13210 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13211   // An expression in a template is not really an expression until it's been
13212   // instantiated, so it doesn't trigger odr-use.
13213   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13214     return false;
13215 
13216   switch (SemaRef.ExprEvalContexts.back().Context) {
13217     case Sema::Unevaluated:
13218     case Sema::UnevaluatedList:
13219     case Sema::UnevaluatedAbstract:
13220     case Sema::DiscardedStatement:
13221       return false;
13222 
13223     case Sema::ConstantEvaluated:
13224     case Sema::PotentiallyEvaluated:
13225       return true;
13226 
13227     case Sema::PotentiallyEvaluatedIfUsed:
13228       return false;
13229   }
13230   llvm_unreachable("Invalid context");
13231 }
13232 
13233 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13234   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13235   return Func->isConstexpr() &&
13236          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13237 }
13238 
13239 /// \brief Mark a function referenced, and check whether it is odr-used
13240 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13241 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13242                                   bool MightBeOdrUse) {
13243   assert(Func && "No function?");
13244 
13245   Func->setReferenced();
13246 
13247   // C++11 [basic.def.odr]p3:
13248   //   A function whose name appears as a potentially-evaluated expression is
13249   //   odr-used if it is the unique lookup result or the selected member of a
13250   //   set of overloaded functions [...].
13251   //
13252   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13253   // can just check that here.
13254   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13255 
13256   // Determine whether we require a function definition to exist, per
13257   // C++11 [temp.inst]p3:
13258   //   Unless a function template specialization has been explicitly
13259   //   instantiated or explicitly specialized, the function template
13260   //   specialization is implicitly instantiated when the specialization is
13261   //   referenced in a context that requires a function definition to exist.
13262   //
13263   // That is either when this is an odr-use, or when a usage of a constexpr
13264   // function occurs within an evaluatable context.
13265   bool NeedDefinition =
13266       OdrUse || (isEvaluatableContext(*this) &&
13267                  isImplicitlyDefinableConstexprFunction(Func));
13268 
13269   // C++14 [temp.expl.spec]p6:
13270   //   If a template [...] is explicitly specialized then that specialization
13271   //   shall be declared before the first use of that specialization that would
13272   //   cause an implicit instantiation to take place, in every translation unit
13273   //   in which such a use occurs
13274   if (NeedDefinition &&
13275       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13276        Func->getMemberSpecializationInfo()))
13277     checkSpecializationVisibility(Loc, Func);
13278 
13279   // C++14 [except.spec]p17:
13280   //   An exception-specification is considered to be needed when:
13281   //   - the function is odr-used or, if it appears in an unevaluated operand,
13282   //     would be odr-used if the expression were potentially-evaluated;
13283   //
13284   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13285   // function is a pure virtual function we're calling, and in that case the
13286   // function was selected by overload resolution and we need to resolve its
13287   // exception specification for a different reason.
13288   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13289   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13290     ResolveExceptionSpec(Loc, FPT);
13291 
13292   // If we don't need to mark the function as used, and we don't need to
13293   // try to provide a definition, there's nothing more to do.
13294   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13295       (!NeedDefinition || Func->getBody()))
13296     return;
13297 
13298   // Note that this declaration has been used.
13299   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13300     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13301     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13302       if (Constructor->isDefaultConstructor()) {
13303         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13304           return;
13305         DefineImplicitDefaultConstructor(Loc, Constructor);
13306       } else if (Constructor->isCopyConstructor()) {
13307         DefineImplicitCopyConstructor(Loc, Constructor);
13308       } else if (Constructor->isMoveConstructor()) {
13309         DefineImplicitMoveConstructor(Loc, Constructor);
13310       }
13311     } else if (Constructor->getInheritedConstructor()) {
13312       DefineInheritingConstructor(Loc, Constructor);
13313     }
13314   } else if (CXXDestructorDecl *Destructor =
13315                  dyn_cast<CXXDestructorDecl>(Func)) {
13316     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13317     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13318       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13319         return;
13320       DefineImplicitDestructor(Loc, Destructor);
13321     }
13322     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13323       MarkVTableUsed(Loc, Destructor->getParent());
13324   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13325     if (MethodDecl->isOverloadedOperator() &&
13326         MethodDecl->getOverloadedOperator() == OO_Equal) {
13327       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13328       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13329         if (MethodDecl->isCopyAssignmentOperator())
13330           DefineImplicitCopyAssignment(Loc, MethodDecl);
13331         else if (MethodDecl->isMoveAssignmentOperator())
13332           DefineImplicitMoveAssignment(Loc, MethodDecl);
13333       }
13334     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13335                MethodDecl->getParent()->isLambda()) {
13336       CXXConversionDecl *Conversion =
13337           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13338       if (Conversion->isLambdaToBlockPointerConversion())
13339         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13340       else
13341         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13342     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13343       MarkVTableUsed(Loc, MethodDecl->getParent());
13344   }
13345 
13346   // Recursive functions should be marked when used from another function.
13347   // FIXME: Is this really right?
13348   if (CurContext == Func) return;
13349 
13350   // Implicit instantiation of function templates and member functions of
13351   // class templates.
13352   if (Func->isImplicitlyInstantiable()) {
13353     bool AlreadyInstantiated = false;
13354     SourceLocation PointOfInstantiation = Loc;
13355     if (FunctionTemplateSpecializationInfo *SpecInfo
13356                               = Func->getTemplateSpecializationInfo()) {
13357       if (SpecInfo->getPointOfInstantiation().isInvalid())
13358         SpecInfo->setPointOfInstantiation(Loc);
13359       else if (SpecInfo->getTemplateSpecializationKind()
13360                  == TSK_ImplicitInstantiation) {
13361         AlreadyInstantiated = true;
13362         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13363       }
13364     } else if (MemberSpecializationInfo *MSInfo
13365                                 = Func->getMemberSpecializationInfo()) {
13366       if (MSInfo->getPointOfInstantiation().isInvalid())
13367         MSInfo->setPointOfInstantiation(Loc);
13368       else if (MSInfo->getTemplateSpecializationKind()
13369                  == TSK_ImplicitInstantiation) {
13370         AlreadyInstantiated = true;
13371         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13372       }
13373     }
13374 
13375     if (!AlreadyInstantiated || Func->isConstexpr()) {
13376       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13377           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13378           ActiveTemplateInstantiations.size())
13379         PendingLocalImplicitInstantiations.push_back(
13380             std::make_pair(Func, PointOfInstantiation));
13381       else if (Func->isConstexpr())
13382         // Do not defer instantiations of constexpr functions, to avoid the
13383         // expression evaluator needing to call back into Sema if it sees a
13384         // call to such a function.
13385         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13386       else {
13387         PendingInstantiations.push_back(std::make_pair(Func,
13388                                                        PointOfInstantiation));
13389         // Notify the consumer that a function was implicitly instantiated.
13390         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13391       }
13392     }
13393   } else {
13394     // Walk redefinitions, as some of them may be instantiable.
13395     for (auto i : Func->redecls()) {
13396       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13397         MarkFunctionReferenced(Loc, i, OdrUse);
13398     }
13399   }
13400 
13401   if (!OdrUse) return;
13402 
13403   // Keep track of used but undefined functions.
13404   if (!Func->isDefined()) {
13405     if (mightHaveNonExternalLinkage(Func))
13406       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13407     else if (Func->getMostRecentDecl()->isInlined() &&
13408              !LangOpts.GNUInline &&
13409              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13410       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13411   }
13412 
13413   Func->markUsed(Context);
13414 }
13415 
13416 static void
13417 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13418                                    ValueDecl *var, DeclContext *DC) {
13419   DeclContext *VarDC = var->getDeclContext();
13420 
13421   //  If the parameter still belongs to the translation unit, then
13422   //  we're actually just using one parameter in the declaration of
13423   //  the next.
13424   if (isa<ParmVarDecl>(var) &&
13425       isa<TranslationUnitDecl>(VarDC))
13426     return;
13427 
13428   // For C code, don't diagnose about capture if we're not actually in code
13429   // right now; it's impossible to write a non-constant expression outside of
13430   // function context, so we'll get other (more useful) diagnostics later.
13431   //
13432   // For C++, things get a bit more nasty... it would be nice to suppress this
13433   // diagnostic for certain cases like using a local variable in an array bound
13434   // for a member of a local class, but the correct predicate is not obvious.
13435   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13436     return;
13437 
13438   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13439   unsigned ContextKind = 3; // unknown
13440   if (isa<CXXMethodDecl>(VarDC) &&
13441       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13442     ContextKind = 2;
13443   } else if (isa<FunctionDecl>(VarDC)) {
13444     ContextKind = 0;
13445   } else if (isa<BlockDecl>(VarDC)) {
13446     ContextKind = 1;
13447   }
13448 
13449   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13450     << var << ValueKind << ContextKind << VarDC;
13451   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13452       << var;
13453 
13454   // FIXME: Add additional diagnostic info about class etc. which prevents
13455   // capture.
13456 }
13457 
13458 
13459 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13460                                       bool &SubCapturesAreNested,
13461                                       QualType &CaptureType,
13462                                       QualType &DeclRefType) {
13463    // Check whether we've already captured it.
13464   if (CSI->CaptureMap.count(Var)) {
13465     // If we found a capture, any subcaptures are nested.
13466     SubCapturesAreNested = true;
13467 
13468     // Retrieve the capture type for this variable.
13469     CaptureType = CSI->getCapture(Var).getCaptureType();
13470 
13471     // Compute the type of an expression that refers to this variable.
13472     DeclRefType = CaptureType.getNonReferenceType();
13473 
13474     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13475     // are mutable in the sense that user can change their value - they are
13476     // private instances of the captured declarations.
13477     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13478     if (Cap.isCopyCapture() &&
13479         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13480         !(isa<CapturedRegionScopeInfo>(CSI) &&
13481           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13482       DeclRefType.addConst();
13483     return true;
13484   }
13485   return false;
13486 }
13487 
13488 // Only block literals, captured statements, and lambda expressions can
13489 // capture; other scopes don't work.
13490 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13491                                  SourceLocation Loc,
13492                                  const bool Diagnose, Sema &S) {
13493   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13494     return getLambdaAwareParentOfDeclContext(DC);
13495   else if (Var->hasLocalStorage()) {
13496     if (Diagnose)
13497        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13498   }
13499   return nullptr;
13500 }
13501 
13502 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13503 // certain types of variables (unnamed, variably modified types etc.)
13504 // so check for eligibility.
13505 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13506                                  SourceLocation Loc,
13507                                  const bool Diagnose, Sema &S) {
13508 
13509   bool IsBlock = isa<BlockScopeInfo>(CSI);
13510   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13511 
13512   // Lambdas are not allowed to capture unnamed variables
13513   // (e.g. anonymous unions).
13514   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13515   // assuming that's the intent.
13516   if (IsLambda && !Var->getDeclName()) {
13517     if (Diagnose) {
13518       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13519       S.Diag(Var->getLocation(), diag::note_declared_at);
13520     }
13521     return false;
13522   }
13523 
13524   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13525   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13526     if (Diagnose) {
13527       S.Diag(Loc, diag::err_ref_vm_type);
13528       S.Diag(Var->getLocation(), diag::note_previous_decl)
13529         << Var->getDeclName();
13530     }
13531     return false;
13532   }
13533   // Prohibit structs with flexible array members too.
13534   // We cannot capture what is in the tail end of the struct.
13535   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13536     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13537       if (Diagnose) {
13538         if (IsBlock)
13539           S.Diag(Loc, diag::err_ref_flexarray_type);
13540         else
13541           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13542             << Var->getDeclName();
13543         S.Diag(Var->getLocation(), diag::note_previous_decl)
13544           << Var->getDeclName();
13545       }
13546       return false;
13547     }
13548   }
13549   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13550   // Lambdas and captured statements are not allowed to capture __block
13551   // variables; they don't support the expected semantics.
13552   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13553     if (Diagnose) {
13554       S.Diag(Loc, diag::err_capture_block_variable)
13555         << Var->getDeclName() << !IsLambda;
13556       S.Diag(Var->getLocation(), diag::note_previous_decl)
13557         << Var->getDeclName();
13558     }
13559     return false;
13560   }
13561 
13562   return true;
13563 }
13564 
13565 // Returns true if the capture by block was successful.
13566 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13567                                  SourceLocation Loc,
13568                                  const bool BuildAndDiagnose,
13569                                  QualType &CaptureType,
13570                                  QualType &DeclRefType,
13571                                  const bool Nested,
13572                                  Sema &S) {
13573   Expr *CopyExpr = nullptr;
13574   bool ByRef = false;
13575 
13576   // Blocks are not allowed to capture arrays.
13577   if (CaptureType->isArrayType()) {
13578     if (BuildAndDiagnose) {
13579       S.Diag(Loc, diag::err_ref_array_type);
13580       S.Diag(Var->getLocation(), diag::note_previous_decl)
13581       << Var->getDeclName();
13582     }
13583     return false;
13584   }
13585 
13586   // Forbid the block-capture of autoreleasing variables.
13587   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13588     if (BuildAndDiagnose) {
13589       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13590         << /*block*/ 0;
13591       S.Diag(Var->getLocation(), diag::note_previous_decl)
13592         << Var->getDeclName();
13593     }
13594     return false;
13595   }
13596 
13597   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13598   if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13599     QualType PointeeTy = PT->getPointeeType();
13600     if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13601         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13602         !isa<AttributedType>(PointeeTy)) {
13603       if (BuildAndDiagnose) {
13604         SourceLocation VarLoc = Var->getLocation();
13605         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13606         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13607             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13608         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13609       }
13610     }
13611   }
13612 
13613   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13614   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13615       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13616     // Block capture by reference does not change the capture or
13617     // declaration reference types.
13618     ByRef = true;
13619   } else {
13620     // Block capture by copy introduces 'const'.
13621     CaptureType = CaptureType.getNonReferenceType().withConst();
13622     DeclRefType = CaptureType;
13623 
13624     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13625       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13626         // The capture logic needs the destructor, so make sure we mark it.
13627         // Usually this is unnecessary because most local variables have
13628         // their destructors marked at declaration time, but parameters are
13629         // an exception because it's technically only the call site that
13630         // actually requires the destructor.
13631         if (isa<ParmVarDecl>(Var))
13632           S.FinalizeVarWithDestructor(Var, Record);
13633 
13634         // Enter a new evaluation context to insulate the copy
13635         // full-expression.
13636         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13637 
13638         // According to the blocks spec, the capture of a variable from
13639         // the stack requires a const copy constructor.  This is not true
13640         // of the copy/move done to move a __block variable to the heap.
13641         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13642                                                   DeclRefType.withConst(),
13643                                                   VK_LValue, Loc);
13644 
13645         ExprResult Result
13646           = S.PerformCopyInitialization(
13647               InitializedEntity::InitializeBlock(Var->getLocation(),
13648                                                   CaptureType, false),
13649               Loc, DeclRef);
13650 
13651         // Build a full-expression copy expression if initialization
13652         // succeeded and used a non-trivial constructor.  Recover from
13653         // errors by pretending that the copy isn't necessary.
13654         if (!Result.isInvalid() &&
13655             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13656                 ->isTrivial()) {
13657           Result = S.MaybeCreateExprWithCleanups(Result);
13658           CopyExpr = Result.get();
13659         }
13660       }
13661     }
13662   }
13663 
13664   // Actually capture the variable.
13665   if (BuildAndDiagnose)
13666     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13667                     SourceLocation(), CaptureType, CopyExpr);
13668 
13669   return true;
13670 
13671 }
13672 
13673 
13674 /// \brief Capture the given variable in the captured region.
13675 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13676                                     VarDecl *Var,
13677                                     SourceLocation Loc,
13678                                     const bool BuildAndDiagnose,
13679                                     QualType &CaptureType,
13680                                     QualType &DeclRefType,
13681                                     const bool RefersToCapturedVariable,
13682                                     Sema &S) {
13683   // By default, capture variables by reference.
13684   bool ByRef = true;
13685   // Using an LValue reference type is consistent with Lambdas (see below).
13686   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13687     if (S.IsOpenMPCapturedDecl(Var))
13688       DeclRefType = DeclRefType.getUnqualifiedType();
13689     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13690   }
13691 
13692   if (ByRef)
13693     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13694   else
13695     CaptureType = DeclRefType;
13696 
13697   Expr *CopyExpr = nullptr;
13698   if (BuildAndDiagnose) {
13699     // The current implementation assumes that all variables are captured
13700     // by references. Since there is no capture by copy, no expression
13701     // evaluation will be needed.
13702     RecordDecl *RD = RSI->TheRecordDecl;
13703 
13704     FieldDecl *Field
13705       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13706                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13707                           nullptr, false, ICIS_NoInit);
13708     Field->setImplicit(true);
13709     Field->setAccess(AS_private);
13710     RD->addDecl(Field);
13711 
13712     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13713                                             DeclRefType, VK_LValue, Loc);
13714     Var->setReferenced(true);
13715     Var->markUsed(S.Context);
13716   }
13717 
13718   // Actually capture the variable.
13719   if (BuildAndDiagnose)
13720     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13721                     SourceLocation(), CaptureType, CopyExpr);
13722 
13723 
13724   return true;
13725 }
13726 
13727 /// \brief Create a field within the lambda class for the variable
13728 /// being captured.
13729 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13730                                     QualType FieldType, QualType DeclRefType,
13731                                     SourceLocation Loc,
13732                                     bool RefersToCapturedVariable) {
13733   CXXRecordDecl *Lambda = LSI->Lambda;
13734 
13735   // Build the non-static data member.
13736   FieldDecl *Field
13737     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13738                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13739                         nullptr, false, ICIS_NoInit);
13740   Field->setImplicit(true);
13741   Field->setAccess(AS_private);
13742   Lambda->addDecl(Field);
13743 }
13744 
13745 /// \brief Capture the given variable in the lambda.
13746 static bool captureInLambda(LambdaScopeInfo *LSI,
13747                             VarDecl *Var,
13748                             SourceLocation Loc,
13749                             const bool BuildAndDiagnose,
13750                             QualType &CaptureType,
13751                             QualType &DeclRefType,
13752                             const bool RefersToCapturedVariable,
13753                             const Sema::TryCaptureKind Kind,
13754                             SourceLocation EllipsisLoc,
13755                             const bool IsTopScope,
13756                             Sema &S) {
13757 
13758   // Determine whether we are capturing by reference or by value.
13759   bool ByRef = false;
13760   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13761     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13762   } else {
13763     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13764   }
13765 
13766   // Compute the type of the field that will capture this variable.
13767   if (ByRef) {
13768     // C++11 [expr.prim.lambda]p15:
13769     //   An entity is captured by reference if it is implicitly or
13770     //   explicitly captured but not captured by copy. It is
13771     //   unspecified whether additional unnamed non-static data
13772     //   members are declared in the closure type for entities
13773     //   captured by reference.
13774     //
13775     // FIXME: It is not clear whether we want to build an lvalue reference
13776     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13777     // to do the former, while EDG does the latter. Core issue 1249 will
13778     // clarify, but for now we follow GCC because it's a more permissive and
13779     // easily defensible position.
13780     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13781   } else {
13782     // C++11 [expr.prim.lambda]p14:
13783     //   For each entity captured by copy, an unnamed non-static
13784     //   data member is declared in the closure type. The
13785     //   declaration order of these members is unspecified. The type
13786     //   of such a data member is the type of the corresponding
13787     //   captured entity if the entity is not a reference to an
13788     //   object, or the referenced type otherwise. [Note: If the
13789     //   captured entity is a reference to a function, the
13790     //   corresponding data member is also a reference to a
13791     //   function. - end note ]
13792     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13793       if (!RefType->getPointeeType()->isFunctionType())
13794         CaptureType = RefType->getPointeeType();
13795     }
13796 
13797     // Forbid the lambda copy-capture of autoreleasing variables.
13798     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13799       if (BuildAndDiagnose) {
13800         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13801         S.Diag(Var->getLocation(), diag::note_previous_decl)
13802           << Var->getDeclName();
13803       }
13804       return false;
13805     }
13806 
13807     // Make sure that by-copy captures are of a complete and non-abstract type.
13808     if (BuildAndDiagnose) {
13809       if (!CaptureType->isDependentType() &&
13810           S.RequireCompleteType(Loc, CaptureType,
13811                                 diag::err_capture_of_incomplete_type,
13812                                 Var->getDeclName()))
13813         return false;
13814 
13815       if (S.RequireNonAbstractType(Loc, CaptureType,
13816                                    diag::err_capture_of_abstract_type))
13817         return false;
13818     }
13819   }
13820 
13821   // Capture this variable in the lambda.
13822   if (BuildAndDiagnose)
13823     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13824                             RefersToCapturedVariable);
13825 
13826   // Compute the type of a reference to this captured variable.
13827   if (ByRef)
13828     DeclRefType = CaptureType.getNonReferenceType();
13829   else {
13830     // C++ [expr.prim.lambda]p5:
13831     //   The closure type for a lambda-expression has a public inline
13832     //   function call operator [...]. This function call operator is
13833     //   declared const (9.3.1) if and only if the lambda-expression's
13834     //   parameter-declaration-clause is not followed by mutable.
13835     DeclRefType = CaptureType.getNonReferenceType();
13836     if (!LSI->Mutable && !CaptureType->isReferenceType())
13837       DeclRefType.addConst();
13838   }
13839 
13840   // Add the capture.
13841   if (BuildAndDiagnose)
13842     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13843                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13844 
13845   return true;
13846 }
13847 
13848 bool Sema::tryCaptureVariable(
13849     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13850     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13851     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13852   // An init-capture is notionally from the context surrounding its
13853   // declaration, but its parent DC is the lambda class.
13854   DeclContext *VarDC = Var->getDeclContext();
13855   if (Var->isInitCapture())
13856     VarDC = VarDC->getParent();
13857 
13858   DeclContext *DC = CurContext;
13859   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13860       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13861   // We need to sync up the Declaration Context with the
13862   // FunctionScopeIndexToStopAt
13863   if (FunctionScopeIndexToStopAt) {
13864     unsigned FSIndex = FunctionScopes.size() - 1;
13865     while (FSIndex != MaxFunctionScopesIndex) {
13866       DC = getLambdaAwareParentOfDeclContext(DC);
13867       --FSIndex;
13868     }
13869   }
13870 
13871 
13872   // If the variable is declared in the current context, there is no need to
13873   // capture it.
13874   if (VarDC == DC) return true;
13875 
13876   // Capture global variables if it is required to use private copy of this
13877   // variable.
13878   bool IsGlobal = !Var->hasLocalStorage();
13879   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13880     return true;
13881 
13882   // Walk up the stack to determine whether we can capture the variable,
13883   // performing the "simple" checks that don't depend on type. We stop when
13884   // we've either hit the declared scope of the variable or find an existing
13885   // capture of that variable.  We start from the innermost capturing-entity
13886   // (the DC) and ensure that all intervening capturing-entities
13887   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13888   // declcontext can either capture the variable or have already captured
13889   // the variable.
13890   CaptureType = Var->getType();
13891   DeclRefType = CaptureType.getNonReferenceType();
13892   bool Nested = false;
13893   bool Explicit = (Kind != TryCapture_Implicit);
13894   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13895   do {
13896     // Only block literals, captured statements, and lambda expressions can
13897     // capture; other scopes don't work.
13898     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13899                                                               ExprLoc,
13900                                                               BuildAndDiagnose,
13901                                                               *this);
13902     // We need to check for the parent *first* because, if we *have*
13903     // private-captured a global variable, we need to recursively capture it in
13904     // intermediate blocks, lambdas, etc.
13905     if (!ParentDC) {
13906       if (IsGlobal) {
13907         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13908         break;
13909       }
13910       return true;
13911     }
13912 
13913     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13914     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13915 
13916 
13917     // Check whether we've already captured it.
13918     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13919                                              DeclRefType))
13920       break;
13921     // If we are instantiating a generic lambda call operator body,
13922     // we do not want to capture new variables.  What was captured
13923     // during either a lambdas transformation or initial parsing
13924     // should be used.
13925     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13926       if (BuildAndDiagnose) {
13927         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13928         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13929           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13930           Diag(Var->getLocation(), diag::note_previous_decl)
13931              << Var->getDeclName();
13932           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13933         } else
13934           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13935       }
13936       return true;
13937     }
13938     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13939     // certain types of variables (unnamed, variably modified types etc.)
13940     // so check for eligibility.
13941     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13942        return true;
13943 
13944     // Try to capture variable-length arrays types.
13945     if (Var->getType()->isVariablyModifiedType()) {
13946       // We're going to walk down into the type and look for VLA
13947       // expressions.
13948       QualType QTy = Var->getType();
13949       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13950         QTy = PVD->getOriginalType();
13951       captureVariablyModifiedType(Context, QTy, CSI);
13952     }
13953 
13954     if (getLangOpts().OpenMP) {
13955       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13956         // OpenMP private variables should not be captured in outer scope, so
13957         // just break here. Similarly, global variables that are captured in a
13958         // target region should not be captured outside the scope of the region.
13959         if (RSI->CapRegionKind == CR_OpenMP) {
13960           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13961           // When we detect target captures we are looking from inside the
13962           // target region, therefore we need to propagate the capture from the
13963           // enclosing region. Therefore, the capture is not initially nested.
13964           if (IsTargetCap)
13965             FunctionScopesIndex--;
13966 
13967           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13968             Nested = !IsTargetCap;
13969             DeclRefType = DeclRefType.getUnqualifiedType();
13970             CaptureType = Context.getLValueReferenceType(DeclRefType);
13971             break;
13972           }
13973         }
13974       }
13975     }
13976     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13977       // No capture-default, and this is not an explicit capture
13978       // so cannot capture this variable.
13979       if (BuildAndDiagnose) {
13980         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13981         Diag(Var->getLocation(), diag::note_previous_decl)
13982           << Var->getDeclName();
13983         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13984           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13985                diag::note_lambda_decl);
13986         // FIXME: If we error out because an outer lambda can not implicitly
13987         // capture a variable that an inner lambda explicitly captures, we
13988         // should have the inner lambda do the explicit capture - because
13989         // it makes for cleaner diagnostics later.  This would purely be done
13990         // so that the diagnostic does not misleadingly claim that a variable
13991         // can not be captured by a lambda implicitly even though it is captured
13992         // explicitly.  Suggestion:
13993         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13994         //    at the function head
13995         //  - cache the StartingDeclContext - this must be a lambda
13996         //  - captureInLambda in the innermost lambda the variable.
13997       }
13998       return true;
13999     }
14000 
14001     FunctionScopesIndex--;
14002     DC = ParentDC;
14003     Explicit = false;
14004   } while (!VarDC->Equals(DC));
14005 
14006   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14007   // computing the type of the capture at each step, checking type-specific
14008   // requirements, and adding captures if requested.
14009   // If the variable had already been captured previously, we start capturing
14010   // at the lambda nested within that one.
14011   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14012        ++I) {
14013     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14014 
14015     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14016       if (!captureInBlock(BSI, Var, ExprLoc,
14017                           BuildAndDiagnose, CaptureType,
14018                           DeclRefType, Nested, *this))
14019         return true;
14020       Nested = true;
14021     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14022       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14023                                    BuildAndDiagnose, CaptureType,
14024                                    DeclRefType, Nested, *this))
14025         return true;
14026       Nested = true;
14027     } else {
14028       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14029       if (!captureInLambda(LSI, Var, ExprLoc,
14030                            BuildAndDiagnose, CaptureType,
14031                            DeclRefType, Nested, Kind, EllipsisLoc,
14032                             /*IsTopScope*/I == N - 1, *this))
14033         return true;
14034       Nested = true;
14035     }
14036   }
14037   return false;
14038 }
14039 
14040 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14041                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14042   QualType CaptureType;
14043   QualType DeclRefType;
14044   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14045                             /*BuildAndDiagnose=*/true, CaptureType,
14046                             DeclRefType, nullptr);
14047 }
14048 
14049 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14050   QualType CaptureType;
14051   QualType DeclRefType;
14052   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14053                              /*BuildAndDiagnose=*/false, CaptureType,
14054                              DeclRefType, nullptr);
14055 }
14056 
14057 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14058   QualType CaptureType;
14059   QualType DeclRefType;
14060 
14061   // Determine whether we can capture this variable.
14062   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14063                          /*BuildAndDiagnose=*/false, CaptureType,
14064                          DeclRefType, nullptr))
14065     return QualType();
14066 
14067   return DeclRefType;
14068 }
14069 
14070 
14071 
14072 // If either the type of the variable or the initializer is dependent,
14073 // return false. Otherwise, determine whether the variable is a constant
14074 // expression. Use this if you need to know if a variable that might or
14075 // might not be dependent is truly a constant expression.
14076 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14077     ASTContext &Context) {
14078 
14079   if (Var->getType()->isDependentType())
14080     return false;
14081   const VarDecl *DefVD = nullptr;
14082   Var->getAnyInitializer(DefVD);
14083   if (!DefVD)
14084     return false;
14085   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14086   Expr *Init = cast<Expr>(Eval->Value);
14087   if (Init->isValueDependent())
14088     return false;
14089   return IsVariableAConstantExpression(Var, Context);
14090 }
14091 
14092 
14093 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14094   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14095   // an object that satisfies the requirements for appearing in a
14096   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14097   // is immediately applied."  This function handles the lvalue-to-rvalue
14098   // conversion part.
14099   MaybeODRUseExprs.erase(E->IgnoreParens());
14100 
14101   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14102   // to a variable that is a constant expression, and if so, identify it as
14103   // a reference to a variable that does not involve an odr-use of that
14104   // variable.
14105   if (LambdaScopeInfo *LSI = getCurLambda()) {
14106     Expr *SansParensExpr = E->IgnoreParens();
14107     VarDecl *Var = nullptr;
14108     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14109       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14110     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14111       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14112 
14113     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14114       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14115   }
14116 }
14117 
14118 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14119   Res = CorrectDelayedTyposInExpr(Res);
14120 
14121   if (!Res.isUsable())
14122     return Res;
14123 
14124   // If a constant-expression is a reference to a variable where we delay
14125   // deciding whether it is an odr-use, just assume we will apply the
14126   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14127   // (a non-type template argument), we have special handling anyway.
14128   UpdateMarkingForLValueToRValue(Res.get());
14129   return Res;
14130 }
14131 
14132 void Sema::CleanupVarDeclMarking() {
14133   for (Expr *E : MaybeODRUseExprs) {
14134     VarDecl *Var;
14135     SourceLocation Loc;
14136     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14137       Var = cast<VarDecl>(DRE->getDecl());
14138       Loc = DRE->getLocation();
14139     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14140       Var = cast<VarDecl>(ME->getMemberDecl());
14141       Loc = ME->getMemberLoc();
14142     } else {
14143       llvm_unreachable("Unexpected expression");
14144     }
14145 
14146     MarkVarDeclODRUsed(Var, Loc, *this,
14147                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14148   }
14149 
14150   MaybeODRUseExprs.clear();
14151 }
14152 
14153 
14154 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14155                                     VarDecl *Var, Expr *E) {
14156   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14157          "Invalid Expr argument to DoMarkVarDeclReferenced");
14158   Var->setReferenced();
14159 
14160   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14161 
14162   bool OdrUseContext = isOdrUseContext(SemaRef);
14163   bool NeedDefinition =
14164       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14165                         Var->isUsableInConstantExpressions(SemaRef.Context));
14166 
14167   VarTemplateSpecializationDecl *VarSpec =
14168       dyn_cast<VarTemplateSpecializationDecl>(Var);
14169   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14170          "Can't instantiate a partial template specialization.");
14171 
14172   // If this might be a member specialization of a static data member, check
14173   // the specialization is visible. We already did the checks for variable
14174   // template specializations when we created them.
14175   if (NeedDefinition && TSK != TSK_Undeclared &&
14176       !isa<VarTemplateSpecializationDecl>(Var))
14177     SemaRef.checkSpecializationVisibility(Loc, Var);
14178 
14179   // Perform implicit instantiation of static data members, static data member
14180   // templates of class templates, and variable template specializations. Delay
14181   // instantiations of variable templates, except for those that could be used
14182   // in a constant expression.
14183   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14184     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14185 
14186     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14187       if (Var->getPointOfInstantiation().isInvalid()) {
14188         // This is a modification of an existing AST node. Notify listeners.
14189         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14190           L->StaticDataMemberInstantiated(Var);
14191       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14192         // Don't bother trying to instantiate it again, unless we might need
14193         // its initializer before we get to the end of the TU.
14194         TryInstantiating = false;
14195     }
14196 
14197     if (Var->getPointOfInstantiation().isInvalid())
14198       Var->setTemplateSpecializationKind(TSK, Loc);
14199 
14200     if (TryInstantiating) {
14201       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14202       bool InstantiationDependent = false;
14203       bool IsNonDependent =
14204           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14205                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14206                   : true;
14207 
14208       // Do not instantiate specializations that are still type-dependent.
14209       if (IsNonDependent) {
14210         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14211           // Do not defer instantiations of variables which could be used in a
14212           // constant expression.
14213           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14214         } else {
14215           SemaRef.PendingInstantiations
14216               .push_back(std::make_pair(Var, PointOfInstantiation));
14217         }
14218       }
14219     }
14220   }
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 (OdrUseContext && E &&
14231       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14232     // A reference initialized by a constant expression can never be
14233     // odr-used, so simply ignore it.
14234     if (!Var->getType()->isReferenceType())
14235       SemaRef.MaybeODRUseExprs.insert(E);
14236   } else if (OdrUseContext) {
14237     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14238                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14239   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14240     // If this is a dependent context, we don't need to mark variables as
14241     // odr-used, but we may still need to track them for lambda capture.
14242     // FIXME: Do we also need to do this inside dependent typeid expressions
14243     // (which are modeled as unevaluated at this point)?
14244     const bool RefersToEnclosingScope =
14245         (SemaRef.CurContext != Var->getDeclContext() &&
14246          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14247     if (RefersToEnclosingScope) {
14248       if (LambdaScopeInfo *const LSI =
14249               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14250         // If a variable could potentially be odr-used, defer marking it so
14251         // until we finish analyzing the full expression for any
14252         // lvalue-to-rvalue
14253         // or discarded value conversions that would obviate odr-use.
14254         // Add it to the list of potential captures that will be analyzed
14255         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14256         // unless the variable is a reference that was initialized by a constant
14257         // expression (this will never need to be captured or odr-used).
14258         assert(E && "Capture variable should be used in an expression.");
14259         if (!Var->getType()->isReferenceType() ||
14260             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14261           LSI->addPotentialCapture(E->IgnoreParens());
14262       }
14263     }
14264   }
14265 }
14266 
14267 /// \brief Mark a variable referenced, and check whether it is odr-used
14268 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14269 /// used directly for normal expressions referring to VarDecl.
14270 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14271   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14272 }
14273 
14274 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14275                                Decl *D, Expr *E, bool MightBeOdrUse) {
14276   if (SemaRef.isInOpenMPDeclareTargetContext())
14277     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14278 
14279   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14280     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14281     return;
14282   }
14283 
14284   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14285 
14286   // If this is a call to a method via a cast, also mark the method in the
14287   // derived class used in case codegen can devirtualize the call.
14288   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14289   if (!ME)
14290     return;
14291   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14292   if (!MD)
14293     return;
14294   // Only attempt to devirtualize if this is truly a virtual call.
14295   bool IsVirtualCall = MD->isVirtual() &&
14296                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14297   if (!IsVirtualCall)
14298     return;
14299   const Expr *Base = ME->getBase();
14300   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14301   if (!MostDerivedClassDecl)
14302     return;
14303   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14304   if (!DM || DM->isPure())
14305     return;
14306   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14307 }
14308 
14309 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14310 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14311   // TODO: update this with DR# once a defect report is filed.
14312   // C++11 defect. The address of a pure member should not be an ODR use, even
14313   // if it's a qualified reference.
14314   bool OdrUse = true;
14315   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14316     if (Method->isVirtual())
14317       OdrUse = false;
14318   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14319 }
14320 
14321 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14322 void Sema::MarkMemberReferenced(MemberExpr *E) {
14323   // C++11 [basic.def.odr]p2:
14324   //   A non-overloaded function whose name appears as a potentially-evaluated
14325   //   expression or a member of a set of candidate functions, if selected by
14326   //   overload resolution when referred to from a potentially-evaluated
14327   //   expression, is odr-used, unless it is a pure virtual function and its
14328   //   name is not explicitly qualified.
14329   bool MightBeOdrUse = true;
14330   if (E->performsVirtualDispatch(getLangOpts())) {
14331     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14332       if (Method->isPure())
14333         MightBeOdrUse = false;
14334   }
14335   SourceLocation Loc = E->getMemberLoc().isValid() ?
14336                             E->getMemberLoc() : E->getLocStart();
14337   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14338 }
14339 
14340 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14341 /// marks the declaration referenced, and performs odr-use checking for
14342 /// functions and variables. This method should not be used when building a
14343 /// normal expression which refers to a variable.
14344 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14345                                  bool MightBeOdrUse) {
14346   if (MightBeOdrUse) {
14347     if (auto *VD = dyn_cast<VarDecl>(D)) {
14348       MarkVariableReferenced(Loc, VD);
14349       return;
14350     }
14351   }
14352   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14353     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14354     return;
14355   }
14356   D->setReferenced();
14357 }
14358 
14359 namespace {
14360   // Mark all of the declarations used by a type as referenced.
14361   // FIXME: Not fully implemented yet! We need to have a better understanding
14362   // of when we're entering a context we should not recurse into.
14363   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14364   // TreeTransforms rebuilding the type in a new context. Rather than
14365   // duplicating the TreeTransform logic, we should consider reusing it here.
14366   // Currently that causes problems when rebuilding LambdaExprs.
14367   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14368     Sema &S;
14369     SourceLocation Loc;
14370 
14371   public:
14372     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14373 
14374     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14375 
14376     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14377   };
14378 }
14379 
14380 bool MarkReferencedDecls::TraverseTemplateArgument(
14381     const TemplateArgument &Arg) {
14382   {
14383     // A non-type template argument is a constant-evaluated context.
14384     EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated);
14385     if (Arg.getKind() == TemplateArgument::Declaration) {
14386       if (Decl *D = Arg.getAsDecl())
14387         S.MarkAnyDeclReferenced(Loc, D, true);
14388     } else if (Arg.getKind() == TemplateArgument::Expression) {
14389       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14390     }
14391   }
14392 
14393   return Inherited::TraverseTemplateArgument(Arg);
14394 }
14395 
14396 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14397   MarkReferencedDecls Marker(*this, Loc);
14398   Marker.TraverseType(T);
14399 }
14400 
14401 namespace {
14402   /// \brief Helper class that marks all of the declarations referenced by
14403   /// potentially-evaluated subexpressions as "referenced".
14404   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14405     Sema &S;
14406     bool SkipLocalVariables;
14407 
14408   public:
14409     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14410 
14411     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14412       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14413 
14414     void VisitDeclRefExpr(DeclRefExpr *E) {
14415       // If we were asked not to visit local variables, don't.
14416       if (SkipLocalVariables) {
14417         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14418           if (VD->hasLocalStorage())
14419             return;
14420       }
14421 
14422       S.MarkDeclRefReferenced(E);
14423     }
14424 
14425     void VisitMemberExpr(MemberExpr *E) {
14426       S.MarkMemberReferenced(E);
14427       Inherited::VisitMemberExpr(E);
14428     }
14429 
14430     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14431       S.MarkFunctionReferenced(E->getLocStart(),
14432             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14433       Visit(E->getSubExpr());
14434     }
14435 
14436     void VisitCXXNewExpr(CXXNewExpr *E) {
14437       if (E->getOperatorNew())
14438         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14439       if (E->getOperatorDelete())
14440         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14441       Inherited::VisitCXXNewExpr(E);
14442     }
14443 
14444     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14445       if (E->getOperatorDelete())
14446         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14447       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14448       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14449         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14450         S.MarkFunctionReferenced(E->getLocStart(),
14451                                     S.LookupDestructor(Record));
14452       }
14453 
14454       Inherited::VisitCXXDeleteExpr(E);
14455     }
14456 
14457     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14458       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14459       Inherited::VisitCXXConstructExpr(E);
14460     }
14461 
14462     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14463       Visit(E->getExpr());
14464     }
14465 
14466     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14467       Inherited::VisitImplicitCastExpr(E);
14468 
14469       if (E->getCastKind() == CK_LValueToRValue)
14470         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14471     }
14472   };
14473 }
14474 
14475 /// \brief Mark any declarations that appear within this expression or any
14476 /// potentially-evaluated subexpressions as "referenced".
14477 ///
14478 /// \param SkipLocalVariables If true, don't mark local variables as
14479 /// 'referenced'.
14480 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14481                                             bool SkipLocalVariables) {
14482   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14483 }
14484 
14485 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14486 /// of the program being compiled.
14487 ///
14488 /// This routine emits the given diagnostic when the code currently being
14489 /// type-checked is "potentially evaluated", meaning that there is a
14490 /// possibility that the code will actually be executable. Code in sizeof()
14491 /// expressions, code used only during overload resolution, etc., are not
14492 /// potentially evaluated. This routine will suppress such diagnostics or,
14493 /// in the absolutely nutty case of potentially potentially evaluated
14494 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14495 /// later.
14496 ///
14497 /// This routine should be used for all diagnostics that describe the run-time
14498 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14499 /// Failure to do so will likely result in spurious diagnostics or failures
14500 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14501 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14502                                const PartialDiagnostic &PD) {
14503   switch (ExprEvalContexts.back().Context) {
14504   case Unevaluated:
14505   case UnevaluatedList:
14506   case UnevaluatedAbstract:
14507   case DiscardedStatement:
14508     // The argument will never be evaluated, so don't complain.
14509     break;
14510 
14511   case ConstantEvaluated:
14512     // Relevant diagnostics should be produced by constant evaluation.
14513     break;
14514 
14515   case PotentiallyEvaluated:
14516   case PotentiallyEvaluatedIfUsed:
14517     if (Statement && getCurFunctionOrMethodDecl()) {
14518       FunctionScopes.back()->PossiblyUnreachableDiags.
14519         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14520     }
14521     else
14522       Diag(Loc, PD);
14523 
14524     return true;
14525   }
14526 
14527   return false;
14528 }
14529 
14530 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14531                                CallExpr *CE, FunctionDecl *FD) {
14532   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14533     return false;
14534 
14535   // If we're inside a decltype's expression, don't check for a valid return
14536   // type or construct temporaries until we know whether this is the last call.
14537   if (ExprEvalContexts.back().IsDecltype) {
14538     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14539     return false;
14540   }
14541 
14542   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14543     FunctionDecl *FD;
14544     CallExpr *CE;
14545 
14546   public:
14547     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14548       : FD(FD), CE(CE) { }
14549 
14550     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14551       if (!FD) {
14552         S.Diag(Loc, diag::err_call_incomplete_return)
14553           << T << CE->getSourceRange();
14554         return;
14555       }
14556 
14557       S.Diag(Loc, diag::err_call_function_incomplete_return)
14558         << CE->getSourceRange() << FD->getDeclName() << T;
14559       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14560           << FD->getDeclName();
14561     }
14562   } Diagnoser(FD, CE);
14563 
14564   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14565     return true;
14566 
14567   return false;
14568 }
14569 
14570 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14571 // will prevent this condition from triggering, which is what we want.
14572 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14573   SourceLocation Loc;
14574 
14575   unsigned diagnostic = diag::warn_condition_is_assignment;
14576   bool IsOrAssign = false;
14577 
14578   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14579     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14580       return;
14581 
14582     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14583 
14584     // Greylist some idioms by putting them into a warning subcategory.
14585     if (ObjCMessageExpr *ME
14586           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14587       Selector Sel = ME->getSelector();
14588 
14589       // self = [<foo> init...]
14590       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14591         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14592 
14593       // <foo> = [<bar> nextObject]
14594       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14595         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14596     }
14597 
14598     Loc = Op->getOperatorLoc();
14599   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14600     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14601       return;
14602 
14603     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14604     Loc = Op->getOperatorLoc();
14605   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14606     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14607   else {
14608     // Not an assignment.
14609     return;
14610   }
14611 
14612   Diag(Loc, diagnostic) << E->getSourceRange();
14613 
14614   SourceLocation Open = E->getLocStart();
14615   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14616   Diag(Loc, diag::note_condition_assign_silence)
14617         << FixItHint::CreateInsertion(Open, "(")
14618         << FixItHint::CreateInsertion(Close, ")");
14619 
14620   if (IsOrAssign)
14621     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14622       << FixItHint::CreateReplacement(Loc, "!=");
14623   else
14624     Diag(Loc, diag::note_condition_assign_to_comparison)
14625       << FixItHint::CreateReplacement(Loc, "==");
14626 }
14627 
14628 /// \brief Redundant parentheses over an equality comparison can indicate
14629 /// that the user intended an assignment used as condition.
14630 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14631   // Don't warn if the parens came from a macro.
14632   SourceLocation parenLoc = ParenE->getLocStart();
14633   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14634     return;
14635   // Don't warn for dependent expressions.
14636   if (ParenE->isTypeDependent())
14637     return;
14638 
14639   Expr *E = ParenE->IgnoreParens();
14640 
14641   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14642     if (opE->getOpcode() == BO_EQ &&
14643         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14644                                                            == Expr::MLV_Valid) {
14645       SourceLocation Loc = opE->getOperatorLoc();
14646 
14647       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14648       SourceRange ParenERange = ParenE->getSourceRange();
14649       Diag(Loc, diag::note_equality_comparison_silence)
14650         << FixItHint::CreateRemoval(ParenERange.getBegin())
14651         << FixItHint::CreateRemoval(ParenERange.getEnd());
14652       Diag(Loc, diag::note_equality_comparison_to_assign)
14653         << FixItHint::CreateReplacement(Loc, "=");
14654     }
14655 }
14656 
14657 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14658                                        bool IsConstexpr) {
14659   DiagnoseAssignmentAsCondition(E);
14660   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14661     DiagnoseEqualityWithExtraParens(parenE);
14662 
14663   ExprResult result = CheckPlaceholderExpr(E);
14664   if (result.isInvalid()) return ExprError();
14665   E = result.get();
14666 
14667   if (!E->isTypeDependent()) {
14668     if (getLangOpts().CPlusPlus)
14669       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14670 
14671     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14672     if (ERes.isInvalid())
14673       return ExprError();
14674     E = ERes.get();
14675 
14676     QualType T = E->getType();
14677     if (!T->isScalarType()) { // C99 6.8.4.1p1
14678       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14679         << T << E->getSourceRange();
14680       return ExprError();
14681     }
14682     CheckBoolLikeConversion(E, Loc);
14683   }
14684 
14685   return E;
14686 }
14687 
14688 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14689                                            Expr *SubExpr, ConditionKind CK) {
14690   // Empty conditions are valid in for-statements.
14691   if (!SubExpr)
14692     return ConditionResult();
14693 
14694   ExprResult Cond;
14695   switch (CK) {
14696   case ConditionKind::Boolean:
14697     Cond = CheckBooleanCondition(Loc, SubExpr);
14698     break;
14699 
14700   case ConditionKind::ConstexprIf:
14701     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14702     break;
14703 
14704   case ConditionKind::Switch:
14705     Cond = CheckSwitchCondition(Loc, SubExpr);
14706     break;
14707   }
14708   if (Cond.isInvalid())
14709     return ConditionError();
14710 
14711   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14712   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14713   if (!FullExpr.get())
14714     return ConditionError();
14715 
14716   return ConditionResult(*this, nullptr, FullExpr,
14717                          CK == ConditionKind::ConstexprIf);
14718 }
14719 
14720 namespace {
14721   /// A visitor for rebuilding a call to an __unknown_any expression
14722   /// to have an appropriate type.
14723   struct RebuildUnknownAnyFunction
14724     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14725 
14726     Sema &S;
14727 
14728     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14729 
14730     ExprResult VisitStmt(Stmt *S) {
14731       llvm_unreachable("unexpected statement!");
14732     }
14733 
14734     ExprResult VisitExpr(Expr *E) {
14735       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14736         << E->getSourceRange();
14737       return ExprError();
14738     }
14739 
14740     /// Rebuild an expression which simply semantically wraps another
14741     /// expression which it shares the type and value kind of.
14742     template <class T> ExprResult rebuildSugarExpr(T *E) {
14743       ExprResult SubResult = Visit(E->getSubExpr());
14744       if (SubResult.isInvalid()) return ExprError();
14745 
14746       Expr *SubExpr = SubResult.get();
14747       E->setSubExpr(SubExpr);
14748       E->setType(SubExpr->getType());
14749       E->setValueKind(SubExpr->getValueKind());
14750       assert(E->getObjectKind() == OK_Ordinary);
14751       return E;
14752     }
14753 
14754     ExprResult VisitParenExpr(ParenExpr *E) {
14755       return rebuildSugarExpr(E);
14756     }
14757 
14758     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14759       return rebuildSugarExpr(E);
14760     }
14761 
14762     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14763       ExprResult SubResult = Visit(E->getSubExpr());
14764       if (SubResult.isInvalid()) return ExprError();
14765 
14766       Expr *SubExpr = SubResult.get();
14767       E->setSubExpr(SubExpr);
14768       E->setType(S.Context.getPointerType(SubExpr->getType()));
14769       assert(E->getValueKind() == VK_RValue);
14770       assert(E->getObjectKind() == OK_Ordinary);
14771       return E;
14772     }
14773 
14774     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14775       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14776 
14777       E->setType(VD->getType());
14778 
14779       assert(E->getValueKind() == VK_RValue);
14780       if (S.getLangOpts().CPlusPlus &&
14781           !(isa<CXXMethodDecl>(VD) &&
14782             cast<CXXMethodDecl>(VD)->isInstance()))
14783         E->setValueKind(VK_LValue);
14784 
14785       return E;
14786     }
14787 
14788     ExprResult VisitMemberExpr(MemberExpr *E) {
14789       return resolveDecl(E, E->getMemberDecl());
14790     }
14791 
14792     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14793       return resolveDecl(E, E->getDecl());
14794     }
14795   };
14796 }
14797 
14798 /// Given a function expression of unknown-any type, try to rebuild it
14799 /// to have a function type.
14800 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14801   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14802   if (Result.isInvalid()) return ExprError();
14803   return S.DefaultFunctionArrayConversion(Result.get());
14804 }
14805 
14806 namespace {
14807   /// A visitor for rebuilding an expression of type __unknown_anytype
14808   /// into one which resolves the type directly on the referring
14809   /// expression.  Strict preservation of the original source
14810   /// structure is not a goal.
14811   struct RebuildUnknownAnyExpr
14812     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14813 
14814     Sema &S;
14815 
14816     /// The current destination type.
14817     QualType DestType;
14818 
14819     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14820       : S(S), DestType(CastType) {}
14821 
14822     ExprResult VisitStmt(Stmt *S) {
14823       llvm_unreachable("unexpected statement!");
14824     }
14825 
14826     ExprResult VisitExpr(Expr *E) {
14827       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14828         << E->getSourceRange();
14829       return ExprError();
14830     }
14831 
14832     ExprResult VisitCallExpr(CallExpr *E);
14833     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14834 
14835     /// Rebuild an expression which simply semantically wraps another
14836     /// expression which it shares the type and value kind of.
14837     template <class T> ExprResult rebuildSugarExpr(T *E) {
14838       ExprResult SubResult = Visit(E->getSubExpr());
14839       if (SubResult.isInvalid()) return ExprError();
14840       Expr *SubExpr = SubResult.get();
14841       E->setSubExpr(SubExpr);
14842       E->setType(SubExpr->getType());
14843       E->setValueKind(SubExpr->getValueKind());
14844       assert(E->getObjectKind() == OK_Ordinary);
14845       return E;
14846     }
14847 
14848     ExprResult VisitParenExpr(ParenExpr *E) {
14849       return rebuildSugarExpr(E);
14850     }
14851 
14852     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14853       return rebuildSugarExpr(E);
14854     }
14855 
14856     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14857       const PointerType *Ptr = DestType->getAs<PointerType>();
14858       if (!Ptr) {
14859         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14860           << E->getSourceRange();
14861         return ExprError();
14862       }
14863 
14864       if (isa<CallExpr>(E->getSubExpr())) {
14865         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14866           << E->getSourceRange();
14867         return ExprError();
14868       }
14869 
14870       assert(E->getValueKind() == VK_RValue);
14871       assert(E->getObjectKind() == OK_Ordinary);
14872       E->setType(DestType);
14873 
14874       // Build the sub-expression as if it were an object of the pointee type.
14875       DestType = Ptr->getPointeeType();
14876       ExprResult SubResult = Visit(E->getSubExpr());
14877       if (SubResult.isInvalid()) return ExprError();
14878       E->setSubExpr(SubResult.get());
14879       return E;
14880     }
14881 
14882     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14883 
14884     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14885 
14886     ExprResult VisitMemberExpr(MemberExpr *E) {
14887       return resolveDecl(E, E->getMemberDecl());
14888     }
14889 
14890     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14891       return resolveDecl(E, E->getDecl());
14892     }
14893   };
14894 }
14895 
14896 /// Rebuilds a call expression which yielded __unknown_anytype.
14897 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14898   Expr *CalleeExpr = E->getCallee();
14899 
14900   enum FnKind {
14901     FK_MemberFunction,
14902     FK_FunctionPointer,
14903     FK_BlockPointer
14904   };
14905 
14906   FnKind Kind;
14907   QualType CalleeType = CalleeExpr->getType();
14908   if (CalleeType == S.Context.BoundMemberTy) {
14909     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14910     Kind = FK_MemberFunction;
14911     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14912   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14913     CalleeType = Ptr->getPointeeType();
14914     Kind = FK_FunctionPointer;
14915   } else {
14916     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14917     Kind = FK_BlockPointer;
14918   }
14919   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14920 
14921   // Verify that this is a legal result type of a function.
14922   if (DestType->isArrayType() || DestType->isFunctionType()) {
14923     unsigned diagID = diag::err_func_returning_array_function;
14924     if (Kind == FK_BlockPointer)
14925       diagID = diag::err_block_returning_array_function;
14926 
14927     S.Diag(E->getExprLoc(), diagID)
14928       << DestType->isFunctionType() << DestType;
14929     return ExprError();
14930   }
14931 
14932   // Otherwise, go ahead and set DestType as the call's result.
14933   E->setType(DestType.getNonLValueExprType(S.Context));
14934   E->setValueKind(Expr::getValueKindForType(DestType));
14935   assert(E->getObjectKind() == OK_Ordinary);
14936 
14937   // Rebuild the function type, replacing the result type with DestType.
14938   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14939   if (Proto) {
14940     // __unknown_anytype(...) is a special case used by the debugger when
14941     // it has no idea what a function's signature is.
14942     //
14943     // We want to build this call essentially under the K&R
14944     // unprototyped rules, but making a FunctionNoProtoType in C++
14945     // would foul up all sorts of assumptions.  However, we cannot
14946     // simply pass all arguments as variadic arguments, nor can we
14947     // portably just call the function under a non-variadic type; see
14948     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14949     // However, it turns out that in practice it is generally safe to
14950     // call a function declared as "A foo(B,C,D);" under the prototype
14951     // "A foo(B,C,D,...);".  The only known exception is with the
14952     // Windows ABI, where any variadic function is implicitly cdecl
14953     // regardless of its normal CC.  Therefore we change the parameter
14954     // types to match the types of the arguments.
14955     //
14956     // This is a hack, but it is far superior to moving the
14957     // corresponding target-specific code from IR-gen to Sema/AST.
14958 
14959     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14960     SmallVector<QualType, 8> ArgTypes;
14961     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14962       ArgTypes.reserve(E->getNumArgs());
14963       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14964         Expr *Arg = E->getArg(i);
14965         QualType ArgType = Arg->getType();
14966         if (E->isLValue()) {
14967           ArgType = S.Context.getLValueReferenceType(ArgType);
14968         } else if (E->isXValue()) {
14969           ArgType = S.Context.getRValueReferenceType(ArgType);
14970         }
14971         ArgTypes.push_back(ArgType);
14972       }
14973       ParamTypes = ArgTypes;
14974     }
14975     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14976                                          Proto->getExtProtoInfo());
14977   } else {
14978     DestType = S.Context.getFunctionNoProtoType(DestType,
14979                                                 FnType->getExtInfo());
14980   }
14981 
14982   // Rebuild the appropriate pointer-to-function type.
14983   switch (Kind) {
14984   case FK_MemberFunction:
14985     // Nothing to do.
14986     break;
14987 
14988   case FK_FunctionPointer:
14989     DestType = S.Context.getPointerType(DestType);
14990     break;
14991 
14992   case FK_BlockPointer:
14993     DestType = S.Context.getBlockPointerType(DestType);
14994     break;
14995   }
14996 
14997   // Finally, we can recurse.
14998   ExprResult CalleeResult = Visit(CalleeExpr);
14999   if (!CalleeResult.isUsable()) return ExprError();
15000   E->setCallee(CalleeResult.get());
15001 
15002   // Bind a temporary if necessary.
15003   return S.MaybeBindToTemporary(E);
15004 }
15005 
15006 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15007   // Verify that this is a legal result type of a call.
15008   if (DestType->isArrayType() || DestType->isFunctionType()) {
15009     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15010       << DestType->isFunctionType() << DestType;
15011     return ExprError();
15012   }
15013 
15014   // Rewrite the method result type if available.
15015   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15016     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15017     Method->setReturnType(DestType);
15018   }
15019 
15020   // Change the type of the message.
15021   E->setType(DestType.getNonReferenceType());
15022   E->setValueKind(Expr::getValueKindForType(DestType));
15023 
15024   return S.MaybeBindToTemporary(E);
15025 }
15026 
15027 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15028   // The only case we should ever see here is a function-to-pointer decay.
15029   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15030     assert(E->getValueKind() == VK_RValue);
15031     assert(E->getObjectKind() == OK_Ordinary);
15032 
15033     E->setType(DestType);
15034 
15035     // Rebuild the sub-expression as the pointee (function) type.
15036     DestType = DestType->castAs<PointerType>()->getPointeeType();
15037 
15038     ExprResult Result = Visit(E->getSubExpr());
15039     if (!Result.isUsable()) return ExprError();
15040 
15041     E->setSubExpr(Result.get());
15042     return E;
15043   } else if (E->getCastKind() == CK_LValueToRValue) {
15044     assert(E->getValueKind() == VK_RValue);
15045     assert(E->getObjectKind() == OK_Ordinary);
15046 
15047     assert(isa<BlockPointerType>(E->getType()));
15048 
15049     E->setType(DestType);
15050 
15051     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15052     DestType = S.Context.getLValueReferenceType(DestType);
15053 
15054     ExprResult Result = Visit(E->getSubExpr());
15055     if (!Result.isUsable()) return ExprError();
15056 
15057     E->setSubExpr(Result.get());
15058     return E;
15059   } else {
15060     llvm_unreachable("Unhandled cast type!");
15061   }
15062 }
15063 
15064 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15065   ExprValueKind ValueKind = VK_LValue;
15066   QualType Type = DestType;
15067 
15068   // We know how to make this work for certain kinds of decls:
15069 
15070   //  - functions
15071   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15072     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15073       DestType = Ptr->getPointeeType();
15074       ExprResult Result = resolveDecl(E, VD);
15075       if (Result.isInvalid()) return ExprError();
15076       return S.ImpCastExprToType(Result.get(), Type,
15077                                  CK_FunctionToPointerDecay, VK_RValue);
15078     }
15079 
15080     if (!Type->isFunctionType()) {
15081       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15082         << VD << E->getSourceRange();
15083       return ExprError();
15084     }
15085     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15086       // We must match the FunctionDecl's type to the hack introduced in
15087       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15088       // type. See the lengthy commentary in that routine.
15089       QualType FDT = FD->getType();
15090       const FunctionType *FnType = FDT->castAs<FunctionType>();
15091       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15092       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15093       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15094         SourceLocation Loc = FD->getLocation();
15095         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15096                                       FD->getDeclContext(),
15097                                       Loc, Loc, FD->getNameInfo().getName(),
15098                                       DestType, FD->getTypeSourceInfo(),
15099                                       SC_None, false/*isInlineSpecified*/,
15100                                       FD->hasPrototype(),
15101                                       false/*isConstexprSpecified*/);
15102 
15103         if (FD->getQualifier())
15104           NewFD->setQualifierInfo(FD->getQualifierLoc());
15105 
15106         SmallVector<ParmVarDecl*, 16> Params;
15107         for (const auto &AI : FT->param_types()) {
15108           ParmVarDecl *Param =
15109             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15110           Param->setScopeInfo(0, Params.size());
15111           Params.push_back(Param);
15112         }
15113         NewFD->setParams(Params);
15114         DRE->setDecl(NewFD);
15115         VD = DRE->getDecl();
15116       }
15117     }
15118 
15119     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15120       if (MD->isInstance()) {
15121         ValueKind = VK_RValue;
15122         Type = S.Context.BoundMemberTy;
15123       }
15124 
15125     // Function references aren't l-values in C.
15126     if (!S.getLangOpts().CPlusPlus)
15127       ValueKind = VK_RValue;
15128 
15129   //  - variables
15130   } else if (isa<VarDecl>(VD)) {
15131     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15132       Type = RefTy->getPointeeType();
15133     } else if (Type->isFunctionType()) {
15134       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15135         << VD << E->getSourceRange();
15136       return ExprError();
15137     }
15138 
15139   //  - nothing else
15140   } else {
15141     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15142       << VD << E->getSourceRange();
15143     return ExprError();
15144   }
15145 
15146   // Modifying the declaration like this is friendly to IR-gen but
15147   // also really dangerous.
15148   VD->setType(DestType);
15149   E->setType(Type);
15150   E->setValueKind(ValueKind);
15151   return E;
15152 }
15153 
15154 /// Check a cast of an unknown-any type.  We intentionally only
15155 /// trigger this for C-style casts.
15156 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15157                                      Expr *CastExpr, CastKind &CastKind,
15158                                      ExprValueKind &VK, CXXCastPath &Path) {
15159   // The type we're casting to must be either void or complete.
15160   if (!CastType->isVoidType() &&
15161       RequireCompleteType(TypeRange.getBegin(), CastType,
15162                           diag::err_typecheck_cast_to_incomplete))
15163     return ExprError();
15164 
15165   // Rewrite the casted expression from scratch.
15166   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15167   if (!result.isUsable()) return ExprError();
15168 
15169   CastExpr = result.get();
15170   VK = CastExpr->getValueKind();
15171   CastKind = CK_NoOp;
15172 
15173   return CastExpr;
15174 }
15175 
15176 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15177   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15178 }
15179 
15180 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15181                                     Expr *arg, QualType &paramType) {
15182   // If the syntactic form of the argument is not an explicit cast of
15183   // any sort, just do default argument promotion.
15184   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15185   if (!castArg) {
15186     ExprResult result = DefaultArgumentPromotion(arg);
15187     if (result.isInvalid()) return ExprError();
15188     paramType = result.get()->getType();
15189     return result;
15190   }
15191 
15192   // Otherwise, use the type that was written in the explicit cast.
15193   assert(!arg->hasPlaceholderType());
15194   paramType = castArg->getTypeAsWritten();
15195 
15196   // Copy-initialize a parameter of that type.
15197   InitializedEntity entity =
15198     InitializedEntity::InitializeParameter(Context, paramType,
15199                                            /*consumed*/ false);
15200   return PerformCopyInitialization(entity, callLoc, arg);
15201 }
15202 
15203 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15204   Expr *orig = E;
15205   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15206   while (true) {
15207     E = E->IgnoreParenImpCasts();
15208     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15209       E = call->getCallee();
15210       diagID = diag::err_uncasted_call_of_unknown_any;
15211     } else {
15212       break;
15213     }
15214   }
15215 
15216   SourceLocation loc;
15217   NamedDecl *d;
15218   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15219     loc = ref->getLocation();
15220     d = ref->getDecl();
15221   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15222     loc = mem->getMemberLoc();
15223     d = mem->getMemberDecl();
15224   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15225     diagID = diag::err_uncasted_call_of_unknown_any;
15226     loc = msg->getSelectorStartLoc();
15227     d = msg->getMethodDecl();
15228     if (!d) {
15229       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15230         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15231         << orig->getSourceRange();
15232       return ExprError();
15233     }
15234   } else {
15235     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15236       << E->getSourceRange();
15237     return ExprError();
15238   }
15239 
15240   S.Diag(loc, diagID) << d << orig->getSourceRange();
15241 
15242   // Never recoverable.
15243   return ExprError();
15244 }
15245 
15246 /// Check for operands with placeholder types and complain if found.
15247 /// Returns true if there was an error and no recovery was possible.
15248 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15249   if (!getLangOpts().CPlusPlus) {
15250     // C cannot handle TypoExpr nodes on either side of a binop because it
15251     // doesn't handle dependent types properly, so make sure any TypoExprs have
15252     // been dealt with before checking the operands.
15253     ExprResult Result = CorrectDelayedTyposInExpr(E);
15254     if (!Result.isUsable()) return ExprError();
15255     E = Result.get();
15256   }
15257 
15258   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15259   if (!placeholderType) return E;
15260 
15261   switch (placeholderType->getKind()) {
15262 
15263   // Overloaded expressions.
15264   case BuiltinType::Overload: {
15265     // Try to resolve a single function template specialization.
15266     // This is obligatory.
15267     ExprResult Result = E;
15268     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15269       return Result;
15270 
15271     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15272     // leaves Result unchanged on failure.
15273     Result = E;
15274     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15275       return Result;
15276 
15277     // If that failed, try to recover with a call.
15278     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15279                          /*complain*/ true);
15280     return Result;
15281   }
15282 
15283   // Bound member functions.
15284   case BuiltinType::BoundMember: {
15285     ExprResult result = E;
15286     const Expr *BME = E->IgnoreParens();
15287     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15288     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15289     if (isa<CXXPseudoDestructorExpr>(BME)) {
15290       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15291     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15292       if (ME->getMemberNameInfo().getName().getNameKind() ==
15293           DeclarationName::CXXDestructorName)
15294         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15295     }
15296     tryToRecoverWithCall(result, PD,
15297                          /*complain*/ true);
15298     return result;
15299   }
15300 
15301   // ARC unbridged casts.
15302   case BuiltinType::ARCUnbridgedCast: {
15303     Expr *realCast = stripARCUnbridgedCast(E);
15304     diagnoseARCUnbridgedCast(realCast);
15305     return realCast;
15306   }
15307 
15308   // Expressions of unknown type.
15309   case BuiltinType::UnknownAny:
15310     return diagnoseUnknownAnyExpr(*this, E);
15311 
15312   // Pseudo-objects.
15313   case BuiltinType::PseudoObject:
15314     return checkPseudoObjectRValue(E);
15315 
15316   case BuiltinType::BuiltinFn: {
15317     // Accept __noop without parens by implicitly converting it to a call expr.
15318     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15319     if (DRE) {
15320       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15321       if (FD->getBuiltinID() == Builtin::BI__noop) {
15322         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15323                               CK_BuiltinFnToFnPtr).get();
15324         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15325                                       VK_RValue, SourceLocation());
15326       }
15327     }
15328 
15329     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15330     return ExprError();
15331   }
15332 
15333   // Expressions of unknown type.
15334   case BuiltinType::OMPArraySection:
15335     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15336     return ExprError();
15337 
15338   // Everything else should be impossible.
15339 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15340   case BuiltinType::Id:
15341 #include "clang/Basic/OpenCLImageTypes.def"
15342 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15343 #define PLACEHOLDER_TYPE(Id, SingletonId)
15344 #include "clang/AST/BuiltinTypes.def"
15345     break;
15346   }
15347 
15348   llvm_unreachable("invalid placeholder type!");
15349 }
15350 
15351 bool Sema::CheckCaseExpression(Expr *E) {
15352   if (E->isTypeDependent())
15353     return true;
15354   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15355     return E->getType()->isIntegralOrEnumerationType();
15356   return false;
15357 }
15358 
15359 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15360 ExprResult
15361 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15362   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15363          "Unknown Objective-C Boolean value!");
15364   QualType BoolT = Context.ObjCBuiltinBoolTy;
15365   if (!Context.getBOOLDecl()) {
15366     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15367                         Sema::LookupOrdinaryName);
15368     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15369       NamedDecl *ND = Result.getFoundDecl();
15370       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15371         Context.setBOOLDecl(TD);
15372     }
15373   }
15374   if (Context.getBOOLDecl())
15375     BoolT = Context.getBOOLType();
15376   return new (Context)
15377       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15378 }
15379 
15380 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15381     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15382     SourceLocation RParen) {
15383 
15384   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15385 
15386   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15387                            [&](const AvailabilitySpec &Spec) {
15388                              return Spec.getPlatform() == Platform;
15389                            });
15390 
15391   VersionTuple Version;
15392   if (Spec != AvailSpecs.end())
15393     Version = Spec->getVersion();
15394 
15395   return new (Context)
15396       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15397 }
15398