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) {
175       if (S.getCurFunctionOrMethodDecl()) {
176         S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
177         return;
178       } else if (S.getCurBlock() || S.getCurLambda()) {
179         S.getCurFunction()->HasPotentialAvailabilityViolations = true;
180         return;
181       }
182     }
183 
184     const ObjCPropertyDecl *ObjCPDecl = nullptr;
185     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
186       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
187         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
188         if (PDeclResult == Result)
189           ObjCPDecl = PD;
190       }
191     }
192 
193     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
194                               ObjCPDecl, ObjCPropertyAccess);
195   }
196 }
197 
198 /// \brief Emit a note explaining that this function is deleted.
199 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
200   assert(Decl->isDeleted());
201 
202   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
203 
204   if (Method && Method->isDeleted() && Method->isDefaulted()) {
205     // If the method was explicitly defaulted, point at that declaration.
206     if (!Method->isImplicit())
207       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
208 
209     // Try to diagnose why this special member function was implicitly
210     // deleted. This might fail, if that reason no longer applies.
211     CXXSpecialMember CSM = getSpecialMember(Method);
212     if (CSM != CXXInvalid)
213       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
214 
215     return;
216   }
217 
218   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
219   if (Ctor && Ctor->isInheritingConstructor())
220     return NoteDeletedInheritingConstructor(Ctor);
221 
222   Diag(Decl->getLocation(), diag::note_availability_specified_here)
223     << Decl << true;
224 }
225 
226 /// \brief Determine whether a FunctionDecl was ever declared with an
227 /// explicit storage class.
228 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
229   for (auto I : D->redecls()) {
230     if (I->getStorageClass() != SC_None)
231       return true;
232   }
233   return false;
234 }
235 
236 /// \brief Check whether we're in an extern inline function and referring to a
237 /// variable or function with internal linkage (C11 6.7.4p3).
238 ///
239 /// This is only a warning because we used to silently accept this code, but
240 /// in many cases it will not behave correctly. This is not enabled in C++ mode
241 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
242 /// and so while there may still be user mistakes, most of the time we can't
243 /// prove that there are errors.
244 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
245                                                       const NamedDecl *D,
246                                                       SourceLocation Loc) {
247   // This is disabled under C++; there are too many ways for this to fire in
248   // contexts where the warning is a false positive, or where it is technically
249   // correct but benign.
250   if (S.getLangOpts().CPlusPlus)
251     return;
252 
253   // Check if this is an inlined function or method.
254   FunctionDecl *Current = S.getCurFunctionDecl();
255   if (!Current)
256     return;
257   if (!Current->isInlined())
258     return;
259   if (!Current->isExternallyVisible())
260     return;
261 
262   // Check if the decl has internal linkage.
263   if (D->getFormalLinkage() != InternalLinkage)
264     return;
265 
266   // Downgrade from ExtWarn to Extension if
267   //  (1) the supposedly external inline function is in the main file,
268   //      and probably won't be included anywhere else.
269   //  (2) the thing we're referencing is a pure function.
270   //  (3) the thing we're referencing is another inline function.
271   // This last can give us false negatives, but it's better than warning on
272   // wrappers for simple C library functions.
273   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
274   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
275   if (!DowngradeWarning && UsedFn)
276     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
277 
278   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
279                                : diag::ext_internal_in_extern_inline)
280     << /*IsVar=*/!UsedFn << D;
281 
282   S.MaybeSuggestAddingStaticToDecl(Current);
283 
284   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
285       << D;
286 }
287 
288 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
289   const FunctionDecl *First = Cur->getFirstDecl();
290 
291   // Suggest "static" on the function, if possible.
292   if (!hasAnyExplicitStorageClass(First)) {
293     SourceLocation DeclBegin = First->getSourceRange().getBegin();
294     Diag(DeclBegin, diag::note_convert_inline_to_static)
295       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
296   }
297 }
298 
299 /// \brief Determine whether the use of this declaration is valid, and
300 /// emit any corresponding diagnostics.
301 ///
302 /// This routine diagnoses various problems with referencing
303 /// declarations that can occur when using a declaration. For example,
304 /// it might warn if a deprecated or unavailable declaration is being
305 /// used, or produce an error (and return true) if a C++0x deleted
306 /// function is being used.
307 ///
308 /// \returns true if there was an error (this declaration cannot be
309 /// referenced), false otherwise.
310 ///
311 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
312                              const ObjCInterfaceDecl *UnknownObjCClass,
313                              bool ObjCPropertyAccess) {
314   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
315     // If there were any diagnostics suppressed by template argument deduction,
316     // emit them now.
317     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
318     if (Pos != SuppressedDiagnostics.end()) {
319       for (const PartialDiagnosticAt &Suppressed : Pos->second)
320         Diag(Suppressed.first, Suppressed.second);
321 
322       // Clear out the list of suppressed diagnostics, so that we don't emit
323       // them again for this specialization. However, we don't obsolete this
324       // entry from the table, because we want to avoid ever emitting these
325       // diagnostics again.
326       Pos->second.clear();
327     }
328 
329     // C++ [basic.start.main]p3:
330     //   The function 'main' shall not be used within a program.
331     if (cast<FunctionDecl>(D)->isMain())
332       Diag(Loc, diag::ext_main_used);
333   }
334 
335   // See if this is an auto-typed variable whose initializer we are parsing.
336   if (ParsingInitForAutoVars.count(D)) {
337     if (isa<BindingDecl>(D)) {
338       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
339         << D->getDeclName();
340     } else {
341       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
342         << D->getDeclName() << cast<VarDecl>(D)->getType();
343     }
344     return true;
345   }
346 
347   // See if this is a deleted function.
348   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
349     if (FD->isDeleted()) {
350       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
351       if (Ctor && Ctor->isInheritingConstructor())
352         Diag(Loc, diag::err_deleted_inherited_ctor_use)
353             << Ctor->getParent()
354             << Ctor->getInheritedConstructor().getConstructor()->getParent();
355       else
356         Diag(Loc, diag::err_deleted_function_use);
357       NoteDeletedFunction(FD);
358       return true;
359     }
360 
361     // If the function has a deduced return type, and we can't deduce it,
362     // then we can't use it either.
363     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
364         DeduceReturnType(FD, Loc))
365       return true;
366 
367     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
368       return true;
369 
370     if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
371       return true;
372   }
373 
374   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
375   // Only the variables omp_in and omp_out are allowed in the combiner.
376   // Only the variables omp_priv and omp_orig are allowed in the
377   // initializer-clause.
378   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
379   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
380       isa<VarDecl>(D)) {
381     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
382         << getCurFunction()->HasOMPDeclareReductionCombiner;
383     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
384     return true;
385   }
386 
387   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
388                              ObjCPropertyAccess);
389 
390   DiagnoseUnusedOfDecl(*this, D, Loc);
391 
392   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
393 
394   return false;
395 }
396 
397 /// \brief Retrieve the message suffix that should be added to a
398 /// diagnostic complaining about the given function being deleted or
399 /// unavailable.
400 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
401   std::string Message;
402   if (FD->getAvailability(&Message))
403     return ": " + Message;
404 
405   return std::string();
406 }
407 
408 /// DiagnoseSentinelCalls - This routine checks whether a call or
409 /// message-send is to a declaration with the sentinel attribute, and
410 /// if so, it checks that the requirements of the sentinel are
411 /// satisfied.
412 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
413                                  ArrayRef<Expr *> Args) {
414   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
415   if (!attr)
416     return;
417 
418   // The number of formal parameters of the declaration.
419   unsigned numFormalParams;
420 
421   // The kind of declaration.  This is also an index into a %select in
422   // the diagnostic.
423   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
424 
425   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
426     numFormalParams = MD->param_size();
427     calleeType = CT_Method;
428   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
429     numFormalParams = FD->param_size();
430     calleeType = CT_Function;
431   } else if (isa<VarDecl>(D)) {
432     QualType type = cast<ValueDecl>(D)->getType();
433     const FunctionType *fn = nullptr;
434     if (const PointerType *ptr = type->getAs<PointerType>()) {
435       fn = ptr->getPointeeType()->getAs<FunctionType>();
436       if (!fn) return;
437       calleeType = CT_Function;
438     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
439       fn = ptr->getPointeeType()->castAs<FunctionType>();
440       calleeType = CT_Block;
441     } else {
442       return;
443     }
444 
445     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
446       numFormalParams = proto->getNumParams();
447     } else {
448       numFormalParams = 0;
449     }
450   } else {
451     return;
452   }
453 
454   // "nullPos" is the number of formal parameters at the end which
455   // effectively count as part of the variadic arguments.  This is
456   // useful if you would prefer to not have *any* formal parameters,
457   // but the language forces you to have at least one.
458   unsigned nullPos = attr->getNullPos();
459   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
460   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
461 
462   // The number of arguments which should follow the sentinel.
463   unsigned numArgsAfterSentinel = attr->getSentinel();
464 
465   // If there aren't enough arguments for all the formal parameters,
466   // the sentinel, and the args after the sentinel, complain.
467   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
468     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
470     return;
471   }
472 
473   // Otherwise, find the sentinel expression.
474   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
475   if (!sentinelExpr) return;
476   if (sentinelExpr->isValueDependent()) return;
477   if (Context.isSentinelNullExpr(sentinelExpr)) return;
478 
479   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
480   // or 'NULL' if those are actually defined in the context.  Only use
481   // 'nil' for ObjC methods, where it's much more likely that the
482   // variadic arguments form a list of object pointers.
483   SourceLocation MissingNilLoc
484     = getLocForEndOfToken(sentinelExpr->getLocEnd());
485   std::string NullValue;
486   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
487     NullValue = "nil";
488   else if (getLangOpts().CPlusPlus11)
489     NullValue = "nullptr";
490   else if (PP.isMacroDefined("NULL"))
491     NullValue = "NULL";
492   else
493     NullValue = "(void*) 0";
494 
495   if (MissingNilLoc.isInvalid())
496     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
497   else
498     Diag(MissingNilLoc, diag::warn_missing_sentinel)
499       << int(calleeType)
500       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
501   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
502 }
503 
504 SourceRange Sema::getExprRange(Expr *E) const {
505   return E ? E->getSourceRange() : SourceRange();
506 }
507 
508 //===----------------------------------------------------------------------===//
509 //  Standard Promotions and Conversions
510 //===----------------------------------------------------------------------===//
511 
512 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
513 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
514   // Handle any placeholder expressions which made it here.
515   if (E->getType()->isPlaceholderType()) {
516     ExprResult result = CheckPlaceholderExpr(E);
517     if (result.isInvalid()) return ExprError();
518     E = result.get();
519   }
520 
521   QualType Ty = E->getType();
522   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
523 
524   if (Ty->isFunctionType()) {
525     // If we are here, we are not calling a function but taking
526     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
527     if (getLangOpts().OpenCL) {
528       if (Diagnose)
529         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
530       return ExprError();
531     }
532 
533     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
534       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
536           return ExprError();
537 
538     E = ImpCastExprToType(E, Context.getPointerType(Ty),
539                           CK_FunctionToPointerDecay).get();
540   } else if (Ty->isArrayType()) {
541     // In C90 mode, arrays only promote to pointers if the array expression is
542     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543     // type 'array of type' is converted to an expression that has type 'pointer
544     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
545     // that has type 'array of type' ...".  The relevant change is "an lvalue"
546     // (C90) to "an expression" (C99).
547     //
548     // C++ 4.2p1:
549     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550     // T" can be converted to an rvalue of type "pointer to T".
551     //
552     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
553       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
554                             CK_ArrayToPointerDecay).get();
555   }
556   return E;
557 }
558 
559 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
560   // Check to see if we are dereferencing a null pointer.  If so,
561   // and if not volatile-qualified, this is undefined behavior that the
562   // optimizer will delete, so warn about it.  People sometimes try to use this
563   // to get a deterministic trap and are surprised by clang's behavior.  This
564   // only handles the pattern "*null", which is a very syntactic check.
565   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
566     if (UO->getOpcode() == UO_Deref &&
567         UO->getSubExpr()->IgnoreParenCasts()->
568           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
569         !UO->getType().isVolatileQualified()) {
570     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571                           S.PDiag(diag::warn_indirection_through_null)
572                             << UO->getSubExpr()->getSourceRange());
573     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
574                         S.PDiag(diag::note_indirection_through_null));
575   }
576 }
577 
578 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
579                                     SourceLocation AssignLoc,
580                                     const Expr* RHS) {
581   const ObjCIvarDecl *IV = OIRE->getDecl();
582   if (!IV)
583     return;
584 
585   DeclarationName MemberName = IV->getDeclName();
586   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
587   if (!Member || !Member->isStr("isa"))
588     return;
589 
590   const Expr *Base = OIRE->getBase();
591   QualType BaseType = Base->getType();
592   if (OIRE->isArrow())
593     BaseType = BaseType->getPointeeType();
594   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
595     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
596       ObjCInterfaceDecl *ClassDeclared = nullptr;
597       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
598       if (!ClassDeclared->getSuperClass()
599           && (*ClassDeclared->ivar_begin()) == IV) {
600         if (RHS) {
601           NamedDecl *ObjectSetClass =
602             S.LookupSingleName(S.TUScope,
603                                &S.Context.Idents.get("object_setClass"),
604                                SourceLocation(), S.LookupOrdinaryName);
605           if (ObjectSetClass) {
606             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
607             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
608             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
609             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
610                                                      AssignLoc), ",") <<
611             FixItHint::CreateInsertion(RHSLocEnd, ")");
612           }
613           else
614             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
615         } else {
616           NamedDecl *ObjectGetClass =
617             S.LookupSingleName(S.TUScope,
618                                &S.Context.Idents.get("object_getClass"),
619                                SourceLocation(), S.LookupOrdinaryName);
620           if (ObjectGetClass)
621             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
622             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
623             FixItHint::CreateReplacement(
624                                          SourceRange(OIRE->getOpLoc(),
625                                                      OIRE->getLocEnd()), ")");
626           else
627             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
628         }
629         S.Diag(IV->getLocation(), diag::note_ivar_decl);
630       }
631     }
632 }
633 
634 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
635   // Handle any placeholder expressions which made it here.
636   if (E->getType()->isPlaceholderType()) {
637     ExprResult result = CheckPlaceholderExpr(E);
638     if (result.isInvalid()) return ExprError();
639     E = result.get();
640   }
641 
642   // C++ [conv.lval]p1:
643   //   A glvalue of a non-function, non-array type T can be
644   //   converted to a prvalue.
645   if (!E->isGLValue()) return E;
646 
647   QualType T = E->getType();
648   assert(!T.isNull() && "r-value conversion on typeless expression?");
649 
650   // We don't want to throw lvalue-to-rvalue casts on top of
651   // expressions of certain types in C++.
652   if (getLangOpts().CPlusPlus &&
653       (E->getType() == Context.OverloadTy ||
654        T->isDependentType() ||
655        T->isRecordType()))
656     return E;
657 
658   // The C standard is actually really unclear on this point, and
659   // DR106 tells us what the result should be but not why.  It's
660   // generally best to say that void types just doesn't undergo
661   // lvalue-to-rvalue at all.  Note that expressions of unqualified
662   // 'void' type are never l-values, but qualified void can be.
663   if (T->isVoidType())
664     return E;
665 
666   // OpenCL usually rejects direct accesses to values of 'half' type.
667   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
668       T->isHalfType()) {
669     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
670       << 0 << T;
671     return ExprError();
672   }
673 
674   CheckForNullPointerDereference(*this, E);
675   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
676     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
677                                      &Context.Idents.get("object_getClass"),
678                                      SourceLocation(), LookupOrdinaryName);
679     if (ObjectGetClass)
680       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
681         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
682         FixItHint::CreateReplacement(
683                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
684     else
685       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
686   }
687   else if (const ObjCIvarRefExpr *OIRE =
688             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
689     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
690 
691   // C++ [conv.lval]p1:
692   //   [...] If T is a non-class type, the type of the prvalue is the
693   //   cv-unqualified version of T. Otherwise, the type of the
694   //   rvalue is T.
695   //
696   // C99 6.3.2.1p2:
697   //   If the lvalue has qualified type, the value has the unqualified
698   //   version of the type of the lvalue; otherwise, the value has the
699   //   type of the lvalue.
700   if (T.hasQualifiers())
701     T = T.getUnqualifiedType();
702 
703   // Under the MS ABI, lock down the inheritance model now.
704   if (T->isMemberPointerType() &&
705       Context.getTargetInfo().getCXXABI().isMicrosoft())
706     (void)isCompleteType(E->getExprLoc(), T);
707 
708   UpdateMarkingForLValueToRValue(E);
709 
710   // Loading a __weak object implicitly retains the value, so we need a cleanup to
711   // balance that.
712   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713     Cleanup.setExprNeedsCleanups(true);
714 
715   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
716                                             nullptr, VK_RValue);
717 
718   // C11 6.3.2.1p2:
719   //   ... if the lvalue has atomic type, the value has the non-atomic version
720   //   of the type of the lvalue ...
721   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
722     T = Atomic->getValueType().getUnqualifiedType();
723     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
724                                    nullptr, VK_RValue);
725   }
726 
727   return Res;
728 }
729 
730 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
731   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
732   if (Res.isInvalid())
733     return ExprError();
734   Res = DefaultLvalueConversion(Res.get());
735   if (Res.isInvalid())
736     return ExprError();
737   return Res;
738 }
739 
740 /// CallExprUnaryConversions - a special case of an unary conversion
741 /// performed on a function designator of a call expression.
742 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
743   QualType Ty = E->getType();
744   ExprResult Res = E;
745   // Only do implicit cast for a function type, but not for a pointer
746   // to function type.
747   if (Ty->isFunctionType()) {
748     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
749                             CK_FunctionToPointerDecay).get();
750     if (Res.isInvalid())
751       return ExprError();
752   }
753   Res = DefaultLvalueConversion(Res.get());
754   if (Res.isInvalid())
755     return ExprError();
756   return Res.get();
757 }
758 
759 /// UsualUnaryConversions - Performs various conversions that are common to most
760 /// operators (C99 6.3). The conversions of array and function types are
761 /// sometimes suppressed. For example, the array->pointer conversion doesn't
762 /// apply if the array is an argument to the sizeof or address (&) operators.
763 /// In these instances, this routine should *not* be called.
764 ExprResult Sema::UsualUnaryConversions(Expr *E) {
765   // First, convert to an r-value.
766   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
767   if (Res.isInvalid())
768     return ExprError();
769   E = Res.get();
770 
771   QualType Ty = E->getType();
772   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
773 
774   // Half FP have to be promoted to float unless it is natively supported
775   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
776     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
777 
778   // Try to perform integral promotions if the object has a theoretically
779   // promotable type.
780   if (Ty->isIntegralOrUnscopedEnumerationType()) {
781     // C99 6.3.1.1p2:
782     //
783     //   The following may be used in an expression wherever an int or
784     //   unsigned int may be used:
785     //     - an object or expression with an integer type whose integer
786     //       conversion rank is less than or equal to the rank of int
787     //       and unsigned int.
788     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
789     //
790     //   If an int can represent all values of the original type, the
791     //   value is converted to an int; otherwise, it is converted to an
792     //   unsigned int. These are called the integer promotions. All
793     //   other types are unchanged by the integer promotions.
794 
795     QualType PTy = Context.isPromotableBitField(E);
796     if (!PTy.isNull()) {
797       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
798       return E;
799     }
800     if (Ty->isPromotableIntegerType()) {
801       QualType PT = Context.getPromotedIntegerType(Ty);
802       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
803       return E;
804     }
805   }
806   return E;
807 }
808 
809 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
810 /// do not have a prototype. Arguments that have type float or __fp16
811 /// are promoted to double. All other argument types are converted by
812 /// UsualUnaryConversions().
813 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
814   QualType Ty = E->getType();
815   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
816 
817   ExprResult Res = UsualUnaryConversions(E);
818   if (Res.isInvalid())
819     return ExprError();
820   E = Res.get();
821 
822   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
823   // double.
824   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
825   if (BTy && (BTy->getKind() == BuiltinType::Half ||
826               BTy->getKind() == BuiltinType::Float)) {
827     if (getLangOpts().OpenCL &&
828         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
829         if (BTy->getKind() == BuiltinType::Half) {
830             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
831         }
832     } else {
833       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
834     }
835   }
836 
837   // C++ performs lvalue-to-rvalue conversion as a default argument
838   // promotion, even on class types, but note:
839   //   C++11 [conv.lval]p2:
840   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
841   //     operand or a subexpression thereof the value contained in the
842   //     referenced object is not accessed. Otherwise, if the glvalue
843   //     has a class type, the conversion copy-initializes a temporary
844   //     of type T from the glvalue and the result of the conversion
845   //     is a prvalue for the temporary.
846   // FIXME: add some way to gate this entire thing for correctness in
847   // potentially potentially evaluated contexts.
848   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
849     ExprResult Temp = PerformCopyInitialization(
850                        InitializedEntity::InitializeTemporary(E->getType()),
851                                                 E->getExprLoc(), E);
852     if (Temp.isInvalid())
853       return ExprError();
854     E = Temp.get();
855   }
856 
857   return E;
858 }
859 
860 /// Determine the degree of POD-ness for an expression.
861 /// Incomplete types are considered POD, since this check can be performed
862 /// when we're in an unevaluated context.
863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
864   if (Ty->isIncompleteType()) {
865     // C++11 [expr.call]p7:
866     //   After these conversions, if the argument does not have arithmetic,
867     //   enumeration, pointer, pointer to member, or class type, the program
868     //   is ill-formed.
869     //
870     // Since we've already performed array-to-pointer and function-to-pointer
871     // decay, the only such type in C++ is cv void. This also handles
872     // initializer lists as variadic arguments.
873     if (Ty->isVoidType())
874       return VAK_Invalid;
875 
876     if (Ty->isObjCObjectType())
877       return VAK_Invalid;
878     return VAK_Valid;
879   }
880 
881   if (Ty.isCXX98PODType(Context))
882     return VAK_Valid;
883 
884   // C++11 [expr.call]p7:
885   //   Passing a potentially-evaluated argument of class type (Clause 9)
886   //   having a non-trivial copy constructor, a non-trivial move constructor,
887   //   or a non-trivial destructor, with no corresponding parameter,
888   //   is conditionally-supported with implementation-defined semantics.
889   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
890     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
891       if (!Record->hasNonTrivialCopyConstructor() &&
892           !Record->hasNonTrivialMoveConstructor() &&
893           !Record->hasNonTrivialDestructor())
894         return VAK_ValidInCXX11;
895 
896   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
897     return VAK_Valid;
898 
899   if (Ty->isObjCObjectType())
900     return VAK_Invalid;
901 
902   if (getLangOpts().MSVCCompat)
903     return VAK_MSVCUndefined;
904 
905   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
906   // permitted to reject them. We should consider doing so.
907   return VAK_Undefined;
908 }
909 
910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
911   // Don't allow one to pass an Objective-C interface to a vararg.
912   const QualType &Ty = E->getType();
913   VarArgKind VAK = isValidVarArgType(Ty);
914 
915   // Complain about passing non-POD types through varargs.
916   switch (VAK) {
917   case VAK_ValidInCXX11:
918     DiagRuntimeBehavior(
919         E->getLocStart(), nullptr,
920         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
921           << Ty << CT);
922     // Fall through.
923   case VAK_Valid:
924     if (Ty->isRecordType()) {
925       // This is unlikely to be what the user intended. If the class has a
926       // 'c_str' member function, the user probably meant to call that.
927       DiagRuntimeBehavior(E->getLocStart(), nullptr,
928                           PDiag(diag::warn_pass_class_arg_to_vararg)
929                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
930     }
931     break;
932 
933   case VAK_Undefined:
934   case VAK_MSVCUndefined:
935     DiagRuntimeBehavior(
936         E->getLocStart(), nullptr,
937         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
938           << getLangOpts().CPlusPlus11 << Ty << CT);
939     break;
940 
941   case VAK_Invalid:
942     if (Ty->isObjCObjectType())
943       DiagRuntimeBehavior(
944           E->getLocStart(), nullptr,
945           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
946             << Ty << CT);
947     else
948       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
949         << isa<InitListExpr>(E) << Ty << CT;
950     break;
951   }
952 }
953 
954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
955 /// will create a trap if the resulting type is not a POD type.
956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
957                                                   FunctionDecl *FDecl) {
958   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
959     // Strip the unbridged-cast placeholder expression off, if applicable.
960     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
961         (CT == VariadicMethod ||
962          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
963       E = stripARCUnbridgedCast(E);
964 
965     // Otherwise, do normal placeholder checking.
966     } else {
967       ExprResult ExprRes = CheckPlaceholderExpr(E);
968       if (ExprRes.isInvalid())
969         return ExprError();
970       E = ExprRes.get();
971     }
972   }
973 
974   ExprResult ExprRes = DefaultArgumentPromotion(E);
975   if (ExprRes.isInvalid())
976     return ExprError();
977   E = ExprRes.get();
978 
979   // Diagnostics regarding non-POD argument types are
980   // emitted along with format string checking in Sema::CheckFunctionCall().
981   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
982     // Turn this into a trap.
983     CXXScopeSpec SS;
984     SourceLocation TemplateKWLoc;
985     UnqualifiedId Name;
986     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
987                        E->getLocStart());
988     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
989                                           Name, true, false);
990     if (TrapFn.isInvalid())
991       return ExprError();
992 
993     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
994                                     E->getLocStart(), None,
995                                     E->getLocEnd());
996     if (Call.isInvalid())
997       return ExprError();
998 
999     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1000                                   Call.get(), E);
1001     if (Comma.isInvalid())
1002       return ExprError();
1003     return Comma.get();
1004   }
1005 
1006   if (!getLangOpts().CPlusPlus &&
1007       RequireCompleteType(E->getExprLoc(), E->getType(),
1008                           diag::err_call_incomplete_argument))
1009     return ExprError();
1010 
1011   return E;
1012 }
1013 
1014 /// \brief Converts an integer to complex float type.  Helper function of
1015 /// UsualArithmeticConversions()
1016 ///
1017 /// \return false if the integer expression is an integer type and is
1018 /// successfully converted to the complex type.
1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1020                                                   ExprResult &ComplexExpr,
1021                                                   QualType IntTy,
1022                                                   QualType ComplexTy,
1023                                                   bool SkipCast) {
1024   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1025   if (SkipCast) return false;
1026   if (IntTy->isIntegerType()) {
1027     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1029     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1030                                   CK_FloatingRealToComplex);
1031   } else {
1032     assert(IntTy->isComplexIntegerType());
1033     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1034                                   CK_IntegralComplexToFloatingComplex);
1035   }
1036   return false;
1037 }
1038 
1039 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1040 /// UsualArithmeticConversions()
1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1042                                              ExprResult &RHS, QualType LHSType,
1043                                              QualType RHSType,
1044                                              bool IsCompAssign) {
1045   // if we have an integer operand, the result is the complex type.
1046   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1047                                              /*skipCast*/false))
1048     return LHSType;
1049   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1050                                              /*skipCast*/IsCompAssign))
1051     return RHSType;
1052 
1053   // This handles complex/complex, complex/float, or float/complex.
1054   // When both operands are complex, the shorter operand is converted to the
1055   // type of the longer, and that is the type of the result. This corresponds
1056   // to what is done when combining two real floating-point operands.
1057   // The fun begins when size promotion occur across type domains.
1058   // From H&S 6.3.4: When one operand is complex and the other is a real
1059   // floating-point type, the less precise type is converted, within it's
1060   // real or complex domain, to the precision of the other type. For example,
1061   // when combining a "long double" with a "double _Complex", the
1062   // "double _Complex" is promoted to "long double _Complex".
1063 
1064   // Compute the rank of the two types, regardless of whether they are complex.
1065   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1066 
1067   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1068   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1069   QualType LHSElementType =
1070       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1071   QualType RHSElementType =
1072       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1073 
1074   QualType ResultType = S.Context.getComplexType(LHSElementType);
1075   if (Order < 0) {
1076     // Promote the precision of the LHS if not an assignment.
1077     ResultType = S.Context.getComplexType(RHSElementType);
1078     if (!IsCompAssign) {
1079       if (LHSComplexType)
1080         LHS =
1081             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1082       else
1083         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1084     }
1085   } else if (Order > 0) {
1086     // Promote the precision of the RHS.
1087     if (RHSComplexType)
1088       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1089     else
1090       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1091   }
1092   return ResultType;
1093 }
1094 
1095 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1096 /// of UsualArithmeticConversions()
1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1098                                            ExprResult &IntExpr,
1099                                            QualType FloatTy, QualType IntTy,
1100                                            bool ConvertFloat, bool ConvertInt) {
1101   if (IntTy->isIntegerType()) {
1102     if (ConvertInt)
1103       // Convert intExpr to the lhs floating point type.
1104       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1105                                     CK_IntegralToFloating);
1106     return FloatTy;
1107   }
1108 
1109   // Convert both sides to the appropriate complex float.
1110   assert(IntTy->isComplexIntegerType());
1111   QualType result = S.Context.getComplexType(FloatTy);
1112 
1113   // _Complex int -> _Complex float
1114   if (ConvertInt)
1115     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1116                                   CK_IntegralComplexToFloatingComplex);
1117 
1118   // float -> _Complex float
1119   if (ConvertFloat)
1120     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1121                                     CK_FloatingRealToComplex);
1122 
1123   return result;
1124 }
1125 
1126 /// \brief Handle arithmethic conversion with floating point types.  Helper
1127 /// function of UsualArithmeticConversions()
1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1129                                       ExprResult &RHS, QualType LHSType,
1130                                       QualType RHSType, bool IsCompAssign) {
1131   bool LHSFloat = LHSType->isRealFloatingType();
1132   bool RHSFloat = RHSType->isRealFloatingType();
1133 
1134   // If we have two real floating types, convert the smaller operand
1135   // to the bigger result.
1136   if (LHSFloat && RHSFloat) {
1137     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1138     if (order > 0) {
1139       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1140       return LHSType;
1141     }
1142 
1143     assert(order < 0 && "illegal float comparison");
1144     if (!IsCompAssign)
1145       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1146     return RHSType;
1147   }
1148 
1149   if (LHSFloat) {
1150     // Half FP has to be promoted to float unless it is natively supported
1151     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1152       LHSType = S.Context.FloatTy;
1153 
1154     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1155                                       /*convertFloat=*/!IsCompAssign,
1156                                       /*convertInt=*/ true);
1157   }
1158   assert(RHSFloat);
1159   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1160                                     /*convertInt=*/ true,
1161                                     /*convertFloat=*/!IsCompAssign);
1162 }
1163 
1164 /// \brief Diagnose attempts to convert between __float128 and long double if
1165 /// there is no support for such conversion. Helper function of
1166 /// UsualArithmeticConversions().
1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1168                                       QualType RHSType) {
1169   /*  No issue converting if at least one of the types is not a floating point
1170       type or the two types have the same rank.
1171   */
1172   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1173       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1174     return false;
1175 
1176   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1177          "The remaining types must be floating point types.");
1178 
1179   auto *LHSComplex = LHSType->getAs<ComplexType>();
1180   auto *RHSComplex = RHSType->getAs<ComplexType>();
1181 
1182   QualType LHSElemType = LHSComplex ?
1183     LHSComplex->getElementType() : LHSType;
1184   QualType RHSElemType = RHSComplex ?
1185     RHSComplex->getElementType() : RHSType;
1186 
1187   // No issue if the two types have the same representation
1188   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1189       &S.Context.getFloatTypeSemantics(RHSElemType))
1190     return false;
1191 
1192   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1193                                 RHSElemType == S.Context.LongDoubleTy);
1194   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1195                             RHSElemType == S.Context.Float128Ty);
1196 
1197   /* We've handled the situation where __float128 and long double have the same
1198      representation. The only other allowable conversion is if long double is
1199      really just double.
1200   */
1201   return Float128AndLongDouble &&
1202     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1203      &llvm::APFloat::IEEEdouble());
1204 }
1205 
1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1207 
1208 namespace {
1209 /// These helper callbacks are placed in an anonymous namespace to
1210 /// permit their use as function template parameters.
1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1212   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1213 }
1214 
1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1216   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1217                              CK_IntegralComplexCast);
1218 }
1219 }
1220 
1221 /// \brief Handle integer arithmetic conversions.  Helper function of
1222 /// UsualArithmeticConversions()
1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1225                                         ExprResult &RHS, QualType LHSType,
1226                                         QualType RHSType, bool IsCompAssign) {
1227   // The rules for this case are in C99 6.3.1.8
1228   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1229   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1230   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1231   if (LHSSigned == RHSSigned) {
1232     // Same signedness; use the higher-ranked type
1233     if (order >= 0) {
1234       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1235       return LHSType;
1236     } else if (!IsCompAssign)
1237       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1238     return RHSType;
1239   } else if (order != (LHSSigned ? 1 : -1)) {
1240     // The unsigned type has greater than or equal rank to the
1241     // signed type, so use the unsigned type
1242     if (RHSSigned) {
1243       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1244       return LHSType;
1245     } else if (!IsCompAssign)
1246       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1247     return RHSType;
1248   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1249     // The two types are different widths; if we are here, that
1250     // means the signed type is larger than the unsigned type, so
1251     // use the signed type.
1252     if (LHSSigned) {
1253       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1254       return LHSType;
1255     } else if (!IsCompAssign)
1256       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1257     return RHSType;
1258   } else {
1259     // The signed type is higher-ranked than the unsigned type,
1260     // but isn't actually any bigger (like unsigned int and long
1261     // on most 32-bit systems).  Use the unsigned type corresponding
1262     // to the signed type.
1263     QualType result =
1264       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1265     RHS = (*doRHSCast)(S, RHS.get(), result);
1266     if (!IsCompAssign)
1267       LHS = (*doLHSCast)(S, LHS.get(), result);
1268     return result;
1269   }
1270 }
1271 
1272 /// \brief Handle conversions with GCC complex int extension.  Helper function
1273 /// of UsualArithmeticConversions()
1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1275                                            ExprResult &RHS, QualType LHSType,
1276                                            QualType RHSType,
1277                                            bool IsCompAssign) {
1278   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1279   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1280 
1281   if (LHSComplexInt && RHSComplexInt) {
1282     QualType LHSEltType = LHSComplexInt->getElementType();
1283     QualType RHSEltType = RHSComplexInt->getElementType();
1284     QualType ScalarType =
1285       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1286         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1287 
1288     return S.Context.getComplexType(ScalarType);
1289   }
1290 
1291   if (LHSComplexInt) {
1292     QualType LHSEltType = LHSComplexInt->getElementType();
1293     QualType ScalarType =
1294       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1295         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1296     QualType ComplexType = S.Context.getComplexType(ScalarType);
1297     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1298                               CK_IntegralRealToComplex);
1299 
1300     return ComplexType;
1301   }
1302 
1303   assert(RHSComplexInt);
1304 
1305   QualType RHSEltType = RHSComplexInt->getElementType();
1306   QualType ScalarType =
1307     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1308       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1309   QualType ComplexType = S.Context.getComplexType(ScalarType);
1310 
1311   if (!IsCompAssign)
1312     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1313                               CK_IntegralRealToComplex);
1314   return ComplexType;
1315 }
1316 
1317 /// UsualArithmeticConversions - Performs various conversions that are common to
1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1319 /// routine returns the first non-arithmetic type found. The client is
1320 /// responsible for emitting appropriate error diagnostics.
1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1322                                           bool IsCompAssign) {
1323   if (!IsCompAssign) {
1324     LHS = UsualUnaryConversions(LHS.get());
1325     if (LHS.isInvalid())
1326       return QualType();
1327   }
1328 
1329   RHS = UsualUnaryConversions(RHS.get());
1330   if (RHS.isInvalid())
1331     return QualType();
1332 
1333   // For conversion purposes, we ignore any qualifiers.
1334   // For example, "const float" and "float" are equivalent.
1335   QualType LHSType =
1336     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1337   QualType RHSType =
1338     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1339 
1340   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1341   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1342     LHSType = AtomicLHS->getValueType();
1343 
1344   // If both types are identical, no conversion is needed.
1345   if (LHSType == RHSType)
1346     return LHSType;
1347 
1348   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1349   // The caller can deal with this (e.g. pointer + int).
1350   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1351     return QualType();
1352 
1353   // Apply unary and bitfield promotions to the LHS's type.
1354   QualType LHSUnpromotedType = LHSType;
1355   if (LHSType->isPromotableIntegerType())
1356     LHSType = Context.getPromotedIntegerType(LHSType);
1357   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1358   if (!LHSBitfieldPromoteTy.isNull())
1359     LHSType = LHSBitfieldPromoteTy;
1360   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1361     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1362 
1363   // If both types are identical, no conversion is needed.
1364   if (LHSType == RHSType)
1365     return LHSType;
1366 
1367   // At this point, we have two different arithmetic types.
1368 
1369   // Diagnose attempts to convert between __float128 and long double where
1370   // such conversions currently can't be handled.
1371   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1372     return QualType();
1373 
1374   // Handle complex types first (C99 6.3.1.8p1).
1375   if (LHSType->isComplexType() || RHSType->isComplexType())
1376     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1377                                         IsCompAssign);
1378 
1379   // Now handle "real" floating types (i.e. float, double, long double).
1380   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1381     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1382                                  IsCompAssign);
1383 
1384   // Handle GCC complex int extension.
1385   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1386     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1387                                       IsCompAssign);
1388 
1389   // Finally, we have two differing integer types.
1390   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1391            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1392 }
1393 
1394 
1395 //===----------------------------------------------------------------------===//
1396 //  Semantic Analysis for various Expression Types
1397 //===----------------------------------------------------------------------===//
1398 
1399 
1400 ExprResult
1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1402                                 SourceLocation DefaultLoc,
1403                                 SourceLocation RParenLoc,
1404                                 Expr *ControllingExpr,
1405                                 ArrayRef<ParsedType> ArgTypes,
1406                                 ArrayRef<Expr *> ArgExprs) {
1407   unsigned NumAssocs = ArgTypes.size();
1408   assert(NumAssocs == ArgExprs.size());
1409 
1410   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1411   for (unsigned i = 0; i < NumAssocs; ++i) {
1412     if (ArgTypes[i])
1413       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1414     else
1415       Types[i] = nullptr;
1416   }
1417 
1418   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1419                                              ControllingExpr,
1420                                              llvm::makeArrayRef(Types, NumAssocs),
1421                                              ArgExprs);
1422   delete [] Types;
1423   return ER;
1424 }
1425 
1426 ExprResult
1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1428                                  SourceLocation DefaultLoc,
1429                                  SourceLocation RParenLoc,
1430                                  Expr *ControllingExpr,
1431                                  ArrayRef<TypeSourceInfo *> Types,
1432                                  ArrayRef<Expr *> Exprs) {
1433   unsigned NumAssocs = Types.size();
1434   assert(NumAssocs == Exprs.size());
1435 
1436   // Decay and strip qualifiers for the controlling expression type, and handle
1437   // placeholder type replacement. See committee discussion from WG14 DR423.
1438   {
1439     EnterExpressionEvaluationContext Unevaluated(
1440         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1441     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1442     if (R.isInvalid())
1443       return ExprError();
1444     ControllingExpr = R.get();
1445   }
1446 
1447   // The controlling expression is an unevaluated operand, so side effects are
1448   // likely unintended.
1449   if (!inTemplateInstantiation() &&
1450       ControllingExpr->HasSideEffects(Context, false))
1451     Diag(ControllingExpr->getExprLoc(),
1452          diag::warn_side_effects_unevaluated_context);
1453 
1454   bool TypeErrorFound = false,
1455        IsResultDependent = ControllingExpr->isTypeDependent(),
1456        ContainsUnexpandedParameterPack
1457          = ControllingExpr->containsUnexpandedParameterPack();
1458 
1459   for (unsigned i = 0; i < NumAssocs; ++i) {
1460     if (Exprs[i]->containsUnexpandedParameterPack())
1461       ContainsUnexpandedParameterPack = true;
1462 
1463     if (Types[i]) {
1464       if (Types[i]->getType()->containsUnexpandedParameterPack())
1465         ContainsUnexpandedParameterPack = true;
1466 
1467       if (Types[i]->getType()->isDependentType()) {
1468         IsResultDependent = true;
1469       } else {
1470         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1471         // complete object type other than a variably modified type."
1472         unsigned D = 0;
1473         if (Types[i]->getType()->isIncompleteType())
1474           D = diag::err_assoc_type_incomplete;
1475         else if (!Types[i]->getType()->isObjectType())
1476           D = diag::err_assoc_type_nonobject;
1477         else if (Types[i]->getType()->isVariablyModifiedType())
1478           D = diag::err_assoc_type_variably_modified;
1479 
1480         if (D != 0) {
1481           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1482             << Types[i]->getTypeLoc().getSourceRange()
1483             << Types[i]->getType();
1484           TypeErrorFound = true;
1485         }
1486 
1487         // C11 6.5.1.1p2 "No two generic associations in the same generic
1488         // selection shall specify compatible types."
1489         for (unsigned j = i+1; j < NumAssocs; ++j)
1490           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1491               Context.typesAreCompatible(Types[i]->getType(),
1492                                          Types[j]->getType())) {
1493             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1494                  diag::err_assoc_compatible_types)
1495               << Types[j]->getTypeLoc().getSourceRange()
1496               << Types[j]->getType()
1497               << Types[i]->getType();
1498             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1499                  diag::note_compat_assoc)
1500               << Types[i]->getTypeLoc().getSourceRange()
1501               << Types[i]->getType();
1502             TypeErrorFound = true;
1503           }
1504       }
1505     }
1506   }
1507   if (TypeErrorFound)
1508     return ExprError();
1509 
1510   // If we determined that the generic selection is result-dependent, don't
1511   // try to compute the result expression.
1512   if (IsResultDependent)
1513     return new (Context) GenericSelectionExpr(
1514         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1515         ContainsUnexpandedParameterPack);
1516 
1517   SmallVector<unsigned, 1> CompatIndices;
1518   unsigned DefaultIndex = -1U;
1519   for (unsigned i = 0; i < NumAssocs; ++i) {
1520     if (!Types[i])
1521       DefaultIndex = i;
1522     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1523                                         Types[i]->getType()))
1524       CompatIndices.push_back(i);
1525   }
1526 
1527   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1528   // type compatible with at most one of the types named in its generic
1529   // association list."
1530   if (CompatIndices.size() > 1) {
1531     // We strip parens here because the controlling expression is typically
1532     // parenthesized in macro definitions.
1533     ControllingExpr = ControllingExpr->IgnoreParens();
1534     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1535       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1536       << (unsigned) CompatIndices.size();
1537     for (unsigned I : CompatIndices) {
1538       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1539            diag::note_compat_assoc)
1540         << Types[I]->getTypeLoc().getSourceRange()
1541         << Types[I]->getType();
1542     }
1543     return ExprError();
1544   }
1545 
1546   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1547   // its controlling expression shall have type compatible with exactly one of
1548   // the types named in its generic association list."
1549   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1550     // We strip parens here because the controlling expression is typically
1551     // parenthesized in macro definitions.
1552     ControllingExpr = ControllingExpr->IgnoreParens();
1553     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1554       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1555     return ExprError();
1556   }
1557 
1558   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1559   // type name that is compatible with the type of the controlling expression,
1560   // then the result expression of the generic selection is the expression
1561   // in that generic association. Otherwise, the result expression of the
1562   // generic selection is the expression in the default generic association."
1563   unsigned ResultIndex =
1564     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1565 
1566   return new (Context) GenericSelectionExpr(
1567       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1568       ContainsUnexpandedParameterPack, ResultIndex);
1569 }
1570 
1571 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1572 /// location of the token and the offset of the ud-suffix within it.
1573 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1574                                      unsigned Offset) {
1575   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1576                                         S.getLangOpts());
1577 }
1578 
1579 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1580 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1581 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1582                                                  IdentifierInfo *UDSuffix,
1583                                                  SourceLocation UDSuffixLoc,
1584                                                  ArrayRef<Expr*> Args,
1585                                                  SourceLocation LitEndLoc) {
1586   assert(Args.size() <= 2 && "too many arguments for literal operator");
1587 
1588   QualType ArgTy[2];
1589   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1590     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1591     if (ArgTy[ArgIdx]->isArrayType())
1592       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1593   }
1594 
1595   DeclarationName OpName =
1596     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1597   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1598   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1599 
1600   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1601   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1602                               /*AllowRaw*/false, /*AllowTemplate*/false,
1603                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1604     return ExprError();
1605 
1606   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1607 }
1608 
1609 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1610 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1611 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1612 /// multiple tokens.  However, the common case is that StringToks points to one
1613 /// string.
1614 ///
1615 ExprResult
1616 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1617   assert(!StringToks.empty() && "Must have at least one string!");
1618 
1619   StringLiteralParser Literal(StringToks, PP);
1620   if (Literal.hadError)
1621     return ExprError();
1622 
1623   SmallVector<SourceLocation, 4> StringTokLocs;
1624   for (const Token &Tok : StringToks)
1625     StringTokLocs.push_back(Tok.getLocation());
1626 
1627   QualType CharTy = Context.CharTy;
1628   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1629   if (Literal.isWide()) {
1630     CharTy = Context.getWideCharType();
1631     Kind = StringLiteral::Wide;
1632   } else if (Literal.isUTF8()) {
1633     Kind = StringLiteral::UTF8;
1634   } else if (Literal.isUTF16()) {
1635     CharTy = Context.Char16Ty;
1636     Kind = StringLiteral::UTF16;
1637   } else if (Literal.isUTF32()) {
1638     CharTy = Context.Char32Ty;
1639     Kind = StringLiteral::UTF32;
1640   } else if (Literal.isPascal()) {
1641     CharTy = Context.UnsignedCharTy;
1642   }
1643 
1644   QualType CharTyConst = CharTy;
1645   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1646   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1647     CharTyConst.addConst();
1648 
1649   // Get an array type for the string, according to C99 6.4.5.  This includes
1650   // the nul terminator character as well as the string length for pascal
1651   // strings.
1652   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1653                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1654                                  ArrayType::Normal, 0);
1655 
1656   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1657   if (getLangOpts().OpenCL) {
1658     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1659   }
1660 
1661   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1662   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1663                                              Kind, Literal.Pascal, StrTy,
1664                                              &StringTokLocs[0],
1665                                              StringTokLocs.size());
1666   if (Literal.getUDSuffix().empty())
1667     return Lit;
1668 
1669   // We're building a user-defined literal.
1670   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1671   SourceLocation UDSuffixLoc =
1672     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1673                    Literal.getUDSuffixOffset());
1674 
1675   // Make sure we're allowed user-defined literals here.
1676   if (!UDLScope)
1677     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1678 
1679   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1680   //   operator "" X (str, len)
1681   QualType SizeType = Context.getSizeType();
1682 
1683   DeclarationName OpName =
1684     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1685   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1686   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1687 
1688   QualType ArgTy[] = {
1689     Context.getArrayDecayedType(StrTy), SizeType
1690   };
1691 
1692   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1693   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1694                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1695                                 /*AllowStringTemplate*/true)) {
1696 
1697   case LOLR_Cooked: {
1698     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1699     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1700                                                     StringTokLocs[0]);
1701     Expr *Args[] = { Lit, LenArg };
1702 
1703     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1704   }
1705 
1706   case LOLR_StringTemplate: {
1707     TemplateArgumentListInfo ExplicitArgs;
1708 
1709     unsigned CharBits = Context.getIntWidth(CharTy);
1710     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1711     llvm::APSInt Value(CharBits, CharIsUnsigned);
1712 
1713     TemplateArgument TypeArg(CharTy);
1714     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1715     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1716 
1717     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1718       Value = Lit->getCodeUnit(I);
1719       TemplateArgument Arg(Context, Value, CharTy);
1720       TemplateArgumentLocInfo ArgInfo;
1721       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1722     }
1723     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1724                                     &ExplicitArgs);
1725   }
1726   case LOLR_Raw:
1727   case LOLR_Template:
1728     llvm_unreachable("unexpected literal operator lookup result");
1729   case LOLR_Error:
1730     return ExprError();
1731   }
1732   llvm_unreachable("unexpected literal operator lookup result");
1733 }
1734 
1735 ExprResult
1736 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1737                        SourceLocation Loc,
1738                        const CXXScopeSpec *SS) {
1739   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1740   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1741 }
1742 
1743 /// BuildDeclRefExpr - Build an expression that references a
1744 /// declaration that does not require a closure capture.
1745 ExprResult
1746 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1747                        const DeclarationNameInfo &NameInfo,
1748                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1749                        const TemplateArgumentListInfo *TemplateArgs) {
1750   bool RefersToCapturedVariable =
1751       isa<VarDecl>(D) &&
1752       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1753 
1754   DeclRefExpr *E;
1755   if (isa<VarTemplateSpecializationDecl>(D)) {
1756     VarTemplateSpecializationDecl *VarSpec =
1757         cast<VarTemplateSpecializationDecl>(D);
1758 
1759     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1760                                         : NestedNameSpecifierLoc(),
1761                             VarSpec->getTemplateKeywordLoc(), D,
1762                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1763                             FoundD, TemplateArgs);
1764   } else {
1765     assert(!TemplateArgs && "No template arguments for non-variable"
1766                             " template specialization references");
1767     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1768                                         : NestedNameSpecifierLoc(),
1769                             SourceLocation(), D, RefersToCapturedVariable,
1770                             NameInfo, Ty, VK, FoundD);
1771   }
1772 
1773   MarkDeclRefReferenced(E);
1774 
1775   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1776       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1777       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1778       recordUseOfEvaluatedWeak(E);
1779 
1780   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1781   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1782     FD = IFD->getAnonField();
1783   if (FD) {
1784     UnusedPrivateFields.remove(FD);
1785     // Just in case we're building an illegal pointer-to-member.
1786     if (FD->isBitField())
1787       E->setObjectKind(OK_BitField);
1788   }
1789 
1790   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1791   // designates a bit-field.
1792   if (auto *BD = dyn_cast<BindingDecl>(D))
1793     if (auto *BE = BD->getBinding())
1794       E->setObjectKind(BE->getObjectKind());
1795 
1796   return E;
1797 }
1798 
1799 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1800 /// possibly a list of template arguments.
1801 ///
1802 /// If this produces template arguments, it is permitted to call
1803 /// DecomposeTemplateName.
1804 ///
1805 /// This actually loses a lot of source location information for
1806 /// non-standard name kinds; we should consider preserving that in
1807 /// some way.
1808 void
1809 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1810                              TemplateArgumentListInfo &Buffer,
1811                              DeclarationNameInfo &NameInfo,
1812                              const TemplateArgumentListInfo *&TemplateArgs) {
1813   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1814     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1815     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1816 
1817     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1818                                        Id.TemplateId->NumArgs);
1819     translateTemplateArguments(TemplateArgsPtr, Buffer);
1820 
1821     TemplateName TName = Id.TemplateId->Template.get();
1822     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1823     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1824     TemplateArgs = &Buffer;
1825   } else {
1826     NameInfo = GetNameFromUnqualifiedId(Id);
1827     TemplateArgs = nullptr;
1828   }
1829 }
1830 
1831 static void emitEmptyLookupTypoDiagnostic(
1832     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1833     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1834     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1835   DeclContext *Ctx =
1836       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1837   if (!TC) {
1838     // Emit a special diagnostic for failed member lookups.
1839     // FIXME: computing the declaration context might fail here (?)
1840     if (Ctx)
1841       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1842                                                  << SS.getRange();
1843     else
1844       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1845     return;
1846   }
1847 
1848   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1849   bool DroppedSpecifier =
1850       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1851   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1852                         ? diag::note_implicit_param_decl
1853                         : diag::note_previous_decl;
1854   if (!Ctx)
1855     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1856                          SemaRef.PDiag(NoteID));
1857   else
1858     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1859                                  << Typo << Ctx << DroppedSpecifier
1860                                  << SS.getRange(),
1861                          SemaRef.PDiag(NoteID));
1862 }
1863 
1864 /// Diagnose an empty lookup.
1865 ///
1866 /// \return false if new lookup candidates were found
1867 bool
1868 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1869                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1870                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1871                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1872   DeclarationName Name = R.getLookupName();
1873 
1874   unsigned diagnostic = diag::err_undeclared_var_use;
1875   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1876   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1877       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1878       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1879     diagnostic = diag::err_undeclared_use;
1880     diagnostic_suggest = diag::err_undeclared_use_suggest;
1881   }
1882 
1883   // If the original lookup was an unqualified lookup, fake an
1884   // unqualified lookup.  This is useful when (for example) the
1885   // original lookup would not have found something because it was a
1886   // dependent name.
1887   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1888   while (DC) {
1889     if (isa<CXXRecordDecl>(DC)) {
1890       LookupQualifiedName(R, DC);
1891 
1892       if (!R.empty()) {
1893         // Don't give errors about ambiguities in this lookup.
1894         R.suppressDiagnostics();
1895 
1896         // During a default argument instantiation the CurContext points
1897         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1898         // function parameter list, hence add an explicit check.
1899         bool isDefaultArgument =
1900             !CodeSynthesisContexts.empty() &&
1901             CodeSynthesisContexts.back().Kind ==
1902                 CodeSynthesisContext::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   if (II && II->isEditorPlaceholder()) {
2138     // FIXME: When typed placeholders are supported we can create a typed
2139     // placeholder expression node.
2140     return ExprError();
2141   }
2142 
2143   // C++ [temp.dep.expr]p3:
2144   //   An id-expression is type-dependent if it contains:
2145   //     -- an identifier that was declared with a dependent type,
2146   //        (note: handled after lookup)
2147   //     -- a template-id that is dependent,
2148   //        (note: handled in BuildTemplateIdExpr)
2149   //     -- a conversion-function-id that specifies a dependent type,
2150   //     -- a nested-name-specifier that contains a class-name that
2151   //        names a dependent type.
2152   // Determine whether this is a member of an unknown specialization;
2153   // we need to handle these differently.
2154   bool DependentID = false;
2155   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2156       Name.getCXXNameType()->isDependentType()) {
2157     DependentID = true;
2158   } else if (SS.isSet()) {
2159     if (DeclContext *DC = computeDeclContext(SS, false)) {
2160       if (RequireCompleteDeclContext(SS, DC))
2161         return ExprError();
2162     } else {
2163       DependentID = true;
2164     }
2165   }
2166 
2167   if (DependentID)
2168     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2169                                       IsAddressOfOperand, TemplateArgs);
2170 
2171   // Perform the required lookup.
2172   LookupResult R(*this, NameInfo,
2173                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2174                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2175   if (TemplateArgs) {
2176     // Lookup the template name again to correctly establish the context in
2177     // which it was found. This is really unfortunate as we already did the
2178     // lookup to determine that it was a template name in the first place. If
2179     // this becomes a performance hit, we can work harder to preserve those
2180     // results until we get here but it's likely not worth it.
2181     bool MemberOfUnknownSpecialization;
2182     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2183                        MemberOfUnknownSpecialization);
2184 
2185     if (MemberOfUnknownSpecialization ||
2186         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2187       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2188                                         IsAddressOfOperand, TemplateArgs);
2189   } else {
2190     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2191     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2192 
2193     // If the result might be in a dependent base class, this is a dependent
2194     // id-expression.
2195     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2196       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2197                                         IsAddressOfOperand, TemplateArgs);
2198 
2199     // If this reference is in an Objective-C method, then we need to do
2200     // some special Objective-C lookup, too.
2201     if (IvarLookupFollowUp) {
2202       ExprResult E(LookupInObjCMethod(R, S, II, true));
2203       if (E.isInvalid())
2204         return ExprError();
2205 
2206       if (Expr *Ex = E.getAs<Expr>())
2207         return Ex;
2208     }
2209   }
2210 
2211   if (R.isAmbiguous())
2212     return ExprError();
2213 
2214   // This could be an implicitly declared function reference (legal in C90,
2215   // extension in C99, forbidden in C++).
2216   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2217     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2218     if (D) R.addDecl(D);
2219   }
2220 
2221   // Determine whether this name might be a candidate for
2222   // argument-dependent lookup.
2223   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2224 
2225   if (R.empty() && !ADL) {
2226     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2227       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2228                                                    TemplateKWLoc, TemplateArgs))
2229         return E;
2230     }
2231 
2232     // Don't diagnose an empty lookup for inline assembly.
2233     if (IsInlineAsmIdentifier)
2234       return ExprError();
2235 
2236     // If this name wasn't predeclared and if this is not a function
2237     // call, diagnose the problem.
2238     TypoExpr *TE = nullptr;
2239     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2240         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2241     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2242     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2243            "Typo correction callback misconfigured");
2244     if (CCC) {
2245       // Make sure the callback knows what the typo being diagnosed is.
2246       CCC->setTypoName(II);
2247       if (SS.isValid())
2248         CCC->setTypoNNS(SS.getScopeRep());
2249     }
2250     if (DiagnoseEmptyLookup(S, SS, R,
2251                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2252                             nullptr, None, &TE)) {
2253       if (TE && KeywordReplacement) {
2254         auto &State = getTypoExprState(TE);
2255         auto BestTC = State.Consumer->getNextCorrection();
2256         if (BestTC.isKeyword()) {
2257           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2258           if (State.DiagHandler)
2259             State.DiagHandler(BestTC);
2260           KeywordReplacement->startToken();
2261           KeywordReplacement->setKind(II->getTokenID());
2262           KeywordReplacement->setIdentifierInfo(II);
2263           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2264           // Clean up the state associated with the TypoExpr, since it has
2265           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2266           clearDelayedTypo(TE);
2267           // Signal that a correction to a keyword was performed by returning a
2268           // valid-but-null ExprResult.
2269           return (Expr*)nullptr;
2270         }
2271         State.Consumer->resetCorrectionStream();
2272       }
2273       return TE ? TE : ExprError();
2274     }
2275 
2276     assert(!R.empty() &&
2277            "DiagnoseEmptyLookup returned false but added no results");
2278 
2279     // If we found an Objective-C instance variable, let
2280     // LookupInObjCMethod build the appropriate expression to
2281     // reference the ivar.
2282     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2283       R.clear();
2284       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2285       // In a hopelessly buggy code, Objective-C instance variable
2286       // lookup fails and no expression will be built to reference it.
2287       if (!E.isInvalid() && !E.get())
2288         return ExprError();
2289       return E;
2290     }
2291   }
2292 
2293   // This is guaranteed from this point on.
2294   assert(!R.empty() || ADL);
2295 
2296   // Check whether this might be a C++ implicit instance member access.
2297   // C++ [class.mfct.non-static]p3:
2298   //   When an id-expression that is not part of a class member access
2299   //   syntax and not used to form a pointer to member is used in the
2300   //   body of a non-static member function of class X, if name lookup
2301   //   resolves the name in the id-expression to a non-static non-type
2302   //   member of some class C, the id-expression is transformed into a
2303   //   class member access expression using (*this) as the
2304   //   postfix-expression to the left of the . operator.
2305   //
2306   // But we don't actually need to do this for '&' operands if R
2307   // resolved to a function or overloaded function set, because the
2308   // expression is ill-formed if it actually works out to be a
2309   // non-static member function:
2310   //
2311   // C++ [expr.ref]p4:
2312   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2313   //   [t]he expression can be used only as the left-hand operand of a
2314   //   member function call.
2315   //
2316   // There are other safeguards against such uses, but it's important
2317   // to get this right here so that we don't end up making a
2318   // spuriously dependent expression if we're inside a dependent
2319   // instance method.
2320   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2321     bool MightBeImplicitMember;
2322     if (!IsAddressOfOperand)
2323       MightBeImplicitMember = true;
2324     else if (!SS.isEmpty())
2325       MightBeImplicitMember = false;
2326     else if (R.isOverloadedResult())
2327       MightBeImplicitMember = false;
2328     else if (R.isUnresolvableResult())
2329       MightBeImplicitMember = true;
2330     else
2331       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2332                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2333                               isa<MSPropertyDecl>(R.getFoundDecl());
2334 
2335     if (MightBeImplicitMember)
2336       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2337                                              R, TemplateArgs, S);
2338   }
2339 
2340   if (TemplateArgs || TemplateKWLoc.isValid()) {
2341 
2342     // In C++1y, if this is a variable template id, then check it
2343     // in BuildTemplateIdExpr().
2344     // The single lookup result must be a variable template declaration.
2345     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2346         Id.TemplateId->Kind == TNK_Var_template) {
2347       assert(R.getAsSingle<VarTemplateDecl>() &&
2348              "There should only be one declaration found.");
2349     }
2350 
2351     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2352   }
2353 
2354   return BuildDeclarationNameExpr(SS, R, ADL);
2355 }
2356 
2357 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2358 /// declaration name, generally during template instantiation.
2359 /// There's a large number of things which don't need to be done along
2360 /// this path.
2361 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2362     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2363     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2364   DeclContext *DC = computeDeclContext(SS, false);
2365   if (!DC)
2366     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2367                                      NameInfo, /*TemplateArgs=*/nullptr);
2368 
2369   if (RequireCompleteDeclContext(SS, DC))
2370     return ExprError();
2371 
2372   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2373   LookupQualifiedName(R, DC);
2374 
2375   if (R.isAmbiguous())
2376     return ExprError();
2377 
2378   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2379     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2380                                      NameInfo, /*TemplateArgs=*/nullptr);
2381 
2382   if (R.empty()) {
2383     Diag(NameInfo.getLoc(), diag::err_no_member)
2384       << NameInfo.getName() << DC << SS.getRange();
2385     return ExprError();
2386   }
2387 
2388   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2389     // Diagnose a missing typename if this resolved unambiguously to a type in
2390     // a dependent context.  If we can recover with a type, downgrade this to
2391     // a warning in Microsoft compatibility mode.
2392     unsigned DiagID = diag::err_typename_missing;
2393     if (RecoveryTSI && getLangOpts().MSVCCompat)
2394       DiagID = diag::ext_typename_missing;
2395     SourceLocation Loc = SS.getBeginLoc();
2396     auto D = Diag(Loc, DiagID);
2397     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2398       << SourceRange(Loc, NameInfo.getEndLoc());
2399 
2400     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2401     // context.
2402     if (!RecoveryTSI)
2403       return ExprError();
2404 
2405     // Only issue the fixit if we're prepared to recover.
2406     D << FixItHint::CreateInsertion(Loc, "typename ");
2407 
2408     // Recover by pretending this was an elaborated type.
2409     QualType Ty = Context.getTypeDeclType(TD);
2410     TypeLocBuilder TLB;
2411     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2412 
2413     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2414     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2415     QTL.setElaboratedKeywordLoc(SourceLocation());
2416     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2417 
2418     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2419 
2420     return ExprEmpty();
2421   }
2422 
2423   // Defend against this resolving to an implicit member access. We usually
2424   // won't get here if this might be a legitimate a class member (we end up in
2425   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2426   // a pointer-to-member or in an unevaluated context in C++11.
2427   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2428     return BuildPossibleImplicitMemberExpr(SS,
2429                                            /*TemplateKWLoc=*/SourceLocation(),
2430                                            R, /*TemplateArgs=*/nullptr, S);
2431 
2432   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2433 }
2434 
2435 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2436 /// detected that we're currently inside an ObjC method.  Perform some
2437 /// additional lookup.
2438 ///
2439 /// Ideally, most of this would be done by lookup, but there's
2440 /// actually quite a lot of extra work involved.
2441 ///
2442 /// Returns a null sentinel to indicate trivial success.
2443 ExprResult
2444 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2445                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2446   SourceLocation Loc = Lookup.getNameLoc();
2447   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2448 
2449   // Check for error condition which is already reported.
2450   if (!CurMethod)
2451     return ExprError();
2452 
2453   // There are two cases to handle here.  1) scoped lookup could have failed,
2454   // in which case we should look for an ivar.  2) scoped lookup could have
2455   // found a decl, but that decl is outside the current instance method (i.e.
2456   // a global variable).  In these two cases, we do a lookup for an ivar with
2457   // this name, if the lookup sucedes, we replace it our current decl.
2458 
2459   // If we're in a class method, we don't normally want to look for
2460   // ivars.  But if we don't find anything else, and there's an
2461   // ivar, that's an error.
2462   bool IsClassMethod = CurMethod->isClassMethod();
2463 
2464   bool LookForIvars;
2465   if (Lookup.empty())
2466     LookForIvars = true;
2467   else if (IsClassMethod)
2468     LookForIvars = false;
2469   else
2470     LookForIvars = (Lookup.isSingleResult() &&
2471                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2472   ObjCInterfaceDecl *IFace = nullptr;
2473   if (LookForIvars) {
2474     IFace = CurMethod->getClassInterface();
2475     ObjCInterfaceDecl *ClassDeclared;
2476     ObjCIvarDecl *IV = nullptr;
2477     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2478       // Diagnose using an ivar in a class method.
2479       if (IsClassMethod)
2480         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2481                          << IV->getDeclName());
2482 
2483       // If we're referencing an invalid decl, just return this as a silent
2484       // error node.  The error diagnostic was already emitted on the decl.
2485       if (IV->isInvalidDecl())
2486         return ExprError();
2487 
2488       // Check if referencing a field with __attribute__((deprecated)).
2489       if (DiagnoseUseOfDecl(IV, Loc))
2490         return ExprError();
2491 
2492       // Diagnose the use of an ivar outside of the declaring class.
2493       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2494           !declaresSameEntity(ClassDeclared, IFace) &&
2495           !getLangOpts().DebuggerSupport)
2496         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2497 
2498       // FIXME: This should use a new expr for a direct reference, don't
2499       // turn this into Self->ivar, just return a BareIVarExpr or something.
2500       IdentifierInfo &II = Context.Idents.get("self");
2501       UnqualifiedId SelfName;
2502       SelfName.setIdentifier(&II, SourceLocation());
2503       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2504       CXXScopeSpec SelfScopeSpec;
2505       SourceLocation TemplateKWLoc;
2506       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2507                                               SelfName, false, false);
2508       if (SelfExpr.isInvalid())
2509         return ExprError();
2510 
2511       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2512       if (SelfExpr.isInvalid())
2513         return ExprError();
2514 
2515       MarkAnyDeclReferenced(Loc, IV, true);
2516 
2517       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2518       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2519           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2520         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2521 
2522       ObjCIvarRefExpr *Result = new (Context)
2523           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2524                           IV->getLocation(), SelfExpr.get(), true, true);
2525 
2526       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2527         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2528           recordUseOfEvaluatedWeak(Result);
2529       }
2530       if (getLangOpts().ObjCAutoRefCount) {
2531         if (CurContext->isClosure())
2532           Diag(Loc, diag::warn_implicitly_retains_self)
2533             << FixItHint::CreateInsertion(Loc, "self->");
2534       }
2535 
2536       return Result;
2537     }
2538   } else if (CurMethod->isInstanceMethod()) {
2539     // We should warn if a local variable hides an ivar.
2540     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2541       ObjCInterfaceDecl *ClassDeclared;
2542       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2543         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2544             declaresSameEntity(IFace, ClassDeclared))
2545           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2546       }
2547     }
2548   } else if (Lookup.isSingleResult() &&
2549              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2550     // If accessing a stand-alone ivar in a class method, this is an error.
2551     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2552       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2553                        << IV->getDeclName());
2554   }
2555 
2556   if (Lookup.empty() && II && AllowBuiltinCreation) {
2557     // FIXME. Consolidate this with similar code in LookupName.
2558     if (unsigned BuiltinID = II->getBuiltinID()) {
2559       if (!(getLangOpts().CPlusPlus &&
2560             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2561         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2562                                            S, Lookup.isForRedeclaration(),
2563                                            Lookup.getNameLoc());
2564         if (D) Lookup.addDecl(D);
2565       }
2566     }
2567   }
2568   // Sentinel value saying that we didn't do anything special.
2569   return ExprResult((Expr *)nullptr);
2570 }
2571 
2572 /// \brief Cast a base object to a member's actual type.
2573 ///
2574 /// Logically this happens in three phases:
2575 ///
2576 /// * First we cast from the base type to the naming class.
2577 ///   The naming class is the class into which we were looking
2578 ///   when we found the member;  it's the qualifier type if a
2579 ///   qualifier was provided, and otherwise it's the base type.
2580 ///
2581 /// * Next we cast from the naming class to the declaring class.
2582 ///   If the member we found was brought into a class's scope by
2583 ///   a using declaration, this is that class;  otherwise it's
2584 ///   the class declaring the member.
2585 ///
2586 /// * Finally we cast from the declaring class to the "true"
2587 ///   declaring class of the member.  This conversion does not
2588 ///   obey access control.
2589 ExprResult
2590 Sema::PerformObjectMemberConversion(Expr *From,
2591                                     NestedNameSpecifier *Qualifier,
2592                                     NamedDecl *FoundDecl,
2593                                     NamedDecl *Member) {
2594   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2595   if (!RD)
2596     return From;
2597 
2598   QualType DestRecordType;
2599   QualType DestType;
2600   QualType FromRecordType;
2601   QualType FromType = From->getType();
2602   bool PointerConversions = false;
2603   if (isa<FieldDecl>(Member)) {
2604     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2605 
2606     if (FromType->getAs<PointerType>()) {
2607       DestType = Context.getPointerType(DestRecordType);
2608       FromRecordType = FromType->getPointeeType();
2609       PointerConversions = true;
2610     } else {
2611       DestType = DestRecordType;
2612       FromRecordType = FromType;
2613     }
2614   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2615     if (Method->isStatic())
2616       return From;
2617 
2618     DestType = Method->getThisType(Context);
2619     DestRecordType = DestType->getPointeeType();
2620 
2621     if (FromType->getAs<PointerType>()) {
2622       FromRecordType = FromType->getPointeeType();
2623       PointerConversions = true;
2624     } else {
2625       FromRecordType = FromType;
2626       DestType = DestRecordType;
2627     }
2628   } else {
2629     // No conversion necessary.
2630     return From;
2631   }
2632 
2633   if (DestType->isDependentType() || FromType->isDependentType())
2634     return From;
2635 
2636   // If the unqualified types are the same, no conversion is necessary.
2637   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2638     return From;
2639 
2640   SourceRange FromRange = From->getSourceRange();
2641   SourceLocation FromLoc = FromRange.getBegin();
2642 
2643   ExprValueKind VK = From->getValueKind();
2644 
2645   // C++ [class.member.lookup]p8:
2646   //   [...] Ambiguities can often be resolved by qualifying a name with its
2647   //   class name.
2648   //
2649   // If the member was a qualified name and the qualified referred to a
2650   // specific base subobject type, we'll cast to that intermediate type
2651   // first and then to the object in which the member is declared. That allows
2652   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2653   //
2654   //   class Base { public: int x; };
2655   //   class Derived1 : public Base { };
2656   //   class Derived2 : public Base { };
2657   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2658   //
2659   //   void VeryDerived::f() {
2660   //     x = 17; // error: ambiguous base subobjects
2661   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2662   //   }
2663   if (Qualifier && Qualifier->getAsType()) {
2664     QualType QType = QualType(Qualifier->getAsType(), 0);
2665     assert(QType->isRecordType() && "lookup done with non-record type");
2666 
2667     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2668 
2669     // In C++98, the qualifier type doesn't actually have to be a base
2670     // type of the object type, in which case we just ignore it.
2671     // Otherwise build the appropriate casts.
2672     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2673       CXXCastPath BasePath;
2674       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2675                                        FromLoc, FromRange, &BasePath))
2676         return ExprError();
2677 
2678       if (PointerConversions)
2679         QType = Context.getPointerType(QType);
2680       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2681                                VK, &BasePath).get();
2682 
2683       FromType = QType;
2684       FromRecordType = QRecordType;
2685 
2686       // If the qualifier type was the same as the destination type,
2687       // we're done.
2688       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2689         return From;
2690     }
2691   }
2692 
2693   bool IgnoreAccess = false;
2694 
2695   // If we actually found the member through a using declaration, cast
2696   // down to the using declaration's type.
2697   //
2698   // Pointer equality is fine here because only one declaration of a
2699   // class ever has member declarations.
2700   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2701     assert(isa<UsingShadowDecl>(FoundDecl));
2702     QualType URecordType = Context.getTypeDeclType(
2703                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2704 
2705     // We only need to do this if the naming-class to declaring-class
2706     // conversion is non-trivial.
2707     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2708       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2709       CXXCastPath BasePath;
2710       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2711                                        FromLoc, FromRange, &BasePath))
2712         return ExprError();
2713 
2714       QualType UType = URecordType;
2715       if (PointerConversions)
2716         UType = Context.getPointerType(UType);
2717       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2718                                VK, &BasePath).get();
2719       FromType = UType;
2720       FromRecordType = URecordType;
2721     }
2722 
2723     // We don't do access control for the conversion from the
2724     // declaring class to the true declaring class.
2725     IgnoreAccess = true;
2726   }
2727 
2728   CXXCastPath BasePath;
2729   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2730                                    FromLoc, FromRange, &BasePath,
2731                                    IgnoreAccess))
2732     return ExprError();
2733 
2734   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2735                            VK, &BasePath);
2736 }
2737 
2738 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2739                                       const LookupResult &R,
2740                                       bool HasTrailingLParen) {
2741   // Only when used directly as the postfix-expression of a call.
2742   if (!HasTrailingLParen)
2743     return false;
2744 
2745   // Never if a scope specifier was provided.
2746   if (SS.isSet())
2747     return false;
2748 
2749   // Only in C++ or ObjC++.
2750   if (!getLangOpts().CPlusPlus)
2751     return false;
2752 
2753   // Turn off ADL when we find certain kinds of declarations during
2754   // normal lookup:
2755   for (NamedDecl *D : R) {
2756     // C++0x [basic.lookup.argdep]p3:
2757     //     -- a declaration of a class member
2758     // Since using decls preserve this property, we check this on the
2759     // original decl.
2760     if (D->isCXXClassMember())
2761       return false;
2762 
2763     // C++0x [basic.lookup.argdep]p3:
2764     //     -- a block-scope function declaration that is not a
2765     //        using-declaration
2766     // NOTE: we also trigger this for function templates (in fact, we
2767     // don't check the decl type at all, since all other decl types
2768     // turn off ADL anyway).
2769     if (isa<UsingShadowDecl>(D))
2770       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2771     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2772       return false;
2773 
2774     // C++0x [basic.lookup.argdep]p3:
2775     //     -- a declaration that is neither a function or a function
2776     //        template
2777     // And also for builtin functions.
2778     if (isa<FunctionDecl>(D)) {
2779       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2780 
2781       // But also builtin functions.
2782       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2783         return false;
2784     } else if (!isa<FunctionTemplateDecl>(D))
2785       return false;
2786   }
2787 
2788   return true;
2789 }
2790 
2791 
2792 /// Diagnoses obvious problems with the use of the given declaration
2793 /// as an expression.  This is only actually called for lookups that
2794 /// were not overloaded, and it doesn't promise that the declaration
2795 /// will in fact be used.
2796 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2797   if (D->isInvalidDecl())
2798     return true;
2799 
2800   if (isa<TypedefNameDecl>(D)) {
2801     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2802     return true;
2803   }
2804 
2805   if (isa<ObjCInterfaceDecl>(D)) {
2806     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2807     return true;
2808   }
2809 
2810   if (isa<NamespaceDecl>(D)) {
2811     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2812     return true;
2813   }
2814 
2815   return false;
2816 }
2817 
2818 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2819                                           LookupResult &R, bool NeedsADL,
2820                                           bool AcceptInvalidDecl) {
2821   // If this is a single, fully-resolved result and we don't need ADL,
2822   // just build an ordinary singleton decl ref.
2823   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2824     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2825                                     R.getRepresentativeDecl(), nullptr,
2826                                     AcceptInvalidDecl);
2827 
2828   // We only need to check the declaration if there's exactly one
2829   // result, because in the overloaded case the results can only be
2830   // functions and function templates.
2831   if (R.isSingleResult() &&
2832       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2833     return ExprError();
2834 
2835   // Otherwise, just build an unresolved lookup expression.  Suppress
2836   // any lookup-related diagnostics; we'll hash these out later, when
2837   // we've picked a target.
2838   R.suppressDiagnostics();
2839 
2840   UnresolvedLookupExpr *ULE
2841     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2842                                    SS.getWithLocInContext(Context),
2843                                    R.getLookupNameInfo(),
2844                                    NeedsADL, R.isOverloadedResult(),
2845                                    R.begin(), R.end());
2846 
2847   return ULE;
2848 }
2849 
2850 static void
2851 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2852                                    ValueDecl *var, DeclContext *DC);
2853 
2854 /// \brief Complete semantic analysis for a reference to the given declaration.
2855 ExprResult Sema::BuildDeclarationNameExpr(
2856     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2857     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2858     bool AcceptInvalidDecl) {
2859   assert(D && "Cannot refer to a NULL declaration");
2860   assert(!isa<FunctionTemplateDecl>(D) &&
2861          "Cannot refer unambiguously to a function template");
2862 
2863   SourceLocation Loc = NameInfo.getLoc();
2864   if (CheckDeclInExpr(*this, Loc, D))
2865     return ExprError();
2866 
2867   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2868     // Specifically diagnose references to class templates that are missing
2869     // a template argument list.
2870     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2871                                            << Template << SS.getRange();
2872     Diag(Template->getLocation(), diag::note_template_decl_here);
2873     return ExprError();
2874   }
2875 
2876   // Make sure that we're referring to a value.
2877   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2878   if (!VD) {
2879     Diag(Loc, diag::err_ref_non_value)
2880       << D << SS.getRange();
2881     Diag(D->getLocation(), diag::note_declared_at);
2882     return ExprError();
2883   }
2884 
2885   // Check whether this declaration can be used. Note that we suppress
2886   // this check when we're going to perform argument-dependent lookup
2887   // on this function name, because this might not be the function
2888   // that overload resolution actually selects.
2889   if (DiagnoseUseOfDecl(VD, Loc))
2890     return ExprError();
2891 
2892   // Only create DeclRefExpr's for valid Decl's.
2893   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2894     return ExprError();
2895 
2896   // Handle members of anonymous structs and unions.  If we got here,
2897   // and the reference is to a class member indirect field, then this
2898   // must be the subject of a pointer-to-member expression.
2899   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2900     if (!indirectField->isCXXClassMember())
2901       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2902                                                       indirectField);
2903 
2904   {
2905     QualType type = VD->getType();
2906     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2907       // C++ [except.spec]p17:
2908       //   An exception-specification is considered to be needed when:
2909       //   - in an expression, the function is the unique lookup result or
2910       //     the selected member of a set of overloaded functions.
2911       ResolveExceptionSpec(Loc, FPT);
2912       type = VD->getType();
2913     }
2914     ExprValueKind valueKind = VK_RValue;
2915 
2916     switch (D->getKind()) {
2917     // Ignore all the non-ValueDecl kinds.
2918 #define ABSTRACT_DECL(kind)
2919 #define VALUE(type, base)
2920 #define DECL(type, base) \
2921     case Decl::type:
2922 #include "clang/AST/DeclNodes.inc"
2923       llvm_unreachable("invalid value decl kind");
2924 
2925     // These shouldn't make it here.
2926     case Decl::ObjCAtDefsField:
2927     case Decl::ObjCIvar:
2928       llvm_unreachable("forming non-member reference to ivar?");
2929 
2930     // Enum constants are always r-values and never references.
2931     // Unresolved using declarations are dependent.
2932     case Decl::EnumConstant:
2933     case Decl::UnresolvedUsingValue:
2934     case Decl::OMPDeclareReduction:
2935       valueKind = VK_RValue;
2936       break;
2937 
2938     // Fields and indirect fields that got here must be for
2939     // pointer-to-member expressions; we just call them l-values for
2940     // internal consistency, because this subexpression doesn't really
2941     // exist in the high-level semantics.
2942     case Decl::Field:
2943     case Decl::IndirectField:
2944       assert(getLangOpts().CPlusPlus &&
2945              "building reference to field in C?");
2946 
2947       // These can't have reference type in well-formed programs, but
2948       // for internal consistency we do this anyway.
2949       type = type.getNonReferenceType();
2950       valueKind = VK_LValue;
2951       break;
2952 
2953     // Non-type template parameters are either l-values or r-values
2954     // depending on the type.
2955     case Decl::NonTypeTemplateParm: {
2956       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2957         type = reftype->getPointeeType();
2958         valueKind = VK_LValue; // even if the parameter is an r-value reference
2959         break;
2960       }
2961 
2962       // For non-references, we need to strip qualifiers just in case
2963       // the template parameter was declared as 'const int' or whatever.
2964       valueKind = VK_RValue;
2965       type = type.getUnqualifiedType();
2966       break;
2967     }
2968 
2969     case Decl::Var:
2970     case Decl::VarTemplateSpecialization:
2971     case Decl::VarTemplatePartialSpecialization:
2972     case Decl::Decomposition:
2973     case Decl::OMPCapturedExpr:
2974       // In C, "extern void blah;" is valid and is an r-value.
2975       if (!getLangOpts().CPlusPlus &&
2976           !type.hasQualifiers() &&
2977           type->isVoidType()) {
2978         valueKind = VK_RValue;
2979         break;
2980       }
2981       // fallthrough
2982 
2983     case Decl::ImplicitParam:
2984     case Decl::ParmVar: {
2985       // These are always l-values.
2986       valueKind = VK_LValue;
2987       type = type.getNonReferenceType();
2988 
2989       // FIXME: Does the addition of const really only apply in
2990       // potentially-evaluated contexts? Since the variable isn't actually
2991       // captured in an unevaluated context, it seems that the answer is no.
2992       if (!isUnevaluatedContext()) {
2993         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2994         if (!CapturedType.isNull())
2995           type = CapturedType;
2996       }
2997 
2998       break;
2999     }
3000 
3001     case Decl::Binding: {
3002       // These are always lvalues.
3003       valueKind = VK_LValue;
3004       type = type.getNonReferenceType();
3005       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3006       // decides how that's supposed to work.
3007       auto *BD = cast<BindingDecl>(VD);
3008       if (BD->getDeclContext()->isFunctionOrMethod() &&
3009           BD->getDeclContext() != CurContext)
3010         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3011       break;
3012     }
3013 
3014     case Decl::Function: {
3015       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3016         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3017           type = Context.BuiltinFnTy;
3018           valueKind = VK_RValue;
3019           break;
3020         }
3021       }
3022 
3023       const FunctionType *fty = type->castAs<FunctionType>();
3024 
3025       // If we're referring to a function with an __unknown_anytype
3026       // result type, make the entire expression __unknown_anytype.
3027       if (fty->getReturnType() == Context.UnknownAnyTy) {
3028         type = Context.UnknownAnyTy;
3029         valueKind = VK_RValue;
3030         break;
3031       }
3032 
3033       // Functions are l-values in C++.
3034       if (getLangOpts().CPlusPlus) {
3035         valueKind = VK_LValue;
3036         break;
3037       }
3038 
3039       // C99 DR 316 says that, if a function type comes from a
3040       // function definition (without a prototype), that type is only
3041       // used for checking compatibility. Therefore, when referencing
3042       // the function, we pretend that we don't have the full function
3043       // type.
3044       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3045           isa<FunctionProtoType>(fty))
3046         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3047                                               fty->getExtInfo());
3048 
3049       // Functions are r-values in C.
3050       valueKind = VK_RValue;
3051       break;
3052     }
3053 
3054     case Decl::CXXDeductionGuide:
3055       llvm_unreachable("building reference to deduction guide");
3056 
3057     case Decl::MSProperty:
3058       valueKind = VK_LValue;
3059       break;
3060 
3061     case Decl::CXXMethod:
3062       // If we're referring to a method with an __unknown_anytype
3063       // result type, make the entire expression __unknown_anytype.
3064       // This should only be possible with a type written directly.
3065       if (const FunctionProtoType *proto
3066             = dyn_cast<FunctionProtoType>(VD->getType()))
3067         if (proto->getReturnType() == Context.UnknownAnyTy) {
3068           type = Context.UnknownAnyTy;
3069           valueKind = VK_RValue;
3070           break;
3071         }
3072 
3073       // C++ methods are l-values if static, r-values if non-static.
3074       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3075         valueKind = VK_LValue;
3076         break;
3077       }
3078       // fallthrough
3079 
3080     case Decl::CXXConversion:
3081     case Decl::CXXDestructor:
3082     case Decl::CXXConstructor:
3083       valueKind = VK_RValue;
3084       break;
3085     }
3086 
3087     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3088                             TemplateArgs);
3089   }
3090 }
3091 
3092 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3093                                     SmallString<32> &Target) {
3094   Target.resize(CharByteWidth * (Source.size() + 1));
3095   char *ResultPtr = &Target[0];
3096   const llvm::UTF8 *ErrorPtr;
3097   bool success =
3098       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3099   (void)success;
3100   assert(success);
3101   Target.resize(ResultPtr - &Target[0]);
3102 }
3103 
3104 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3105                                      PredefinedExpr::IdentType IT) {
3106   // Pick the current block, lambda, captured statement or function.
3107   Decl *currentDecl = nullptr;
3108   if (const BlockScopeInfo *BSI = getCurBlock())
3109     currentDecl = BSI->TheDecl;
3110   else if (const LambdaScopeInfo *LSI = getCurLambda())
3111     currentDecl = LSI->CallOperator;
3112   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3113     currentDecl = CSI->TheCapturedDecl;
3114   else
3115     currentDecl = getCurFunctionOrMethodDecl();
3116 
3117   if (!currentDecl) {
3118     Diag(Loc, diag::ext_predef_outside_function);
3119     currentDecl = Context.getTranslationUnitDecl();
3120   }
3121 
3122   QualType ResTy;
3123   StringLiteral *SL = nullptr;
3124   if (cast<DeclContext>(currentDecl)->isDependentContext())
3125     ResTy = Context.DependentTy;
3126   else {
3127     // Pre-defined identifiers are of type char[x], where x is the length of
3128     // the string.
3129     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3130     unsigned Length = Str.length();
3131 
3132     llvm::APInt LengthI(32, Length + 1);
3133     if (IT == PredefinedExpr::LFunction) {
3134       ResTy = Context.WideCharTy.withConst();
3135       SmallString<32> RawChars;
3136       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3137                               Str, RawChars);
3138       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3139                                            /*IndexTypeQuals*/ 0);
3140       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3141                                  /*Pascal*/ false, ResTy, Loc);
3142     } else {
3143       ResTy = Context.CharTy.withConst();
3144       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3145                                            /*IndexTypeQuals*/ 0);
3146       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3147                                  /*Pascal*/ false, ResTy, Loc);
3148     }
3149   }
3150 
3151   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3152 }
3153 
3154 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3155   PredefinedExpr::IdentType IT;
3156 
3157   switch (Kind) {
3158   default: llvm_unreachable("Unknown simple primary expr!");
3159   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3160   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3161   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3162   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3163   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3164   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3165   }
3166 
3167   return BuildPredefinedExpr(Loc, IT);
3168 }
3169 
3170 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3171   SmallString<16> CharBuffer;
3172   bool Invalid = false;
3173   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3174   if (Invalid)
3175     return ExprError();
3176 
3177   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3178                             PP, Tok.getKind());
3179   if (Literal.hadError())
3180     return ExprError();
3181 
3182   QualType Ty;
3183   if (Literal.isWide())
3184     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3185   else if (Literal.isUTF16())
3186     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3187   else if (Literal.isUTF32())
3188     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3189   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3190     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3191   else
3192     Ty = Context.CharTy;  // 'x' -> char in C++
3193 
3194   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3195   if (Literal.isWide())
3196     Kind = CharacterLiteral::Wide;
3197   else if (Literal.isUTF16())
3198     Kind = CharacterLiteral::UTF16;
3199   else if (Literal.isUTF32())
3200     Kind = CharacterLiteral::UTF32;
3201   else if (Literal.isUTF8())
3202     Kind = CharacterLiteral::UTF8;
3203 
3204   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3205                                              Tok.getLocation());
3206 
3207   if (Literal.getUDSuffix().empty())
3208     return Lit;
3209 
3210   // We're building a user-defined literal.
3211   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3212   SourceLocation UDSuffixLoc =
3213     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3214 
3215   // Make sure we're allowed user-defined literals here.
3216   if (!UDLScope)
3217     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3218 
3219   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3220   //   operator "" X (ch)
3221   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3222                                         Lit, Tok.getLocation());
3223 }
3224 
3225 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3226   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3227   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3228                                 Context.IntTy, Loc);
3229 }
3230 
3231 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3232                                   QualType Ty, SourceLocation Loc) {
3233   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3234 
3235   using llvm::APFloat;
3236   APFloat Val(Format);
3237 
3238   APFloat::opStatus result = Literal.GetFloatValue(Val);
3239 
3240   // Overflow is always an error, but underflow is only an error if
3241   // we underflowed to zero (APFloat reports denormals as underflow).
3242   if ((result & APFloat::opOverflow) ||
3243       ((result & APFloat::opUnderflow) && Val.isZero())) {
3244     unsigned diagnostic;
3245     SmallString<20> buffer;
3246     if (result & APFloat::opOverflow) {
3247       diagnostic = diag::warn_float_overflow;
3248       APFloat::getLargest(Format).toString(buffer);
3249     } else {
3250       diagnostic = diag::warn_float_underflow;
3251       APFloat::getSmallest(Format).toString(buffer);
3252     }
3253 
3254     S.Diag(Loc, diagnostic)
3255       << Ty
3256       << StringRef(buffer.data(), buffer.size());
3257   }
3258 
3259   bool isExact = (result == APFloat::opOK);
3260   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3261 }
3262 
3263 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3264   assert(E && "Invalid expression");
3265 
3266   if (E->isValueDependent())
3267     return false;
3268 
3269   QualType QT = E->getType();
3270   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3271     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3272     return true;
3273   }
3274 
3275   llvm::APSInt ValueAPS;
3276   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3277 
3278   if (R.isInvalid())
3279     return true;
3280 
3281   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3282   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3283     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3284         << ValueAPS.toString(10) << ValueIsPositive;
3285     return true;
3286   }
3287 
3288   return false;
3289 }
3290 
3291 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3292   // Fast path for a single digit (which is quite common).  A single digit
3293   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3294   if (Tok.getLength() == 1) {
3295     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3296     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3297   }
3298 
3299   SmallString<128> SpellingBuffer;
3300   // NumericLiteralParser wants to overread by one character.  Add padding to
3301   // the buffer in case the token is copied to the buffer.  If getSpelling()
3302   // returns a StringRef to the memory buffer, it should have a null char at
3303   // the EOF, so it is also safe.
3304   SpellingBuffer.resize(Tok.getLength() + 1);
3305 
3306   // Get the spelling of the token, which eliminates trigraphs, etc.
3307   bool Invalid = false;
3308   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3309   if (Invalid)
3310     return ExprError();
3311 
3312   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3313   if (Literal.hadError)
3314     return ExprError();
3315 
3316   if (Literal.hasUDSuffix()) {
3317     // We're building a user-defined literal.
3318     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3319     SourceLocation UDSuffixLoc =
3320       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3321 
3322     // Make sure we're allowed user-defined literals here.
3323     if (!UDLScope)
3324       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3325 
3326     QualType CookedTy;
3327     if (Literal.isFloatingLiteral()) {
3328       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3329       // long double, the literal is treated as a call of the form
3330       //   operator "" X (f L)
3331       CookedTy = Context.LongDoubleTy;
3332     } else {
3333       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3334       // unsigned long long, the literal is treated as a call of the form
3335       //   operator "" X (n ULL)
3336       CookedTy = Context.UnsignedLongLongTy;
3337     }
3338 
3339     DeclarationName OpName =
3340       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3341     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3342     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3343 
3344     SourceLocation TokLoc = Tok.getLocation();
3345 
3346     // Perform literal operator lookup to determine if we're building a raw
3347     // literal or a cooked one.
3348     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3349     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3350                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3351                                   /*AllowStringTemplate*/false)) {
3352     case LOLR_Error:
3353       return ExprError();
3354 
3355     case LOLR_Cooked: {
3356       Expr *Lit;
3357       if (Literal.isFloatingLiteral()) {
3358         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3359       } else {
3360         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3361         if (Literal.GetIntegerValue(ResultVal))
3362           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3363               << /* Unsigned */ 1;
3364         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3365                                      Tok.getLocation());
3366       }
3367       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3368     }
3369 
3370     case LOLR_Raw: {
3371       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3372       // literal is treated as a call of the form
3373       //   operator "" X ("n")
3374       unsigned Length = Literal.getUDSuffixOffset();
3375       QualType StrTy = Context.getConstantArrayType(
3376           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3377           ArrayType::Normal, 0);
3378       Expr *Lit = StringLiteral::Create(
3379           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3380           /*Pascal*/false, StrTy, &TokLoc, 1);
3381       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3382     }
3383 
3384     case LOLR_Template: {
3385       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3386       // template), L is treated as a call fo the form
3387       //   operator "" X <'c1', 'c2', ... 'ck'>()
3388       // where n is the source character sequence c1 c2 ... ck.
3389       TemplateArgumentListInfo ExplicitArgs;
3390       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3391       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3392       llvm::APSInt Value(CharBits, CharIsUnsigned);
3393       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3394         Value = TokSpelling[I];
3395         TemplateArgument Arg(Context, Value, Context.CharTy);
3396         TemplateArgumentLocInfo ArgInfo;
3397         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3398       }
3399       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3400                                       &ExplicitArgs);
3401     }
3402     case LOLR_StringTemplate:
3403       llvm_unreachable("unexpected literal operator lookup result");
3404     }
3405   }
3406 
3407   Expr *Res;
3408 
3409   if (Literal.isFloatingLiteral()) {
3410     QualType Ty;
3411     if (Literal.isHalf){
3412       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3413         Ty = Context.HalfTy;
3414       else {
3415         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3416         return ExprError();
3417       }
3418     } else if (Literal.isFloat)
3419       Ty = Context.FloatTy;
3420     else if (Literal.isLong)
3421       Ty = Context.LongDoubleTy;
3422     else if (Literal.isFloat128)
3423       Ty = Context.Float128Ty;
3424     else
3425       Ty = Context.DoubleTy;
3426 
3427     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3428 
3429     if (Ty == Context.DoubleTy) {
3430       if (getLangOpts().SinglePrecisionConstants) {
3431         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3432         if (BTy->getKind() != BuiltinType::Float) {
3433           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3434         }
3435       } else if (getLangOpts().OpenCL &&
3436                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3437         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3438         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3439         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3440       }
3441     }
3442   } else if (!Literal.isIntegerLiteral()) {
3443     return ExprError();
3444   } else {
3445     QualType Ty;
3446 
3447     // 'long long' is a C99 or C++11 feature.
3448     if (!getLangOpts().C99 && Literal.isLongLong) {
3449       if (getLangOpts().CPlusPlus)
3450         Diag(Tok.getLocation(),
3451              getLangOpts().CPlusPlus11 ?
3452              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3453       else
3454         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3455     }
3456 
3457     // Get the value in the widest-possible width.
3458     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3459     llvm::APInt ResultVal(MaxWidth, 0);
3460 
3461     if (Literal.GetIntegerValue(ResultVal)) {
3462       // If this value didn't fit into uintmax_t, error and force to ull.
3463       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3464           << /* Unsigned */ 1;
3465       Ty = Context.UnsignedLongLongTy;
3466       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3467              "long long is not intmax_t?");
3468     } else {
3469       // If this value fits into a ULL, try to figure out what else it fits into
3470       // according to the rules of C99 6.4.4.1p5.
3471 
3472       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3473       // be an unsigned int.
3474       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3475 
3476       // Check from smallest to largest, picking the smallest type we can.
3477       unsigned Width = 0;
3478 
3479       // Microsoft specific integer suffixes are explicitly sized.
3480       if (Literal.MicrosoftInteger) {
3481         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3482           Width = 8;
3483           Ty = Context.CharTy;
3484         } else {
3485           Width = Literal.MicrosoftInteger;
3486           Ty = Context.getIntTypeForBitwidth(Width,
3487                                              /*Signed=*/!Literal.isUnsigned);
3488         }
3489       }
3490 
3491       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3492         // Are int/unsigned possibilities?
3493         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3494 
3495         // Does it fit in a unsigned int?
3496         if (ResultVal.isIntN(IntSize)) {
3497           // Does it fit in a signed int?
3498           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3499             Ty = Context.IntTy;
3500           else if (AllowUnsigned)
3501             Ty = Context.UnsignedIntTy;
3502           Width = IntSize;
3503         }
3504       }
3505 
3506       // Are long/unsigned long possibilities?
3507       if (Ty.isNull() && !Literal.isLongLong) {
3508         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3509 
3510         // Does it fit in a unsigned long?
3511         if (ResultVal.isIntN(LongSize)) {
3512           // Does it fit in a signed long?
3513           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3514             Ty = Context.LongTy;
3515           else if (AllowUnsigned)
3516             Ty = Context.UnsignedLongTy;
3517           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3518           // is compatible.
3519           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3520             const unsigned LongLongSize =
3521                 Context.getTargetInfo().getLongLongWidth();
3522             Diag(Tok.getLocation(),
3523                  getLangOpts().CPlusPlus
3524                      ? Literal.isLong
3525                            ? diag::warn_old_implicitly_unsigned_long_cxx
3526                            : /*C++98 UB*/ diag::
3527                                  ext_old_implicitly_unsigned_long_cxx
3528                      : diag::warn_old_implicitly_unsigned_long)
3529                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3530                                             : /*will be ill-formed*/ 1);
3531             Ty = Context.UnsignedLongTy;
3532           }
3533           Width = LongSize;
3534         }
3535       }
3536 
3537       // Check long long if needed.
3538       if (Ty.isNull()) {
3539         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3540 
3541         // Does it fit in a unsigned long long?
3542         if (ResultVal.isIntN(LongLongSize)) {
3543           // Does it fit in a signed long long?
3544           // To be compatible with MSVC, hex integer literals ending with the
3545           // LL or i64 suffix are always signed in Microsoft mode.
3546           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3547               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3548             Ty = Context.LongLongTy;
3549           else if (AllowUnsigned)
3550             Ty = Context.UnsignedLongLongTy;
3551           Width = LongLongSize;
3552         }
3553       }
3554 
3555       // If we still couldn't decide a type, we probably have something that
3556       // does not fit in a signed long long, but has no U suffix.
3557       if (Ty.isNull()) {
3558         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3559         Ty = Context.UnsignedLongLongTy;
3560         Width = Context.getTargetInfo().getLongLongWidth();
3561       }
3562 
3563       if (ResultVal.getBitWidth() != Width)
3564         ResultVal = ResultVal.trunc(Width);
3565     }
3566     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3567   }
3568 
3569   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3570   if (Literal.isImaginary)
3571     Res = new (Context) ImaginaryLiteral(Res,
3572                                         Context.getComplexType(Res->getType()));
3573 
3574   return Res;
3575 }
3576 
3577 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3578   assert(E && "ActOnParenExpr() missing expr");
3579   return new (Context) ParenExpr(L, R, E);
3580 }
3581 
3582 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3583                                          SourceLocation Loc,
3584                                          SourceRange ArgRange) {
3585   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3586   // scalar or vector data type argument..."
3587   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3588   // type (C99 6.2.5p18) or void.
3589   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3590     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3591       << T << ArgRange;
3592     return true;
3593   }
3594 
3595   assert((T->isVoidType() || !T->isIncompleteType()) &&
3596          "Scalar types should always be complete");
3597   return false;
3598 }
3599 
3600 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3601                                            SourceLocation Loc,
3602                                            SourceRange ArgRange,
3603                                            UnaryExprOrTypeTrait TraitKind) {
3604   // Invalid types must be hard errors for SFINAE in C++.
3605   if (S.LangOpts.CPlusPlus)
3606     return true;
3607 
3608   // C99 6.5.3.4p1:
3609   if (T->isFunctionType() &&
3610       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3611     // sizeof(function)/alignof(function) is allowed as an extension.
3612     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3613       << TraitKind << ArgRange;
3614     return false;
3615   }
3616 
3617   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3618   // this is an error (OpenCL v1.1 s6.3.k)
3619   if (T->isVoidType()) {
3620     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3621                                         : diag::ext_sizeof_alignof_void_type;
3622     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3623     return false;
3624   }
3625 
3626   return true;
3627 }
3628 
3629 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3630                                              SourceLocation Loc,
3631                                              SourceRange ArgRange,
3632                                              UnaryExprOrTypeTrait TraitKind) {
3633   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3634   // runtime doesn't allow it.
3635   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3636     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3637       << T << (TraitKind == UETT_SizeOf)
3638       << ArgRange;
3639     return true;
3640   }
3641 
3642   return false;
3643 }
3644 
3645 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3646 /// pointer type is equal to T) and emit a warning if it is.
3647 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3648                                      Expr *E) {
3649   // Don't warn if the operation changed the type.
3650   if (T != E->getType())
3651     return;
3652 
3653   // Now look for array decays.
3654   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3655   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3656     return;
3657 
3658   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3659                                              << ICE->getType()
3660                                              << ICE->getSubExpr()->getType();
3661 }
3662 
3663 /// \brief Check the constraints on expression operands to unary type expression
3664 /// and type traits.
3665 ///
3666 /// Completes any types necessary and validates the constraints on the operand
3667 /// expression. The logic mostly mirrors the type-based overload, but may modify
3668 /// the expression as it completes the type for that expression through template
3669 /// instantiation, etc.
3670 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3671                                             UnaryExprOrTypeTrait ExprKind) {
3672   QualType ExprTy = E->getType();
3673   assert(!ExprTy->isReferenceType());
3674 
3675   if (ExprKind == UETT_VecStep)
3676     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3677                                         E->getSourceRange());
3678 
3679   // Whitelist some types as extensions
3680   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3681                                       E->getSourceRange(), ExprKind))
3682     return false;
3683 
3684   // 'alignof' applied to an expression only requires the base element type of
3685   // the expression to be complete. 'sizeof' requires the expression's type to
3686   // be complete (and will attempt to complete it if it's an array of unknown
3687   // bound).
3688   if (ExprKind == UETT_AlignOf) {
3689     if (RequireCompleteType(E->getExprLoc(),
3690                             Context.getBaseElementType(E->getType()),
3691                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3692                             E->getSourceRange()))
3693       return true;
3694   } else {
3695     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3696                                 ExprKind, E->getSourceRange()))
3697       return true;
3698   }
3699 
3700   // Completing the expression's type may have changed it.
3701   ExprTy = E->getType();
3702   assert(!ExprTy->isReferenceType());
3703 
3704   if (ExprTy->isFunctionType()) {
3705     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3706       << ExprKind << E->getSourceRange();
3707     return true;
3708   }
3709 
3710   // The operand for sizeof and alignof is in an unevaluated expression context,
3711   // so side effects could result in unintended consequences.
3712   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3713       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3714     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3715 
3716   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3717                                        E->getSourceRange(), ExprKind))
3718     return true;
3719 
3720   if (ExprKind == UETT_SizeOf) {
3721     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3722       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3723         QualType OType = PVD->getOriginalType();
3724         QualType Type = PVD->getType();
3725         if (Type->isPointerType() && OType->isArrayType()) {
3726           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3727             << Type << OType;
3728           Diag(PVD->getLocation(), diag::note_declared_at);
3729         }
3730       }
3731     }
3732 
3733     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3734     // decays into a pointer and returns an unintended result. This is most
3735     // likely a typo for "sizeof(array) op x".
3736     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3737       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3738                                BO->getLHS());
3739       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3740                                BO->getRHS());
3741     }
3742   }
3743 
3744   return false;
3745 }
3746 
3747 /// \brief Check the constraints on operands to unary expression and type
3748 /// traits.
3749 ///
3750 /// This will complete any types necessary, and validate the various constraints
3751 /// on those operands.
3752 ///
3753 /// The UsualUnaryConversions() function is *not* called by this routine.
3754 /// C99 6.3.2.1p[2-4] all state:
3755 ///   Except when it is the operand of the sizeof operator ...
3756 ///
3757 /// C++ [expr.sizeof]p4
3758 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3759 ///   standard conversions are not applied to the operand of sizeof.
3760 ///
3761 /// This policy is followed for all of the unary trait expressions.
3762 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3763                                             SourceLocation OpLoc,
3764                                             SourceRange ExprRange,
3765                                             UnaryExprOrTypeTrait ExprKind) {
3766   if (ExprType->isDependentType())
3767     return false;
3768 
3769   // C++ [expr.sizeof]p2:
3770   //     When applied to a reference or a reference type, the result
3771   //     is the size of the referenced type.
3772   // C++11 [expr.alignof]p3:
3773   //     When alignof is applied to a reference type, the result
3774   //     shall be the alignment of the referenced type.
3775   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3776     ExprType = Ref->getPointeeType();
3777 
3778   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3779   //   When alignof or _Alignof is applied to an array type, the result
3780   //   is the alignment of the element type.
3781   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3782     ExprType = Context.getBaseElementType(ExprType);
3783 
3784   if (ExprKind == UETT_VecStep)
3785     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3786 
3787   // Whitelist some types as extensions
3788   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3789                                       ExprKind))
3790     return false;
3791 
3792   if (RequireCompleteType(OpLoc, ExprType,
3793                           diag::err_sizeof_alignof_incomplete_type,
3794                           ExprKind, ExprRange))
3795     return true;
3796 
3797   if (ExprType->isFunctionType()) {
3798     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3799       << ExprKind << ExprRange;
3800     return true;
3801   }
3802 
3803   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3804                                        ExprKind))
3805     return true;
3806 
3807   return false;
3808 }
3809 
3810 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3811   E = E->IgnoreParens();
3812 
3813   // Cannot know anything else if the expression is dependent.
3814   if (E->isTypeDependent())
3815     return false;
3816 
3817   if (E->getObjectKind() == OK_BitField) {
3818     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3819        << 1 << E->getSourceRange();
3820     return true;
3821   }
3822 
3823   ValueDecl *D = nullptr;
3824   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3825     D = DRE->getDecl();
3826   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3827     D = ME->getMemberDecl();
3828   }
3829 
3830   // If it's a field, require the containing struct to have a
3831   // complete definition so that we can compute the layout.
3832   //
3833   // This can happen in C++11 onwards, either by naming the member
3834   // in a way that is not transformed into a member access expression
3835   // (in an unevaluated operand, for instance), or by naming the member
3836   // in a trailing-return-type.
3837   //
3838   // For the record, since __alignof__ on expressions is a GCC
3839   // extension, GCC seems to permit this but always gives the
3840   // nonsensical answer 0.
3841   //
3842   // We don't really need the layout here --- we could instead just
3843   // directly check for all the appropriate alignment-lowing
3844   // attributes --- but that would require duplicating a lot of
3845   // logic that just isn't worth duplicating for such a marginal
3846   // use-case.
3847   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3848     // Fast path this check, since we at least know the record has a
3849     // definition if we can find a member of it.
3850     if (!FD->getParent()->isCompleteDefinition()) {
3851       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3852         << E->getSourceRange();
3853       return true;
3854     }
3855 
3856     // Otherwise, if it's a field, and the field doesn't have
3857     // reference type, then it must have a complete type (or be a
3858     // flexible array member, which we explicitly want to
3859     // white-list anyway), which makes the following checks trivial.
3860     if (!FD->getType()->isReferenceType())
3861       return false;
3862   }
3863 
3864   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3865 }
3866 
3867 bool Sema::CheckVecStepExpr(Expr *E) {
3868   E = E->IgnoreParens();
3869 
3870   // Cannot know anything else if the expression is dependent.
3871   if (E->isTypeDependent())
3872     return false;
3873 
3874   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3875 }
3876 
3877 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3878                                         CapturingScopeInfo *CSI) {
3879   assert(T->isVariablyModifiedType());
3880   assert(CSI != nullptr);
3881 
3882   // We're going to walk down into the type and look for VLA expressions.
3883   do {
3884     const Type *Ty = T.getTypePtr();
3885     switch (Ty->getTypeClass()) {
3886 #define TYPE(Class, Base)
3887 #define ABSTRACT_TYPE(Class, Base)
3888 #define NON_CANONICAL_TYPE(Class, Base)
3889 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3890 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3891 #include "clang/AST/TypeNodes.def"
3892       T = QualType();
3893       break;
3894     // These types are never variably-modified.
3895     case Type::Builtin:
3896     case Type::Complex:
3897     case Type::Vector:
3898     case Type::ExtVector:
3899     case Type::Record:
3900     case Type::Enum:
3901     case Type::Elaborated:
3902     case Type::TemplateSpecialization:
3903     case Type::ObjCObject:
3904     case Type::ObjCInterface:
3905     case Type::ObjCObjectPointer:
3906     case Type::ObjCTypeParam:
3907     case Type::Pipe:
3908       llvm_unreachable("type class is never variably-modified!");
3909     case Type::Adjusted:
3910       T = cast<AdjustedType>(Ty)->getOriginalType();
3911       break;
3912     case Type::Decayed:
3913       T = cast<DecayedType>(Ty)->getPointeeType();
3914       break;
3915     case Type::Pointer:
3916       T = cast<PointerType>(Ty)->getPointeeType();
3917       break;
3918     case Type::BlockPointer:
3919       T = cast<BlockPointerType>(Ty)->getPointeeType();
3920       break;
3921     case Type::LValueReference:
3922     case Type::RValueReference:
3923       T = cast<ReferenceType>(Ty)->getPointeeType();
3924       break;
3925     case Type::MemberPointer:
3926       T = cast<MemberPointerType>(Ty)->getPointeeType();
3927       break;
3928     case Type::ConstantArray:
3929     case Type::IncompleteArray:
3930       // Losing element qualification here is fine.
3931       T = cast<ArrayType>(Ty)->getElementType();
3932       break;
3933     case Type::VariableArray: {
3934       // Losing element qualification here is fine.
3935       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3936 
3937       // Unknown size indication requires no size computation.
3938       // Otherwise, evaluate and record it.
3939       if (auto Size = VAT->getSizeExpr()) {
3940         if (!CSI->isVLATypeCaptured(VAT)) {
3941           RecordDecl *CapRecord = nullptr;
3942           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3943             CapRecord = LSI->Lambda;
3944           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3945             CapRecord = CRSI->TheRecordDecl;
3946           }
3947           if (CapRecord) {
3948             auto ExprLoc = Size->getExprLoc();
3949             auto SizeType = Context.getSizeType();
3950             // Build the non-static data member.
3951             auto Field =
3952                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3953                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3954                                   /*BW*/ nullptr, /*Mutable*/ false,
3955                                   /*InitStyle*/ ICIS_NoInit);
3956             Field->setImplicit(true);
3957             Field->setAccess(AS_private);
3958             Field->setCapturedVLAType(VAT);
3959             CapRecord->addDecl(Field);
3960 
3961             CSI->addVLATypeCapture(ExprLoc, SizeType);
3962           }
3963         }
3964       }
3965       T = VAT->getElementType();
3966       break;
3967     }
3968     case Type::FunctionProto:
3969     case Type::FunctionNoProto:
3970       T = cast<FunctionType>(Ty)->getReturnType();
3971       break;
3972     case Type::Paren:
3973     case Type::TypeOf:
3974     case Type::UnaryTransform:
3975     case Type::Attributed:
3976     case Type::SubstTemplateTypeParm:
3977     case Type::PackExpansion:
3978       // Keep walking after single level desugaring.
3979       T = T.getSingleStepDesugaredType(Context);
3980       break;
3981     case Type::Typedef:
3982       T = cast<TypedefType>(Ty)->desugar();
3983       break;
3984     case Type::Decltype:
3985       T = cast<DecltypeType>(Ty)->desugar();
3986       break;
3987     case Type::Auto:
3988     case Type::DeducedTemplateSpecialization:
3989       T = cast<DeducedType>(Ty)->getDeducedType();
3990       break;
3991     case Type::TypeOfExpr:
3992       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3993       break;
3994     case Type::Atomic:
3995       T = cast<AtomicType>(Ty)->getValueType();
3996       break;
3997     }
3998   } while (!T.isNull() && T->isVariablyModifiedType());
3999 }
4000 
4001 /// \brief Build a sizeof or alignof expression given a type operand.
4002 ExprResult
4003 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4004                                      SourceLocation OpLoc,
4005                                      UnaryExprOrTypeTrait ExprKind,
4006                                      SourceRange R) {
4007   if (!TInfo)
4008     return ExprError();
4009 
4010   QualType T = TInfo->getType();
4011 
4012   if (!T->isDependentType() &&
4013       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4014     return ExprError();
4015 
4016   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4017     if (auto *TT = T->getAs<TypedefType>()) {
4018       for (auto I = FunctionScopes.rbegin(),
4019                 E = std::prev(FunctionScopes.rend());
4020            I != E; ++I) {
4021         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4022         if (CSI == nullptr)
4023           break;
4024         DeclContext *DC = nullptr;
4025         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4026           DC = LSI->CallOperator;
4027         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4028           DC = CRSI->TheCapturedDecl;
4029         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4030           DC = BSI->TheDecl;
4031         if (DC) {
4032           if (DC->containsDecl(TT->getDecl()))
4033             break;
4034           captureVariablyModifiedType(Context, T, CSI);
4035         }
4036       }
4037     }
4038   }
4039 
4040   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4041   return new (Context) UnaryExprOrTypeTraitExpr(
4042       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4043 }
4044 
4045 /// \brief Build a sizeof or alignof expression given an expression
4046 /// operand.
4047 ExprResult
4048 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4049                                      UnaryExprOrTypeTrait ExprKind) {
4050   ExprResult PE = CheckPlaceholderExpr(E);
4051   if (PE.isInvalid())
4052     return ExprError();
4053 
4054   E = PE.get();
4055 
4056   // Verify that the operand is valid.
4057   bool isInvalid = false;
4058   if (E->isTypeDependent()) {
4059     // Delay type-checking for type-dependent expressions.
4060   } else if (ExprKind == UETT_AlignOf) {
4061     isInvalid = CheckAlignOfExpr(*this, E);
4062   } else if (ExprKind == UETT_VecStep) {
4063     isInvalid = CheckVecStepExpr(E);
4064   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4065       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4066       isInvalid = true;
4067   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4068     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4069     isInvalid = true;
4070   } else {
4071     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4072   }
4073 
4074   if (isInvalid)
4075     return ExprError();
4076 
4077   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4078     PE = TransformToPotentiallyEvaluated(E);
4079     if (PE.isInvalid()) return ExprError();
4080     E = PE.get();
4081   }
4082 
4083   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4084   return new (Context) UnaryExprOrTypeTraitExpr(
4085       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4086 }
4087 
4088 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4089 /// expr and the same for @c alignof and @c __alignof
4090 /// Note that the ArgRange is invalid if isType is false.
4091 ExprResult
4092 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4093                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4094                                     void *TyOrEx, SourceRange ArgRange) {
4095   // If error parsing type, ignore.
4096   if (!TyOrEx) return ExprError();
4097 
4098   if (IsType) {
4099     TypeSourceInfo *TInfo;
4100     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4101     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4102   }
4103 
4104   Expr *ArgEx = (Expr *)TyOrEx;
4105   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4106   return Result;
4107 }
4108 
4109 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4110                                      bool IsReal) {
4111   if (V.get()->isTypeDependent())
4112     return S.Context.DependentTy;
4113 
4114   // _Real and _Imag are only l-values for normal l-values.
4115   if (V.get()->getObjectKind() != OK_Ordinary) {
4116     V = S.DefaultLvalueConversion(V.get());
4117     if (V.isInvalid())
4118       return QualType();
4119   }
4120 
4121   // These operators return the element type of a complex type.
4122   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4123     return CT->getElementType();
4124 
4125   // Otherwise they pass through real integer and floating point types here.
4126   if (V.get()->getType()->isArithmeticType())
4127     return V.get()->getType();
4128 
4129   // Test for placeholders.
4130   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4131   if (PR.isInvalid()) return QualType();
4132   if (PR.get() != V.get()) {
4133     V = PR;
4134     return CheckRealImagOperand(S, V, Loc, IsReal);
4135   }
4136 
4137   // Reject anything else.
4138   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4139     << (IsReal ? "__real" : "__imag");
4140   return QualType();
4141 }
4142 
4143 
4144 
4145 ExprResult
4146 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4147                           tok::TokenKind Kind, Expr *Input) {
4148   UnaryOperatorKind Opc;
4149   switch (Kind) {
4150   default: llvm_unreachable("Unknown unary op!");
4151   case tok::plusplus:   Opc = UO_PostInc; break;
4152   case tok::minusminus: Opc = UO_PostDec; break;
4153   }
4154 
4155   // Since this might is a postfix expression, get rid of ParenListExprs.
4156   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4157   if (Result.isInvalid()) return ExprError();
4158   Input = Result.get();
4159 
4160   return BuildUnaryOp(S, OpLoc, Opc, Input);
4161 }
4162 
4163 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4164 ///
4165 /// \return true on error
4166 static bool checkArithmeticOnObjCPointer(Sema &S,
4167                                          SourceLocation opLoc,
4168                                          Expr *op) {
4169   assert(op->getType()->isObjCObjectPointerType());
4170   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4171       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4172     return false;
4173 
4174   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4175     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4176     << op->getSourceRange();
4177   return true;
4178 }
4179 
4180 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4181   auto *BaseNoParens = Base->IgnoreParens();
4182   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4183     return MSProp->getPropertyDecl()->getType()->isArrayType();
4184   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4185 }
4186 
4187 ExprResult
4188 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4189                               Expr *idx, SourceLocation rbLoc) {
4190   if (base && !base->getType().isNull() &&
4191       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4192     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4193                                     /*Length=*/nullptr, rbLoc);
4194 
4195   // Since this might be a postfix expression, get rid of ParenListExprs.
4196   if (isa<ParenListExpr>(base)) {
4197     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4198     if (result.isInvalid()) return ExprError();
4199     base = result.get();
4200   }
4201 
4202   // Handle any non-overload placeholder types in the base and index
4203   // expressions.  We can't handle overloads here because the other
4204   // operand might be an overloadable type, in which case the overload
4205   // resolution for the operator overload should get the first crack
4206   // at the overload.
4207   bool IsMSPropertySubscript = false;
4208   if (base->getType()->isNonOverloadPlaceholderType()) {
4209     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4210     if (!IsMSPropertySubscript) {
4211       ExprResult result = CheckPlaceholderExpr(base);
4212       if (result.isInvalid())
4213         return ExprError();
4214       base = result.get();
4215     }
4216   }
4217   if (idx->getType()->isNonOverloadPlaceholderType()) {
4218     ExprResult result = CheckPlaceholderExpr(idx);
4219     if (result.isInvalid()) return ExprError();
4220     idx = result.get();
4221   }
4222 
4223   // Build an unanalyzed expression if either operand is type-dependent.
4224   if (getLangOpts().CPlusPlus &&
4225       (base->isTypeDependent() || idx->isTypeDependent())) {
4226     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4227                                             VK_LValue, OK_Ordinary, rbLoc);
4228   }
4229 
4230   // MSDN, property (C++)
4231   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4232   // This attribute can also be used in the declaration of an empty array in a
4233   // class or structure definition. For example:
4234   // __declspec(property(get=GetX, put=PutX)) int x[];
4235   // The above statement indicates that x[] can be used with one or more array
4236   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4237   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4238   if (IsMSPropertySubscript) {
4239     // Build MS property subscript expression if base is MS property reference
4240     // or MS property subscript.
4241     return new (Context) MSPropertySubscriptExpr(
4242         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4243   }
4244 
4245   // Use C++ overloaded-operator rules if either operand has record
4246   // type.  The spec says to do this if either type is *overloadable*,
4247   // but enum types can't declare subscript operators or conversion
4248   // operators, so there's nothing interesting for overload resolution
4249   // to do if there aren't any record types involved.
4250   //
4251   // ObjC pointers have their own subscripting logic that is not tied
4252   // to overload resolution and so should not take this path.
4253   if (getLangOpts().CPlusPlus &&
4254       (base->getType()->isRecordType() ||
4255        (!base->getType()->isObjCObjectPointerType() &&
4256         idx->getType()->isRecordType()))) {
4257     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4258   }
4259 
4260   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4261 }
4262 
4263 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4264                                           Expr *LowerBound,
4265                                           SourceLocation ColonLoc, Expr *Length,
4266                                           SourceLocation RBLoc) {
4267   if (Base->getType()->isPlaceholderType() &&
4268       !Base->getType()->isSpecificPlaceholderType(
4269           BuiltinType::OMPArraySection)) {
4270     ExprResult Result = CheckPlaceholderExpr(Base);
4271     if (Result.isInvalid())
4272       return ExprError();
4273     Base = Result.get();
4274   }
4275   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4276     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4277     if (Result.isInvalid())
4278       return ExprError();
4279     Result = DefaultLvalueConversion(Result.get());
4280     if (Result.isInvalid())
4281       return ExprError();
4282     LowerBound = Result.get();
4283   }
4284   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4285     ExprResult Result = CheckPlaceholderExpr(Length);
4286     if (Result.isInvalid())
4287       return ExprError();
4288     Result = DefaultLvalueConversion(Result.get());
4289     if (Result.isInvalid())
4290       return ExprError();
4291     Length = Result.get();
4292   }
4293 
4294   // Build an unanalyzed expression if either operand is type-dependent.
4295   if (Base->isTypeDependent() ||
4296       (LowerBound &&
4297        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4298       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4299     return new (Context)
4300         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4301                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4302   }
4303 
4304   // Perform default conversions.
4305   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4306   QualType ResultTy;
4307   if (OriginalTy->isAnyPointerType()) {
4308     ResultTy = OriginalTy->getPointeeType();
4309   } else if (OriginalTy->isArrayType()) {
4310     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4311   } else {
4312     return ExprError(
4313         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4314         << Base->getSourceRange());
4315   }
4316   // C99 6.5.2.1p1
4317   if (LowerBound) {
4318     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4319                                                       LowerBound);
4320     if (Res.isInvalid())
4321       return ExprError(Diag(LowerBound->getExprLoc(),
4322                             diag::err_omp_typecheck_section_not_integer)
4323                        << 0 << LowerBound->getSourceRange());
4324     LowerBound = Res.get();
4325 
4326     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4327         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4328       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4329           << 0 << LowerBound->getSourceRange();
4330   }
4331   if (Length) {
4332     auto Res =
4333         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4334     if (Res.isInvalid())
4335       return ExprError(Diag(Length->getExprLoc(),
4336                             diag::err_omp_typecheck_section_not_integer)
4337                        << 1 << Length->getSourceRange());
4338     Length = Res.get();
4339 
4340     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4341         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4342       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4343           << 1 << Length->getSourceRange();
4344   }
4345 
4346   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4347   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4348   // type. Note that functions are not objects, and that (in C99 parlance)
4349   // incomplete types are not object types.
4350   if (ResultTy->isFunctionType()) {
4351     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4352         << ResultTy << Base->getSourceRange();
4353     return ExprError();
4354   }
4355 
4356   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4357                           diag::err_omp_section_incomplete_type, Base))
4358     return ExprError();
4359 
4360   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4361     llvm::APSInt LowerBoundValue;
4362     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4363       // OpenMP 4.5, [2.4 Array Sections]
4364       // The array section must be a subset of the original array.
4365       if (LowerBoundValue.isNegative()) {
4366         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4367             << LowerBound->getSourceRange();
4368         return ExprError();
4369       }
4370     }
4371   }
4372 
4373   if (Length) {
4374     llvm::APSInt LengthValue;
4375     if (Length->EvaluateAsInt(LengthValue, Context)) {
4376       // OpenMP 4.5, [2.4 Array Sections]
4377       // The length must evaluate to non-negative integers.
4378       if (LengthValue.isNegative()) {
4379         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4380             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4381             << Length->getSourceRange();
4382         return ExprError();
4383       }
4384     }
4385   } else if (ColonLoc.isValid() &&
4386              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4387                                       !OriginalTy->isVariableArrayType()))) {
4388     // OpenMP 4.5, [2.4 Array Sections]
4389     // When the size of the array dimension is not known, the length must be
4390     // specified explicitly.
4391     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4392         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4393     return ExprError();
4394   }
4395 
4396   if (!Base->getType()->isSpecificPlaceholderType(
4397           BuiltinType::OMPArraySection)) {
4398     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4399     if (Result.isInvalid())
4400       return ExprError();
4401     Base = Result.get();
4402   }
4403   return new (Context)
4404       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4405                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4406 }
4407 
4408 ExprResult
4409 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4410                                       Expr *Idx, SourceLocation RLoc) {
4411   Expr *LHSExp = Base;
4412   Expr *RHSExp = Idx;
4413 
4414   ExprValueKind VK = VK_LValue;
4415   ExprObjectKind OK = OK_Ordinary;
4416 
4417   // Per C++ core issue 1213, the result is an xvalue if either operand is
4418   // a non-lvalue array, and an lvalue otherwise.
4419   if (getLangOpts().CPlusPlus11 &&
4420       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4421        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4422     VK = VK_XValue;
4423 
4424   // Perform default conversions.
4425   if (!LHSExp->getType()->getAs<VectorType>()) {
4426     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4427     if (Result.isInvalid())
4428       return ExprError();
4429     LHSExp = Result.get();
4430   }
4431   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4432   if (Result.isInvalid())
4433     return ExprError();
4434   RHSExp = Result.get();
4435 
4436   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4437 
4438   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4439   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4440   // in the subscript position. As a result, we need to derive the array base
4441   // and index from the expression types.
4442   Expr *BaseExpr, *IndexExpr;
4443   QualType ResultType;
4444   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4445     BaseExpr = LHSExp;
4446     IndexExpr = RHSExp;
4447     ResultType = Context.DependentTy;
4448   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4449     BaseExpr = LHSExp;
4450     IndexExpr = RHSExp;
4451     ResultType = PTy->getPointeeType();
4452   } else if (const ObjCObjectPointerType *PTy =
4453                LHSTy->getAs<ObjCObjectPointerType>()) {
4454     BaseExpr = LHSExp;
4455     IndexExpr = RHSExp;
4456 
4457     // Use custom logic if this should be the pseudo-object subscript
4458     // expression.
4459     if (!LangOpts.isSubscriptPointerArithmetic())
4460       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4461                                           nullptr);
4462 
4463     ResultType = PTy->getPointeeType();
4464   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4465      // Handle the uncommon case of "123[Ptr]".
4466     BaseExpr = RHSExp;
4467     IndexExpr = LHSExp;
4468     ResultType = PTy->getPointeeType();
4469   } else if (const ObjCObjectPointerType *PTy =
4470                RHSTy->getAs<ObjCObjectPointerType>()) {
4471      // Handle the uncommon case of "123[Ptr]".
4472     BaseExpr = RHSExp;
4473     IndexExpr = LHSExp;
4474     ResultType = PTy->getPointeeType();
4475     if (!LangOpts.isSubscriptPointerArithmetic()) {
4476       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4477         << ResultType << BaseExpr->getSourceRange();
4478       return ExprError();
4479     }
4480   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4481     BaseExpr = LHSExp;    // vectors: V[123]
4482     IndexExpr = RHSExp;
4483     VK = LHSExp->getValueKind();
4484     if (VK != VK_RValue)
4485       OK = OK_VectorComponent;
4486 
4487     // FIXME: need to deal with const...
4488     ResultType = VTy->getElementType();
4489   } else if (LHSTy->isArrayType()) {
4490     // If we see an array that wasn't promoted by
4491     // DefaultFunctionArrayLvalueConversion, it must be an array that
4492     // wasn't promoted because of the C90 rule that doesn't
4493     // allow promoting non-lvalue arrays.  Warn, then
4494     // force the promotion here.
4495     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4496         LHSExp->getSourceRange();
4497     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4498                                CK_ArrayToPointerDecay).get();
4499     LHSTy = LHSExp->getType();
4500 
4501     BaseExpr = LHSExp;
4502     IndexExpr = RHSExp;
4503     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4504   } else if (RHSTy->isArrayType()) {
4505     // Same as previous, except for 123[f().a] case
4506     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4507         RHSExp->getSourceRange();
4508     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4509                                CK_ArrayToPointerDecay).get();
4510     RHSTy = RHSExp->getType();
4511 
4512     BaseExpr = RHSExp;
4513     IndexExpr = LHSExp;
4514     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4515   } else {
4516     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4517        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4518   }
4519   // C99 6.5.2.1p1
4520   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4521     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4522                      << IndexExpr->getSourceRange());
4523 
4524   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4525        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4526          && !IndexExpr->isTypeDependent())
4527     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4528 
4529   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4530   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4531   // type. Note that Functions are not objects, and that (in C99 parlance)
4532   // incomplete types are not object types.
4533   if (ResultType->isFunctionType()) {
4534     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4535       << ResultType << BaseExpr->getSourceRange();
4536     return ExprError();
4537   }
4538 
4539   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4540     // GNU extension: subscripting on pointer to void
4541     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4542       << BaseExpr->getSourceRange();
4543 
4544     // C forbids expressions of unqualified void type from being l-values.
4545     // See IsCForbiddenLValueType.
4546     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4547   } else if (!ResultType->isDependentType() &&
4548       RequireCompleteType(LLoc, ResultType,
4549                           diag::err_subscript_incomplete_type, BaseExpr))
4550     return ExprError();
4551 
4552   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4553          !ResultType.isCForbiddenLValueType());
4554 
4555   return new (Context)
4556       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4557 }
4558 
4559 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4560                                   ParmVarDecl *Param) {
4561   if (Param->hasUnparsedDefaultArg()) {
4562     Diag(CallLoc,
4563          diag::err_use_of_default_argument_to_function_declared_later) <<
4564       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4565     Diag(UnparsedDefaultArgLocs[Param],
4566          diag::note_default_argument_declared_here);
4567     return true;
4568   }
4569 
4570   if (Param->hasUninstantiatedDefaultArg()) {
4571     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4572 
4573     EnterExpressionEvaluationContext EvalContext(
4574         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4575 
4576     // Instantiate the expression.
4577     MultiLevelTemplateArgumentList MutiLevelArgList
4578       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4579 
4580     InstantiatingTemplate Inst(*this, CallLoc, Param,
4581                                MutiLevelArgList.getInnermost());
4582     if (Inst.isInvalid())
4583       return true;
4584     if (Inst.isAlreadyInstantiating()) {
4585       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4586       Param->setInvalidDecl();
4587       return true;
4588     }
4589 
4590     ExprResult Result;
4591     {
4592       // C++ [dcl.fct.default]p5:
4593       //   The names in the [default argument] expression are bound, and
4594       //   the semantic constraints are checked, at the point where the
4595       //   default argument expression appears.
4596       ContextRAII SavedContext(*this, FD);
4597       LocalInstantiationScope Local(*this);
4598       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4599                                 /*DirectInit*/false);
4600     }
4601     if (Result.isInvalid())
4602       return true;
4603 
4604     // Check the expression as an initializer for the parameter.
4605     InitializedEntity Entity
4606       = InitializedEntity::InitializeParameter(Context, Param);
4607     InitializationKind Kind
4608       = InitializationKind::CreateCopy(Param->getLocation(),
4609              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4610     Expr *ResultE = Result.getAs<Expr>();
4611 
4612     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4613     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4614     if (Result.isInvalid())
4615       return true;
4616 
4617     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4618                                  Param->getOuterLocStart());
4619     if (Result.isInvalid())
4620       return true;
4621 
4622     // Remember the instantiated default argument.
4623     Param->setDefaultArg(Result.getAs<Expr>());
4624     if (ASTMutationListener *L = getASTMutationListener()) {
4625       L->DefaultArgumentInstantiated(Param);
4626     }
4627   }
4628 
4629   // If the default argument expression is not set yet, we are building it now.
4630   if (!Param->hasInit()) {
4631     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4632     Param->setInvalidDecl();
4633     return true;
4634   }
4635 
4636   // If the default expression creates temporaries, we need to
4637   // push them to the current stack of expression temporaries so they'll
4638   // be properly destroyed.
4639   // FIXME: We should really be rebuilding the default argument with new
4640   // bound temporaries; see the comment in PR5810.
4641   // We don't need to do that with block decls, though, because
4642   // blocks in default argument expression can never capture anything.
4643   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4644     // Set the "needs cleanups" bit regardless of whether there are
4645     // any explicit objects.
4646     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4647 
4648     // Append all the objects to the cleanup list.  Right now, this
4649     // should always be a no-op, because blocks in default argument
4650     // expressions should never be able to capture anything.
4651     assert(!Init->getNumObjects() &&
4652            "default argument expression has capturing blocks?");
4653   }
4654 
4655   // We already type-checked the argument, so we know it works.
4656   // Just mark all of the declarations in this potentially-evaluated expression
4657   // as being "referenced".
4658   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4659                                    /*SkipLocalVariables=*/true);
4660   return false;
4661 }
4662 
4663 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4664                                         FunctionDecl *FD, ParmVarDecl *Param) {
4665   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4666     return ExprError();
4667   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4668 }
4669 
4670 Sema::VariadicCallType
4671 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4672                           Expr *Fn) {
4673   if (Proto && Proto->isVariadic()) {
4674     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4675       return VariadicConstructor;
4676     else if (Fn && Fn->getType()->isBlockPointerType())
4677       return VariadicBlock;
4678     else if (FDecl) {
4679       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4680         if (Method->isInstance())
4681           return VariadicMethod;
4682     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4683       return VariadicMethod;
4684     return VariadicFunction;
4685   }
4686   return VariadicDoesNotApply;
4687 }
4688 
4689 namespace {
4690 class FunctionCallCCC : public FunctionCallFilterCCC {
4691 public:
4692   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4693                   unsigned NumArgs, MemberExpr *ME)
4694       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4695         FunctionName(FuncName) {}
4696 
4697   bool ValidateCandidate(const TypoCorrection &candidate) override {
4698     if (!candidate.getCorrectionSpecifier() ||
4699         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4700       return false;
4701     }
4702 
4703     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4704   }
4705 
4706 private:
4707   const IdentifierInfo *const FunctionName;
4708 };
4709 }
4710 
4711 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4712                                                FunctionDecl *FDecl,
4713                                                ArrayRef<Expr *> Args) {
4714   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4715   DeclarationName FuncName = FDecl->getDeclName();
4716   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4717 
4718   if (TypoCorrection Corrected = S.CorrectTypo(
4719           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4720           S.getScopeForContext(S.CurContext), nullptr,
4721           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4722                                              Args.size(), ME),
4723           Sema::CTK_ErrorRecovery)) {
4724     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4725       if (Corrected.isOverloaded()) {
4726         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4727         OverloadCandidateSet::iterator Best;
4728         for (NamedDecl *CD : Corrected) {
4729           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4730             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4731                                    OCS);
4732         }
4733         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4734         case OR_Success:
4735           ND = Best->FoundDecl;
4736           Corrected.setCorrectionDecl(ND);
4737           break;
4738         default:
4739           break;
4740         }
4741       }
4742       ND = ND->getUnderlyingDecl();
4743       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4744         return Corrected;
4745     }
4746   }
4747   return TypoCorrection();
4748 }
4749 
4750 /// ConvertArgumentsForCall - Converts the arguments specified in
4751 /// Args/NumArgs to the parameter types of the function FDecl with
4752 /// function prototype Proto. Call is the call expression itself, and
4753 /// Fn is the function expression. For a C++ member function, this
4754 /// routine does not attempt to convert the object argument. Returns
4755 /// true if the call is ill-formed.
4756 bool
4757 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4758                               FunctionDecl *FDecl,
4759                               const FunctionProtoType *Proto,
4760                               ArrayRef<Expr *> Args,
4761                               SourceLocation RParenLoc,
4762                               bool IsExecConfig) {
4763   // Bail out early if calling a builtin with custom typechecking.
4764   if (FDecl)
4765     if (unsigned ID = FDecl->getBuiltinID())
4766       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4767         return false;
4768 
4769   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4770   // assignment, to the types of the corresponding parameter, ...
4771   unsigned NumParams = Proto->getNumParams();
4772   bool Invalid = false;
4773   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4774   unsigned FnKind = Fn->getType()->isBlockPointerType()
4775                        ? 1 /* block */
4776                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4777                                        : 0 /* function */);
4778 
4779   // If too few arguments are available (and we don't have default
4780   // arguments for the remaining parameters), don't make the call.
4781   if (Args.size() < NumParams) {
4782     if (Args.size() < MinArgs) {
4783       TypoCorrection TC;
4784       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4785         unsigned diag_id =
4786             MinArgs == NumParams && !Proto->isVariadic()
4787                 ? diag::err_typecheck_call_too_few_args_suggest
4788                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4789         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4790                                         << static_cast<unsigned>(Args.size())
4791                                         << TC.getCorrectionRange());
4792       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4793         Diag(RParenLoc,
4794              MinArgs == NumParams && !Proto->isVariadic()
4795                  ? diag::err_typecheck_call_too_few_args_one
4796                  : diag::err_typecheck_call_too_few_args_at_least_one)
4797             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4798       else
4799         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4800                             ? diag::err_typecheck_call_too_few_args
4801                             : diag::err_typecheck_call_too_few_args_at_least)
4802             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4803             << Fn->getSourceRange();
4804 
4805       // Emit the location of the prototype.
4806       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4807         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4808           << FDecl;
4809 
4810       return true;
4811     }
4812     Call->setNumArgs(Context, NumParams);
4813   }
4814 
4815   // If too many are passed and not variadic, error on the extras and drop
4816   // them.
4817   if (Args.size() > NumParams) {
4818     if (!Proto->isVariadic()) {
4819       TypoCorrection TC;
4820       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4821         unsigned diag_id =
4822             MinArgs == NumParams && !Proto->isVariadic()
4823                 ? diag::err_typecheck_call_too_many_args_suggest
4824                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4825         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4826                                         << static_cast<unsigned>(Args.size())
4827                                         << TC.getCorrectionRange());
4828       } else if (NumParams == 1 && FDecl &&
4829                  FDecl->getParamDecl(0)->getDeclName())
4830         Diag(Args[NumParams]->getLocStart(),
4831              MinArgs == NumParams
4832                  ? diag::err_typecheck_call_too_many_args_one
4833                  : diag::err_typecheck_call_too_many_args_at_most_one)
4834             << FnKind << FDecl->getParamDecl(0)
4835             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4836             << SourceRange(Args[NumParams]->getLocStart(),
4837                            Args.back()->getLocEnd());
4838       else
4839         Diag(Args[NumParams]->getLocStart(),
4840              MinArgs == NumParams
4841                  ? diag::err_typecheck_call_too_many_args
4842                  : diag::err_typecheck_call_too_many_args_at_most)
4843             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4844             << Fn->getSourceRange()
4845             << SourceRange(Args[NumParams]->getLocStart(),
4846                            Args.back()->getLocEnd());
4847 
4848       // Emit the location of the prototype.
4849       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4850         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4851           << FDecl;
4852 
4853       // This deletes the extra arguments.
4854       Call->setNumArgs(Context, NumParams);
4855       return true;
4856     }
4857   }
4858   SmallVector<Expr *, 8> AllArgs;
4859   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4860 
4861   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4862                                    Proto, 0, Args, AllArgs, CallType);
4863   if (Invalid)
4864     return true;
4865   unsigned TotalNumArgs = AllArgs.size();
4866   for (unsigned i = 0; i < TotalNumArgs; ++i)
4867     Call->setArg(i, AllArgs[i]);
4868 
4869   return false;
4870 }
4871 
4872 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4873                                   const FunctionProtoType *Proto,
4874                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4875                                   SmallVectorImpl<Expr *> &AllArgs,
4876                                   VariadicCallType CallType, bool AllowExplicit,
4877                                   bool IsListInitialization) {
4878   unsigned NumParams = Proto->getNumParams();
4879   bool Invalid = false;
4880   size_t ArgIx = 0;
4881   // Continue to check argument types (even if we have too few/many args).
4882   for (unsigned i = FirstParam; i < NumParams; i++) {
4883     QualType ProtoArgType = Proto->getParamType(i);
4884 
4885     Expr *Arg;
4886     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4887     if (ArgIx < Args.size()) {
4888       Arg = Args[ArgIx++];
4889 
4890       if (RequireCompleteType(Arg->getLocStart(),
4891                               ProtoArgType,
4892                               diag::err_call_incomplete_argument, Arg))
4893         return true;
4894 
4895       // Strip the unbridged-cast placeholder expression off, if applicable.
4896       bool CFAudited = false;
4897       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4898           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4899           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4900         Arg = stripARCUnbridgedCast(Arg);
4901       else if (getLangOpts().ObjCAutoRefCount &&
4902                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4903                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4904         CFAudited = true;
4905 
4906       InitializedEntity Entity =
4907           Param ? InitializedEntity::InitializeParameter(Context, Param,
4908                                                          ProtoArgType)
4909                 : InitializedEntity::InitializeParameter(
4910                       Context, ProtoArgType, Proto->isParamConsumed(i));
4911 
4912       // Remember that parameter belongs to a CF audited API.
4913       if (CFAudited)
4914         Entity.setParameterCFAudited();
4915 
4916       ExprResult ArgE = PerformCopyInitialization(
4917           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4918       if (ArgE.isInvalid())
4919         return true;
4920 
4921       Arg = ArgE.getAs<Expr>();
4922     } else {
4923       assert(Param && "can't use default arguments without a known callee");
4924 
4925       ExprResult ArgExpr =
4926         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4927       if (ArgExpr.isInvalid())
4928         return true;
4929 
4930       Arg = ArgExpr.getAs<Expr>();
4931     }
4932 
4933     // Check for array bounds violations for each argument to the call. This
4934     // check only triggers warnings when the argument isn't a more complex Expr
4935     // with its own checking, such as a BinaryOperator.
4936     CheckArrayAccess(Arg);
4937 
4938     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4939     CheckStaticArrayArgument(CallLoc, Param, Arg);
4940 
4941     AllArgs.push_back(Arg);
4942   }
4943 
4944   // If this is a variadic call, handle args passed through "...".
4945   if (CallType != VariadicDoesNotApply) {
4946     // Assume that extern "C" functions with variadic arguments that
4947     // return __unknown_anytype aren't *really* variadic.
4948     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4949         FDecl->isExternC()) {
4950       for (Expr *A : Args.slice(ArgIx)) {
4951         QualType paramType; // ignored
4952         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4953         Invalid |= arg.isInvalid();
4954         AllArgs.push_back(arg.get());
4955       }
4956 
4957     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4958     } else {
4959       for (Expr *A : Args.slice(ArgIx)) {
4960         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4961         Invalid |= Arg.isInvalid();
4962         AllArgs.push_back(Arg.get());
4963       }
4964     }
4965 
4966     // Check for array bounds violations.
4967     for (Expr *A : Args.slice(ArgIx))
4968       CheckArrayAccess(A);
4969   }
4970   return Invalid;
4971 }
4972 
4973 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4974   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4975   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4976     TL = DTL.getOriginalLoc();
4977   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4978     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4979       << ATL.getLocalSourceRange();
4980 }
4981 
4982 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4983 /// array parameter, check that it is non-null, and that if it is formed by
4984 /// array-to-pointer decay, the underlying array is sufficiently large.
4985 ///
4986 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4987 /// array type derivation, then for each call to the function, the value of the
4988 /// corresponding actual argument shall provide access to the first element of
4989 /// an array with at least as many elements as specified by the size expression.
4990 void
4991 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4992                                ParmVarDecl *Param,
4993                                const Expr *ArgExpr) {
4994   // Static array parameters are not supported in C++.
4995   if (!Param || getLangOpts().CPlusPlus)
4996     return;
4997 
4998   QualType OrigTy = Param->getOriginalType();
4999 
5000   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5001   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5002     return;
5003 
5004   if (ArgExpr->isNullPointerConstant(Context,
5005                                      Expr::NPC_NeverValueDependent)) {
5006     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5007     DiagnoseCalleeStaticArrayParam(*this, Param);
5008     return;
5009   }
5010 
5011   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5012   if (!CAT)
5013     return;
5014 
5015   const ConstantArrayType *ArgCAT =
5016     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5017   if (!ArgCAT)
5018     return;
5019 
5020   if (ArgCAT->getSize().ult(CAT->getSize())) {
5021     Diag(CallLoc, diag::warn_static_array_too_small)
5022       << ArgExpr->getSourceRange()
5023       << (unsigned) ArgCAT->getSize().getZExtValue()
5024       << (unsigned) CAT->getSize().getZExtValue();
5025     DiagnoseCalleeStaticArrayParam(*this, Param);
5026   }
5027 }
5028 
5029 /// Given a function expression of unknown-any type, try to rebuild it
5030 /// to have a function type.
5031 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5032 
5033 /// Is the given type a placeholder that we need to lower out
5034 /// immediately during argument processing?
5035 static bool isPlaceholderToRemoveAsArg(QualType type) {
5036   // Placeholders are never sugared.
5037   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5038   if (!placeholder) return false;
5039 
5040   switch (placeholder->getKind()) {
5041   // Ignore all the non-placeholder types.
5042 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5043   case BuiltinType::Id:
5044 #include "clang/Basic/OpenCLImageTypes.def"
5045 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5046 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5047 #include "clang/AST/BuiltinTypes.def"
5048     return false;
5049 
5050   // We cannot lower out overload sets; they might validly be resolved
5051   // by the call machinery.
5052   case BuiltinType::Overload:
5053     return false;
5054 
5055   // Unbridged casts in ARC can be handled in some call positions and
5056   // should be left in place.
5057   case BuiltinType::ARCUnbridgedCast:
5058     return false;
5059 
5060   // Pseudo-objects should be converted as soon as possible.
5061   case BuiltinType::PseudoObject:
5062     return true;
5063 
5064   // The debugger mode could theoretically but currently does not try
5065   // to resolve unknown-typed arguments based on known parameter types.
5066   case BuiltinType::UnknownAny:
5067     return true;
5068 
5069   // These are always invalid as call arguments and should be reported.
5070   case BuiltinType::BoundMember:
5071   case BuiltinType::BuiltinFn:
5072   case BuiltinType::OMPArraySection:
5073     return true;
5074 
5075   }
5076   llvm_unreachable("bad builtin type kind");
5077 }
5078 
5079 /// Check an argument list for placeholders that we won't try to
5080 /// handle later.
5081 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5082   // Apply this processing to all the arguments at once instead of
5083   // dying at the first failure.
5084   bool hasInvalid = false;
5085   for (size_t i = 0, e = args.size(); i != e; i++) {
5086     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5087       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5088       if (result.isInvalid()) hasInvalid = true;
5089       else args[i] = result.get();
5090     } else if (hasInvalid) {
5091       (void)S.CorrectDelayedTyposInExpr(args[i]);
5092     }
5093   }
5094   return hasInvalid;
5095 }
5096 
5097 /// If a builtin function has a pointer argument with no explicit address
5098 /// space, then it should be able to accept a pointer to any address
5099 /// space as input.  In order to do this, we need to replace the
5100 /// standard builtin declaration with one that uses the same address space
5101 /// as the call.
5102 ///
5103 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5104 ///                  it does not contain any pointer arguments without
5105 ///                  an address space qualifer.  Otherwise the rewritten
5106 ///                  FunctionDecl is returned.
5107 /// TODO: Handle pointer return types.
5108 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5109                                                 const FunctionDecl *FDecl,
5110                                                 MultiExprArg ArgExprs) {
5111 
5112   QualType DeclType = FDecl->getType();
5113   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5114 
5115   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5116       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5117     return nullptr;
5118 
5119   bool NeedsNewDecl = false;
5120   unsigned i = 0;
5121   SmallVector<QualType, 8> OverloadParams;
5122 
5123   for (QualType ParamType : FT->param_types()) {
5124 
5125     // Convert array arguments to pointer to simplify type lookup.
5126     ExprResult ArgRes =
5127         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5128     if (ArgRes.isInvalid())
5129       return nullptr;
5130     Expr *Arg = ArgRes.get();
5131     QualType ArgType = Arg->getType();
5132     if (!ParamType->isPointerType() ||
5133         ParamType.getQualifiers().hasAddressSpace() ||
5134         !ArgType->isPointerType() ||
5135         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5136       OverloadParams.push_back(ParamType);
5137       continue;
5138     }
5139 
5140     NeedsNewDecl = true;
5141     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5142 
5143     QualType PointeeType = ParamType->getPointeeType();
5144     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5145     OverloadParams.push_back(Context.getPointerType(PointeeType));
5146   }
5147 
5148   if (!NeedsNewDecl)
5149     return nullptr;
5150 
5151   FunctionProtoType::ExtProtoInfo EPI;
5152   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5153                                                 OverloadParams, EPI);
5154   DeclContext *Parent = Context.getTranslationUnitDecl();
5155   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5156                                                     FDecl->getLocation(),
5157                                                     FDecl->getLocation(),
5158                                                     FDecl->getIdentifier(),
5159                                                     OverloadTy,
5160                                                     /*TInfo=*/nullptr,
5161                                                     SC_Extern, false,
5162                                                     /*hasPrototype=*/true);
5163   SmallVector<ParmVarDecl*, 16> Params;
5164   FT = cast<FunctionProtoType>(OverloadTy);
5165   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5166     QualType ParamType = FT->getParamType(i);
5167     ParmVarDecl *Parm =
5168         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5169                                 SourceLocation(), nullptr, ParamType,
5170                                 /*TInfo=*/nullptr, SC_None, nullptr);
5171     Parm->setScopeInfo(0, i);
5172     Params.push_back(Parm);
5173   }
5174   OverloadDecl->setParams(Params);
5175   return OverloadDecl;
5176 }
5177 
5178 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5179                                     FunctionDecl *Callee,
5180                                     MultiExprArg ArgExprs) {
5181   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5182   // similar attributes) really don't like it when functions are called with an
5183   // invalid number of args.
5184   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5185                          /*PartialOverloading=*/false) &&
5186       !Callee->isVariadic())
5187     return;
5188   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5189     return;
5190 
5191   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5192     S.Diag(Fn->getLocStart(),
5193            isa<CXXMethodDecl>(Callee)
5194                ? diag::err_ovl_no_viable_member_function_in_call
5195                : diag::err_ovl_no_viable_function_in_call)
5196         << Callee << Callee->getSourceRange();
5197     S.Diag(Callee->getLocation(),
5198            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5199         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5200     return;
5201   }
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 if there's an '&' involved.
5279     if (!find.HasFormOfMemberPointer) {
5280       OverloadExpr *ovl = find.Expression;
5281       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5282         return BuildOverloadedCallExpr(
5283             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5284             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5285       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5286                                        RParenLoc);
5287     }
5288   }
5289 
5290   // If we're directly calling a function, get the appropriate declaration.
5291   if (Fn->getType() == Context.UnknownAnyTy) {
5292     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5293     if (result.isInvalid()) return ExprError();
5294     Fn = result.get();
5295   }
5296 
5297   Expr *NakedFn = Fn->IgnoreParens();
5298 
5299   bool CallingNDeclIndirectly = false;
5300   NamedDecl *NDecl = nullptr;
5301   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5302     if (UnOp->getOpcode() == UO_AddrOf) {
5303       CallingNDeclIndirectly = true;
5304       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5305     }
5306   }
5307 
5308   if (isa<DeclRefExpr>(NakedFn)) {
5309     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5310 
5311     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5312     if (FDecl && FDecl->getBuiltinID()) {
5313       // Rewrite the function decl for this builtin by replacing parameters
5314       // with no explicit address space with the address space of the arguments
5315       // in ArgExprs.
5316       if ((FDecl =
5317                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5318         NDecl = FDecl;
5319         Fn = DeclRefExpr::Create(
5320             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5321             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5322       }
5323     }
5324   } else if (isa<MemberExpr>(NakedFn))
5325     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5326 
5327   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5328     if (CallingNDeclIndirectly &&
5329         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5330                                            Fn->getLocStart()))
5331       return ExprError();
5332 
5333     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5334       return ExprError();
5335 
5336     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5337   }
5338 
5339   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5340                                ExecConfig, IsExecConfig);
5341 }
5342 
5343 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5344 ///
5345 /// __builtin_astype( value, dst type )
5346 ///
5347 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5348                                  SourceLocation BuiltinLoc,
5349                                  SourceLocation RParenLoc) {
5350   ExprValueKind VK = VK_RValue;
5351   ExprObjectKind OK = OK_Ordinary;
5352   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5353   QualType SrcTy = E->getType();
5354   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5355     return ExprError(Diag(BuiltinLoc,
5356                           diag::err_invalid_astype_of_different_size)
5357                      << DstTy
5358                      << SrcTy
5359                      << E->getSourceRange());
5360   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5361 }
5362 
5363 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5364 /// provided arguments.
5365 ///
5366 /// __builtin_convertvector( value, dst type )
5367 ///
5368 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5369                                         SourceLocation BuiltinLoc,
5370                                         SourceLocation RParenLoc) {
5371   TypeSourceInfo *TInfo;
5372   GetTypeFromParser(ParsedDestTy, &TInfo);
5373   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5374 }
5375 
5376 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5377 /// i.e. an expression not of \p OverloadTy.  The expression should
5378 /// unary-convert to an expression of function-pointer or
5379 /// block-pointer type.
5380 ///
5381 /// \param NDecl the declaration being called, if available
5382 ExprResult
5383 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5384                             SourceLocation LParenLoc,
5385                             ArrayRef<Expr *> Args,
5386                             SourceLocation RParenLoc,
5387                             Expr *Config, bool IsExecConfig) {
5388   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5389   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5390 
5391   // Functions with 'interrupt' attribute cannot be called directly.
5392   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5393     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5394     return ExprError();
5395   }
5396 
5397   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5398   // so there's some risk when calling out to non-interrupt handler functions
5399   // that the callee might not preserve them. This is easy to diagnose here,
5400   // but can be very challenging to debug.
5401   if (auto *Caller = getCurFunctionDecl())
5402     if (Caller->hasAttr<ARMInterruptAttr>())
5403       if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())
5404         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5405 
5406   // Promote the function operand.
5407   // We special-case function promotion here because we only allow promoting
5408   // builtin functions to function pointers in the callee of a call.
5409   ExprResult Result;
5410   if (BuiltinID &&
5411       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5412     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5413                                CK_BuiltinFnToFnPtr).get();
5414   } else {
5415     Result = CallExprUnaryConversions(Fn);
5416   }
5417   if (Result.isInvalid())
5418     return ExprError();
5419   Fn = Result.get();
5420 
5421   // Make the call expr early, before semantic checks.  This guarantees cleanup
5422   // of arguments and function on error.
5423   CallExpr *TheCall;
5424   if (Config)
5425     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5426                                                cast<CallExpr>(Config), Args,
5427                                                Context.BoolTy, VK_RValue,
5428                                                RParenLoc);
5429   else
5430     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5431                                      VK_RValue, RParenLoc);
5432 
5433   if (!getLangOpts().CPlusPlus) {
5434     // C cannot always handle TypoExpr nodes in builtin calls and direct
5435     // function calls as their argument checking don't necessarily handle
5436     // dependent types properly, so make sure any TypoExprs have been
5437     // dealt with.
5438     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5439     if (!Result.isUsable()) return ExprError();
5440     TheCall = dyn_cast<CallExpr>(Result.get());
5441     if (!TheCall) return Result;
5442     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5443   }
5444 
5445   // Bail out early if calling a builtin with custom typechecking.
5446   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5447     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5448 
5449  retry:
5450   const FunctionType *FuncT;
5451   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5452     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5453     // have type pointer to function".
5454     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5455     if (!FuncT)
5456       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5457                          << Fn->getType() << Fn->getSourceRange());
5458   } else if (const BlockPointerType *BPT =
5459                Fn->getType()->getAs<BlockPointerType>()) {
5460     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5461   } else {
5462     // Handle calls to expressions of unknown-any type.
5463     if (Fn->getType() == Context.UnknownAnyTy) {
5464       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5465       if (rewrite.isInvalid()) return ExprError();
5466       Fn = rewrite.get();
5467       TheCall->setCallee(Fn);
5468       goto retry;
5469     }
5470 
5471     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5472       << Fn->getType() << Fn->getSourceRange());
5473   }
5474 
5475   if (getLangOpts().CUDA) {
5476     if (Config) {
5477       // CUDA: Kernel calls must be to global functions
5478       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5479         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5480             << FDecl->getName() << Fn->getSourceRange());
5481 
5482       // CUDA: Kernel function must have 'void' return type
5483       if (!FuncT->getReturnType()->isVoidType())
5484         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5485             << Fn->getType() << Fn->getSourceRange());
5486     } else {
5487       // CUDA: Calls to global functions must be configured
5488       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5489         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5490             << FDecl->getName() << Fn->getSourceRange());
5491     }
5492   }
5493 
5494   // Check for a valid return type
5495   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5496                           FDecl))
5497     return ExprError();
5498 
5499   // We know the result type of the call, set it.
5500   TheCall->setType(FuncT->getCallResultType(Context));
5501   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5502 
5503   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5504   if (Proto) {
5505     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5506                                 IsExecConfig))
5507       return ExprError();
5508   } else {
5509     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5510 
5511     if (FDecl) {
5512       // Check if we have too few/too many template arguments, based
5513       // on our knowledge of the function definition.
5514       const FunctionDecl *Def = nullptr;
5515       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5516         Proto = Def->getType()->getAs<FunctionProtoType>();
5517        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5518           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5519           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5520       }
5521 
5522       // If the function we're calling isn't a function prototype, but we have
5523       // a function prototype from a prior declaratiom, use that prototype.
5524       if (!FDecl->hasPrototype())
5525         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5526     }
5527 
5528     // Promote the arguments (C99 6.5.2.2p6).
5529     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5530       Expr *Arg = Args[i];
5531 
5532       if (Proto && i < Proto->getNumParams()) {
5533         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5534             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5535         ExprResult ArgE =
5536             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5537         if (ArgE.isInvalid())
5538           return true;
5539 
5540         Arg = ArgE.getAs<Expr>();
5541 
5542       } else {
5543         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5544 
5545         if (ArgE.isInvalid())
5546           return true;
5547 
5548         Arg = ArgE.getAs<Expr>();
5549       }
5550 
5551       if (RequireCompleteType(Arg->getLocStart(),
5552                               Arg->getType(),
5553                               diag::err_call_incomplete_argument, Arg))
5554         return ExprError();
5555 
5556       TheCall->setArg(i, Arg);
5557     }
5558   }
5559 
5560   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5561     if (!Method->isStatic())
5562       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5563         << Fn->getSourceRange());
5564 
5565   // Check for sentinels
5566   if (NDecl)
5567     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5568 
5569   // Do special checking on direct calls to functions.
5570   if (FDecl) {
5571     if (CheckFunctionCall(FDecl, TheCall, Proto))
5572       return ExprError();
5573 
5574     if (BuiltinID)
5575       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5576   } else if (NDecl) {
5577     if (CheckPointerCall(NDecl, TheCall, Proto))
5578       return ExprError();
5579   } else {
5580     if (CheckOtherCall(TheCall, Proto))
5581       return ExprError();
5582   }
5583 
5584   return MaybeBindToTemporary(TheCall);
5585 }
5586 
5587 ExprResult
5588 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5589                            SourceLocation RParenLoc, Expr *InitExpr) {
5590   assert(Ty && "ActOnCompoundLiteral(): missing type");
5591   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5592 
5593   TypeSourceInfo *TInfo;
5594   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5595   if (!TInfo)
5596     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5597 
5598   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5599 }
5600 
5601 ExprResult
5602 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5603                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5604   QualType literalType = TInfo->getType();
5605 
5606   if (literalType->isArrayType()) {
5607     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5608           diag::err_illegal_decl_array_incomplete_type,
5609           SourceRange(LParenLoc,
5610                       LiteralExpr->getSourceRange().getEnd())))
5611       return ExprError();
5612     if (literalType->isVariableArrayType())
5613       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5614         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5615   } else if (!literalType->isDependentType() &&
5616              RequireCompleteType(LParenLoc, literalType,
5617                diag::err_typecheck_decl_incomplete_type,
5618                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5619     return ExprError();
5620 
5621   InitializedEntity Entity
5622     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5623   InitializationKind Kind
5624     = InitializationKind::CreateCStyleCast(LParenLoc,
5625                                            SourceRange(LParenLoc, RParenLoc),
5626                                            /*InitList=*/true);
5627   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5628   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5629                                       &literalType);
5630   if (Result.isInvalid())
5631     return ExprError();
5632   LiteralExpr = Result.get();
5633 
5634   bool isFileScope = !CurContext->isFunctionOrMethod();
5635   if (isFileScope &&
5636       !LiteralExpr->isTypeDependent() &&
5637       !LiteralExpr->isValueDependent() &&
5638       !literalType->isDependentType()) { // 6.5.2.5p3
5639     if (CheckForConstantInitializer(LiteralExpr, literalType))
5640       return ExprError();
5641   }
5642 
5643   // In C, compound literals are l-values for some reason.
5644   // For GCC compatibility, in C++, file-scope array compound literals with
5645   // constant initializers are also l-values, and compound literals are
5646   // otherwise prvalues.
5647   //
5648   // (GCC also treats C++ list-initialized file-scope array prvalues with
5649   // constant initializers as l-values, but that's non-conforming, so we don't
5650   // follow it there.)
5651   //
5652   // FIXME: It would be better to handle the lvalue cases as materializing and
5653   // lifetime-extending a temporary object, but our materialized temporaries
5654   // representation only supports lifetime extension from a variable, not "out
5655   // of thin air".
5656   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5657   // is bound to the result of applying array-to-pointer decay to the compound
5658   // literal.
5659   // FIXME: GCC supports compound literals of reference type, which should
5660   // obviously have a value kind derived from the kind of reference involved.
5661   ExprValueKind VK =
5662       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5663           ? VK_RValue
5664           : VK_LValue;
5665 
5666   return MaybeBindToTemporary(
5667       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5668                                         VK, LiteralExpr, isFileScope));
5669 }
5670 
5671 ExprResult
5672 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5673                     SourceLocation RBraceLoc) {
5674   // Immediately handle non-overload placeholders.  Overloads can be
5675   // resolved contextually, but everything else here can't.
5676   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5677     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5678       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5679 
5680       // Ignore failures; dropping the entire initializer list because
5681       // of one failure would be terrible for indexing/etc.
5682       if (result.isInvalid()) continue;
5683 
5684       InitArgList[I] = result.get();
5685     }
5686   }
5687 
5688   // Semantic analysis for initializers is done by ActOnDeclarator() and
5689   // CheckInitializer() - it requires knowledge of the object being intialized.
5690 
5691   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5692                                                RBraceLoc);
5693   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5694   return E;
5695 }
5696 
5697 /// Do an explicit extend of the given block pointer if we're in ARC.
5698 void Sema::maybeExtendBlockObject(ExprResult &E) {
5699   assert(E.get()->getType()->isBlockPointerType());
5700   assert(E.get()->isRValue());
5701 
5702   // Only do this in an r-value context.
5703   if (!getLangOpts().ObjCAutoRefCount) return;
5704 
5705   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5706                                CK_ARCExtendBlockObject, E.get(),
5707                                /*base path*/ nullptr, VK_RValue);
5708   Cleanup.setExprNeedsCleanups(true);
5709 }
5710 
5711 /// Prepare a conversion of the given expression to an ObjC object
5712 /// pointer type.
5713 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5714   QualType type = E.get()->getType();
5715   if (type->isObjCObjectPointerType()) {
5716     return CK_BitCast;
5717   } else if (type->isBlockPointerType()) {
5718     maybeExtendBlockObject(E);
5719     return CK_BlockPointerToObjCPointerCast;
5720   } else {
5721     assert(type->isPointerType());
5722     return CK_CPointerToObjCPointerCast;
5723   }
5724 }
5725 
5726 /// Prepares for a scalar cast, performing all the necessary stages
5727 /// except the final cast and returning the kind required.
5728 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5729   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5730   // Also, callers should have filtered out the invalid cases with
5731   // pointers.  Everything else should be possible.
5732 
5733   QualType SrcTy = Src.get()->getType();
5734   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5735     return CK_NoOp;
5736 
5737   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5738   case Type::STK_MemberPointer:
5739     llvm_unreachable("member pointer type in C");
5740 
5741   case Type::STK_CPointer:
5742   case Type::STK_BlockPointer:
5743   case Type::STK_ObjCObjectPointer:
5744     switch (DestTy->getScalarTypeKind()) {
5745     case Type::STK_CPointer: {
5746       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5747       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5748       if (SrcAS != DestAS)
5749         return CK_AddressSpaceConversion;
5750       return CK_BitCast;
5751     }
5752     case Type::STK_BlockPointer:
5753       return (SrcKind == Type::STK_BlockPointer
5754                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5755     case Type::STK_ObjCObjectPointer:
5756       if (SrcKind == Type::STK_ObjCObjectPointer)
5757         return CK_BitCast;
5758       if (SrcKind == Type::STK_CPointer)
5759         return CK_CPointerToObjCPointerCast;
5760       maybeExtendBlockObject(Src);
5761       return CK_BlockPointerToObjCPointerCast;
5762     case Type::STK_Bool:
5763       return CK_PointerToBoolean;
5764     case Type::STK_Integral:
5765       return CK_PointerToIntegral;
5766     case Type::STK_Floating:
5767     case Type::STK_FloatingComplex:
5768     case Type::STK_IntegralComplex:
5769     case Type::STK_MemberPointer:
5770       llvm_unreachable("illegal cast from pointer");
5771     }
5772     llvm_unreachable("Should have returned before this");
5773 
5774   case Type::STK_Bool: // casting from bool is like casting from an integer
5775   case Type::STK_Integral:
5776     switch (DestTy->getScalarTypeKind()) {
5777     case Type::STK_CPointer:
5778     case Type::STK_ObjCObjectPointer:
5779     case Type::STK_BlockPointer:
5780       if (Src.get()->isNullPointerConstant(Context,
5781                                            Expr::NPC_ValueDependentIsNull))
5782         return CK_NullToPointer;
5783       return CK_IntegralToPointer;
5784     case Type::STK_Bool:
5785       return CK_IntegralToBoolean;
5786     case Type::STK_Integral:
5787       return CK_IntegralCast;
5788     case Type::STK_Floating:
5789       return CK_IntegralToFloating;
5790     case Type::STK_IntegralComplex:
5791       Src = ImpCastExprToType(Src.get(),
5792                       DestTy->castAs<ComplexType>()->getElementType(),
5793                       CK_IntegralCast);
5794       return CK_IntegralRealToComplex;
5795     case Type::STK_FloatingComplex:
5796       Src = ImpCastExprToType(Src.get(),
5797                       DestTy->castAs<ComplexType>()->getElementType(),
5798                       CK_IntegralToFloating);
5799       return CK_FloatingRealToComplex;
5800     case Type::STK_MemberPointer:
5801       llvm_unreachable("member pointer type in C");
5802     }
5803     llvm_unreachable("Should have returned before this");
5804 
5805   case Type::STK_Floating:
5806     switch (DestTy->getScalarTypeKind()) {
5807     case Type::STK_Floating:
5808       return CK_FloatingCast;
5809     case Type::STK_Bool:
5810       return CK_FloatingToBoolean;
5811     case Type::STK_Integral:
5812       return CK_FloatingToIntegral;
5813     case Type::STK_FloatingComplex:
5814       Src = ImpCastExprToType(Src.get(),
5815                               DestTy->castAs<ComplexType>()->getElementType(),
5816                               CK_FloatingCast);
5817       return CK_FloatingRealToComplex;
5818     case Type::STK_IntegralComplex:
5819       Src = ImpCastExprToType(Src.get(),
5820                               DestTy->castAs<ComplexType>()->getElementType(),
5821                               CK_FloatingToIntegral);
5822       return CK_IntegralRealToComplex;
5823     case Type::STK_CPointer:
5824     case Type::STK_ObjCObjectPointer:
5825     case Type::STK_BlockPointer:
5826       llvm_unreachable("valid float->pointer cast?");
5827     case Type::STK_MemberPointer:
5828       llvm_unreachable("member pointer type in C");
5829     }
5830     llvm_unreachable("Should have returned before this");
5831 
5832   case Type::STK_FloatingComplex:
5833     switch (DestTy->getScalarTypeKind()) {
5834     case Type::STK_FloatingComplex:
5835       return CK_FloatingComplexCast;
5836     case Type::STK_IntegralComplex:
5837       return CK_FloatingComplexToIntegralComplex;
5838     case Type::STK_Floating: {
5839       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5840       if (Context.hasSameType(ET, DestTy))
5841         return CK_FloatingComplexToReal;
5842       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5843       return CK_FloatingCast;
5844     }
5845     case Type::STK_Bool:
5846       return CK_FloatingComplexToBoolean;
5847     case Type::STK_Integral:
5848       Src = ImpCastExprToType(Src.get(),
5849                               SrcTy->castAs<ComplexType>()->getElementType(),
5850                               CK_FloatingComplexToReal);
5851       return CK_FloatingToIntegral;
5852     case Type::STK_CPointer:
5853     case Type::STK_ObjCObjectPointer:
5854     case Type::STK_BlockPointer:
5855       llvm_unreachable("valid complex float->pointer cast?");
5856     case Type::STK_MemberPointer:
5857       llvm_unreachable("member pointer type in C");
5858     }
5859     llvm_unreachable("Should have returned before this");
5860 
5861   case Type::STK_IntegralComplex:
5862     switch (DestTy->getScalarTypeKind()) {
5863     case Type::STK_FloatingComplex:
5864       return CK_IntegralComplexToFloatingComplex;
5865     case Type::STK_IntegralComplex:
5866       return CK_IntegralComplexCast;
5867     case Type::STK_Integral: {
5868       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5869       if (Context.hasSameType(ET, DestTy))
5870         return CK_IntegralComplexToReal;
5871       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5872       return CK_IntegralCast;
5873     }
5874     case Type::STK_Bool:
5875       return CK_IntegralComplexToBoolean;
5876     case Type::STK_Floating:
5877       Src = ImpCastExprToType(Src.get(),
5878                               SrcTy->castAs<ComplexType>()->getElementType(),
5879                               CK_IntegralComplexToReal);
5880       return CK_IntegralToFloating;
5881     case Type::STK_CPointer:
5882     case Type::STK_ObjCObjectPointer:
5883     case Type::STK_BlockPointer:
5884       llvm_unreachable("valid complex int->pointer cast?");
5885     case Type::STK_MemberPointer:
5886       llvm_unreachable("member pointer type in C");
5887     }
5888     llvm_unreachable("Should have returned before this");
5889   }
5890 
5891   llvm_unreachable("Unhandled scalar cast");
5892 }
5893 
5894 static bool breakDownVectorType(QualType type, uint64_t &len,
5895                                 QualType &eltType) {
5896   // Vectors are simple.
5897   if (const VectorType *vecType = type->getAs<VectorType>()) {
5898     len = vecType->getNumElements();
5899     eltType = vecType->getElementType();
5900     assert(eltType->isScalarType());
5901     return true;
5902   }
5903 
5904   // We allow lax conversion to and from non-vector types, but only if
5905   // they're real types (i.e. non-complex, non-pointer scalar types).
5906   if (!type->isRealType()) return false;
5907 
5908   len = 1;
5909   eltType = type;
5910   return true;
5911 }
5912 
5913 /// Are the two types lax-compatible vector types?  That is, given
5914 /// that one of them is a vector, do they have equal storage sizes,
5915 /// where the storage size is the number of elements times the element
5916 /// size?
5917 ///
5918 /// This will also return false if either of the types is neither a
5919 /// vector nor a real type.
5920 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5921   assert(destTy->isVectorType() || srcTy->isVectorType());
5922 
5923   // Disallow lax conversions between scalars and ExtVectors (these
5924   // conversions are allowed for other vector types because common headers
5925   // depend on them).  Most scalar OP ExtVector cases are handled by the
5926   // splat path anyway, which does what we want (convert, not bitcast).
5927   // What this rules out for ExtVectors is crazy things like char4*float.
5928   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5929   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5930 
5931   uint64_t srcLen, destLen;
5932   QualType srcEltTy, destEltTy;
5933   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5934   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5935 
5936   // ASTContext::getTypeSize will return the size rounded up to a
5937   // power of 2, so instead of using that, we need to use the raw
5938   // element size multiplied by the element count.
5939   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5940   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5941 
5942   return (srcLen * srcEltSize == destLen * destEltSize);
5943 }
5944 
5945 /// Is this a legal conversion between two types, one of which is
5946 /// known to be a vector type?
5947 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5948   assert(destTy->isVectorType() || srcTy->isVectorType());
5949 
5950   if (!Context.getLangOpts().LaxVectorConversions)
5951     return false;
5952   return areLaxCompatibleVectorTypes(srcTy, destTy);
5953 }
5954 
5955 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5956                            CastKind &Kind) {
5957   assert(VectorTy->isVectorType() && "Not a vector type!");
5958 
5959   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5960     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5961       return Diag(R.getBegin(),
5962                   Ty->isVectorType() ?
5963                   diag::err_invalid_conversion_between_vectors :
5964                   diag::err_invalid_conversion_between_vector_and_integer)
5965         << VectorTy << Ty << R;
5966   } else
5967     return Diag(R.getBegin(),
5968                 diag::err_invalid_conversion_between_vector_and_scalar)
5969       << VectorTy << Ty << R;
5970 
5971   Kind = CK_BitCast;
5972   return false;
5973 }
5974 
5975 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5976   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5977 
5978   if (DestElemTy == SplattedExpr->getType())
5979     return SplattedExpr;
5980 
5981   assert(DestElemTy->isFloatingType() ||
5982          DestElemTy->isIntegralOrEnumerationType());
5983 
5984   CastKind CK;
5985   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5986     // OpenCL requires that we convert `true` boolean expressions to -1, but
5987     // only when splatting vectors.
5988     if (DestElemTy->isFloatingType()) {
5989       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5990       // in two steps: boolean to signed integral, then to floating.
5991       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5992                                                  CK_BooleanToSignedIntegral);
5993       SplattedExpr = CastExprRes.get();
5994       CK = CK_IntegralToFloating;
5995     } else {
5996       CK = CK_BooleanToSignedIntegral;
5997     }
5998   } else {
5999     ExprResult CastExprRes = SplattedExpr;
6000     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6001     if (CastExprRes.isInvalid())
6002       return ExprError();
6003     SplattedExpr = CastExprRes.get();
6004   }
6005   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6006 }
6007 
6008 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6009                                     Expr *CastExpr, CastKind &Kind) {
6010   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6011 
6012   QualType SrcTy = CastExpr->getType();
6013 
6014   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6015   // an ExtVectorType.
6016   // In OpenCL, casts between vectors of different types are not allowed.
6017   // (See OpenCL 6.2).
6018   if (SrcTy->isVectorType()) {
6019     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6020         || (getLangOpts().OpenCL &&
6021             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6022       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6023         << DestTy << SrcTy << R;
6024       return ExprError();
6025     }
6026     Kind = CK_BitCast;
6027     return CastExpr;
6028   }
6029 
6030   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6031   // conversion will take place first from scalar to elt type, and then
6032   // splat from elt type to vector.
6033   if (SrcTy->isPointerType())
6034     return Diag(R.getBegin(),
6035                 diag::err_invalid_conversion_between_vector_and_scalar)
6036       << DestTy << SrcTy << R;
6037 
6038   Kind = CK_VectorSplat;
6039   return prepareVectorSplat(DestTy, CastExpr);
6040 }
6041 
6042 ExprResult
6043 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6044                     Declarator &D, ParsedType &Ty,
6045                     SourceLocation RParenLoc, Expr *CastExpr) {
6046   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6047          "ActOnCastExpr(): missing type or expr");
6048 
6049   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6050   if (D.isInvalidType())
6051     return ExprError();
6052 
6053   if (getLangOpts().CPlusPlus) {
6054     // Check that there are no default arguments (C++ only).
6055     CheckExtraCXXDefaultArguments(D);
6056   } else {
6057     // Make sure any TypoExprs have been dealt with.
6058     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6059     if (!Res.isUsable())
6060       return ExprError();
6061     CastExpr = Res.get();
6062   }
6063 
6064   checkUnusedDeclAttributes(D);
6065 
6066   QualType castType = castTInfo->getType();
6067   Ty = CreateParsedType(castType, castTInfo);
6068 
6069   bool isVectorLiteral = false;
6070 
6071   // Check for an altivec or OpenCL literal,
6072   // i.e. all the elements are integer constants.
6073   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6074   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6075   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6076        && castType->isVectorType() && (PE || PLE)) {
6077     if (PLE && PLE->getNumExprs() == 0) {
6078       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6079       return ExprError();
6080     }
6081     if (PE || PLE->getNumExprs() == 1) {
6082       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6083       if (!E->getType()->isVectorType())
6084         isVectorLiteral = true;
6085     }
6086     else
6087       isVectorLiteral = true;
6088   }
6089 
6090   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6091   // then handle it as such.
6092   if (isVectorLiteral)
6093     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6094 
6095   // If the Expr being casted is a ParenListExpr, handle it specially.
6096   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6097   // sequence of BinOp comma operators.
6098   if (isa<ParenListExpr>(CastExpr)) {
6099     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6100     if (Result.isInvalid()) return ExprError();
6101     CastExpr = Result.get();
6102   }
6103 
6104   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6105       !getSourceManager().isInSystemMacro(LParenLoc))
6106     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6107 
6108   CheckTollFreeBridgeCast(castType, CastExpr);
6109 
6110   CheckObjCBridgeRelatedCast(castType, CastExpr);
6111 
6112   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6113 
6114   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6115 }
6116 
6117 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6118                                     SourceLocation RParenLoc, Expr *E,
6119                                     TypeSourceInfo *TInfo) {
6120   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6121          "Expected paren or paren list expression");
6122 
6123   Expr **exprs;
6124   unsigned numExprs;
6125   Expr *subExpr;
6126   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6127   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6128     LiteralLParenLoc = PE->getLParenLoc();
6129     LiteralRParenLoc = PE->getRParenLoc();
6130     exprs = PE->getExprs();
6131     numExprs = PE->getNumExprs();
6132   } else { // isa<ParenExpr> by assertion at function entrance
6133     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6134     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6135     subExpr = cast<ParenExpr>(E)->getSubExpr();
6136     exprs = &subExpr;
6137     numExprs = 1;
6138   }
6139 
6140   QualType Ty = TInfo->getType();
6141   assert(Ty->isVectorType() && "Expected vector type");
6142 
6143   SmallVector<Expr *, 8> initExprs;
6144   const VectorType *VTy = Ty->getAs<VectorType>();
6145   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6146 
6147   // '(...)' form of vector initialization in AltiVec: the number of
6148   // initializers must be one or must match the size of the vector.
6149   // If a single value is specified in the initializer then it will be
6150   // replicated to all the components of the vector
6151   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6152     // The number of initializers must be one or must match the size of the
6153     // vector. If a single value is specified in the initializer then it will
6154     // be replicated to all the components of the vector
6155     if (numExprs == 1) {
6156       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6157       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6158       if (Literal.isInvalid())
6159         return ExprError();
6160       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6161                                   PrepareScalarCast(Literal, ElemTy));
6162       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6163     }
6164     else if (numExprs < numElems) {
6165       Diag(E->getExprLoc(),
6166            diag::err_incorrect_number_of_vector_initializers);
6167       return ExprError();
6168     }
6169     else
6170       initExprs.append(exprs, exprs + numExprs);
6171   }
6172   else {
6173     // For OpenCL, when the number of initializers is a single value,
6174     // it will be replicated to all components of the vector.
6175     if (getLangOpts().OpenCL &&
6176         VTy->getVectorKind() == VectorType::GenericVector &&
6177         numExprs == 1) {
6178         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6179         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6180         if (Literal.isInvalid())
6181           return ExprError();
6182         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6183                                     PrepareScalarCast(Literal, ElemTy));
6184         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6185     }
6186 
6187     initExprs.append(exprs, exprs + numExprs);
6188   }
6189   // FIXME: This means that pretty-printing the final AST will produce curly
6190   // braces instead of the original commas.
6191   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6192                                                    initExprs, LiteralRParenLoc);
6193   initE->setType(Ty);
6194   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6195 }
6196 
6197 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6198 /// the ParenListExpr into a sequence of comma binary operators.
6199 ExprResult
6200 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6201   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6202   if (!E)
6203     return OrigExpr;
6204 
6205   ExprResult Result(E->getExpr(0));
6206 
6207   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6208     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6209                         E->getExpr(i));
6210 
6211   if (Result.isInvalid()) return ExprError();
6212 
6213   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6214 }
6215 
6216 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6217                                     SourceLocation R,
6218                                     MultiExprArg Val) {
6219   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6220   return expr;
6221 }
6222 
6223 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6224 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6225 /// emitted.
6226 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6227                                       SourceLocation QuestionLoc) {
6228   Expr *NullExpr = LHSExpr;
6229   Expr *NonPointerExpr = RHSExpr;
6230   Expr::NullPointerConstantKind NullKind =
6231       NullExpr->isNullPointerConstant(Context,
6232                                       Expr::NPC_ValueDependentIsNotNull);
6233 
6234   if (NullKind == Expr::NPCK_NotNull) {
6235     NullExpr = RHSExpr;
6236     NonPointerExpr = LHSExpr;
6237     NullKind =
6238         NullExpr->isNullPointerConstant(Context,
6239                                         Expr::NPC_ValueDependentIsNotNull);
6240   }
6241 
6242   if (NullKind == Expr::NPCK_NotNull)
6243     return false;
6244 
6245   if (NullKind == Expr::NPCK_ZeroExpression)
6246     return false;
6247 
6248   if (NullKind == Expr::NPCK_ZeroLiteral) {
6249     // In this case, check to make sure that we got here from a "NULL"
6250     // string in the source code.
6251     NullExpr = NullExpr->IgnoreParenImpCasts();
6252     SourceLocation loc = NullExpr->getExprLoc();
6253     if (!findMacroSpelling(loc, "NULL"))
6254       return false;
6255   }
6256 
6257   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6258   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6259       << NonPointerExpr->getType() << DiagType
6260       << NonPointerExpr->getSourceRange();
6261   return true;
6262 }
6263 
6264 /// \brief Return false if the condition expression is valid, true otherwise.
6265 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6266   QualType CondTy = Cond->getType();
6267 
6268   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6269   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6270     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6271       << CondTy << Cond->getSourceRange();
6272     return true;
6273   }
6274 
6275   // C99 6.5.15p2
6276   if (CondTy->isScalarType()) return false;
6277 
6278   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6279     << CondTy << Cond->getSourceRange();
6280   return true;
6281 }
6282 
6283 /// \brief Handle when one or both operands are void type.
6284 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6285                                          ExprResult &RHS) {
6286     Expr *LHSExpr = LHS.get();
6287     Expr *RHSExpr = RHS.get();
6288 
6289     if (!LHSExpr->getType()->isVoidType())
6290       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6291         << RHSExpr->getSourceRange();
6292     if (!RHSExpr->getType()->isVoidType())
6293       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6294         << LHSExpr->getSourceRange();
6295     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6296     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6297     return S.Context.VoidTy;
6298 }
6299 
6300 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6301 /// true otherwise.
6302 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6303                                         QualType PointerTy) {
6304   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6305       !NullExpr.get()->isNullPointerConstant(S.Context,
6306                                             Expr::NPC_ValueDependentIsNull))
6307     return true;
6308 
6309   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6310   return false;
6311 }
6312 
6313 /// \brief Checks compatibility between two pointers and return the resulting
6314 /// type.
6315 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6316                                                      ExprResult &RHS,
6317                                                      SourceLocation Loc) {
6318   QualType LHSTy = LHS.get()->getType();
6319   QualType RHSTy = RHS.get()->getType();
6320 
6321   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6322     // Two identical pointers types are always compatible.
6323     return LHSTy;
6324   }
6325 
6326   QualType lhptee, rhptee;
6327 
6328   // Get the pointee types.
6329   bool IsBlockPointer = false;
6330   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6331     lhptee = LHSBTy->getPointeeType();
6332     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6333     IsBlockPointer = true;
6334   } else {
6335     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6336     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6337   }
6338 
6339   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6340   // differently qualified versions of compatible types, the result type is
6341   // a pointer to an appropriately qualified version of the composite
6342   // type.
6343 
6344   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6345   // clause doesn't make sense for our extensions. E.g. address space 2 should
6346   // be incompatible with address space 3: they may live on different devices or
6347   // anything.
6348   Qualifiers lhQual = lhptee.getQualifiers();
6349   Qualifiers rhQual = rhptee.getQualifiers();
6350 
6351   unsigned ResultAddrSpace = 0;
6352   unsigned LAddrSpace = lhQual.getAddressSpace();
6353   unsigned RAddrSpace = rhQual.getAddressSpace();
6354   if (S.getLangOpts().OpenCL) {
6355     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6356     // spaces is disallowed.
6357     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6358       ResultAddrSpace = LAddrSpace;
6359     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6360       ResultAddrSpace = RAddrSpace;
6361     else {
6362       S.Diag(Loc,
6363              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6364           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6365           << RHS.get()->getSourceRange();
6366       return QualType();
6367     }
6368   }
6369 
6370   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6371   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6372   lhQual.removeCVRQualifiers();
6373   rhQual.removeCVRQualifiers();
6374 
6375   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6376   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6377   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6378   // qual types are compatible iff
6379   //  * corresponded types are compatible
6380   //  * CVR qualifiers are equal
6381   //  * address spaces are equal
6382   // Thus for conditional operator we merge CVR and address space unqualified
6383   // pointees and if there is a composite type we return a pointer to it with
6384   // merged qualifiers.
6385   if (S.getLangOpts().OpenCL) {
6386     LHSCastKind = LAddrSpace == ResultAddrSpace
6387                       ? CK_BitCast
6388                       : CK_AddressSpaceConversion;
6389     RHSCastKind = RAddrSpace == ResultAddrSpace
6390                       ? CK_BitCast
6391                       : CK_AddressSpaceConversion;
6392     lhQual.removeAddressSpace();
6393     rhQual.removeAddressSpace();
6394   }
6395 
6396   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6397   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6398 
6399   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6400 
6401   if (CompositeTy.isNull()) {
6402     // In this situation, we assume void* type. No especially good
6403     // reason, but this is what gcc does, and we do have to pick
6404     // to get a consistent AST.
6405     QualType incompatTy;
6406     incompatTy = S.Context.getPointerType(
6407         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6408     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6409     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6410     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6411     // for casts between types with incompatible address space qualifiers.
6412     // For the following code the compiler produces casts between global and
6413     // local address spaces of the corresponded innermost pointees:
6414     // local int *global *a;
6415     // global int *global *b;
6416     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6417     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6418         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6419         << RHS.get()->getSourceRange();
6420     return incompatTy;
6421   }
6422 
6423   // The pointer types are compatible.
6424   // In case of OpenCL ResultTy should have the address space qualifier
6425   // which is a superset of address spaces of both the 2nd and the 3rd
6426   // operands of the conditional operator.
6427   QualType ResultTy = [&, ResultAddrSpace]() {
6428     if (S.getLangOpts().OpenCL) {
6429       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6430       CompositeQuals.setAddressSpace(ResultAddrSpace);
6431       return S.Context
6432           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6433           .withCVRQualifiers(MergedCVRQual);
6434     } else
6435       return CompositeTy.withCVRQualifiers(MergedCVRQual);
6436   }();
6437   if (IsBlockPointer)
6438     ResultTy = S.Context.getBlockPointerType(ResultTy);
6439   else {
6440     ResultTy = S.Context.getPointerType(ResultTy);
6441   }
6442 
6443   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6444   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6445   return ResultTy;
6446 }
6447 
6448 /// \brief Return the resulting type when the operands are both block pointers.
6449 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6450                                                           ExprResult &LHS,
6451                                                           ExprResult &RHS,
6452                                                           SourceLocation Loc) {
6453   QualType LHSTy = LHS.get()->getType();
6454   QualType RHSTy = RHS.get()->getType();
6455 
6456   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6457     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6458       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6459       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6460       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6461       return destType;
6462     }
6463     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6464       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6465       << RHS.get()->getSourceRange();
6466     return QualType();
6467   }
6468 
6469   // We have 2 block pointer types.
6470   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6471 }
6472 
6473 /// \brief Return the resulting type when the operands are both pointers.
6474 static QualType
6475 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6476                                             ExprResult &RHS,
6477                                             SourceLocation Loc) {
6478   // get the pointer types
6479   QualType LHSTy = LHS.get()->getType();
6480   QualType RHSTy = RHS.get()->getType();
6481 
6482   // get the "pointed to" types
6483   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6484   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6485 
6486   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6487   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6488     // Figure out necessary qualifiers (C99 6.5.15p6)
6489     QualType destPointee
6490       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6491     QualType destType = S.Context.getPointerType(destPointee);
6492     // Add qualifiers if necessary.
6493     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6494     // Promote to void*.
6495     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6496     return destType;
6497   }
6498   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6499     QualType destPointee
6500       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6501     QualType destType = S.Context.getPointerType(destPointee);
6502     // Add qualifiers if necessary.
6503     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6504     // Promote to void*.
6505     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6506     return destType;
6507   }
6508 
6509   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6510 }
6511 
6512 /// \brief Return false if the first expression is not an integer and the second
6513 /// expression is not a pointer, true otherwise.
6514 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6515                                         Expr* PointerExpr, SourceLocation Loc,
6516                                         bool IsIntFirstExpr) {
6517   if (!PointerExpr->getType()->isPointerType() ||
6518       !Int.get()->getType()->isIntegerType())
6519     return false;
6520 
6521   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6522   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6523 
6524   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6525     << Expr1->getType() << Expr2->getType()
6526     << Expr1->getSourceRange() << Expr2->getSourceRange();
6527   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6528                             CK_IntegralToPointer);
6529   return true;
6530 }
6531 
6532 /// \brief Simple conversion between integer and floating point types.
6533 ///
6534 /// Used when handling the OpenCL conditional operator where the
6535 /// condition is a vector while the other operands are scalar.
6536 ///
6537 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6538 /// types are either integer or floating type. Between the two
6539 /// operands, the type with the higher rank is defined as the "result
6540 /// type". The other operand needs to be promoted to the same type. No
6541 /// other type promotion is allowed. We cannot use
6542 /// UsualArithmeticConversions() for this purpose, since it always
6543 /// promotes promotable types.
6544 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6545                                             ExprResult &RHS,
6546                                             SourceLocation QuestionLoc) {
6547   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6548   if (LHS.isInvalid())
6549     return QualType();
6550   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6551   if (RHS.isInvalid())
6552     return QualType();
6553 
6554   // For conversion purposes, we ignore any qualifiers.
6555   // For example, "const float" and "float" are equivalent.
6556   QualType LHSType =
6557     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6558   QualType RHSType =
6559     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6560 
6561   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6562     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6563       << LHSType << LHS.get()->getSourceRange();
6564     return QualType();
6565   }
6566 
6567   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6568     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6569       << RHSType << RHS.get()->getSourceRange();
6570     return QualType();
6571   }
6572 
6573   // If both types are identical, no conversion is needed.
6574   if (LHSType == RHSType)
6575     return LHSType;
6576 
6577   // Now handle "real" floating types (i.e. float, double, long double).
6578   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6579     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6580                                  /*IsCompAssign = */ false);
6581 
6582   // Finally, we have two differing integer types.
6583   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6584   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6585 }
6586 
6587 /// \brief Convert scalar operands to a vector that matches the
6588 ///        condition in length.
6589 ///
6590 /// Used when handling the OpenCL conditional operator where the
6591 /// condition is a vector while the other operands are scalar.
6592 ///
6593 /// We first compute the "result type" for the scalar operands
6594 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6595 /// into a vector of that type where the length matches the condition
6596 /// vector type. s6.11.6 requires that the element types of the result
6597 /// and the condition must have the same number of bits.
6598 static QualType
6599 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6600                               QualType CondTy, SourceLocation QuestionLoc) {
6601   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6602   if (ResTy.isNull()) return QualType();
6603 
6604   const VectorType *CV = CondTy->getAs<VectorType>();
6605   assert(CV);
6606 
6607   // Determine the vector result type
6608   unsigned NumElements = CV->getNumElements();
6609   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6610 
6611   // Ensure that all types have the same number of bits
6612   if (S.Context.getTypeSize(CV->getElementType())
6613       != S.Context.getTypeSize(ResTy)) {
6614     // Since VectorTy is created internally, it does not pretty print
6615     // with an OpenCL name. Instead, we just print a description.
6616     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6617     SmallString<64> Str;
6618     llvm::raw_svector_ostream OS(Str);
6619     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6620     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6621       << CondTy << OS.str();
6622     return QualType();
6623   }
6624 
6625   // Convert operands to the vector result type
6626   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6627   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6628 
6629   return VectorTy;
6630 }
6631 
6632 /// \brief Return false if this is a valid OpenCL condition vector
6633 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6634                                        SourceLocation QuestionLoc) {
6635   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6636   // integral type.
6637   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6638   assert(CondTy);
6639   QualType EleTy = CondTy->getElementType();
6640   if (EleTy->isIntegerType()) return false;
6641 
6642   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6643     << Cond->getType() << Cond->getSourceRange();
6644   return true;
6645 }
6646 
6647 /// \brief Return false if the vector condition type and the vector
6648 ///        result type are compatible.
6649 ///
6650 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6651 /// number of elements, and their element types have the same number
6652 /// of bits.
6653 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6654                               SourceLocation QuestionLoc) {
6655   const VectorType *CV = CondTy->getAs<VectorType>();
6656   const VectorType *RV = VecResTy->getAs<VectorType>();
6657   assert(CV && RV);
6658 
6659   if (CV->getNumElements() != RV->getNumElements()) {
6660     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6661       << CondTy << VecResTy;
6662     return true;
6663   }
6664 
6665   QualType CVE = CV->getElementType();
6666   QualType RVE = RV->getElementType();
6667 
6668   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6669     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6670       << CondTy << VecResTy;
6671     return true;
6672   }
6673 
6674   return false;
6675 }
6676 
6677 /// \brief Return the resulting type for the conditional operator in
6678 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6679 ///        s6.3.i) when the condition is a vector type.
6680 static QualType
6681 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6682                              ExprResult &LHS, ExprResult &RHS,
6683                              SourceLocation QuestionLoc) {
6684   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6685   if (Cond.isInvalid())
6686     return QualType();
6687   QualType CondTy = Cond.get()->getType();
6688 
6689   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6690     return QualType();
6691 
6692   // If either operand is a vector then find the vector type of the
6693   // result as specified in OpenCL v1.1 s6.3.i.
6694   if (LHS.get()->getType()->isVectorType() ||
6695       RHS.get()->getType()->isVectorType()) {
6696     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6697                                               /*isCompAssign*/false,
6698                                               /*AllowBothBool*/true,
6699                                               /*AllowBoolConversions*/false);
6700     if (VecResTy.isNull()) return QualType();
6701     // The result type must match the condition type as specified in
6702     // OpenCL v1.1 s6.11.6.
6703     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6704       return QualType();
6705     return VecResTy;
6706   }
6707 
6708   // Both operands are scalar.
6709   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6710 }
6711 
6712 /// \brief Return true if the Expr is block type
6713 static bool checkBlockType(Sema &S, const Expr *E) {
6714   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6715     QualType Ty = CE->getCallee()->getType();
6716     if (Ty->isBlockPointerType()) {
6717       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6718       return true;
6719     }
6720   }
6721   return false;
6722 }
6723 
6724 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6725 /// In that case, LHS = cond.
6726 /// C99 6.5.15
6727 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6728                                         ExprResult &RHS, ExprValueKind &VK,
6729                                         ExprObjectKind &OK,
6730                                         SourceLocation QuestionLoc) {
6731 
6732   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6733   if (!LHSResult.isUsable()) return QualType();
6734   LHS = LHSResult;
6735 
6736   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6737   if (!RHSResult.isUsable()) return QualType();
6738   RHS = RHSResult;
6739 
6740   // C++ is sufficiently different to merit its own checker.
6741   if (getLangOpts().CPlusPlus)
6742     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6743 
6744   VK = VK_RValue;
6745   OK = OK_Ordinary;
6746 
6747   // The OpenCL operator with a vector condition is sufficiently
6748   // different to merit its own checker.
6749   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6750     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6751 
6752   // First, check the condition.
6753   Cond = UsualUnaryConversions(Cond.get());
6754   if (Cond.isInvalid())
6755     return QualType();
6756   if (checkCondition(*this, Cond.get(), QuestionLoc))
6757     return QualType();
6758 
6759   // Now check the two expressions.
6760   if (LHS.get()->getType()->isVectorType() ||
6761       RHS.get()->getType()->isVectorType())
6762     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6763                                /*AllowBothBool*/true,
6764                                /*AllowBoolConversions*/false);
6765 
6766   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6767   if (LHS.isInvalid() || RHS.isInvalid())
6768     return QualType();
6769 
6770   QualType LHSTy = LHS.get()->getType();
6771   QualType RHSTy = RHS.get()->getType();
6772 
6773   // Diagnose attempts to convert between __float128 and long double where
6774   // such conversions currently can't be handled.
6775   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6776     Diag(QuestionLoc,
6777          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6778       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6779     return QualType();
6780   }
6781 
6782   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6783   // selection operator (?:).
6784   if (getLangOpts().OpenCL &&
6785       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6786     return QualType();
6787   }
6788 
6789   // If both operands have arithmetic type, do the usual arithmetic conversions
6790   // to find a common type: C99 6.5.15p3,5.
6791   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6792     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6793     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6794 
6795     return ResTy;
6796   }
6797 
6798   // If both operands are the same structure or union type, the result is that
6799   // type.
6800   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6801     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6802       if (LHSRT->getDecl() == RHSRT->getDecl())
6803         // "If both the operands have structure or union type, the result has
6804         // that type."  This implies that CV qualifiers are dropped.
6805         return LHSTy.getUnqualifiedType();
6806     // FIXME: Type of conditional expression must be complete in C mode.
6807   }
6808 
6809   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6810   // The following || allows only one side to be void (a GCC-ism).
6811   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6812     return checkConditionalVoidType(*this, LHS, RHS);
6813   }
6814 
6815   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6816   // the type of the other operand."
6817   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6818   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6819 
6820   // All objective-c pointer type analysis is done here.
6821   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6822                                                         QuestionLoc);
6823   if (LHS.isInvalid() || RHS.isInvalid())
6824     return QualType();
6825   if (!compositeType.isNull())
6826     return compositeType;
6827 
6828 
6829   // Handle block pointer types.
6830   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6831     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6832                                                      QuestionLoc);
6833 
6834   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6835   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6836     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6837                                                        QuestionLoc);
6838 
6839   // GCC compatibility: soften pointer/integer mismatch.  Note that
6840   // null pointers have been filtered out by this point.
6841   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6842       /*isIntFirstExpr=*/true))
6843     return RHSTy;
6844   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6845       /*isIntFirstExpr=*/false))
6846     return LHSTy;
6847 
6848   // Emit a better diagnostic if one of the expressions is a null pointer
6849   // constant and the other is not a pointer type. In this case, the user most
6850   // likely forgot to take the address of the other expression.
6851   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6852     return QualType();
6853 
6854   // Otherwise, the operands are not compatible.
6855   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6856     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6857     << RHS.get()->getSourceRange();
6858   return QualType();
6859 }
6860 
6861 /// FindCompositeObjCPointerType - Helper method to find composite type of
6862 /// two objective-c pointer types of the two input expressions.
6863 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6864                                             SourceLocation QuestionLoc) {
6865   QualType LHSTy = LHS.get()->getType();
6866   QualType RHSTy = RHS.get()->getType();
6867 
6868   // Handle things like Class and struct objc_class*.  Here we case the result
6869   // to the pseudo-builtin, because that will be implicitly cast back to the
6870   // redefinition type if an attempt is made to access its fields.
6871   if (LHSTy->isObjCClassType() &&
6872       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6873     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6874     return LHSTy;
6875   }
6876   if (RHSTy->isObjCClassType() &&
6877       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6878     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6879     return RHSTy;
6880   }
6881   // And the same for struct objc_object* / id
6882   if (LHSTy->isObjCIdType() &&
6883       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6884     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6885     return LHSTy;
6886   }
6887   if (RHSTy->isObjCIdType() &&
6888       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6889     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6890     return RHSTy;
6891   }
6892   // And the same for struct objc_selector* / SEL
6893   if (Context.isObjCSelType(LHSTy) &&
6894       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6895     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6896     return LHSTy;
6897   }
6898   if (Context.isObjCSelType(RHSTy) &&
6899       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6900     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6901     return RHSTy;
6902   }
6903   // Check constraints for Objective-C object pointers types.
6904   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6905 
6906     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6907       // Two identical object pointer types are always compatible.
6908       return LHSTy;
6909     }
6910     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6911     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6912     QualType compositeType = LHSTy;
6913 
6914     // If both operands are interfaces and either operand can be
6915     // assigned to the other, use that type as the composite
6916     // type. This allows
6917     //   xxx ? (A*) a : (B*) b
6918     // where B is a subclass of A.
6919     //
6920     // Additionally, as for assignment, if either type is 'id'
6921     // allow silent coercion. Finally, if the types are
6922     // incompatible then make sure to use 'id' as the composite
6923     // type so the result is acceptable for sending messages to.
6924 
6925     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6926     // It could return the composite type.
6927     if (!(compositeType =
6928           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6929       // Nothing more to do.
6930     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6931       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6932     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6933       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6934     } else if ((LHSTy->isObjCQualifiedIdType() ||
6935                 RHSTy->isObjCQualifiedIdType()) &&
6936                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6937       // Need to handle "id<xx>" explicitly.
6938       // GCC allows qualified id and any Objective-C type to devolve to
6939       // id. Currently localizing to here until clear this should be
6940       // part of ObjCQualifiedIdTypesAreCompatible.
6941       compositeType = Context.getObjCIdType();
6942     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6943       compositeType = Context.getObjCIdType();
6944     } else {
6945       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6946       << LHSTy << RHSTy
6947       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6948       QualType incompatTy = Context.getObjCIdType();
6949       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6950       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6951       return incompatTy;
6952     }
6953     // The object pointer types are compatible.
6954     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6955     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6956     return compositeType;
6957   }
6958   // Check Objective-C object pointer types and 'void *'
6959   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6960     if (getLangOpts().ObjCAutoRefCount) {
6961       // ARC forbids the implicit conversion of object pointers to 'void *',
6962       // so these types are not compatible.
6963       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6964           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6965       LHS = RHS = true;
6966       return QualType();
6967     }
6968     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6969     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6970     QualType destPointee
6971     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6972     QualType destType = Context.getPointerType(destPointee);
6973     // Add qualifiers if necessary.
6974     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6975     // Promote to void*.
6976     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6977     return destType;
6978   }
6979   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6980     if (getLangOpts().ObjCAutoRefCount) {
6981       // ARC forbids the implicit conversion of object pointers to 'void *',
6982       // so these types are not compatible.
6983       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6984           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6985       LHS = RHS = true;
6986       return QualType();
6987     }
6988     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6989     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6990     QualType destPointee
6991     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6992     QualType destType = Context.getPointerType(destPointee);
6993     // Add qualifiers if necessary.
6994     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6995     // Promote to void*.
6996     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6997     return destType;
6998   }
6999   return QualType();
7000 }
7001 
7002 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7003 /// ParenRange in parentheses.
7004 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7005                                const PartialDiagnostic &Note,
7006                                SourceRange ParenRange) {
7007   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7008   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7009       EndLoc.isValid()) {
7010     Self.Diag(Loc, Note)
7011       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7012       << FixItHint::CreateInsertion(EndLoc, ")");
7013   } else {
7014     // We can't display the parentheses, so just show the bare note.
7015     Self.Diag(Loc, Note) << ParenRange;
7016   }
7017 }
7018 
7019 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7020   return BinaryOperator::isAdditiveOp(Opc) ||
7021          BinaryOperator::isMultiplicativeOp(Opc) ||
7022          BinaryOperator::isShiftOp(Opc);
7023 }
7024 
7025 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7026 /// expression, either using a built-in or overloaded operator,
7027 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7028 /// expression.
7029 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7030                                    Expr **RHSExprs) {
7031   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7032   E = E->IgnoreImpCasts();
7033   E = E->IgnoreConversionOperator();
7034   E = E->IgnoreImpCasts();
7035 
7036   // Built-in binary operator.
7037   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7038     if (IsArithmeticOp(OP->getOpcode())) {
7039       *Opcode = OP->getOpcode();
7040       *RHSExprs = OP->getRHS();
7041       return true;
7042     }
7043   }
7044 
7045   // Overloaded operator.
7046   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7047     if (Call->getNumArgs() != 2)
7048       return false;
7049 
7050     // Make sure this is really a binary operator that is safe to pass into
7051     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7052     OverloadedOperatorKind OO = Call->getOperator();
7053     if (OO < OO_Plus || OO > OO_Arrow ||
7054         OO == OO_PlusPlus || OO == OO_MinusMinus)
7055       return false;
7056 
7057     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7058     if (IsArithmeticOp(OpKind)) {
7059       *Opcode = OpKind;
7060       *RHSExprs = Call->getArg(1);
7061       return true;
7062     }
7063   }
7064 
7065   return false;
7066 }
7067 
7068 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7069 /// or is a logical expression such as (x==y) which has int type, but is
7070 /// commonly interpreted as boolean.
7071 static bool ExprLooksBoolean(Expr *E) {
7072   E = E->IgnoreParenImpCasts();
7073 
7074   if (E->getType()->isBooleanType())
7075     return true;
7076   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7077     return OP->isComparisonOp() || OP->isLogicalOp();
7078   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7079     return OP->getOpcode() == UO_LNot;
7080   if (E->getType()->isPointerType())
7081     return true;
7082 
7083   return false;
7084 }
7085 
7086 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7087 /// and binary operator are mixed in a way that suggests the programmer assumed
7088 /// the conditional operator has higher precedence, for example:
7089 /// "int x = a + someBinaryCondition ? 1 : 2".
7090 static void DiagnoseConditionalPrecedence(Sema &Self,
7091                                           SourceLocation OpLoc,
7092                                           Expr *Condition,
7093                                           Expr *LHSExpr,
7094                                           Expr *RHSExpr) {
7095   BinaryOperatorKind CondOpcode;
7096   Expr *CondRHS;
7097 
7098   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7099     return;
7100   if (!ExprLooksBoolean(CondRHS))
7101     return;
7102 
7103   // The condition is an arithmetic binary expression, with a right-
7104   // hand side that looks boolean, so warn.
7105 
7106   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7107       << Condition->getSourceRange()
7108       << BinaryOperator::getOpcodeStr(CondOpcode);
7109 
7110   SuggestParentheses(Self, OpLoc,
7111     Self.PDiag(diag::note_precedence_silence)
7112       << BinaryOperator::getOpcodeStr(CondOpcode),
7113     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7114 
7115   SuggestParentheses(Self, OpLoc,
7116     Self.PDiag(diag::note_precedence_conditional_first),
7117     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7118 }
7119 
7120 /// Compute the nullability of a conditional expression.
7121 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7122                                               QualType LHSTy, QualType RHSTy,
7123                                               ASTContext &Ctx) {
7124   if (!ResTy->isAnyPointerType())
7125     return ResTy;
7126 
7127   auto GetNullability = [&Ctx](QualType Ty) {
7128     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7129     if (Kind)
7130       return *Kind;
7131     return NullabilityKind::Unspecified;
7132   };
7133 
7134   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7135   NullabilityKind MergedKind;
7136 
7137   // Compute nullability of a binary conditional expression.
7138   if (IsBin) {
7139     if (LHSKind == NullabilityKind::NonNull)
7140       MergedKind = NullabilityKind::NonNull;
7141     else
7142       MergedKind = RHSKind;
7143   // Compute nullability of a normal conditional expression.
7144   } else {
7145     if (LHSKind == NullabilityKind::Nullable ||
7146         RHSKind == NullabilityKind::Nullable)
7147       MergedKind = NullabilityKind::Nullable;
7148     else if (LHSKind == NullabilityKind::NonNull)
7149       MergedKind = RHSKind;
7150     else if (RHSKind == NullabilityKind::NonNull)
7151       MergedKind = LHSKind;
7152     else
7153       MergedKind = NullabilityKind::Unspecified;
7154   }
7155 
7156   // Return if ResTy already has the correct nullability.
7157   if (GetNullability(ResTy) == MergedKind)
7158     return ResTy;
7159 
7160   // Strip all nullability from ResTy.
7161   while (ResTy->getNullability(Ctx))
7162     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7163 
7164   // Create a new AttributedType with the new nullability kind.
7165   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7166   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7167 }
7168 
7169 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7170 /// in the case of a the GNU conditional expr extension.
7171 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7172                                     SourceLocation ColonLoc,
7173                                     Expr *CondExpr, Expr *LHSExpr,
7174                                     Expr *RHSExpr) {
7175   if (!getLangOpts().CPlusPlus) {
7176     // C cannot handle TypoExpr nodes in the condition because it
7177     // doesn't handle dependent types properly, so make sure any TypoExprs have
7178     // been dealt with before checking the operands.
7179     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7180     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7181     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7182 
7183     if (!CondResult.isUsable())
7184       return ExprError();
7185 
7186     if (LHSExpr) {
7187       if (!LHSResult.isUsable())
7188         return ExprError();
7189     }
7190 
7191     if (!RHSResult.isUsable())
7192       return ExprError();
7193 
7194     CondExpr = CondResult.get();
7195     LHSExpr = LHSResult.get();
7196     RHSExpr = RHSResult.get();
7197   }
7198 
7199   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7200   // was the condition.
7201   OpaqueValueExpr *opaqueValue = nullptr;
7202   Expr *commonExpr = nullptr;
7203   if (!LHSExpr) {
7204     commonExpr = CondExpr;
7205     // Lower out placeholder types first.  This is important so that we don't
7206     // try to capture a placeholder. This happens in few cases in C++; such
7207     // as Objective-C++'s dictionary subscripting syntax.
7208     if (commonExpr->hasPlaceholderType()) {
7209       ExprResult result = CheckPlaceholderExpr(commonExpr);
7210       if (!result.isUsable()) return ExprError();
7211       commonExpr = result.get();
7212     }
7213     // We usually want to apply unary conversions *before* saving, except
7214     // in the special case of a C++ l-value conditional.
7215     if (!(getLangOpts().CPlusPlus
7216           && !commonExpr->isTypeDependent()
7217           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7218           && commonExpr->isGLValue()
7219           && commonExpr->isOrdinaryOrBitFieldObject()
7220           && RHSExpr->isOrdinaryOrBitFieldObject()
7221           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7222       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7223       if (commonRes.isInvalid())
7224         return ExprError();
7225       commonExpr = commonRes.get();
7226     }
7227 
7228     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7229                                                 commonExpr->getType(),
7230                                                 commonExpr->getValueKind(),
7231                                                 commonExpr->getObjectKind(),
7232                                                 commonExpr);
7233     LHSExpr = CondExpr = opaqueValue;
7234   }
7235 
7236   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7237   ExprValueKind VK = VK_RValue;
7238   ExprObjectKind OK = OK_Ordinary;
7239   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7240   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7241                                              VK, OK, QuestionLoc);
7242   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7243       RHS.isInvalid())
7244     return ExprError();
7245 
7246   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7247                                 RHS.get());
7248 
7249   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7250 
7251   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7252                                          Context);
7253 
7254   if (!commonExpr)
7255     return new (Context)
7256         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7257                             RHS.get(), result, VK, OK);
7258 
7259   return new (Context) BinaryConditionalOperator(
7260       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7261       ColonLoc, result, VK, OK);
7262 }
7263 
7264 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7265 // being closely modeled after the C99 spec:-). The odd characteristic of this
7266 // routine is it effectively iqnores the qualifiers on the top level pointee.
7267 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7268 // FIXME: add a couple examples in this comment.
7269 static Sema::AssignConvertType
7270 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7271   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7272   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7273 
7274   // get the "pointed to" type (ignoring qualifiers at the top level)
7275   const Type *lhptee, *rhptee;
7276   Qualifiers lhq, rhq;
7277   std::tie(lhptee, lhq) =
7278       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7279   std::tie(rhptee, rhq) =
7280       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7281 
7282   Sema::AssignConvertType ConvTy = Sema::Compatible;
7283 
7284   // C99 6.5.16.1p1: This following citation is common to constraints
7285   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7286   // qualifiers of the type *pointed to* by the right;
7287 
7288   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7289   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7290       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7291     // Ignore lifetime for further calculation.
7292     lhq.removeObjCLifetime();
7293     rhq.removeObjCLifetime();
7294   }
7295 
7296   if (!lhq.compatiblyIncludes(rhq)) {
7297     // Treat address-space mismatches as fatal.  TODO: address subspaces
7298     if (!lhq.isAddressSpaceSupersetOf(rhq))
7299       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7300 
7301     // It's okay to add or remove GC or lifetime qualifiers when converting to
7302     // and from void*.
7303     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7304                         .compatiblyIncludes(
7305                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7306              && (lhptee->isVoidType() || rhptee->isVoidType()))
7307       ; // keep old
7308 
7309     // Treat lifetime mismatches as fatal.
7310     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7311       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7312 
7313     // For GCC/MS compatibility, other qualifier mismatches are treated
7314     // as still compatible in C.
7315     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7316   }
7317 
7318   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7319   // incomplete type and the other is a pointer to a qualified or unqualified
7320   // version of void...
7321   if (lhptee->isVoidType()) {
7322     if (rhptee->isIncompleteOrObjectType())
7323       return ConvTy;
7324 
7325     // As an extension, we allow cast to/from void* to function pointer.
7326     assert(rhptee->isFunctionType());
7327     return Sema::FunctionVoidPointer;
7328   }
7329 
7330   if (rhptee->isVoidType()) {
7331     if (lhptee->isIncompleteOrObjectType())
7332       return ConvTy;
7333 
7334     // As an extension, we allow cast to/from void* to function pointer.
7335     assert(lhptee->isFunctionType());
7336     return Sema::FunctionVoidPointer;
7337   }
7338 
7339   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7340   // unqualified versions of compatible types, ...
7341   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7342   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7343     // Check if the pointee types are compatible ignoring the sign.
7344     // We explicitly check for char so that we catch "char" vs
7345     // "unsigned char" on systems where "char" is unsigned.
7346     if (lhptee->isCharType())
7347       ltrans = S.Context.UnsignedCharTy;
7348     else if (lhptee->hasSignedIntegerRepresentation())
7349       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7350 
7351     if (rhptee->isCharType())
7352       rtrans = S.Context.UnsignedCharTy;
7353     else if (rhptee->hasSignedIntegerRepresentation())
7354       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7355 
7356     if (ltrans == rtrans) {
7357       // Types are compatible ignoring the sign. Qualifier incompatibility
7358       // takes priority over sign incompatibility because the sign
7359       // warning can be disabled.
7360       if (ConvTy != Sema::Compatible)
7361         return ConvTy;
7362 
7363       return Sema::IncompatiblePointerSign;
7364     }
7365 
7366     // If we are a multi-level pointer, it's possible that our issue is simply
7367     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7368     // the eventual target type is the same and the pointers have the same
7369     // level of indirection, this must be the issue.
7370     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7371       do {
7372         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7373         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7374       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7375 
7376       if (lhptee == rhptee)
7377         return Sema::IncompatibleNestedPointerQualifiers;
7378     }
7379 
7380     // General pointer incompatibility takes priority over qualifiers.
7381     return Sema::IncompatiblePointer;
7382   }
7383   if (!S.getLangOpts().CPlusPlus &&
7384       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7385     return Sema::IncompatiblePointer;
7386   return ConvTy;
7387 }
7388 
7389 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7390 /// block pointer types are compatible or whether a block and normal pointer
7391 /// are compatible. It is more restrict than comparing two function pointer
7392 // types.
7393 static Sema::AssignConvertType
7394 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7395                                     QualType RHSType) {
7396   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7397   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7398 
7399   QualType lhptee, rhptee;
7400 
7401   // get the "pointed to" type (ignoring qualifiers at the top level)
7402   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7403   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7404 
7405   // In C++, the types have to match exactly.
7406   if (S.getLangOpts().CPlusPlus)
7407     return Sema::IncompatibleBlockPointer;
7408 
7409   Sema::AssignConvertType ConvTy = Sema::Compatible;
7410 
7411   // For blocks we enforce that qualifiers are identical.
7412   Qualifiers LQuals = lhptee.getLocalQualifiers();
7413   Qualifiers RQuals = rhptee.getLocalQualifiers();
7414   if (S.getLangOpts().OpenCL) {
7415     LQuals.removeAddressSpace();
7416     RQuals.removeAddressSpace();
7417   }
7418   if (LQuals != RQuals)
7419     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7420 
7421   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7422   // assignment.
7423   // The current behavior is similar to C++ lambdas. A block might be
7424   // assigned to a variable iff its return type and parameters are compatible
7425   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7426   // an assignment. Presumably it should behave in way that a function pointer
7427   // assignment does in C, so for each parameter and return type:
7428   //  * CVR and address space of LHS should be a superset of CVR and address
7429   //  space of RHS.
7430   //  * unqualified types should be compatible.
7431   if (S.getLangOpts().OpenCL) {
7432     if (!S.Context.typesAreBlockPointerCompatible(
7433             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7434             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7435       return Sema::IncompatibleBlockPointer;
7436   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7437     return Sema::IncompatibleBlockPointer;
7438 
7439   return ConvTy;
7440 }
7441 
7442 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7443 /// for assignment compatibility.
7444 static Sema::AssignConvertType
7445 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7446                                    QualType RHSType) {
7447   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7448   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7449 
7450   if (LHSType->isObjCBuiltinType()) {
7451     // Class is not compatible with ObjC object pointers.
7452     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7453         !RHSType->isObjCQualifiedClassType())
7454       return Sema::IncompatiblePointer;
7455     return Sema::Compatible;
7456   }
7457   if (RHSType->isObjCBuiltinType()) {
7458     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7459         !LHSType->isObjCQualifiedClassType())
7460       return Sema::IncompatiblePointer;
7461     return Sema::Compatible;
7462   }
7463   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7464   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7465 
7466   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7467       // make an exception for id<P>
7468       !LHSType->isObjCQualifiedIdType())
7469     return Sema::CompatiblePointerDiscardsQualifiers;
7470 
7471   if (S.Context.typesAreCompatible(LHSType, RHSType))
7472     return Sema::Compatible;
7473   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7474     return Sema::IncompatibleObjCQualifiedId;
7475   return Sema::IncompatiblePointer;
7476 }
7477 
7478 Sema::AssignConvertType
7479 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7480                                  QualType LHSType, QualType RHSType) {
7481   // Fake up an opaque expression.  We don't actually care about what
7482   // cast operations are required, so if CheckAssignmentConstraints
7483   // adds casts to this they'll be wasted, but fortunately that doesn't
7484   // usually happen on valid code.
7485   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7486   ExprResult RHSPtr = &RHSExpr;
7487   CastKind K = CK_Invalid;
7488 
7489   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7490 }
7491 
7492 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7493 /// has code to accommodate several GCC extensions when type checking
7494 /// pointers. Here are some objectionable examples that GCC considers warnings:
7495 ///
7496 ///  int a, *pint;
7497 ///  short *pshort;
7498 ///  struct foo *pfoo;
7499 ///
7500 ///  pint = pshort; // warning: assignment from incompatible pointer type
7501 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7502 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7503 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7504 ///
7505 /// As a result, the code for dealing with pointers is more complex than the
7506 /// C99 spec dictates.
7507 ///
7508 /// Sets 'Kind' for any result kind except Incompatible.
7509 Sema::AssignConvertType
7510 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7511                                  CastKind &Kind, bool ConvertRHS) {
7512   QualType RHSType = RHS.get()->getType();
7513   QualType OrigLHSType = LHSType;
7514 
7515   // Get canonical types.  We're not formatting these types, just comparing
7516   // them.
7517   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7518   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7519 
7520   // Common case: no conversion required.
7521   if (LHSType == RHSType) {
7522     Kind = CK_NoOp;
7523     return Compatible;
7524   }
7525 
7526   // If we have an atomic type, try a non-atomic assignment, then just add an
7527   // atomic qualification step.
7528   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7529     Sema::AssignConvertType result =
7530       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7531     if (result != Compatible)
7532       return result;
7533     if (Kind != CK_NoOp && ConvertRHS)
7534       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7535     Kind = CK_NonAtomicToAtomic;
7536     return Compatible;
7537   }
7538 
7539   // If the left-hand side is a reference type, then we are in a
7540   // (rare!) case where we've allowed the use of references in C,
7541   // e.g., as a parameter type in a built-in function. In this case,
7542   // just make sure that the type referenced is compatible with the
7543   // right-hand side type. The caller is responsible for adjusting
7544   // LHSType so that the resulting expression does not have reference
7545   // type.
7546   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7547     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7548       Kind = CK_LValueBitCast;
7549       return Compatible;
7550     }
7551     return Incompatible;
7552   }
7553 
7554   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7555   // to the same ExtVector type.
7556   if (LHSType->isExtVectorType()) {
7557     if (RHSType->isExtVectorType())
7558       return Incompatible;
7559     if (RHSType->isArithmeticType()) {
7560       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7561       if (ConvertRHS)
7562         RHS = prepareVectorSplat(LHSType, RHS.get());
7563       Kind = CK_VectorSplat;
7564       return Compatible;
7565     }
7566   }
7567 
7568   // Conversions to or from vector type.
7569   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7570     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7571       // Allow assignments of an AltiVec vector type to an equivalent GCC
7572       // vector type and vice versa
7573       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7574         Kind = CK_BitCast;
7575         return Compatible;
7576       }
7577 
7578       // If we are allowing lax vector conversions, and LHS and RHS are both
7579       // vectors, the total size only needs to be the same. This is a bitcast;
7580       // no bits are changed but the result type is different.
7581       if (isLaxVectorConversion(RHSType, LHSType)) {
7582         Kind = CK_BitCast;
7583         return IncompatibleVectors;
7584       }
7585     }
7586 
7587     // When the RHS comes from another lax conversion (e.g. binops between
7588     // scalars and vectors) the result is canonicalized as a vector. When the
7589     // LHS is also a vector, the lax is allowed by the condition above. Handle
7590     // the case where LHS is a scalar.
7591     if (LHSType->isScalarType()) {
7592       const VectorType *VecType = RHSType->getAs<VectorType>();
7593       if (VecType && VecType->getNumElements() == 1 &&
7594           isLaxVectorConversion(RHSType, LHSType)) {
7595         ExprResult *VecExpr = &RHS;
7596         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7597         Kind = CK_BitCast;
7598         return Compatible;
7599       }
7600     }
7601 
7602     return Incompatible;
7603   }
7604 
7605   // Diagnose attempts to convert between __float128 and long double where
7606   // such conversions currently can't be handled.
7607   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7608     return Incompatible;
7609 
7610   // Arithmetic conversions.
7611   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7612       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7613     if (ConvertRHS)
7614       Kind = PrepareScalarCast(RHS, LHSType);
7615     return Compatible;
7616   }
7617 
7618   // Conversions to normal pointers.
7619   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7620     // U* -> T*
7621     if (isa<PointerType>(RHSType)) {
7622       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7623       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7624       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7625       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7626     }
7627 
7628     // int -> T*
7629     if (RHSType->isIntegerType()) {
7630       Kind = CK_IntegralToPointer; // FIXME: null?
7631       return IntToPointer;
7632     }
7633 
7634     // C pointers are not compatible with ObjC object pointers,
7635     // with two exceptions:
7636     if (isa<ObjCObjectPointerType>(RHSType)) {
7637       //  - conversions to void*
7638       if (LHSPointer->getPointeeType()->isVoidType()) {
7639         Kind = CK_BitCast;
7640         return Compatible;
7641       }
7642 
7643       //  - conversions from 'Class' to the redefinition type
7644       if (RHSType->isObjCClassType() &&
7645           Context.hasSameType(LHSType,
7646                               Context.getObjCClassRedefinitionType())) {
7647         Kind = CK_BitCast;
7648         return Compatible;
7649       }
7650 
7651       Kind = CK_BitCast;
7652       return IncompatiblePointer;
7653     }
7654 
7655     // U^ -> void*
7656     if (RHSType->getAs<BlockPointerType>()) {
7657       if (LHSPointer->getPointeeType()->isVoidType()) {
7658         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7659         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7660                                   ->getPointeeType()
7661                                   .getAddressSpace();
7662         Kind =
7663             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7664         return Compatible;
7665       }
7666     }
7667 
7668     return Incompatible;
7669   }
7670 
7671   // Conversions to block pointers.
7672   if (isa<BlockPointerType>(LHSType)) {
7673     // U^ -> T^
7674     if (RHSType->isBlockPointerType()) {
7675       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7676                                 ->getPointeeType()
7677                                 .getAddressSpace();
7678       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7679                                 ->getPointeeType()
7680                                 .getAddressSpace();
7681       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7682       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7683     }
7684 
7685     // int or null -> T^
7686     if (RHSType->isIntegerType()) {
7687       Kind = CK_IntegralToPointer; // FIXME: null
7688       return IntToBlockPointer;
7689     }
7690 
7691     // id -> T^
7692     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7693       Kind = CK_AnyPointerToBlockPointerCast;
7694       return Compatible;
7695     }
7696 
7697     // void* -> T^
7698     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7699       if (RHSPT->getPointeeType()->isVoidType()) {
7700         Kind = CK_AnyPointerToBlockPointerCast;
7701         return Compatible;
7702       }
7703 
7704     return Incompatible;
7705   }
7706 
7707   // Conversions to Objective-C pointers.
7708   if (isa<ObjCObjectPointerType>(LHSType)) {
7709     // A* -> B*
7710     if (RHSType->isObjCObjectPointerType()) {
7711       Kind = CK_BitCast;
7712       Sema::AssignConvertType result =
7713         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7714       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7715           result == Compatible &&
7716           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7717         result = IncompatibleObjCWeakRef;
7718       return result;
7719     }
7720 
7721     // int or null -> A*
7722     if (RHSType->isIntegerType()) {
7723       Kind = CK_IntegralToPointer; // FIXME: null
7724       return IntToPointer;
7725     }
7726 
7727     // In general, C pointers are not compatible with ObjC object pointers,
7728     // with two exceptions:
7729     if (isa<PointerType>(RHSType)) {
7730       Kind = CK_CPointerToObjCPointerCast;
7731 
7732       //  - conversions from 'void*'
7733       if (RHSType->isVoidPointerType()) {
7734         return Compatible;
7735       }
7736 
7737       //  - conversions to 'Class' from its redefinition type
7738       if (LHSType->isObjCClassType() &&
7739           Context.hasSameType(RHSType,
7740                               Context.getObjCClassRedefinitionType())) {
7741         return Compatible;
7742       }
7743 
7744       return IncompatiblePointer;
7745     }
7746 
7747     // Only under strict condition T^ is compatible with an Objective-C pointer.
7748     if (RHSType->isBlockPointerType() &&
7749         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7750       if (ConvertRHS)
7751         maybeExtendBlockObject(RHS);
7752       Kind = CK_BlockPointerToObjCPointerCast;
7753       return Compatible;
7754     }
7755 
7756     return Incompatible;
7757   }
7758 
7759   // Conversions from pointers that are not covered by the above.
7760   if (isa<PointerType>(RHSType)) {
7761     // T* -> _Bool
7762     if (LHSType == Context.BoolTy) {
7763       Kind = CK_PointerToBoolean;
7764       return Compatible;
7765     }
7766 
7767     // T* -> int
7768     if (LHSType->isIntegerType()) {
7769       Kind = CK_PointerToIntegral;
7770       return PointerToInt;
7771     }
7772 
7773     return Incompatible;
7774   }
7775 
7776   // Conversions from Objective-C pointers that are not covered by the above.
7777   if (isa<ObjCObjectPointerType>(RHSType)) {
7778     // T* -> _Bool
7779     if (LHSType == Context.BoolTy) {
7780       Kind = CK_PointerToBoolean;
7781       return Compatible;
7782     }
7783 
7784     // T* -> int
7785     if (LHSType->isIntegerType()) {
7786       Kind = CK_PointerToIntegral;
7787       return PointerToInt;
7788     }
7789 
7790     return Incompatible;
7791   }
7792 
7793   // struct A -> struct B
7794   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7795     if (Context.typesAreCompatible(LHSType, RHSType)) {
7796       Kind = CK_NoOp;
7797       return Compatible;
7798     }
7799   }
7800 
7801   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7802     Kind = CK_IntToOCLSampler;
7803     return Compatible;
7804   }
7805 
7806   return Incompatible;
7807 }
7808 
7809 /// \brief Constructs a transparent union from an expression that is
7810 /// used to initialize the transparent union.
7811 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7812                                       ExprResult &EResult, QualType UnionType,
7813                                       FieldDecl *Field) {
7814   // Build an initializer list that designates the appropriate member
7815   // of the transparent union.
7816   Expr *E = EResult.get();
7817   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7818                                                    E, SourceLocation());
7819   Initializer->setType(UnionType);
7820   Initializer->setInitializedFieldInUnion(Field);
7821 
7822   // Build a compound literal constructing a value of the transparent
7823   // union type from this initializer list.
7824   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7825   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7826                                         VK_RValue, Initializer, false);
7827 }
7828 
7829 Sema::AssignConvertType
7830 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7831                                                ExprResult &RHS) {
7832   QualType RHSType = RHS.get()->getType();
7833 
7834   // If the ArgType is a Union type, we want to handle a potential
7835   // transparent_union GCC extension.
7836   const RecordType *UT = ArgType->getAsUnionType();
7837   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7838     return Incompatible;
7839 
7840   // The field to initialize within the transparent union.
7841   RecordDecl *UD = UT->getDecl();
7842   FieldDecl *InitField = nullptr;
7843   // It's compatible if the expression matches any of the fields.
7844   for (auto *it : UD->fields()) {
7845     if (it->getType()->isPointerType()) {
7846       // If the transparent union contains a pointer type, we allow:
7847       // 1) void pointer
7848       // 2) null pointer constant
7849       if (RHSType->isPointerType())
7850         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7851           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7852           InitField = it;
7853           break;
7854         }
7855 
7856       if (RHS.get()->isNullPointerConstant(Context,
7857                                            Expr::NPC_ValueDependentIsNull)) {
7858         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7859                                 CK_NullToPointer);
7860         InitField = it;
7861         break;
7862       }
7863     }
7864 
7865     CastKind Kind = CK_Invalid;
7866     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7867           == Compatible) {
7868       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7869       InitField = it;
7870       break;
7871     }
7872   }
7873 
7874   if (!InitField)
7875     return Incompatible;
7876 
7877   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7878   return Compatible;
7879 }
7880 
7881 Sema::AssignConvertType
7882 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7883                                        bool Diagnose,
7884                                        bool DiagnoseCFAudited,
7885                                        bool ConvertRHS) {
7886   // We need to be able to tell the caller whether we diagnosed a problem, if
7887   // they ask us to issue diagnostics.
7888   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7889 
7890   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7891   // we can't avoid *all* modifications at the moment, so we need some somewhere
7892   // to put the updated value.
7893   ExprResult LocalRHS = CallerRHS;
7894   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7895 
7896   if (getLangOpts().CPlusPlus) {
7897     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7898       // C++ 5.17p3: If the left operand is not of class type, the
7899       // expression is implicitly converted (C++ 4) to the
7900       // cv-unqualified type of the left operand.
7901       QualType RHSType = RHS.get()->getType();
7902       if (Diagnose) {
7903         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7904                                         AA_Assigning);
7905       } else {
7906         ImplicitConversionSequence ICS =
7907             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7908                                   /*SuppressUserConversions=*/false,
7909                                   /*AllowExplicit=*/false,
7910                                   /*InOverloadResolution=*/false,
7911                                   /*CStyle=*/false,
7912                                   /*AllowObjCWritebackConversion=*/false);
7913         if (ICS.isFailure())
7914           return Incompatible;
7915         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7916                                         ICS, AA_Assigning);
7917       }
7918       if (RHS.isInvalid())
7919         return Incompatible;
7920       Sema::AssignConvertType result = Compatible;
7921       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7922           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7923         result = IncompatibleObjCWeakRef;
7924       return result;
7925     }
7926 
7927     // FIXME: Currently, we fall through and treat C++ classes like C
7928     // structures.
7929     // FIXME: We also fall through for atomics; not sure what should
7930     // happen there, though.
7931   } else if (RHS.get()->getType() == Context.OverloadTy) {
7932     // As a set of extensions to C, we support overloading on functions. These
7933     // functions need to be resolved here.
7934     DeclAccessPair DAP;
7935     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7936             RHS.get(), LHSType, /*Complain=*/false, DAP))
7937       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7938     else
7939       return Incompatible;
7940   }
7941 
7942   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7943   // a null pointer constant.
7944   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7945        LHSType->isBlockPointerType()) &&
7946       RHS.get()->isNullPointerConstant(Context,
7947                                        Expr::NPC_ValueDependentIsNull)) {
7948     if (Diagnose || ConvertRHS) {
7949       CastKind Kind;
7950       CXXCastPath Path;
7951       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7952                              /*IgnoreBaseAccess=*/false, Diagnose);
7953       if (ConvertRHS)
7954         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7955     }
7956     return Compatible;
7957   }
7958 
7959   // This check seems unnatural, however it is necessary to ensure the proper
7960   // conversion of functions/arrays. If the conversion were done for all
7961   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7962   // expressions that suppress this implicit conversion (&, sizeof).
7963   //
7964   // Suppress this for references: C++ 8.5.3p5.
7965   if (!LHSType->isReferenceType()) {
7966     // FIXME: We potentially allocate here even if ConvertRHS is false.
7967     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7968     if (RHS.isInvalid())
7969       return Incompatible;
7970   }
7971 
7972   Expr *PRE = RHS.get()->IgnoreParenCasts();
7973   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7974     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7975     if (PDecl && !PDecl->hasDefinition()) {
7976       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7977       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7978     }
7979   }
7980 
7981   CastKind Kind = CK_Invalid;
7982   Sema::AssignConvertType result =
7983     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7984 
7985   // C99 6.5.16.1p2: The value of the right operand is converted to the
7986   // type of the assignment expression.
7987   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7988   // so that we can use references in built-in functions even in C.
7989   // The getNonReferenceType() call makes sure that the resulting expression
7990   // does not have reference type.
7991   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7992     QualType Ty = LHSType.getNonLValueExprType(Context);
7993     Expr *E = RHS.get();
7994 
7995     // Check for various Objective-C errors. If we are not reporting
7996     // diagnostics and just checking for errors, e.g., during overload
7997     // resolution, return Incompatible to indicate the failure.
7998     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7999         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8000                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8001       if (!Diagnose)
8002         return Incompatible;
8003     }
8004     if (getLangOpts().ObjC1 &&
8005         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8006                                            E->getType(), E, Diagnose) ||
8007          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8008       if (!Diagnose)
8009         return Incompatible;
8010       // Replace the expression with a corrected version and continue so we
8011       // can find further errors.
8012       RHS = E;
8013       return Compatible;
8014     }
8015 
8016     if (ConvertRHS)
8017       RHS = ImpCastExprToType(E, Ty, Kind);
8018   }
8019   return result;
8020 }
8021 
8022 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8023                                ExprResult &RHS) {
8024   Diag(Loc, diag::err_typecheck_invalid_operands)
8025     << LHS.get()->getType() << RHS.get()->getType()
8026     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8027   return QualType();
8028 }
8029 
8030 /// Try to convert a value of non-vector type to a vector type by converting
8031 /// the type to the element type of the vector and then performing a splat.
8032 /// If the language is OpenCL, we only use conversions that promote scalar
8033 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8034 /// for float->int.
8035 ///
8036 /// \param scalar - if non-null, actually perform the conversions
8037 /// \return true if the operation fails (but without diagnosing the failure)
8038 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8039                                      QualType scalarTy,
8040                                      QualType vectorEltTy,
8041                                      QualType vectorTy) {
8042   // The conversion to apply to the scalar before splatting it,
8043   // if necessary.
8044   CastKind scalarCast = CK_Invalid;
8045 
8046   if (vectorEltTy->isIntegralType(S.Context)) {
8047     if (!scalarTy->isIntegralType(S.Context))
8048       return true;
8049     if (S.getLangOpts().OpenCL &&
8050         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8051       return true;
8052     scalarCast = CK_IntegralCast;
8053   } else if (vectorEltTy->isRealFloatingType()) {
8054     if (scalarTy->isRealFloatingType()) {
8055       if (S.getLangOpts().OpenCL &&
8056           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8057         return true;
8058       scalarCast = CK_FloatingCast;
8059     }
8060     else if (scalarTy->isIntegralType(S.Context))
8061       scalarCast = CK_IntegralToFloating;
8062     else
8063       return true;
8064   } else {
8065     return true;
8066   }
8067 
8068   // Adjust scalar if desired.
8069   if (scalar) {
8070     if (scalarCast != CK_Invalid)
8071       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8072     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8073   }
8074   return false;
8075 }
8076 
8077 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8078                                    SourceLocation Loc, bool IsCompAssign,
8079                                    bool AllowBothBool,
8080                                    bool AllowBoolConversions) {
8081   if (!IsCompAssign) {
8082     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8083     if (LHS.isInvalid())
8084       return QualType();
8085   }
8086   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8087   if (RHS.isInvalid())
8088     return QualType();
8089 
8090   // For conversion purposes, we ignore any qualifiers.
8091   // For example, "const float" and "float" are equivalent.
8092   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8093   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8094 
8095   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8096   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8097   assert(LHSVecType || RHSVecType);
8098 
8099   // AltiVec-style "vector bool op vector bool" combinations are allowed
8100   // for some operators but not others.
8101   if (!AllowBothBool &&
8102       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8103       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8104     return InvalidOperands(Loc, LHS, RHS);
8105 
8106   // If the vector types are identical, return.
8107   if (Context.hasSameType(LHSType, RHSType))
8108     return LHSType;
8109 
8110   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8111   if (LHSVecType && RHSVecType &&
8112       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8113     if (isa<ExtVectorType>(LHSVecType)) {
8114       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8115       return LHSType;
8116     }
8117 
8118     if (!IsCompAssign)
8119       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8120     return RHSType;
8121   }
8122 
8123   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8124   // can be mixed, with the result being the non-bool type.  The non-bool
8125   // operand must have integer element type.
8126   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8127       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8128       (Context.getTypeSize(LHSVecType->getElementType()) ==
8129        Context.getTypeSize(RHSVecType->getElementType()))) {
8130     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8131         LHSVecType->getElementType()->isIntegerType() &&
8132         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8133       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8134       return LHSType;
8135     }
8136     if (!IsCompAssign &&
8137         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8138         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8139         RHSVecType->getElementType()->isIntegerType()) {
8140       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8141       return RHSType;
8142     }
8143   }
8144 
8145   // If there's an ext-vector type and a scalar, try to convert the scalar to
8146   // the vector element type and splat.
8147   // FIXME: this should also work for regular vector types as supported in GCC.
8148   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8149     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8150                                   LHSVecType->getElementType(), LHSType))
8151       return LHSType;
8152   }
8153   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8154     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8155                                   LHSType, RHSVecType->getElementType(),
8156                                   RHSType))
8157       return RHSType;
8158   }
8159 
8160   // FIXME: The code below also handles conversion between vectors and
8161   // non-scalars, we should break this down into fine grained specific checks
8162   // and emit proper diagnostics.
8163   QualType VecType = LHSVecType ? LHSType : RHSType;
8164   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8165   QualType OtherType = LHSVecType ? RHSType : LHSType;
8166   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8167   if (isLaxVectorConversion(OtherType, VecType)) {
8168     // If we're allowing lax vector conversions, only the total (data) size
8169     // needs to be the same. For non compound assignment, if one of the types is
8170     // scalar, the result is always the vector type.
8171     if (!IsCompAssign) {
8172       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8173       return VecType;
8174     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8175     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8176     // type. Note that this is already done by non-compound assignments in
8177     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8178     // <1 x T> -> T. The result is also a vector type.
8179     } else if (OtherType->isExtVectorType() ||
8180                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8181       ExprResult *RHSExpr = &RHS;
8182       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8183       return VecType;
8184     }
8185   }
8186 
8187   // Okay, the expression is invalid.
8188 
8189   // If there's a non-vector, non-real operand, diagnose that.
8190   if ((!RHSVecType && !RHSType->isRealType()) ||
8191       (!LHSVecType && !LHSType->isRealType())) {
8192     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8193       << LHSType << RHSType
8194       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8195     return QualType();
8196   }
8197 
8198   // OpenCL V1.1 6.2.6.p1:
8199   // If the operands are of more than one vector type, then an error shall
8200   // occur. Implicit conversions between vector types are not permitted, per
8201   // section 6.2.1.
8202   if (getLangOpts().OpenCL &&
8203       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8204       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8205     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8206                                                            << RHSType;
8207     return QualType();
8208   }
8209 
8210   // Otherwise, use the generic diagnostic.
8211   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8212     << LHSType << RHSType
8213     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8214   return QualType();
8215 }
8216 
8217 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8218 // expression.  These are mainly cases where the null pointer is used as an
8219 // integer instead of a pointer.
8220 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8221                                 SourceLocation Loc, bool IsCompare) {
8222   // The canonical way to check for a GNU null is with isNullPointerConstant,
8223   // but we use a bit of a hack here for speed; this is a relatively
8224   // hot path, and isNullPointerConstant is slow.
8225   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8226   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8227 
8228   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8229 
8230   // Avoid analyzing cases where the result will either be invalid (and
8231   // diagnosed as such) or entirely valid and not something to warn about.
8232   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8233       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8234     return;
8235 
8236   // Comparison operations would not make sense with a null pointer no matter
8237   // what the other expression is.
8238   if (!IsCompare) {
8239     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8240         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8241         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8242     return;
8243   }
8244 
8245   // The rest of the operations only make sense with a null pointer
8246   // if the other expression is a pointer.
8247   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8248       NonNullType->canDecayToPointerType())
8249     return;
8250 
8251   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8252       << LHSNull /* LHS is NULL */ << NonNullType
8253       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8254 }
8255 
8256 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8257                                                ExprResult &RHS,
8258                                                SourceLocation Loc, bool IsDiv) {
8259   // Check for division/remainder by zero.
8260   llvm::APSInt RHSValue;
8261   if (!RHS.get()->isValueDependent() &&
8262       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8263     S.DiagRuntimeBehavior(Loc, RHS.get(),
8264                           S.PDiag(diag::warn_remainder_division_by_zero)
8265                             << IsDiv << RHS.get()->getSourceRange());
8266 }
8267 
8268 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8269                                            SourceLocation Loc,
8270                                            bool IsCompAssign, bool IsDiv) {
8271   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8272 
8273   if (LHS.get()->getType()->isVectorType() ||
8274       RHS.get()->getType()->isVectorType())
8275     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8276                                /*AllowBothBool*/getLangOpts().AltiVec,
8277                                /*AllowBoolConversions*/false);
8278 
8279   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8280   if (LHS.isInvalid() || RHS.isInvalid())
8281     return QualType();
8282 
8283 
8284   if (compType.isNull() || !compType->isArithmeticType())
8285     return InvalidOperands(Loc, LHS, RHS);
8286   if (IsDiv)
8287     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8288   return compType;
8289 }
8290 
8291 QualType Sema::CheckRemainderOperands(
8292   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8293   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8294 
8295   if (LHS.get()->getType()->isVectorType() ||
8296       RHS.get()->getType()->isVectorType()) {
8297     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8298         RHS.get()->getType()->hasIntegerRepresentation())
8299       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8300                                  /*AllowBothBool*/getLangOpts().AltiVec,
8301                                  /*AllowBoolConversions*/false);
8302     return InvalidOperands(Loc, LHS, RHS);
8303   }
8304 
8305   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8306   if (LHS.isInvalid() || RHS.isInvalid())
8307     return QualType();
8308 
8309   if (compType.isNull() || !compType->isIntegerType())
8310     return InvalidOperands(Loc, LHS, RHS);
8311   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8312   return compType;
8313 }
8314 
8315 /// \brief Diagnose invalid arithmetic on two void pointers.
8316 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8317                                                 Expr *LHSExpr, Expr *RHSExpr) {
8318   S.Diag(Loc, S.getLangOpts().CPlusPlus
8319                 ? diag::err_typecheck_pointer_arith_void_type
8320                 : diag::ext_gnu_void_ptr)
8321     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8322                             << RHSExpr->getSourceRange();
8323 }
8324 
8325 /// \brief Diagnose invalid arithmetic on a void pointer.
8326 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8327                                             Expr *Pointer) {
8328   S.Diag(Loc, S.getLangOpts().CPlusPlus
8329                 ? diag::err_typecheck_pointer_arith_void_type
8330                 : diag::ext_gnu_void_ptr)
8331     << 0 /* one pointer */ << Pointer->getSourceRange();
8332 }
8333 
8334 /// \brief Diagnose invalid arithmetic on two function pointers.
8335 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8336                                                     Expr *LHS, Expr *RHS) {
8337   assert(LHS->getType()->isAnyPointerType());
8338   assert(RHS->getType()->isAnyPointerType());
8339   S.Diag(Loc, S.getLangOpts().CPlusPlus
8340                 ? diag::err_typecheck_pointer_arith_function_type
8341                 : diag::ext_gnu_ptr_func_arith)
8342     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8343     // We only show the second type if it differs from the first.
8344     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8345                                                    RHS->getType())
8346     << RHS->getType()->getPointeeType()
8347     << LHS->getSourceRange() << RHS->getSourceRange();
8348 }
8349 
8350 /// \brief Diagnose invalid arithmetic on a function pointer.
8351 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8352                                                 Expr *Pointer) {
8353   assert(Pointer->getType()->isAnyPointerType());
8354   S.Diag(Loc, S.getLangOpts().CPlusPlus
8355                 ? diag::err_typecheck_pointer_arith_function_type
8356                 : diag::ext_gnu_ptr_func_arith)
8357     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8358     << 0 /* one pointer, so only one type */
8359     << Pointer->getSourceRange();
8360 }
8361 
8362 /// \brief Emit error if Operand is incomplete pointer type
8363 ///
8364 /// \returns True if pointer has incomplete type
8365 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8366                                                  Expr *Operand) {
8367   QualType ResType = Operand->getType();
8368   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8369     ResType = ResAtomicType->getValueType();
8370 
8371   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8372   QualType PointeeTy = ResType->getPointeeType();
8373   return S.RequireCompleteType(Loc, PointeeTy,
8374                                diag::err_typecheck_arithmetic_incomplete_type,
8375                                PointeeTy, Operand->getSourceRange());
8376 }
8377 
8378 /// \brief Check the validity of an arithmetic pointer operand.
8379 ///
8380 /// If the operand has pointer type, this code will check for pointer types
8381 /// which are invalid in arithmetic operations. These will be diagnosed
8382 /// appropriately, including whether or not the use is supported as an
8383 /// extension.
8384 ///
8385 /// \returns True when the operand is valid to use (even if as an extension).
8386 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8387                                             Expr *Operand) {
8388   QualType ResType = Operand->getType();
8389   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8390     ResType = ResAtomicType->getValueType();
8391 
8392   if (!ResType->isAnyPointerType()) return true;
8393 
8394   QualType PointeeTy = ResType->getPointeeType();
8395   if (PointeeTy->isVoidType()) {
8396     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8397     return !S.getLangOpts().CPlusPlus;
8398   }
8399   if (PointeeTy->isFunctionType()) {
8400     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8401     return !S.getLangOpts().CPlusPlus;
8402   }
8403 
8404   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8405 
8406   return true;
8407 }
8408 
8409 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8410 /// operands.
8411 ///
8412 /// This routine will diagnose any invalid arithmetic on pointer operands much
8413 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8414 /// for emitting a single diagnostic even for operations where both LHS and RHS
8415 /// are (potentially problematic) pointers.
8416 ///
8417 /// \returns True when the operand is valid to use (even if as an extension).
8418 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8419                                                 Expr *LHSExpr, Expr *RHSExpr) {
8420   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8421   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8422   if (!isLHSPointer && !isRHSPointer) return true;
8423 
8424   QualType LHSPointeeTy, RHSPointeeTy;
8425   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8426   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8427 
8428   // if both are pointers check if operation is valid wrt address spaces
8429   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8430     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8431     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8432     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8433       S.Diag(Loc,
8434              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8435           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8436           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8437       return false;
8438     }
8439   }
8440 
8441   // Check for arithmetic on pointers to incomplete types.
8442   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8443   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8444   if (isLHSVoidPtr || isRHSVoidPtr) {
8445     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8446     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8447     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8448 
8449     return !S.getLangOpts().CPlusPlus;
8450   }
8451 
8452   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8453   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8454   if (isLHSFuncPtr || isRHSFuncPtr) {
8455     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8456     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8457                                                                 RHSExpr);
8458     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8459 
8460     return !S.getLangOpts().CPlusPlus;
8461   }
8462 
8463   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8464     return false;
8465   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8466     return false;
8467 
8468   return true;
8469 }
8470 
8471 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8472 /// literal.
8473 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8474                                   Expr *LHSExpr, Expr *RHSExpr) {
8475   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8476   Expr* IndexExpr = RHSExpr;
8477   if (!StrExpr) {
8478     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8479     IndexExpr = LHSExpr;
8480   }
8481 
8482   bool IsStringPlusInt = StrExpr &&
8483       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8484   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8485     return;
8486 
8487   llvm::APSInt index;
8488   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8489     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8490     if (index.isNonNegative() &&
8491         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8492                               index.isUnsigned()))
8493       return;
8494   }
8495 
8496   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8497   Self.Diag(OpLoc, diag::warn_string_plus_int)
8498       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8499 
8500   // Only print a fixit for "str" + int, not for int + "str".
8501   if (IndexExpr == RHSExpr) {
8502     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8503     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8504         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8505         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8506         << FixItHint::CreateInsertion(EndLoc, "]");
8507   } else
8508     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8509 }
8510 
8511 /// \brief Emit a warning when adding a char literal to a string.
8512 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8513                                    Expr *LHSExpr, Expr *RHSExpr) {
8514   const Expr *StringRefExpr = LHSExpr;
8515   const CharacterLiteral *CharExpr =
8516       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8517 
8518   if (!CharExpr) {
8519     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8520     StringRefExpr = RHSExpr;
8521   }
8522 
8523   if (!CharExpr || !StringRefExpr)
8524     return;
8525 
8526   const QualType StringType = StringRefExpr->getType();
8527 
8528   // Return if not a PointerType.
8529   if (!StringType->isAnyPointerType())
8530     return;
8531 
8532   // Return if not a CharacterType.
8533   if (!StringType->getPointeeType()->isAnyCharacterType())
8534     return;
8535 
8536   ASTContext &Ctx = Self.getASTContext();
8537   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8538 
8539   const QualType CharType = CharExpr->getType();
8540   if (!CharType->isAnyCharacterType() &&
8541       CharType->isIntegerType() &&
8542       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8543     Self.Diag(OpLoc, diag::warn_string_plus_char)
8544         << DiagRange << Ctx.CharTy;
8545   } else {
8546     Self.Diag(OpLoc, diag::warn_string_plus_char)
8547         << DiagRange << CharExpr->getType();
8548   }
8549 
8550   // Only print a fixit for str + char, not for char + str.
8551   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8552     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8553     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8554         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8555         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8556         << FixItHint::CreateInsertion(EndLoc, "]");
8557   } else {
8558     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8559   }
8560 }
8561 
8562 /// \brief Emit error when two pointers are incompatible.
8563 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8564                                            Expr *LHSExpr, Expr *RHSExpr) {
8565   assert(LHSExpr->getType()->isAnyPointerType());
8566   assert(RHSExpr->getType()->isAnyPointerType());
8567   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8568     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8569     << RHSExpr->getSourceRange();
8570 }
8571 
8572 // C99 6.5.6
8573 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8574                                      SourceLocation Loc, BinaryOperatorKind Opc,
8575                                      QualType* CompLHSTy) {
8576   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8577 
8578   if (LHS.get()->getType()->isVectorType() ||
8579       RHS.get()->getType()->isVectorType()) {
8580     QualType compType = CheckVectorOperands(
8581         LHS, RHS, Loc, CompLHSTy,
8582         /*AllowBothBool*/getLangOpts().AltiVec,
8583         /*AllowBoolConversions*/getLangOpts().ZVector);
8584     if (CompLHSTy) *CompLHSTy = compType;
8585     return compType;
8586   }
8587 
8588   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8589   if (LHS.isInvalid() || RHS.isInvalid())
8590     return QualType();
8591 
8592   // Diagnose "string literal" '+' int and string '+' "char literal".
8593   if (Opc == BO_Add) {
8594     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8595     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8596   }
8597 
8598   // handle the common case first (both operands are arithmetic).
8599   if (!compType.isNull() && compType->isArithmeticType()) {
8600     if (CompLHSTy) *CompLHSTy = compType;
8601     return compType;
8602   }
8603 
8604   // Type-checking.  Ultimately the pointer's going to be in PExp;
8605   // note that we bias towards the LHS being the pointer.
8606   Expr *PExp = LHS.get(), *IExp = RHS.get();
8607 
8608   bool isObjCPointer;
8609   if (PExp->getType()->isPointerType()) {
8610     isObjCPointer = false;
8611   } else if (PExp->getType()->isObjCObjectPointerType()) {
8612     isObjCPointer = true;
8613   } else {
8614     std::swap(PExp, IExp);
8615     if (PExp->getType()->isPointerType()) {
8616       isObjCPointer = false;
8617     } else if (PExp->getType()->isObjCObjectPointerType()) {
8618       isObjCPointer = true;
8619     } else {
8620       return InvalidOperands(Loc, LHS, RHS);
8621     }
8622   }
8623   assert(PExp->getType()->isAnyPointerType());
8624 
8625   if (!IExp->getType()->isIntegerType())
8626     return InvalidOperands(Loc, LHS, RHS);
8627 
8628   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8629     return QualType();
8630 
8631   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8632     return QualType();
8633 
8634   // Check array bounds for pointer arithemtic
8635   CheckArrayAccess(PExp, IExp);
8636 
8637   if (CompLHSTy) {
8638     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8639     if (LHSTy.isNull()) {
8640       LHSTy = LHS.get()->getType();
8641       if (LHSTy->isPromotableIntegerType())
8642         LHSTy = Context.getPromotedIntegerType(LHSTy);
8643     }
8644     *CompLHSTy = LHSTy;
8645   }
8646 
8647   return PExp->getType();
8648 }
8649 
8650 // C99 6.5.6
8651 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8652                                         SourceLocation Loc,
8653                                         QualType* CompLHSTy) {
8654   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8655 
8656   if (LHS.get()->getType()->isVectorType() ||
8657       RHS.get()->getType()->isVectorType()) {
8658     QualType compType = CheckVectorOperands(
8659         LHS, RHS, Loc, CompLHSTy,
8660         /*AllowBothBool*/getLangOpts().AltiVec,
8661         /*AllowBoolConversions*/getLangOpts().ZVector);
8662     if (CompLHSTy) *CompLHSTy = compType;
8663     return compType;
8664   }
8665 
8666   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8667   if (LHS.isInvalid() || RHS.isInvalid())
8668     return QualType();
8669 
8670   // Enforce type constraints: C99 6.5.6p3.
8671 
8672   // Handle the common case first (both operands are arithmetic).
8673   if (!compType.isNull() && compType->isArithmeticType()) {
8674     if (CompLHSTy) *CompLHSTy = compType;
8675     return compType;
8676   }
8677 
8678   // Either ptr - int   or   ptr - ptr.
8679   if (LHS.get()->getType()->isAnyPointerType()) {
8680     QualType lpointee = LHS.get()->getType()->getPointeeType();
8681 
8682     // Diagnose bad cases where we step over interface counts.
8683     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8684         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8685       return QualType();
8686 
8687     // The result type of a pointer-int computation is the pointer type.
8688     if (RHS.get()->getType()->isIntegerType()) {
8689       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8690         return QualType();
8691 
8692       // Check array bounds for pointer arithemtic
8693       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8694                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8695 
8696       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8697       return LHS.get()->getType();
8698     }
8699 
8700     // Handle pointer-pointer subtractions.
8701     if (const PointerType *RHSPTy
8702           = RHS.get()->getType()->getAs<PointerType>()) {
8703       QualType rpointee = RHSPTy->getPointeeType();
8704 
8705       if (getLangOpts().CPlusPlus) {
8706         // Pointee types must be the same: C++ [expr.add]
8707         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8708           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8709         }
8710       } else {
8711         // Pointee types must be compatible C99 6.5.6p3
8712         if (!Context.typesAreCompatible(
8713                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8714                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8715           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8716           return QualType();
8717         }
8718       }
8719 
8720       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8721                                                LHS.get(), RHS.get()))
8722         return QualType();
8723 
8724       // The pointee type may have zero size.  As an extension, a structure or
8725       // union may have zero size or an array may have zero length.  In this
8726       // case subtraction does not make sense.
8727       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8728         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8729         if (ElementSize.isZero()) {
8730           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8731             << rpointee.getUnqualifiedType()
8732             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8733         }
8734       }
8735 
8736       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8737       return Context.getPointerDiffType();
8738     }
8739   }
8740 
8741   return InvalidOperands(Loc, LHS, RHS);
8742 }
8743 
8744 static bool isScopedEnumerationType(QualType T) {
8745   if (const EnumType *ET = T->getAs<EnumType>())
8746     return ET->getDecl()->isScoped();
8747   return false;
8748 }
8749 
8750 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8751                                    SourceLocation Loc, BinaryOperatorKind Opc,
8752                                    QualType LHSType) {
8753   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8754   // so skip remaining warnings as we don't want to modify values within Sema.
8755   if (S.getLangOpts().OpenCL)
8756     return;
8757 
8758   llvm::APSInt Right;
8759   // Check right/shifter operand
8760   if (RHS.get()->isValueDependent() ||
8761       !RHS.get()->EvaluateAsInt(Right, S.Context))
8762     return;
8763 
8764   if (Right.isNegative()) {
8765     S.DiagRuntimeBehavior(Loc, RHS.get(),
8766                           S.PDiag(diag::warn_shift_negative)
8767                             << RHS.get()->getSourceRange());
8768     return;
8769   }
8770   llvm::APInt LeftBits(Right.getBitWidth(),
8771                        S.Context.getTypeSize(LHS.get()->getType()));
8772   if (Right.uge(LeftBits)) {
8773     S.DiagRuntimeBehavior(Loc, RHS.get(),
8774                           S.PDiag(diag::warn_shift_gt_typewidth)
8775                             << RHS.get()->getSourceRange());
8776     return;
8777   }
8778   if (Opc != BO_Shl)
8779     return;
8780 
8781   // When left shifting an ICE which is signed, we can check for overflow which
8782   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8783   // integers have defined behavior modulo one more than the maximum value
8784   // representable in the result type, so never warn for those.
8785   llvm::APSInt Left;
8786   if (LHS.get()->isValueDependent() ||
8787       LHSType->hasUnsignedIntegerRepresentation() ||
8788       !LHS.get()->EvaluateAsInt(Left, S.Context))
8789     return;
8790 
8791   // If LHS does not have a signed type and non-negative value
8792   // then, the behavior is undefined. Warn about it.
8793   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8794     S.DiagRuntimeBehavior(Loc, LHS.get(),
8795                           S.PDiag(diag::warn_shift_lhs_negative)
8796                             << LHS.get()->getSourceRange());
8797     return;
8798   }
8799 
8800   llvm::APInt ResultBits =
8801       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8802   if (LeftBits.uge(ResultBits))
8803     return;
8804   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8805   Result = Result.shl(Right);
8806 
8807   // Print the bit representation of the signed integer as an unsigned
8808   // hexadecimal number.
8809   SmallString<40> HexResult;
8810   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8811 
8812   // If we are only missing a sign bit, this is less likely to result in actual
8813   // bugs -- if the result is cast back to an unsigned type, it will have the
8814   // expected value. Thus we place this behind a different warning that can be
8815   // turned off separately if needed.
8816   if (LeftBits == ResultBits - 1) {
8817     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8818         << HexResult << LHSType
8819         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8820     return;
8821   }
8822 
8823   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8824     << HexResult.str() << Result.getMinSignedBits() << LHSType
8825     << Left.getBitWidth() << LHS.get()->getSourceRange()
8826     << RHS.get()->getSourceRange();
8827 }
8828 
8829 /// \brief Return the resulting type when a vector is shifted
8830 ///        by a scalar or vector shift amount.
8831 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8832                                  SourceLocation Loc, bool IsCompAssign) {
8833   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8834   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8835       !LHS.get()->getType()->isVectorType()) {
8836     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8837       << RHS.get()->getType() << LHS.get()->getType()
8838       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8839     return QualType();
8840   }
8841 
8842   if (!IsCompAssign) {
8843     LHS = S.UsualUnaryConversions(LHS.get());
8844     if (LHS.isInvalid()) return QualType();
8845   }
8846 
8847   RHS = S.UsualUnaryConversions(RHS.get());
8848   if (RHS.isInvalid()) return QualType();
8849 
8850   QualType LHSType = LHS.get()->getType();
8851   // Note that LHS might be a scalar because the routine calls not only in
8852   // OpenCL case.
8853   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8854   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8855 
8856   // Note that RHS might not be a vector.
8857   QualType RHSType = RHS.get()->getType();
8858   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8859   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8860 
8861   // The operands need to be integers.
8862   if (!LHSEleType->isIntegerType()) {
8863     S.Diag(Loc, diag::err_typecheck_expect_int)
8864       << LHS.get()->getType() << LHS.get()->getSourceRange();
8865     return QualType();
8866   }
8867 
8868   if (!RHSEleType->isIntegerType()) {
8869     S.Diag(Loc, diag::err_typecheck_expect_int)
8870       << RHS.get()->getType() << RHS.get()->getSourceRange();
8871     return QualType();
8872   }
8873 
8874   if (!LHSVecTy) {
8875     assert(RHSVecTy);
8876     if (IsCompAssign)
8877       return RHSType;
8878     if (LHSEleType != RHSEleType) {
8879       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8880       LHSEleType = RHSEleType;
8881     }
8882     QualType VecTy =
8883         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8884     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8885     LHSType = VecTy;
8886   } else if (RHSVecTy) {
8887     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8888     // are applied component-wise. So if RHS is a vector, then ensure
8889     // that the number of elements is the same as LHS...
8890     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8891       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8892         << LHS.get()->getType() << RHS.get()->getType()
8893         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8894       return QualType();
8895     }
8896     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8897       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8898       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8899       if (LHSBT != RHSBT &&
8900           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8901         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8902             << LHS.get()->getType() << RHS.get()->getType()
8903             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8904       }
8905     }
8906   } else {
8907     // ...else expand RHS to match the number of elements in LHS.
8908     QualType VecTy =
8909       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8910     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8911   }
8912 
8913   return LHSType;
8914 }
8915 
8916 // C99 6.5.7
8917 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8918                                   SourceLocation Loc, BinaryOperatorKind Opc,
8919                                   bool IsCompAssign) {
8920   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8921 
8922   // Vector shifts promote their scalar inputs to vector type.
8923   if (LHS.get()->getType()->isVectorType() ||
8924       RHS.get()->getType()->isVectorType()) {
8925     if (LangOpts.ZVector) {
8926       // The shift operators for the z vector extensions work basically
8927       // like general shifts, except that neither the LHS nor the RHS is
8928       // allowed to be a "vector bool".
8929       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8930         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8931           return InvalidOperands(Loc, LHS, RHS);
8932       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8933         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8934           return InvalidOperands(Loc, LHS, RHS);
8935     }
8936     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8937   }
8938 
8939   // Shifts don't perform usual arithmetic conversions, they just do integer
8940   // promotions on each operand. C99 6.5.7p3
8941 
8942   // For the LHS, do usual unary conversions, but then reset them away
8943   // if this is a compound assignment.
8944   ExprResult OldLHS = LHS;
8945   LHS = UsualUnaryConversions(LHS.get());
8946   if (LHS.isInvalid())
8947     return QualType();
8948   QualType LHSType = LHS.get()->getType();
8949   if (IsCompAssign) LHS = OldLHS;
8950 
8951   // The RHS is simpler.
8952   RHS = UsualUnaryConversions(RHS.get());
8953   if (RHS.isInvalid())
8954     return QualType();
8955   QualType RHSType = RHS.get()->getType();
8956 
8957   // C99 6.5.7p2: Each of the operands shall have integer type.
8958   if (!LHSType->hasIntegerRepresentation() ||
8959       !RHSType->hasIntegerRepresentation())
8960     return InvalidOperands(Loc, LHS, RHS);
8961 
8962   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8963   // hasIntegerRepresentation() above instead of this.
8964   if (isScopedEnumerationType(LHSType) ||
8965       isScopedEnumerationType(RHSType)) {
8966     return InvalidOperands(Loc, LHS, RHS);
8967   }
8968   // Sanity-check shift operands
8969   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8970 
8971   // "The type of the result is that of the promoted left operand."
8972   return LHSType;
8973 }
8974 
8975 static bool IsWithinTemplateSpecialization(Decl *D) {
8976   if (DeclContext *DC = D->getDeclContext()) {
8977     if (isa<ClassTemplateSpecializationDecl>(DC))
8978       return true;
8979     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8980       return FD->isFunctionTemplateSpecialization();
8981   }
8982   return false;
8983 }
8984 
8985 /// If two different enums are compared, raise a warning.
8986 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8987                                 Expr *RHS) {
8988   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8989   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8990 
8991   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8992   if (!LHSEnumType)
8993     return;
8994   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8995   if (!RHSEnumType)
8996     return;
8997 
8998   // Ignore anonymous enums.
8999   if (!LHSEnumType->getDecl()->getIdentifier())
9000     return;
9001   if (!RHSEnumType->getDecl()->getIdentifier())
9002     return;
9003 
9004   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9005     return;
9006 
9007   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9008       << LHSStrippedType << RHSStrippedType
9009       << LHS->getSourceRange() << RHS->getSourceRange();
9010 }
9011 
9012 /// \brief Diagnose bad pointer comparisons.
9013 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9014                                               ExprResult &LHS, ExprResult &RHS,
9015                                               bool IsError) {
9016   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9017                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9018     << LHS.get()->getType() << RHS.get()->getType()
9019     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9020 }
9021 
9022 /// \brief Returns false if the pointers are converted to a composite type,
9023 /// true otherwise.
9024 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9025                                            ExprResult &LHS, ExprResult &RHS) {
9026   // C++ [expr.rel]p2:
9027   //   [...] Pointer conversions (4.10) and qualification
9028   //   conversions (4.4) are performed on pointer operands (or on
9029   //   a pointer operand and a null pointer constant) to bring
9030   //   them to their composite pointer type. [...]
9031   //
9032   // C++ [expr.eq]p1 uses the same notion for (in)equality
9033   // comparisons of pointers.
9034 
9035   QualType LHSType = LHS.get()->getType();
9036   QualType RHSType = RHS.get()->getType();
9037   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9038          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9039 
9040   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9041   if (T.isNull()) {
9042     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9043         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9044       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9045     else
9046       S.InvalidOperands(Loc, LHS, RHS);
9047     return true;
9048   }
9049 
9050   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9051   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9052   return false;
9053 }
9054 
9055 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9056                                                     ExprResult &LHS,
9057                                                     ExprResult &RHS,
9058                                                     bool IsError) {
9059   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9060                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9061     << LHS.get()->getType() << RHS.get()->getType()
9062     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9063 }
9064 
9065 static bool isObjCObjectLiteral(ExprResult &E) {
9066   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9067   case Stmt::ObjCArrayLiteralClass:
9068   case Stmt::ObjCDictionaryLiteralClass:
9069   case Stmt::ObjCStringLiteralClass:
9070   case Stmt::ObjCBoxedExprClass:
9071     return true;
9072   default:
9073     // Note that ObjCBoolLiteral is NOT an object literal!
9074     return false;
9075   }
9076 }
9077 
9078 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9079   const ObjCObjectPointerType *Type =
9080     LHS->getType()->getAs<ObjCObjectPointerType>();
9081 
9082   // If this is not actually an Objective-C object, bail out.
9083   if (!Type)
9084     return false;
9085 
9086   // Get the LHS object's interface type.
9087   QualType InterfaceType = Type->getPointeeType();
9088 
9089   // If the RHS isn't an Objective-C object, bail out.
9090   if (!RHS->getType()->isObjCObjectPointerType())
9091     return false;
9092 
9093   // Try to find the -isEqual: method.
9094   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9095   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9096                                                       InterfaceType,
9097                                                       /*instance=*/true);
9098   if (!Method) {
9099     if (Type->isObjCIdType()) {
9100       // For 'id', just check the global pool.
9101       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9102                                                   /*receiverId=*/true);
9103     } else {
9104       // Check protocols.
9105       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9106                                              /*instance=*/true);
9107     }
9108   }
9109 
9110   if (!Method)
9111     return false;
9112 
9113   QualType T = Method->parameters()[0]->getType();
9114   if (!T->isObjCObjectPointerType())
9115     return false;
9116 
9117   QualType R = Method->getReturnType();
9118   if (!R->isScalarType())
9119     return false;
9120 
9121   return true;
9122 }
9123 
9124 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9125   FromE = FromE->IgnoreParenImpCasts();
9126   switch (FromE->getStmtClass()) {
9127     default:
9128       break;
9129     case Stmt::ObjCStringLiteralClass:
9130       // "string literal"
9131       return LK_String;
9132     case Stmt::ObjCArrayLiteralClass:
9133       // "array literal"
9134       return LK_Array;
9135     case Stmt::ObjCDictionaryLiteralClass:
9136       // "dictionary literal"
9137       return LK_Dictionary;
9138     case Stmt::BlockExprClass:
9139       return LK_Block;
9140     case Stmt::ObjCBoxedExprClass: {
9141       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9142       switch (Inner->getStmtClass()) {
9143         case Stmt::IntegerLiteralClass:
9144         case Stmt::FloatingLiteralClass:
9145         case Stmt::CharacterLiteralClass:
9146         case Stmt::ObjCBoolLiteralExprClass:
9147         case Stmt::CXXBoolLiteralExprClass:
9148           // "numeric literal"
9149           return LK_Numeric;
9150         case Stmt::ImplicitCastExprClass: {
9151           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9152           // Boolean literals can be represented by implicit casts.
9153           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9154             return LK_Numeric;
9155           break;
9156         }
9157         default:
9158           break;
9159       }
9160       return LK_Boxed;
9161     }
9162   }
9163   return LK_None;
9164 }
9165 
9166 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9167                                           ExprResult &LHS, ExprResult &RHS,
9168                                           BinaryOperator::Opcode Opc){
9169   Expr *Literal;
9170   Expr *Other;
9171   if (isObjCObjectLiteral(LHS)) {
9172     Literal = LHS.get();
9173     Other = RHS.get();
9174   } else {
9175     Literal = RHS.get();
9176     Other = LHS.get();
9177   }
9178 
9179   // Don't warn on comparisons against nil.
9180   Other = Other->IgnoreParenCasts();
9181   if (Other->isNullPointerConstant(S.getASTContext(),
9182                                    Expr::NPC_ValueDependentIsNotNull))
9183     return;
9184 
9185   // This should be kept in sync with warn_objc_literal_comparison.
9186   // LK_String should always be after the other literals, since it has its own
9187   // warning flag.
9188   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9189   assert(LiteralKind != Sema::LK_Block);
9190   if (LiteralKind == Sema::LK_None) {
9191     llvm_unreachable("Unknown Objective-C object literal kind");
9192   }
9193 
9194   if (LiteralKind == Sema::LK_String)
9195     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9196       << Literal->getSourceRange();
9197   else
9198     S.Diag(Loc, diag::warn_objc_literal_comparison)
9199       << LiteralKind << Literal->getSourceRange();
9200 
9201   if (BinaryOperator::isEqualityOp(Opc) &&
9202       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9203     SourceLocation Start = LHS.get()->getLocStart();
9204     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9205     CharSourceRange OpRange =
9206       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9207 
9208     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9209       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9210       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9211       << FixItHint::CreateInsertion(End, "]");
9212   }
9213 }
9214 
9215 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9216 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9217                                            ExprResult &RHS, SourceLocation Loc,
9218                                            BinaryOperatorKind Opc) {
9219   // Check that left hand side is !something.
9220   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9221   if (!UO || UO->getOpcode() != UO_LNot) return;
9222 
9223   // Only check if the right hand side is non-bool arithmetic type.
9224   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9225 
9226   // Make sure that the something in !something is not bool.
9227   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9228   if (SubExpr->isKnownToHaveBooleanValue()) return;
9229 
9230   // Emit warning.
9231   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9232   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9233       << Loc << IsBitwiseOp;
9234 
9235   // First note suggest !(x < y)
9236   SourceLocation FirstOpen = SubExpr->getLocStart();
9237   SourceLocation FirstClose = RHS.get()->getLocEnd();
9238   FirstClose = S.getLocForEndOfToken(FirstClose);
9239   if (FirstClose.isInvalid())
9240     FirstOpen = SourceLocation();
9241   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9242       << IsBitwiseOp
9243       << FixItHint::CreateInsertion(FirstOpen, "(")
9244       << FixItHint::CreateInsertion(FirstClose, ")");
9245 
9246   // Second note suggests (!x) < y
9247   SourceLocation SecondOpen = LHS.get()->getLocStart();
9248   SourceLocation SecondClose = LHS.get()->getLocEnd();
9249   SecondClose = S.getLocForEndOfToken(SecondClose);
9250   if (SecondClose.isInvalid())
9251     SecondOpen = SourceLocation();
9252   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9253       << FixItHint::CreateInsertion(SecondOpen, "(")
9254       << FixItHint::CreateInsertion(SecondClose, ")");
9255 }
9256 
9257 // Get the decl for a simple expression: a reference to a variable,
9258 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9259 static ValueDecl *getCompareDecl(Expr *E) {
9260   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9261     return DR->getDecl();
9262   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9263     if (Ivar->isFreeIvar())
9264       return Ivar->getDecl();
9265   }
9266   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9267     if (Mem->isImplicitAccess())
9268       return Mem->getMemberDecl();
9269   }
9270   return nullptr;
9271 }
9272 
9273 // C99 6.5.8, C++ [expr.rel]
9274 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9275                                     SourceLocation Loc, BinaryOperatorKind Opc,
9276                                     bool IsRelational) {
9277   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9278 
9279   // Handle vector comparisons separately.
9280   if (LHS.get()->getType()->isVectorType() ||
9281       RHS.get()->getType()->isVectorType())
9282     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9283 
9284   QualType LHSType = LHS.get()->getType();
9285   QualType RHSType = RHS.get()->getType();
9286 
9287   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9288   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9289 
9290   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9291   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9292 
9293   if (!LHSType->hasFloatingRepresentation() &&
9294       !(LHSType->isBlockPointerType() && IsRelational) &&
9295       !LHS.get()->getLocStart().isMacroID() &&
9296       !RHS.get()->getLocStart().isMacroID() &&
9297       !inTemplateInstantiation()) {
9298     // For non-floating point types, check for self-comparisons of the form
9299     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9300     // often indicate logic errors in the program.
9301     //
9302     // NOTE: Don't warn about comparison expressions resulting from macro
9303     // expansion. Also don't warn about comparisons which are only self
9304     // comparisons within a template specialization. The warnings should catch
9305     // obvious cases in the definition of the template anyways. The idea is to
9306     // warn when the typed comparison operator will always evaluate to the same
9307     // result.
9308     ValueDecl *DL = getCompareDecl(LHSStripped);
9309     ValueDecl *DR = getCompareDecl(RHSStripped);
9310     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9311       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9312                           << 0 // self-
9313                           << (Opc == BO_EQ
9314                               || Opc == BO_LE
9315                               || Opc == BO_GE));
9316     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9317                !DL->getType()->isReferenceType() &&
9318                !DR->getType()->isReferenceType()) {
9319         // what is it always going to eval to?
9320         char always_evals_to;
9321         switch(Opc) {
9322         case BO_EQ: // e.g. array1 == array2
9323           always_evals_to = 0; // false
9324           break;
9325         case BO_NE: // e.g. array1 != array2
9326           always_evals_to = 1; // true
9327           break;
9328         default:
9329           // best we can say is 'a constant'
9330           always_evals_to = 2; // e.g. array1 <= array2
9331           break;
9332         }
9333         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9334                             << 1 // array
9335                             << always_evals_to);
9336     }
9337 
9338     if (isa<CastExpr>(LHSStripped))
9339       LHSStripped = LHSStripped->IgnoreParenCasts();
9340     if (isa<CastExpr>(RHSStripped))
9341       RHSStripped = RHSStripped->IgnoreParenCasts();
9342 
9343     // Warn about comparisons against a string constant (unless the other
9344     // operand is null), the user probably wants strcmp.
9345     Expr *literalString = nullptr;
9346     Expr *literalStringStripped = nullptr;
9347     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9348         !RHSStripped->isNullPointerConstant(Context,
9349                                             Expr::NPC_ValueDependentIsNull)) {
9350       literalString = LHS.get();
9351       literalStringStripped = LHSStripped;
9352     } else if ((isa<StringLiteral>(RHSStripped) ||
9353                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9354                !LHSStripped->isNullPointerConstant(Context,
9355                                             Expr::NPC_ValueDependentIsNull)) {
9356       literalString = RHS.get();
9357       literalStringStripped = RHSStripped;
9358     }
9359 
9360     if (literalString) {
9361       DiagRuntimeBehavior(Loc, nullptr,
9362         PDiag(diag::warn_stringcompare)
9363           << isa<ObjCEncodeExpr>(literalStringStripped)
9364           << literalString->getSourceRange());
9365     }
9366   }
9367 
9368   // C99 6.5.8p3 / C99 6.5.9p4
9369   UsualArithmeticConversions(LHS, RHS);
9370   if (LHS.isInvalid() || RHS.isInvalid())
9371     return QualType();
9372 
9373   LHSType = LHS.get()->getType();
9374   RHSType = RHS.get()->getType();
9375 
9376   // The result of comparisons is 'bool' in C++, 'int' in C.
9377   QualType ResultTy = Context.getLogicalOperationType();
9378 
9379   if (IsRelational) {
9380     if (LHSType->isRealType() && RHSType->isRealType())
9381       return ResultTy;
9382   } else {
9383     // Check for comparisons of floating point operands using != and ==.
9384     if (LHSType->hasFloatingRepresentation())
9385       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9386 
9387     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9388       return ResultTy;
9389   }
9390 
9391   const Expr::NullPointerConstantKind LHSNullKind =
9392       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9393   const Expr::NullPointerConstantKind RHSNullKind =
9394       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9395   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9396   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9397 
9398   if (!IsRelational && LHSIsNull != RHSIsNull) {
9399     bool IsEquality = Opc == BO_EQ;
9400     if (RHSIsNull)
9401       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9402                                    RHS.get()->getSourceRange());
9403     else
9404       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9405                                    LHS.get()->getSourceRange());
9406   }
9407 
9408   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9409       (RHSType->isIntegerType() && !RHSIsNull)) {
9410     // Skip normal pointer conversion checks in this case; we have better
9411     // diagnostics for this below.
9412   } else if (getLangOpts().CPlusPlus) {
9413     // Equality comparison of a function pointer to a void pointer is invalid,
9414     // but we allow it as an extension.
9415     // FIXME: If we really want to allow this, should it be part of composite
9416     // pointer type computation so it works in conditionals too?
9417     if (!IsRelational &&
9418         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9419          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9420       // This is a gcc extension compatibility comparison.
9421       // In a SFINAE context, we treat this as a hard error to maintain
9422       // conformance with the C++ standard.
9423       diagnoseFunctionPointerToVoidComparison(
9424           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9425 
9426       if (isSFINAEContext())
9427         return QualType();
9428 
9429       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9430       return ResultTy;
9431     }
9432 
9433     // C++ [expr.eq]p2:
9434     //   If at least one operand is a pointer [...] bring them to their
9435     //   composite pointer type.
9436     // C++ [expr.rel]p2:
9437     //   If both operands are pointers, [...] bring them to their composite
9438     //   pointer type.
9439     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9440             (IsRelational ? 2 : 1) &&
9441         (!LangOpts.ObjCAutoRefCount ||
9442          !(LHSType->isObjCObjectPointerType() ||
9443            RHSType->isObjCObjectPointerType()))) {
9444       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9445         return QualType();
9446       else
9447         return ResultTy;
9448     }
9449   } else if (LHSType->isPointerType() &&
9450              RHSType->isPointerType()) { // C99 6.5.8p2
9451     // All of the following pointer-related warnings are GCC extensions, except
9452     // when handling null pointer constants.
9453     QualType LCanPointeeTy =
9454       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9455     QualType RCanPointeeTy =
9456       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9457 
9458     // C99 6.5.9p2 and C99 6.5.8p2
9459     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9460                                    RCanPointeeTy.getUnqualifiedType())) {
9461       // Valid unless a relational comparison of function pointers
9462       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9463         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9464           << LHSType << RHSType << LHS.get()->getSourceRange()
9465           << RHS.get()->getSourceRange();
9466       }
9467     } else if (!IsRelational &&
9468                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9469       // Valid unless comparison between non-null pointer and function pointer
9470       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9471           && !LHSIsNull && !RHSIsNull)
9472         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9473                                                 /*isError*/false);
9474     } else {
9475       // Invalid
9476       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9477     }
9478     if (LCanPointeeTy != RCanPointeeTy) {
9479       // Treat NULL constant as a special case in OpenCL.
9480       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9481         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9482         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9483           Diag(Loc,
9484                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9485               << LHSType << RHSType << 0 /* comparison */
9486               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9487         }
9488       }
9489       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9490       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9491       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9492                                                : CK_BitCast;
9493       if (LHSIsNull && !RHSIsNull)
9494         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9495       else
9496         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9497     }
9498     return ResultTy;
9499   }
9500 
9501   if (getLangOpts().CPlusPlus) {
9502     // C++ [expr.eq]p4:
9503     //   Two operands of type std::nullptr_t or one operand of type
9504     //   std::nullptr_t and the other a null pointer constant compare equal.
9505     if (!IsRelational && LHSIsNull && RHSIsNull) {
9506       if (LHSType->isNullPtrType()) {
9507         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9508         return ResultTy;
9509       }
9510       if (RHSType->isNullPtrType()) {
9511         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9512         return ResultTy;
9513       }
9514     }
9515 
9516     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9517     // These aren't covered by the composite pointer type rules.
9518     if (!IsRelational && RHSType->isNullPtrType() &&
9519         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9520       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9521       return ResultTy;
9522     }
9523     if (!IsRelational && LHSType->isNullPtrType() &&
9524         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9525       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9526       return ResultTy;
9527     }
9528 
9529     if (IsRelational &&
9530         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9531          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9532       // HACK: Relational comparison of nullptr_t against a pointer type is
9533       // invalid per DR583, but we allow it within std::less<> and friends,
9534       // since otherwise common uses of it break.
9535       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9536       // friends to have std::nullptr_t overload candidates.
9537       DeclContext *DC = CurContext;
9538       if (isa<FunctionDecl>(DC))
9539         DC = DC->getParent();
9540       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9541         if (CTSD->isInStdNamespace() &&
9542             llvm::StringSwitch<bool>(CTSD->getName())
9543                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9544                 .Default(false)) {
9545           if (RHSType->isNullPtrType())
9546             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9547           else
9548             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9549           return ResultTy;
9550         }
9551       }
9552     }
9553 
9554     // C++ [expr.eq]p2:
9555     //   If at least one operand is a pointer to member, [...] bring them to
9556     //   their composite pointer type.
9557     if (!IsRelational &&
9558         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9559       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9560         return QualType();
9561       else
9562         return ResultTy;
9563     }
9564 
9565     // Handle scoped enumeration types specifically, since they don't promote
9566     // to integers.
9567     if (LHS.get()->getType()->isEnumeralType() &&
9568         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9569                                        RHS.get()->getType()))
9570       return ResultTy;
9571   }
9572 
9573   // Handle block pointer types.
9574   if (!IsRelational && LHSType->isBlockPointerType() &&
9575       RHSType->isBlockPointerType()) {
9576     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9577     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9578 
9579     if (!LHSIsNull && !RHSIsNull &&
9580         !Context.typesAreCompatible(lpointee, rpointee)) {
9581       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9582         << LHSType << RHSType << LHS.get()->getSourceRange()
9583         << RHS.get()->getSourceRange();
9584     }
9585     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9586     return ResultTy;
9587   }
9588 
9589   // Allow block pointers to be compared with null pointer constants.
9590   if (!IsRelational
9591       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9592           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9593     if (!LHSIsNull && !RHSIsNull) {
9594       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9595              ->getPointeeType()->isVoidType())
9596             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9597                 ->getPointeeType()->isVoidType())))
9598         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9599           << LHSType << RHSType << LHS.get()->getSourceRange()
9600           << RHS.get()->getSourceRange();
9601     }
9602     if (LHSIsNull && !RHSIsNull)
9603       LHS = ImpCastExprToType(LHS.get(), RHSType,
9604                               RHSType->isPointerType() ? CK_BitCast
9605                                 : CK_AnyPointerToBlockPointerCast);
9606     else
9607       RHS = ImpCastExprToType(RHS.get(), LHSType,
9608                               LHSType->isPointerType() ? CK_BitCast
9609                                 : CK_AnyPointerToBlockPointerCast);
9610     return ResultTy;
9611   }
9612 
9613   if (LHSType->isObjCObjectPointerType() ||
9614       RHSType->isObjCObjectPointerType()) {
9615     const PointerType *LPT = LHSType->getAs<PointerType>();
9616     const PointerType *RPT = RHSType->getAs<PointerType>();
9617     if (LPT || RPT) {
9618       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9619       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9620 
9621       if (!LPtrToVoid && !RPtrToVoid &&
9622           !Context.typesAreCompatible(LHSType, RHSType)) {
9623         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9624                                           /*isError*/false);
9625       }
9626       if (LHSIsNull && !RHSIsNull) {
9627         Expr *E = LHS.get();
9628         if (getLangOpts().ObjCAutoRefCount)
9629           CheckObjCConversion(SourceRange(), RHSType, E,
9630                               CCK_ImplicitConversion);
9631         LHS = ImpCastExprToType(E, RHSType,
9632                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9633       }
9634       else {
9635         Expr *E = RHS.get();
9636         if (getLangOpts().ObjCAutoRefCount)
9637           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9638                               /*Diagnose=*/true,
9639                               /*DiagnoseCFAudited=*/false, Opc);
9640         RHS = ImpCastExprToType(E, LHSType,
9641                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9642       }
9643       return ResultTy;
9644     }
9645     if (LHSType->isObjCObjectPointerType() &&
9646         RHSType->isObjCObjectPointerType()) {
9647       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9648         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9649                                           /*isError*/false);
9650       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9651         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9652 
9653       if (LHSIsNull && !RHSIsNull)
9654         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9655       else
9656         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9657       return ResultTy;
9658     }
9659   }
9660   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9661       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9662     unsigned DiagID = 0;
9663     bool isError = false;
9664     if (LangOpts.DebuggerSupport) {
9665       // Under a debugger, allow the comparison of pointers to integers,
9666       // since users tend to want to compare addresses.
9667     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9668                (RHSIsNull && RHSType->isIntegerType())) {
9669       if (IsRelational) {
9670         isError = getLangOpts().CPlusPlus;
9671         DiagID =
9672           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9673                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9674       }
9675     } else if (getLangOpts().CPlusPlus) {
9676       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9677       isError = true;
9678     } else if (IsRelational)
9679       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9680     else
9681       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9682 
9683     if (DiagID) {
9684       Diag(Loc, DiagID)
9685         << LHSType << RHSType << LHS.get()->getSourceRange()
9686         << RHS.get()->getSourceRange();
9687       if (isError)
9688         return QualType();
9689     }
9690 
9691     if (LHSType->isIntegerType())
9692       LHS = ImpCastExprToType(LHS.get(), RHSType,
9693                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9694     else
9695       RHS = ImpCastExprToType(RHS.get(), LHSType,
9696                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9697     return ResultTy;
9698   }
9699 
9700   // Handle block pointers.
9701   if (!IsRelational && RHSIsNull
9702       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9703     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9704     return ResultTy;
9705   }
9706   if (!IsRelational && LHSIsNull
9707       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9708     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9709     return ResultTy;
9710   }
9711 
9712   if (getLangOpts().OpenCLVersion >= 200) {
9713     if (LHSIsNull && RHSType->isQueueT()) {
9714       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9715       return ResultTy;
9716     }
9717 
9718     if (LHSType->isQueueT() && RHSIsNull) {
9719       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9720       return ResultTy;
9721     }
9722   }
9723 
9724   return InvalidOperands(Loc, LHS, RHS);
9725 }
9726 
9727 // Return a signed ext_vector_type that is of identical size and number of
9728 // elements. For floating point vectors, return an integer type of identical
9729 // size and number of elements. In the non ext_vector_type case, search from
9730 // the largest type to the smallest type to avoid cases where long long == long,
9731 // where long gets picked over long long.
9732 QualType Sema::GetSignedVectorType(QualType V) {
9733   const VectorType *VTy = V->getAs<VectorType>();
9734   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9735 
9736   if (isa<ExtVectorType>(VTy)) {
9737     if (TypeSize == Context.getTypeSize(Context.CharTy))
9738       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9739     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9740       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9741     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9742       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9743     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9744       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9745     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9746            "Unhandled vector element size in vector compare");
9747     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9748   }
9749 
9750   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9751     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9752                                  VectorType::GenericVector);
9753   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9754     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9755                                  VectorType::GenericVector);
9756   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9757     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9758                                  VectorType::GenericVector);
9759   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9760     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9761                                  VectorType::GenericVector);
9762   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9763          "Unhandled vector element size in vector compare");
9764   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9765                                VectorType::GenericVector);
9766 }
9767 
9768 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9769 /// operates on extended vector types.  Instead of producing an IntTy result,
9770 /// like a scalar comparison, a vector comparison produces a vector of integer
9771 /// types.
9772 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9773                                           SourceLocation Loc,
9774                                           bool IsRelational) {
9775   // Check to make sure we're operating on vectors of the same type and width,
9776   // Allowing one side to be a scalar of element type.
9777   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9778                               /*AllowBothBool*/true,
9779                               /*AllowBoolConversions*/getLangOpts().ZVector);
9780   if (vType.isNull())
9781     return vType;
9782 
9783   QualType LHSType = LHS.get()->getType();
9784 
9785   // If AltiVec, the comparison results in a numeric type, i.e.
9786   // bool for C++, int for C
9787   if (getLangOpts().AltiVec &&
9788       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9789     return Context.getLogicalOperationType();
9790 
9791   // For non-floating point types, check for self-comparisons of the form
9792   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9793   // often indicate logic errors in the program.
9794   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9795     if (DeclRefExpr* DRL
9796           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9797       if (DeclRefExpr* DRR
9798             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9799         if (DRL->getDecl() == DRR->getDecl())
9800           DiagRuntimeBehavior(Loc, nullptr,
9801                               PDiag(diag::warn_comparison_always)
9802                                 << 0 // self-
9803                                 << 2 // "a constant"
9804                               );
9805   }
9806 
9807   // Check for comparisons of floating point operands using != and ==.
9808   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9809     assert (RHS.get()->getType()->hasFloatingRepresentation());
9810     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9811   }
9812 
9813   // Return a signed type for the vector.
9814   return GetSignedVectorType(vType);
9815 }
9816 
9817 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9818                                           SourceLocation Loc) {
9819   // Ensure that either both operands are of the same vector type, or
9820   // one operand is of a vector type and the other is of its element type.
9821   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9822                                        /*AllowBothBool*/true,
9823                                        /*AllowBoolConversions*/false);
9824   if (vType.isNull())
9825     return InvalidOperands(Loc, LHS, RHS);
9826   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9827       vType->hasFloatingRepresentation())
9828     return InvalidOperands(Loc, LHS, RHS);
9829 
9830   return GetSignedVectorType(LHS.get()->getType());
9831 }
9832 
9833 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9834                                            SourceLocation Loc,
9835                                            BinaryOperatorKind Opc) {
9836   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9837 
9838   bool IsCompAssign =
9839       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9840 
9841   if (LHS.get()->getType()->isVectorType() ||
9842       RHS.get()->getType()->isVectorType()) {
9843     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9844         RHS.get()->getType()->hasIntegerRepresentation())
9845       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9846                         /*AllowBothBool*/true,
9847                         /*AllowBoolConversions*/getLangOpts().ZVector);
9848     return InvalidOperands(Loc, LHS, RHS);
9849   }
9850 
9851   if (Opc == BO_And)
9852     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9853 
9854   ExprResult LHSResult = LHS, RHSResult = RHS;
9855   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9856                                                  IsCompAssign);
9857   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9858     return QualType();
9859   LHS = LHSResult.get();
9860   RHS = RHSResult.get();
9861 
9862   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9863     return compType;
9864   return InvalidOperands(Loc, LHS, RHS);
9865 }
9866 
9867 // C99 6.5.[13,14]
9868 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9869                                            SourceLocation Loc,
9870                                            BinaryOperatorKind Opc) {
9871   // Check vector operands differently.
9872   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9873     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9874 
9875   // Diagnose cases where the user write a logical and/or but probably meant a
9876   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9877   // is a constant.
9878   if (LHS.get()->getType()->isIntegerType() &&
9879       !LHS.get()->getType()->isBooleanType() &&
9880       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9881       // Don't warn in macros or template instantiations.
9882       !Loc.isMacroID() && !inTemplateInstantiation()) {
9883     // If the RHS can be constant folded, and if it constant folds to something
9884     // that isn't 0 or 1 (which indicate a potential logical operation that
9885     // happened to fold to true/false) then warn.
9886     // Parens on the RHS are ignored.
9887     llvm::APSInt Result;
9888     if (RHS.get()->EvaluateAsInt(Result, Context))
9889       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9890            !RHS.get()->getExprLoc().isMacroID()) ||
9891           (Result != 0 && Result != 1)) {
9892         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9893           << RHS.get()->getSourceRange()
9894           << (Opc == BO_LAnd ? "&&" : "||");
9895         // Suggest replacing the logical operator with the bitwise version
9896         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9897             << (Opc == BO_LAnd ? "&" : "|")
9898             << FixItHint::CreateReplacement(SourceRange(
9899                                                  Loc, getLocForEndOfToken(Loc)),
9900                                             Opc == BO_LAnd ? "&" : "|");
9901         if (Opc == BO_LAnd)
9902           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9903           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9904               << FixItHint::CreateRemoval(
9905                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9906                               RHS.get()->getLocEnd()));
9907       }
9908   }
9909 
9910   if (!Context.getLangOpts().CPlusPlus) {
9911     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9912     // not operate on the built-in scalar and vector float types.
9913     if (Context.getLangOpts().OpenCL &&
9914         Context.getLangOpts().OpenCLVersion < 120) {
9915       if (LHS.get()->getType()->isFloatingType() ||
9916           RHS.get()->getType()->isFloatingType())
9917         return InvalidOperands(Loc, LHS, RHS);
9918     }
9919 
9920     LHS = UsualUnaryConversions(LHS.get());
9921     if (LHS.isInvalid())
9922       return QualType();
9923 
9924     RHS = UsualUnaryConversions(RHS.get());
9925     if (RHS.isInvalid())
9926       return QualType();
9927 
9928     if (!LHS.get()->getType()->isScalarType() ||
9929         !RHS.get()->getType()->isScalarType())
9930       return InvalidOperands(Loc, LHS, RHS);
9931 
9932     return Context.IntTy;
9933   }
9934 
9935   // The following is safe because we only use this method for
9936   // non-overloadable operands.
9937 
9938   // C++ [expr.log.and]p1
9939   // C++ [expr.log.or]p1
9940   // The operands are both contextually converted to type bool.
9941   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9942   if (LHSRes.isInvalid())
9943     return InvalidOperands(Loc, LHS, RHS);
9944   LHS = LHSRes;
9945 
9946   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9947   if (RHSRes.isInvalid())
9948     return InvalidOperands(Loc, LHS, RHS);
9949   RHS = RHSRes;
9950 
9951   // C++ [expr.log.and]p2
9952   // C++ [expr.log.or]p2
9953   // The result is a bool.
9954   return Context.BoolTy;
9955 }
9956 
9957 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9958   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9959   if (!ME) return false;
9960   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9961   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9962       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9963   if (!Base) return false;
9964   return Base->getMethodDecl() != nullptr;
9965 }
9966 
9967 /// Is the given expression (which must be 'const') a reference to a
9968 /// variable which was originally non-const, but which has become
9969 /// 'const' due to being captured within a block?
9970 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9971 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9972   assert(E->isLValue() && E->getType().isConstQualified());
9973   E = E->IgnoreParens();
9974 
9975   // Must be a reference to a declaration from an enclosing scope.
9976   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9977   if (!DRE) return NCCK_None;
9978   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9979 
9980   // The declaration must be a variable which is not declared 'const'.
9981   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9982   if (!var) return NCCK_None;
9983   if (var->getType().isConstQualified()) return NCCK_None;
9984   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9985 
9986   // Decide whether the first capture was for a block or a lambda.
9987   DeclContext *DC = S.CurContext, *Prev = nullptr;
9988   // Decide whether the first capture was for a block or a lambda.
9989   while (DC) {
9990     // For init-capture, it is possible that the variable belongs to the
9991     // template pattern of the current context.
9992     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9993       if (var->isInitCapture() &&
9994           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9995         break;
9996     if (DC == var->getDeclContext())
9997       break;
9998     Prev = DC;
9999     DC = DC->getParent();
10000   }
10001   // Unless we have an init-capture, we've gone one step too far.
10002   if (!var->isInitCapture())
10003     DC = Prev;
10004   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10005 }
10006 
10007 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10008   Ty = Ty.getNonReferenceType();
10009   if (IsDereference && Ty->isPointerType())
10010     Ty = Ty->getPointeeType();
10011   return !Ty.isConstQualified();
10012 }
10013 
10014 /// Emit the "read-only variable not assignable" error and print notes to give
10015 /// more information about why the variable is not assignable, such as pointing
10016 /// to the declaration of a const variable, showing that a method is const, or
10017 /// that the function is returning a const reference.
10018 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10019                                     SourceLocation Loc) {
10020   // Update err_typecheck_assign_const and note_typecheck_assign_const
10021   // when this enum is changed.
10022   enum {
10023     ConstFunction,
10024     ConstVariable,
10025     ConstMember,
10026     ConstMethod,
10027     ConstUnknown,  // Keep as last element
10028   };
10029 
10030   SourceRange ExprRange = E->getSourceRange();
10031 
10032   // Only emit one error on the first const found.  All other consts will emit
10033   // a note to the error.
10034   bool DiagnosticEmitted = false;
10035 
10036   // Track if the current expression is the result of a dereference, and if the
10037   // next checked expression is the result of a dereference.
10038   bool IsDereference = false;
10039   bool NextIsDereference = false;
10040 
10041   // Loop to process MemberExpr chains.
10042   while (true) {
10043     IsDereference = NextIsDereference;
10044 
10045     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10046     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10047       NextIsDereference = ME->isArrow();
10048       const ValueDecl *VD = ME->getMemberDecl();
10049       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10050         // Mutable fields can be modified even if the class is const.
10051         if (Field->isMutable()) {
10052           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10053           break;
10054         }
10055 
10056         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10057           if (!DiagnosticEmitted) {
10058             S.Diag(Loc, diag::err_typecheck_assign_const)
10059                 << ExprRange << ConstMember << false /*static*/ << Field
10060                 << Field->getType();
10061             DiagnosticEmitted = true;
10062           }
10063           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10064               << ConstMember << false /*static*/ << Field << Field->getType()
10065               << Field->getSourceRange();
10066         }
10067         E = ME->getBase();
10068         continue;
10069       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10070         if (VDecl->getType().isConstQualified()) {
10071           if (!DiagnosticEmitted) {
10072             S.Diag(Loc, diag::err_typecheck_assign_const)
10073                 << ExprRange << ConstMember << true /*static*/ << VDecl
10074                 << VDecl->getType();
10075             DiagnosticEmitted = true;
10076           }
10077           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10078               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10079               << VDecl->getSourceRange();
10080         }
10081         // Static fields do not inherit constness from parents.
10082         break;
10083       }
10084       break;
10085     } // End MemberExpr
10086     break;
10087   }
10088 
10089   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10090     // Function calls
10091     const FunctionDecl *FD = CE->getDirectCallee();
10092     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10093       if (!DiagnosticEmitted) {
10094         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10095                                                       << ConstFunction << FD;
10096         DiagnosticEmitted = true;
10097       }
10098       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10099              diag::note_typecheck_assign_const)
10100           << ConstFunction << FD << FD->getReturnType()
10101           << FD->getReturnTypeSourceRange();
10102     }
10103   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10104     // Point to variable declaration.
10105     if (const ValueDecl *VD = DRE->getDecl()) {
10106       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10107         if (!DiagnosticEmitted) {
10108           S.Diag(Loc, diag::err_typecheck_assign_const)
10109               << ExprRange << ConstVariable << VD << VD->getType();
10110           DiagnosticEmitted = true;
10111         }
10112         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10113             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10114       }
10115     }
10116   } else if (isa<CXXThisExpr>(E)) {
10117     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10118       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10119         if (MD->isConst()) {
10120           if (!DiagnosticEmitted) {
10121             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10122                                                           << ConstMethod << MD;
10123             DiagnosticEmitted = true;
10124           }
10125           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10126               << ConstMethod << MD << MD->getSourceRange();
10127         }
10128       }
10129     }
10130   }
10131 
10132   if (DiagnosticEmitted)
10133     return;
10134 
10135   // Can't determine a more specific message, so display the generic error.
10136   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10137 }
10138 
10139 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10140 /// emit an error and return true.  If so, return false.
10141 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10142   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10143 
10144   S.CheckShadowingDeclModification(E, Loc);
10145 
10146   SourceLocation OrigLoc = Loc;
10147   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10148                                                               &Loc);
10149   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10150     IsLV = Expr::MLV_InvalidMessageExpression;
10151   if (IsLV == Expr::MLV_Valid)
10152     return false;
10153 
10154   unsigned DiagID = 0;
10155   bool NeedType = false;
10156   switch (IsLV) { // C99 6.5.16p2
10157   case Expr::MLV_ConstQualified:
10158     // Use a specialized diagnostic when we're assigning to an object
10159     // from an enclosing function or block.
10160     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10161       if (NCCK == NCCK_Block)
10162         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10163       else
10164         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10165       break;
10166     }
10167 
10168     // In ARC, use some specialized diagnostics for occasions where we
10169     // infer 'const'.  These are always pseudo-strong variables.
10170     if (S.getLangOpts().ObjCAutoRefCount) {
10171       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10172       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10173         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10174 
10175         // Use the normal diagnostic if it's pseudo-__strong but the
10176         // user actually wrote 'const'.
10177         if (var->isARCPseudoStrong() &&
10178             (!var->getTypeSourceInfo() ||
10179              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10180           // There are two pseudo-strong cases:
10181           //  - self
10182           ObjCMethodDecl *method = S.getCurMethodDecl();
10183           if (method && var == method->getSelfDecl())
10184             DiagID = method->isClassMethod()
10185               ? diag::err_typecheck_arc_assign_self_class_method
10186               : diag::err_typecheck_arc_assign_self;
10187 
10188           //  - fast enumeration variables
10189           else
10190             DiagID = diag::err_typecheck_arr_assign_enumeration;
10191 
10192           SourceRange Assign;
10193           if (Loc != OrigLoc)
10194             Assign = SourceRange(OrigLoc, OrigLoc);
10195           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10196           // We need to preserve the AST regardless, so migration tool
10197           // can do its job.
10198           return false;
10199         }
10200       }
10201     }
10202 
10203     // If none of the special cases above are triggered, then this is a
10204     // simple const assignment.
10205     if (DiagID == 0) {
10206       DiagnoseConstAssignment(S, E, Loc);
10207       return true;
10208     }
10209 
10210     break;
10211   case Expr::MLV_ConstAddrSpace:
10212     DiagnoseConstAssignment(S, E, Loc);
10213     return true;
10214   case Expr::MLV_ArrayType:
10215   case Expr::MLV_ArrayTemporary:
10216     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10217     NeedType = true;
10218     break;
10219   case Expr::MLV_NotObjectType:
10220     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10221     NeedType = true;
10222     break;
10223   case Expr::MLV_LValueCast:
10224     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10225     break;
10226   case Expr::MLV_Valid:
10227     llvm_unreachable("did not take early return for MLV_Valid");
10228   case Expr::MLV_InvalidExpression:
10229   case Expr::MLV_MemberFunction:
10230   case Expr::MLV_ClassTemporary:
10231     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10232     break;
10233   case Expr::MLV_IncompleteType:
10234   case Expr::MLV_IncompleteVoidType:
10235     return S.RequireCompleteType(Loc, E->getType(),
10236              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10237   case Expr::MLV_DuplicateVectorComponents:
10238     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10239     break;
10240   case Expr::MLV_NoSetterProperty:
10241     llvm_unreachable("readonly properties should be processed differently");
10242   case Expr::MLV_InvalidMessageExpression:
10243     DiagID = diag::err_readonly_message_assignment;
10244     break;
10245   case Expr::MLV_SubObjCPropertySetting:
10246     DiagID = diag::err_no_subobject_property_setting;
10247     break;
10248   }
10249 
10250   SourceRange Assign;
10251   if (Loc != OrigLoc)
10252     Assign = SourceRange(OrigLoc, OrigLoc);
10253   if (NeedType)
10254     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10255   else
10256     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10257   return true;
10258 }
10259 
10260 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10261                                          SourceLocation Loc,
10262                                          Sema &Sema) {
10263   // C / C++ fields
10264   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10265   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10266   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10267     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10268       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10269   }
10270 
10271   // Objective-C instance variables
10272   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10273   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10274   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10275     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10276     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10277     if (RL && RR && RL->getDecl() == RR->getDecl())
10278       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10279   }
10280 }
10281 
10282 // C99 6.5.16.1
10283 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10284                                        SourceLocation Loc,
10285                                        QualType CompoundType) {
10286   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10287 
10288   // Verify that LHS is a modifiable lvalue, and emit error if not.
10289   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10290     return QualType();
10291 
10292   QualType LHSType = LHSExpr->getType();
10293   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10294                                              CompoundType;
10295   // OpenCL v1.2 s6.1.1.1 p2:
10296   // The half data type can only be used to declare a pointer to a buffer that
10297   // contains half values
10298   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10299     LHSType->isHalfType()) {
10300     Diag(Loc, diag::err_opencl_half_load_store) << 1
10301         << LHSType.getUnqualifiedType();
10302     return QualType();
10303   }
10304 
10305   AssignConvertType ConvTy;
10306   if (CompoundType.isNull()) {
10307     Expr *RHSCheck = RHS.get();
10308 
10309     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10310 
10311     QualType LHSTy(LHSType);
10312     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10313     if (RHS.isInvalid())
10314       return QualType();
10315     // Special case of NSObject attributes on c-style pointer types.
10316     if (ConvTy == IncompatiblePointer &&
10317         ((Context.isObjCNSObjectType(LHSType) &&
10318           RHSType->isObjCObjectPointerType()) ||
10319          (Context.isObjCNSObjectType(RHSType) &&
10320           LHSType->isObjCObjectPointerType())))
10321       ConvTy = Compatible;
10322 
10323     if (ConvTy == Compatible &&
10324         LHSType->isObjCObjectType())
10325         Diag(Loc, diag::err_objc_object_assignment)
10326           << LHSType;
10327 
10328     // If the RHS is a unary plus or minus, check to see if they = and + are
10329     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10330     // instead of "x += 4".
10331     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10332       RHSCheck = ICE->getSubExpr();
10333     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10334       if ((UO->getOpcode() == UO_Plus ||
10335            UO->getOpcode() == UO_Minus) &&
10336           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10337           // Only if the two operators are exactly adjacent.
10338           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10339           // And there is a space or other character before the subexpr of the
10340           // unary +/-.  We don't want to warn on "x=-1".
10341           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10342           UO->getSubExpr()->getLocStart().isFileID()) {
10343         Diag(Loc, diag::warn_not_compound_assign)
10344           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10345           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10346       }
10347     }
10348 
10349     if (ConvTy == Compatible) {
10350       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10351         // Warn about retain cycles where a block captures the LHS, but
10352         // not if the LHS is a simple variable into which the block is
10353         // being stored...unless that variable can be captured by reference!
10354         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10355         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10356         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10357           checkRetainCycles(LHSExpr, RHS.get());
10358       }
10359 
10360       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10361           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10362         // It is safe to assign a weak reference into a strong variable.
10363         // Although this code can still have problems:
10364         //   id x = self.weakProp;
10365         //   id y = self.weakProp;
10366         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10367         // paths through the function. This should be revisited if
10368         // -Wrepeated-use-of-weak is made flow-sensitive.
10369         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10370         // variable, which will be valid for the current autorelease scope.
10371         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10372                              RHS.get()->getLocStart()))
10373           getCurFunction()->markSafeWeakUse(RHS.get());
10374 
10375       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10376         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10377       }
10378     }
10379   } else {
10380     // Compound assignment "x += y"
10381     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10382   }
10383 
10384   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10385                                RHS.get(), AA_Assigning))
10386     return QualType();
10387 
10388   CheckForNullPointerDereference(*this, LHSExpr);
10389 
10390   // C99 6.5.16p3: The type of an assignment expression is the type of the
10391   // left operand unless the left operand has qualified type, in which case
10392   // it is the unqualified version of the type of the left operand.
10393   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10394   // is converted to the type of the assignment expression (above).
10395   // C++ 5.17p1: the type of the assignment expression is that of its left
10396   // operand.
10397   return (getLangOpts().CPlusPlus
10398           ? LHSType : LHSType.getUnqualifiedType());
10399 }
10400 
10401 // Only ignore explicit casts to void.
10402 static bool IgnoreCommaOperand(const Expr *E) {
10403   E = E->IgnoreParens();
10404 
10405   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10406     if (CE->getCastKind() == CK_ToVoid) {
10407       return true;
10408     }
10409   }
10410 
10411   return false;
10412 }
10413 
10414 // Look for instances where it is likely the comma operator is confused with
10415 // another operator.  There is a whitelist of acceptable expressions for the
10416 // left hand side of the comma operator, otherwise emit a warning.
10417 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10418   // No warnings in macros
10419   if (Loc.isMacroID())
10420     return;
10421 
10422   // Don't warn in template instantiations.
10423   if (inTemplateInstantiation())
10424     return;
10425 
10426   // Scope isn't fine-grained enough to whitelist the specific cases, so
10427   // instead, skip more than needed, then call back into here with the
10428   // CommaVisitor in SemaStmt.cpp.
10429   // The whitelisted locations are the initialization and increment portions
10430   // of a for loop.  The additional checks are on the condition of
10431   // if statements, do/while loops, and for loops.
10432   const unsigned ForIncrementFlags =
10433       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10434   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10435   const unsigned ScopeFlags = getCurScope()->getFlags();
10436   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10437       (ScopeFlags & ForInitFlags) == ForInitFlags)
10438     return;
10439 
10440   // If there are multiple comma operators used together, get the RHS of the
10441   // of the comma operator as the LHS.
10442   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10443     if (BO->getOpcode() != BO_Comma)
10444       break;
10445     LHS = BO->getRHS();
10446   }
10447 
10448   // Only allow some expressions on LHS to not warn.
10449   if (IgnoreCommaOperand(LHS))
10450     return;
10451 
10452   Diag(Loc, diag::warn_comma_operator);
10453   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10454       << LHS->getSourceRange()
10455       << FixItHint::CreateInsertion(LHS->getLocStart(),
10456                                     LangOpts.CPlusPlus ? "static_cast<void>("
10457                                                        : "(void)(")
10458       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10459                                     ")");
10460 }
10461 
10462 // C99 6.5.17
10463 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10464                                    SourceLocation Loc) {
10465   LHS = S.CheckPlaceholderExpr(LHS.get());
10466   RHS = S.CheckPlaceholderExpr(RHS.get());
10467   if (LHS.isInvalid() || RHS.isInvalid())
10468     return QualType();
10469 
10470   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10471   // operands, but not unary promotions.
10472   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10473 
10474   // So we treat the LHS as a ignored value, and in C++ we allow the
10475   // containing site to determine what should be done with the RHS.
10476   LHS = S.IgnoredValueConversions(LHS.get());
10477   if (LHS.isInvalid())
10478     return QualType();
10479 
10480   S.DiagnoseUnusedExprResult(LHS.get());
10481 
10482   if (!S.getLangOpts().CPlusPlus) {
10483     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10484     if (RHS.isInvalid())
10485       return QualType();
10486     if (!RHS.get()->getType()->isVoidType())
10487       S.RequireCompleteType(Loc, RHS.get()->getType(),
10488                             diag::err_incomplete_type);
10489   }
10490 
10491   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10492     S.DiagnoseCommaOperator(LHS.get(), Loc);
10493 
10494   return RHS.get()->getType();
10495 }
10496 
10497 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10498 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10499 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10500                                                ExprValueKind &VK,
10501                                                ExprObjectKind &OK,
10502                                                SourceLocation OpLoc,
10503                                                bool IsInc, bool IsPrefix) {
10504   if (Op->isTypeDependent())
10505     return S.Context.DependentTy;
10506 
10507   QualType ResType = Op->getType();
10508   // Atomic types can be used for increment / decrement where the non-atomic
10509   // versions can, so ignore the _Atomic() specifier for the purpose of
10510   // checking.
10511   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10512     ResType = ResAtomicType->getValueType();
10513 
10514   assert(!ResType.isNull() && "no type for increment/decrement expression");
10515 
10516   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10517     // Decrement of bool is not allowed.
10518     if (!IsInc) {
10519       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10520       return QualType();
10521     }
10522     // Increment of bool sets it to true, but is deprecated.
10523     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10524                                               : diag::warn_increment_bool)
10525       << Op->getSourceRange();
10526   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10527     // Error on enum increments and decrements in C++ mode
10528     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10529     return QualType();
10530   } else if (ResType->isRealType()) {
10531     // OK!
10532   } else if (ResType->isPointerType()) {
10533     // C99 6.5.2.4p2, 6.5.6p2
10534     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10535       return QualType();
10536   } else if (ResType->isObjCObjectPointerType()) {
10537     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10538     // Otherwise, we just need a complete type.
10539     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10540         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10541       return QualType();
10542   } else if (ResType->isAnyComplexType()) {
10543     // C99 does not support ++/-- on complex types, we allow as an extension.
10544     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10545       << ResType << Op->getSourceRange();
10546   } else if (ResType->isPlaceholderType()) {
10547     ExprResult PR = S.CheckPlaceholderExpr(Op);
10548     if (PR.isInvalid()) return QualType();
10549     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10550                                           IsInc, IsPrefix);
10551   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10552     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10553   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10554              (ResType->getAs<VectorType>()->getVectorKind() !=
10555               VectorType::AltiVecBool)) {
10556     // The z vector extensions allow ++ and -- for non-bool vectors.
10557   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10558             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10559     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10560   } else {
10561     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10562       << ResType << int(IsInc) << Op->getSourceRange();
10563     return QualType();
10564   }
10565   // At this point, we know we have a real, complex or pointer type.
10566   // Now make sure the operand is a modifiable lvalue.
10567   if (CheckForModifiableLvalue(Op, OpLoc, S))
10568     return QualType();
10569   // In C++, a prefix increment is the same type as the operand. Otherwise
10570   // (in C or with postfix), the increment is the unqualified type of the
10571   // operand.
10572   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10573     VK = VK_LValue;
10574     OK = Op->getObjectKind();
10575     return ResType;
10576   } else {
10577     VK = VK_RValue;
10578     return ResType.getUnqualifiedType();
10579   }
10580 }
10581 
10582 
10583 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10584 /// This routine allows us to typecheck complex/recursive expressions
10585 /// where the declaration is needed for type checking. We only need to
10586 /// handle cases when the expression references a function designator
10587 /// or is an lvalue. Here are some examples:
10588 ///  - &(x) => x
10589 ///  - &*****f => f for f a function designator.
10590 ///  - &s.xx => s
10591 ///  - &s.zz[1].yy -> s, if zz is an array
10592 ///  - *(x + 1) -> x, if x is an array
10593 ///  - &"123"[2] -> 0
10594 ///  - & __real__ x -> x
10595 static ValueDecl *getPrimaryDecl(Expr *E) {
10596   switch (E->getStmtClass()) {
10597   case Stmt::DeclRefExprClass:
10598     return cast<DeclRefExpr>(E)->getDecl();
10599   case Stmt::MemberExprClass:
10600     // If this is an arrow operator, the address is an offset from
10601     // the base's value, so the object the base refers to is
10602     // irrelevant.
10603     if (cast<MemberExpr>(E)->isArrow())
10604       return nullptr;
10605     // Otherwise, the expression refers to a part of the base
10606     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10607   case Stmt::ArraySubscriptExprClass: {
10608     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10609     // promotion of register arrays earlier.
10610     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10611     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10612       if (ICE->getSubExpr()->getType()->isArrayType())
10613         return getPrimaryDecl(ICE->getSubExpr());
10614     }
10615     return nullptr;
10616   }
10617   case Stmt::UnaryOperatorClass: {
10618     UnaryOperator *UO = cast<UnaryOperator>(E);
10619 
10620     switch(UO->getOpcode()) {
10621     case UO_Real:
10622     case UO_Imag:
10623     case UO_Extension:
10624       return getPrimaryDecl(UO->getSubExpr());
10625     default:
10626       return nullptr;
10627     }
10628   }
10629   case Stmt::ParenExprClass:
10630     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10631   case Stmt::ImplicitCastExprClass:
10632     // If the result of an implicit cast is an l-value, we care about
10633     // the sub-expression; otherwise, the result here doesn't matter.
10634     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10635   default:
10636     return nullptr;
10637   }
10638 }
10639 
10640 namespace {
10641   enum {
10642     AO_Bit_Field = 0,
10643     AO_Vector_Element = 1,
10644     AO_Property_Expansion = 2,
10645     AO_Register_Variable = 3,
10646     AO_No_Error = 4
10647   };
10648 }
10649 /// \brief Diagnose invalid operand for address of operations.
10650 ///
10651 /// \param Type The type of operand which cannot have its address taken.
10652 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10653                                          Expr *E, unsigned Type) {
10654   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10655 }
10656 
10657 /// CheckAddressOfOperand - The operand of & must be either a function
10658 /// designator or an lvalue designating an object. If it is an lvalue, the
10659 /// object cannot be declared with storage class register or be a bit field.
10660 /// Note: The usual conversions are *not* applied to the operand of the &
10661 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10662 /// In C++, the operand might be an overloaded function name, in which case
10663 /// we allow the '&' but retain the overloaded-function type.
10664 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10665   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10666     if (PTy->getKind() == BuiltinType::Overload) {
10667       Expr *E = OrigOp.get()->IgnoreParens();
10668       if (!isa<OverloadExpr>(E)) {
10669         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10670         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10671           << OrigOp.get()->getSourceRange();
10672         return QualType();
10673       }
10674 
10675       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10676       if (isa<UnresolvedMemberExpr>(Ovl))
10677         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10678           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10679             << OrigOp.get()->getSourceRange();
10680           return QualType();
10681         }
10682 
10683       return Context.OverloadTy;
10684     }
10685 
10686     if (PTy->getKind() == BuiltinType::UnknownAny)
10687       return Context.UnknownAnyTy;
10688 
10689     if (PTy->getKind() == BuiltinType::BoundMember) {
10690       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10691         << OrigOp.get()->getSourceRange();
10692       return QualType();
10693     }
10694 
10695     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10696     if (OrigOp.isInvalid()) return QualType();
10697   }
10698 
10699   if (OrigOp.get()->isTypeDependent())
10700     return Context.DependentTy;
10701 
10702   assert(!OrigOp.get()->getType()->isPlaceholderType());
10703 
10704   // Make sure to ignore parentheses in subsequent checks
10705   Expr *op = OrigOp.get()->IgnoreParens();
10706 
10707   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10708   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10709     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10710     return QualType();
10711   }
10712 
10713   if (getLangOpts().C99) {
10714     // Implement C99-only parts of addressof rules.
10715     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10716       if (uOp->getOpcode() == UO_Deref)
10717         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10718         // (assuming the deref expression is valid).
10719         return uOp->getSubExpr()->getType();
10720     }
10721     // Technically, there should be a check for array subscript
10722     // expressions here, but the result of one is always an lvalue anyway.
10723   }
10724   ValueDecl *dcl = getPrimaryDecl(op);
10725 
10726   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10727     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10728                                            op->getLocStart()))
10729       return QualType();
10730 
10731   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10732   unsigned AddressOfError = AO_No_Error;
10733 
10734   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10735     bool sfinae = (bool)isSFINAEContext();
10736     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10737                                   : diag::ext_typecheck_addrof_temporary)
10738       << op->getType() << op->getSourceRange();
10739     if (sfinae)
10740       return QualType();
10741     // Materialize the temporary as an lvalue so that we can take its address.
10742     OrigOp = op =
10743         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10744   } else if (isa<ObjCSelectorExpr>(op)) {
10745     return Context.getPointerType(op->getType());
10746   } else if (lval == Expr::LV_MemberFunction) {
10747     // If it's an instance method, make a member pointer.
10748     // The expression must have exactly the form &A::foo.
10749 
10750     // If the underlying expression isn't a decl ref, give up.
10751     if (!isa<DeclRefExpr>(op)) {
10752       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10753         << OrigOp.get()->getSourceRange();
10754       return QualType();
10755     }
10756     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10757     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10758 
10759     // The id-expression was parenthesized.
10760     if (OrigOp.get() != DRE) {
10761       Diag(OpLoc, diag::err_parens_pointer_member_function)
10762         << OrigOp.get()->getSourceRange();
10763 
10764     // The method was named without a qualifier.
10765     } else if (!DRE->getQualifier()) {
10766       if (MD->getParent()->getName().empty())
10767         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10768           << op->getSourceRange();
10769       else {
10770         SmallString<32> Str;
10771         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10772         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10773           << op->getSourceRange()
10774           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10775       }
10776     }
10777 
10778     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10779     if (isa<CXXDestructorDecl>(MD))
10780       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10781 
10782     QualType MPTy = Context.getMemberPointerType(
10783         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10784     // Under the MS ABI, lock down the inheritance model now.
10785     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10786       (void)isCompleteType(OpLoc, MPTy);
10787     return MPTy;
10788   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10789     // C99 6.5.3.2p1
10790     // The operand must be either an l-value or a function designator
10791     if (!op->getType()->isFunctionType()) {
10792       // Use a special diagnostic for loads from property references.
10793       if (isa<PseudoObjectExpr>(op)) {
10794         AddressOfError = AO_Property_Expansion;
10795       } else {
10796         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10797           << op->getType() << op->getSourceRange();
10798         return QualType();
10799       }
10800     }
10801   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10802     // The operand cannot be a bit-field
10803     AddressOfError = AO_Bit_Field;
10804   } else if (op->getObjectKind() == OK_VectorComponent) {
10805     // The operand cannot be an element of a vector
10806     AddressOfError = AO_Vector_Element;
10807   } else if (dcl) { // C99 6.5.3.2p1
10808     // We have an lvalue with a decl. Make sure the decl is not declared
10809     // with the register storage-class specifier.
10810     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10811       // in C++ it is not error to take address of a register
10812       // variable (c++03 7.1.1P3)
10813       if (vd->getStorageClass() == SC_Register &&
10814           !getLangOpts().CPlusPlus) {
10815         AddressOfError = AO_Register_Variable;
10816       }
10817     } else if (isa<MSPropertyDecl>(dcl)) {
10818       AddressOfError = AO_Property_Expansion;
10819     } else if (isa<FunctionTemplateDecl>(dcl)) {
10820       return Context.OverloadTy;
10821     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10822       // Okay: we can take the address of a field.
10823       // Could be a pointer to member, though, if there is an explicit
10824       // scope qualifier for the class.
10825       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10826         DeclContext *Ctx = dcl->getDeclContext();
10827         if (Ctx && Ctx->isRecord()) {
10828           if (dcl->getType()->isReferenceType()) {
10829             Diag(OpLoc,
10830                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10831               << dcl->getDeclName() << dcl->getType();
10832             return QualType();
10833           }
10834 
10835           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10836             Ctx = Ctx->getParent();
10837 
10838           QualType MPTy = Context.getMemberPointerType(
10839               op->getType(),
10840               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10841           // Under the MS ABI, lock down the inheritance model now.
10842           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10843             (void)isCompleteType(OpLoc, MPTy);
10844           return MPTy;
10845         }
10846       }
10847     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10848                !isa<BindingDecl>(dcl))
10849       llvm_unreachable("Unknown/unexpected decl type");
10850   }
10851 
10852   if (AddressOfError != AO_No_Error) {
10853     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10854     return QualType();
10855   }
10856 
10857   if (lval == Expr::LV_IncompleteVoidType) {
10858     // Taking the address of a void variable is technically illegal, but we
10859     // allow it in cases which are otherwise valid.
10860     // Example: "extern void x; void* y = &x;".
10861     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10862   }
10863 
10864   // If the operand has type "type", the result has type "pointer to type".
10865   if (op->getType()->isObjCObjectType())
10866     return Context.getObjCObjectPointerType(op->getType());
10867 
10868   CheckAddressOfPackedMember(op);
10869 
10870   return Context.getPointerType(op->getType());
10871 }
10872 
10873 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10874   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10875   if (!DRE)
10876     return;
10877   const Decl *D = DRE->getDecl();
10878   if (!D)
10879     return;
10880   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10881   if (!Param)
10882     return;
10883   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10884     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10885       return;
10886   if (FunctionScopeInfo *FD = S.getCurFunction())
10887     if (!FD->ModifiedNonNullParams.count(Param))
10888       FD->ModifiedNonNullParams.insert(Param);
10889 }
10890 
10891 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10892 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10893                                         SourceLocation OpLoc) {
10894   if (Op->isTypeDependent())
10895     return S.Context.DependentTy;
10896 
10897   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10898   if (ConvResult.isInvalid())
10899     return QualType();
10900   Op = ConvResult.get();
10901   QualType OpTy = Op->getType();
10902   QualType Result;
10903 
10904   if (isa<CXXReinterpretCastExpr>(Op)) {
10905     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10906     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10907                                      Op->getSourceRange());
10908   }
10909 
10910   if (const PointerType *PT = OpTy->getAs<PointerType>())
10911   {
10912     Result = PT->getPointeeType();
10913   }
10914   else if (const ObjCObjectPointerType *OPT =
10915              OpTy->getAs<ObjCObjectPointerType>())
10916     Result = OPT->getPointeeType();
10917   else {
10918     ExprResult PR = S.CheckPlaceholderExpr(Op);
10919     if (PR.isInvalid()) return QualType();
10920     if (PR.get() != Op)
10921       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10922   }
10923 
10924   if (Result.isNull()) {
10925     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10926       << OpTy << Op->getSourceRange();
10927     return QualType();
10928   }
10929 
10930   // Note that per both C89 and C99, indirection is always legal, even if Result
10931   // is an incomplete type or void.  It would be possible to warn about
10932   // dereferencing a void pointer, but it's completely well-defined, and such a
10933   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10934   // for pointers to 'void' but is fine for any other pointer type:
10935   //
10936   // C++ [expr.unary.op]p1:
10937   //   [...] the expression to which [the unary * operator] is applied shall
10938   //   be a pointer to an object type, or a pointer to a function type
10939   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10940     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10941       << OpTy << Op->getSourceRange();
10942 
10943   // Dereferences are usually l-values...
10944   VK = VK_LValue;
10945 
10946   // ...except that certain expressions are never l-values in C.
10947   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10948     VK = VK_RValue;
10949 
10950   return Result;
10951 }
10952 
10953 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10954   BinaryOperatorKind Opc;
10955   switch (Kind) {
10956   default: llvm_unreachable("Unknown binop!");
10957   case tok::periodstar:           Opc = BO_PtrMemD; break;
10958   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10959   case tok::star:                 Opc = BO_Mul; break;
10960   case tok::slash:                Opc = BO_Div; break;
10961   case tok::percent:              Opc = BO_Rem; break;
10962   case tok::plus:                 Opc = BO_Add; break;
10963   case tok::minus:                Opc = BO_Sub; break;
10964   case tok::lessless:             Opc = BO_Shl; break;
10965   case tok::greatergreater:       Opc = BO_Shr; break;
10966   case tok::lessequal:            Opc = BO_LE; break;
10967   case tok::less:                 Opc = BO_LT; break;
10968   case tok::greaterequal:         Opc = BO_GE; break;
10969   case tok::greater:              Opc = BO_GT; break;
10970   case tok::exclaimequal:         Opc = BO_NE; break;
10971   case tok::equalequal:           Opc = BO_EQ; break;
10972   case tok::amp:                  Opc = BO_And; break;
10973   case tok::caret:                Opc = BO_Xor; break;
10974   case tok::pipe:                 Opc = BO_Or; break;
10975   case tok::ampamp:               Opc = BO_LAnd; break;
10976   case tok::pipepipe:             Opc = BO_LOr; break;
10977   case tok::equal:                Opc = BO_Assign; break;
10978   case tok::starequal:            Opc = BO_MulAssign; break;
10979   case tok::slashequal:           Opc = BO_DivAssign; break;
10980   case tok::percentequal:         Opc = BO_RemAssign; break;
10981   case tok::plusequal:            Opc = BO_AddAssign; break;
10982   case tok::minusequal:           Opc = BO_SubAssign; break;
10983   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10984   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10985   case tok::ampequal:             Opc = BO_AndAssign; break;
10986   case tok::caretequal:           Opc = BO_XorAssign; break;
10987   case tok::pipeequal:            Opc = BO_OrAssign; break;
10988   case tok::comma:                Opc = BO_Comma; break;
10989   }
10990   return Opc;
10991 }
10992 
10993 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10994   tok::TokenKind Kind) {
10995   UnaryOperatorKind Opc;
10996   switch (Kind) {
10997   default: llvm_unreachable("Unknown unary op!");
10998   case tok::plusplus:     Opc = UO_PreInc; break;
10999   case tok::minusminus:   Opc = UO_PreDec; break;
11000   case tok::amp:          Opc = UO_AddrOf; break;
11001   case tok::star:         Opc = UO_Deref; break;
11002   case tok::plus:         Opc = UO_Plus; break;
11003   case tok::minus:        Opc = UO_Minus; break;
11004   case tok::tilde:        Opc = UO_Not; break;
11005   case tok::exclaim:      Opc = UO_LNot; break;
11006   case tok::kw___real:    Opc = UO_Real; break;
11007   case tok::kw___imag:    Opc = UO_Imag; break;
11008   case tok::kw___extension__: Opc = UO_Extension; break;
11009   }
11010   return Opc;
11011 }
11012 
11013 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11014 /// This warning is only emitted for builtin assignment operations. It is also
11015 /// suppressed in the event of macro expansions.
11016 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11017                                    SourceLocation OpLoc) {
11018   if (S.inTemplateInstantiation())
11019     return;
11020   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11021     return;
11022   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11023   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11024   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11025   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11026   if (!LHSDeclRef || !RHSDeclRef ||
11027       LHSDeclRef->getLocation().isMacroID() ||
11028       RHSDeclRef->getLocation().isMacroID())
11029     return;
11030   const ValueDecl *LHSDecl =
11031     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11032   const ValueDecl *RHSDecl =
11033     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11034   if (LHSDecl != RHSDecl)
11035     return;
11036   if (LHSDecl->getType().isVolatileQualified())
11037     return;
11038   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11039     if (RefTy->getPointeeType().isVolatileQualified())
11040       return;
11041 
11042   S.Diag(OpLoc, diag::warn_self_assignment)
11043       << LHSDeclRef->getType()
11044       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11045 }
11046 
11047 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11048 /// is usually indicative of introspection within the Objective-C pointer.
11049 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11050                                           SourceLocation OpLoc) {
11051   if (!S.getLangOpts().ObjC1)
11052     return;
11053 
11054   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11055   const Expr *LHS = L.get();
11056   const Expr *RHS = R.get();
11057 
11058   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11059     ObjCPointerExpr = LHS;
11060     OtherExpr = RHS;
11061   }
11062   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11063     ObjCPointerExpr = RHS;
11064     OtherExpr = LHS;
11065   }
11066 
11067   // This warning is deliberately made very specific to reduce false
11068   // positives with logic that uses '&' for hashing.  This logic mainly
11069   // looks for code trying to introspect into tagged pointers, which
11070   // code should generally never do.
11071   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11072     unsigned Diag = diag::warn_objc_pointer_masking;
11073     // Determine if we are introspecting the result of performSelectorXXX.
11074     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11075     // Special case messages to -performSelector and friends, which
11076     // can return non-pointer values boxed in a pointer value.
11077     // Some clients may wish to silence warnings in this subcase.
11078     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11079       Selector S = ME->getSelector();
11080       StringRef SelArg0 = S.getNameForSlot(0);
11081       if (SelArg0.startswith("performSelector"))
11082         Diag = diag::warn_objc_pointer_masking_performSelector;
11083     }
11084 
11085     S.Diag(OpLoc, Diag)
11086       << ObjCPointerExpr->getSourceRange();
11087   }
11088 }
11089 
11090 static NamedDecl *getDeclFromExpr(Expr *E) {
11091   if (!E)
11092     return nullptr;
11093   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11094     return DRE->getDecl();
11095   if (auto *ME = dyn_cast<MemberExpr>(E))
11096     return ME->getMemberDecl();
11097   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11098     return IRE->getDecl();
11099   return nullptr;
11100 }
11101 
11102 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11103 /// operator @p Opc at location @c TokLoc. This routine only supports
11104 /// built-in operations; ActOnBinOp handles overloaded operators.
11105 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11106                                     BinaryOperatorKind Opc,
11107                                     Expr *LHSExpr, Expr *RHSExpr) {
11108   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11109     // The syntax only allows initializer lists on the RHS of assignment,
11110     // so we don't need to worry about accepting invalid code for
11111     // non-assignment operators.
11112     // C++11 5.17p9:
11113     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11114     //   of x = {} is x = T().
11115     InitializationKind Kind =
11116         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11117     InitializedEntity Entity =
11118         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11119     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11120     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11121     if (Init.isInvalid())
11122       return Init;
11123     RHSExpr = Init.get();
11124   }
11125 
11126   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11127   QualType ResultTy;     // Result type of the binary operator.
11128   // The following two variables are used for compound assignment operators
11129   QualType CompLHSTy;    // Type of LHS after promotions for computation
11130   QualType CompResultTy; // Type of computation result
11131   ExprValueKind VK = VK_RValue;
11132   ExprObjectKind OK = OK_Ordinary;
11133 
11134   if (!getLangOpts().CPlusPlus) {
11135     // C cannot handle TypoExpr nodes on either side of a binop because it
11136     // doesn't handle dependent types properly, so make sure any TypoExprs have
11137     // been dealt with before checking the operands.
11138     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11139     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11140       if (Opc != BO_Assign)
11141         return ExprResult(E);
11142       // Avoid correcting the RHS to the same Expr as the LHS.
11143       Decl *D = getDeclFromExpr(E);
11144       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11145     });
11146     if (!LHS.isUsable() || !RHS.isUsable())
11147       return ExprError();
11148   }
11149 
11150   if (getLangOpts().OpenCL) {
11151     QualType LHSTy = LHSExpr->getType();
11152     QualType RHSTy = RHSExpr->getType();
11153     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11154     // the ATOMIC_VAR_INIT macro.
11155     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11156       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11157       if (BO_Assign == Opc)
11158         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11159       else
11160         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11161       return ExprError();
11162     }
11163 
11164     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11165     // only with a builtin functions and therefore should be disallowed here.
11166     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11167         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11168         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11169         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11170       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11171       return ExprError();
11172     }
11173   }
11174 
11175   switch (Opc) {
11176   case BO_Assign:
11177     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11178     if (getLangOpts().CPlusPlus &&
11179         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11180       VK = LHS.get()->getValueKind();
11181       OK = LHS.get()->getObjectKind();
11182     }
11183     if (!ResultTy.isNull()) {
11184       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11185       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11186     }
11187     RecordModifiableNonNullParam(*this, LHS.get());
11188     break;
11189   case BO_PtrMemD:
11190   case BO_PtrMemI:
11191     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11192                                             Opc == BO_PtrMemI);
11193     break;
11194   case BO_Mul:
11195   case BO_Div:
11196     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11197                                            Opc == BO_Div);
11198     break;
11199   case BO_Rem:
11200     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11201     break;
11202   case BO_Add:
11203     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11204     break;
11205   case BO_Sub:
11206     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11207     break;
11208   case BO_Shl:
11209   case BO_Shr:
11210     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11211     break;
11212   case BO_LE:
11213   case BO_LT:
11214   case BO_GE:
11215   case BO_GT:
11216     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11217     break;
11218   case BO_EQ:
11219   case BO_NE:
11220     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11221     break;
11222   case BO_And:
11223     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11224   case BO_Xor:
11225   case BO_Or:
11226     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11227     break;
11228   case BO_LAnd:
11229   case BO_LOr:
11230     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11231     break;
11232   case BO_MulAssign:
11233   case BO_DivAssign:
11234     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11235                                                Opc == BO_DivAssign);
11236     CompLHSTy = CompResultTy;
11237     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11238       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11239     break;
11240   case BO_RemAssign:
11241     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11242     CompLHSTy = CompResultTy;
11243     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11244       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11245     break;
11246   case BO_AddAssign:
11247     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11248     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11249       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11250     break;
11251   case BO_SubAssign:
11252     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11253     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11254       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11255     break;
11256   case BO_ShlAssign:
11257   case BO_ShrAssign:
11258     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11259     CompLHSTy = CompResultTy;
11260     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11261       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11262     break;
11263   case BO_AndAssign:
11264   case BO_OrAssign: // fallthrough
11265     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11266   case BO_XorAssign:
11267     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11268     CompLHSTy = CompResultTy;
11269     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11270       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11271     break;
11272   case BO_Comma:
11273     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11274     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11275       VK = RHS.get()->getValueKind();
11276       OK = RHS.get()->getObjectKind();
11277     }
11278     break;
11279   }
11280   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11281     return ExprError();
11282 
11283   // Check for array bounds violations for both sides of the BinaryOperator
11284   CheckArrayAccess(LHS.get());
11285   CheckArrayAccess(RHS.get());
11286 
11287   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11288     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11289                                                  &Context.Idents.get("object_setClass"),
11290                                                  SourceLocation(), LookupOrdinaryName);
11291     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11292       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11293       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11294       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11295       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11296       FixItHint::CreateInsertion(RHSLocEnd, ")");
11297     }
11298     else
11299       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11300   }
11301   else if (const ObjCIvarRefExpr *OIRE =
11302            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11303     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11304 
11305   if (CompResultTy.isNull())
11306     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11307                                         OK, OpLoc, FPFeatures);
11308   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11309       OK_ObjCProperty) {
11310     VK = VK_LValue;
11311     OK = LHS.get()->getObjectKind();
11312   }
11313   return new (Context) CompoundAssignOperator(
11314       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11315       OpLoc, FPFeatures);
11316 }
11317 
11318 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11319 /// operators are mixed in a way that suggests that the programmer forgot that
11320 /// comparison operators have higher precedence. The most typical example of
11321 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11322 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11323                                       SourceLocation OpLoc, Expr *LHSExpr,
11324                                       Expr *RHSExpr) {
11325   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11326   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11327 
11328   // Check that one of the sides is a comparison operator and the other isn't.
11329   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11330   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11331   if (isLeftComp == isRightComp)
11332     return;
11333 
11334   // Bitwise operations are sometimes used as eager logical ops.
11335   // Don't diagnose this.
11336   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11337   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11338   if (isLeftBitwise || isRightBitwise)
11339     return;
11340 
11341   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11342                                                    OpLoc)
11343                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11344   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11345   SourceRange ParensRange = isLeftComp ?
11346       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11347     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11348 
11349   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11350     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11351   SuggestParentheses(Self, OpLoc,
11352     Self.PDiag(diag::note_precedence_silence) << OpStr,
11353     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11354   SuggestParentheses(Self, OpLoc,
11355     Self.PDiag(diag::note_precedence_bitwise_first)
11356       << BinaryOperator::getOpcodeStr(Opc),
11357     ParensRange);
11358 }
11359 
11360 /// \brief It accepts a '&&' expr that is inside a '||' one.
11361 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11362 /// in parentheses.
11363 static void
11364 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11365                                        BinaryOperator *Bop) {
11366   assert(Bop->getOpcode() == BO_LAnd);
11367   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11368       << Bop->getSourceRange() << OpLoc;
11369   SuggestParentheses(Self, Bop->getOperatorLoc(),
11370     Self.PDiag(diag::note_precedence_silence)
11371       << Bop->getOpcodeStr(),
11372     Bop->getSourceRange());
11373 }
11374 
11375 /// \brief Returns true if the given expression can be evaluated as a constant
11376 /// 'true'.
11377 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11378   bool Res;
11379   return !E->isValueDependent() &&
11380          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11381 }
11382 
11383 /// \brief Returns true if the given expression can be evaluated as a constant
11384 /// 'false'.
11385 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11386   bool Res;
11387   return !E->isValueDependent() &&
11388          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11389 }
11390 
11391 /// \brief Look for '&&' in the left hand of a '||' expr.
11392 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11393                                              Expr *LHSExpr, Expr *RHSExpr) {
11394   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11395     if (Bop->getOpcode() == BO_LAnd) {
11396       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11397       if (EvaluatesAsFalse(S, RHSExpr))
11398         return;
11399       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11400       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11401         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11402     } else if (Bop->getOpcode() == BO_LOr) {
11403       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11404         // If it's "a || b && 1 || c" we didn't warn earlier for
11405         // "a || b && 1", but warn now.
11406         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11407           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11408       }
11409     }
11410   }
11411 }
11412 
11413 /// \brief Look for '&&' in the right hand of a '||' expr.
11414 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11415                                              Expr *LHSExpr, Expr *RHSExpr) {
11416   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11417     if (Bop->getOpcode() == BO_LAnd) {
11418       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11419       if (EvaluatesAsFalse(S, LHSExpr))
11420         return;
11421       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11422       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11423         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11424     }
11425   }
11426 }
11427 
11428 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11429 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11430 /// the '&' expression in parentheses.
11431 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11432                                          SourceLocation OpLoc, Expr *SubExpr) {
11433   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11434     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11435       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11436         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11437         << Bop->getSourceRange() << OpLoc;
11438       SuggestParentheses(S, Bop->getOperatorLoc(),
11439         S.PDiag(diag::note_precedence_silence)
11440           << Bop->getOpcodeStr(),
11441         Bop->getSourceRange());
11442     }
11443   }
11444 }
11445 
11446 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11447                                     Expr *SubExpr, StringRef Shift) {
11448   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11449     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11450       StringRef Op = Bop->getOpcodeStr();
11451       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11452           << Bop->getSourceRange() << OpLoc << Shift << Op;
11453       SuggestParentheses(S, Bop->getOperatorLoc(),
11454           S.PDiag(diag::note_precedence_silence) << Op,
11455           Bop->getSourceRange());
11456     }
11457   }
11458 }
11459 
11460 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11461                                  Expr *LHSExpr, Expr *RHSExpr) {
11462   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11463   if (!OCE)
11464     return;
11465 
11466   FunctionDecl *FD = OCE->getDirectCallee();
11467   if (!FD || !FD->isOverloadedOperator())
11468     return;
11469 
11470   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11471   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11472     return;
11473 
11474   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11475       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11476       << (Kind == OO_LessLess);
11477   SuggestParentheses(S, OCE->getOperatorLoc(),
11478                      S.PDiag(diag::note_precedence_silence)
11479                          << (Kind == OO_LessLess ? "<<" : ">>"),
11480                      OCE->getSourceRange());
11481   SuggestParentheses(S, OpLoc,
11482                      S.PDiag(diag::note_evaluate_comparison_first),
11483                      SourceRange(OCE->getArg(1)->getLocStart(),
11484                                  RHSExpr->getLocEnd()));
11485 }
11486 
11487 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11488 /// precedence.
11489 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11490                                     SourceLocation OpLoc, Expr *LHSExpr,
11491                                     Expr *RHSExpr){
11492   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11493   if (BinaryOperator::isBitwiseOp(Opc))
11494     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11495 
11496   // Diagnose "arg1 & arg2 | arg3"
11497   if ((Opc == BO_Or || Opc == BO_Xor) &&
11498       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11499     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11500     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11501   }
11502 
11503   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11504   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11505   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11506     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11507     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11508   }
11509 
11510   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11511       || Opc == BO_Shr) {
11512     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11513     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11514     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11515   }
11516 
11517   // Warn on overloaded shift operators and comparisons, such as:
11518   // cout << 5 == 4;
11519   if (BinaryOperator::isComparisonOp(Opc))
11520     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11521 }
11522 
11523 // Binary Operators.  'Tok' is the token for the operator.
11524 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11525                             tok::TokenKind Kind,
11526                             Expr *LHSExpr, Expr *RHSExpr) {
11527   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11528   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11529   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11530 
11531   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11532   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11533 
11534   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11535 }
11536 
11537 /// Build an overloaded binary operator expression in the given scope.
11538 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11539                                        BinaryOperatorKind Opc,
11540                                        Expr *LHS, Expr *RHS) {
11541   // Find all of the overloaded operators visible from this
11542   // point. We perform both an operator-name lookup from the local
11543   // scope and an argument-dependent lookup based on the types of
11544   // the arguments.
11545   UnresolvedSet<16> Functions;
11546   OverloadedOperatorKind OverOp
11547     = BinaryOperator::getOverloadedOperator(Opc);
11548   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11549     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11550                                    RHS->getType(), Functions);
11551 
11552   // Build the (potentially-overloaded, potentially-dependent)
11553   // binary operation.
11554   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11555 }
11556 
11557 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11558                             BinaryOperatorKind Opc,
11559                             Expr *LHSExpr, Expr *RHSExpr) {
11560   // We want to end up calling one of checkPseudoObjectAssignment
11561   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11562   // both expressions are overloadable or either is type-dependent),
11563   // or CreateBuiltinBinOp (in any other case).  We also want to get
11564   // any placeholder types out of the way.
11565 
11566   // Handle pseudo-objects in the LHS.
11567   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11568     // Assignments with a pseudo-object l-value need special analysis.
11569     if (pty->getKind() == BuiltinType::PseudoObject &&
11570         BinaryOperator::isAssignmentOp(Opc))
11571       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11572 
11573     // Don't resolve overloads if the other type is overloadable.
11574     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11575       // We can't actually test that if we still have a placeholder,
11576       // though.  Fortunately, none of the exceptions we see in that
11577       // code below are valid when the LHS is an overload set.  Note
11578       // that an overload set can be dependently-typed, but it never
11579       // instantiates to having an overloadable type.
11580       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11581       if (resolvedRHS.isInvalid()) return ExprError();
11582       RHSExpr = resolvedRHS.get();
11583 
11584       if (RHSExpr->isTypeDependent() ||
11585           RHSExpr->getType()->isOverloadableType())
11586         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11587     }
11588 
11589     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11590     if (LHS.isInvalid()) return ExprError();
11591     LHSExpr = LHS.get();
11592   }
11593 
11594   // Handle pseudo-objects in the RHS.
11595   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11596     // An overload in the RHS can potentially be resolved by the type
11597     // being assigned to.
11598     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11599       if (getLangOpts().CPlusPlus &&
11600           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11601            LHSExpr->getType()->isOverloadableType()))
11602         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11603 
11604       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11605     }
11606 
11607     // Don't resolve overloads if the other type is overloadable.
11608     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11609         LHSExpr->getType()->isOverloadableType())
11610       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11611 
11612     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11613     if (!resolvedRHS.isUsable()) return ExprError();
11614     RHSExpr = resolvedRHS.get();
11615   }
11616 
11617   if (getLangOpts().CPlusPlus) {
11618     // If either expression is type-dependent, always build an
11619     // overloaded op.
11620     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11621       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11622 
11623     // Otherwise, build an overloaded op if either expression has an
11624     // overloadable type.
11625     if (LHSExpr->getType()->isOverloadableType() ||
11626         RHSExpr->getType()->isOverloadableType())
11627       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11628   }
11629 
11630   // Build a built-in binary operation.
11631   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11632 }
11633 
11634 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11635                                       UnaryOperatorKind Opc,
11636                                       Expr *InputExpr) {
11637   ExprResult Input = InputExpr;
11638   ExprValueKind VK = VK_RValue;
11639   ExprObjectKind OK = OK_Ordinary;
11640   QualType resultType;
11641   if (getLangOpts().OpenCL) {
11642     QualType Ty = InputExpr->getType();
11643     // The only legal unary operation for atomics is '&'.
11644     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11645     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11646     // only with a builtin functions and therefore should be disallowed here.
11647         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11648         || Ty->isBlockPointerType())) {
11649       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11650                        << InputExpr->getType()
11651                        << Input.get()->getSourceRange());
11652     }
11653   }
11654   switch (Opc) {
11655   case UO_PreInc:
11656   case UO_PreDec:
11657   case UO_PostInc:
11658   case UO_PostDec:
11659     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11660                                                 OpLoc,
11661                                                 Opc == UO_PreInc ||
11662                                                 Opc == UO_PostInc,
11663                                                 Opc == UO_PreInc ||
11664                                                 Opc == UO_PreDec);
11665     break;
11666   case UO_AddrOf:
11667     resultType = CheckAddressOfOperand(Input, OpLoc);
11668     RecordModifiableNonNullParam(*this, InputExpr);
11669     break;
11670   case UO_Deref: {
11671     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11672     if (Input.isInvalid()) return ExprError();
11673     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11674     break;
11675   }
11676   case UO_Plus:
11677   case UO_Minus:
11678     Input = UsualUnaryConversions(Input.get());
11679     if (Input.isInvalid()) return ExprError();
11680     resultType = Input.get()->getType();
11681     if (resultType->isDependentType())
11682       break;
11683     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11684       break;
11685     else if (resultType->isVectorType() &&
11686              // The z vector extensions don't allow + or - with bool vectors.
11687              (!Context.getLangOpts().ZVector ||
11688               resultType->getAs<VectorType>()->getVectorKind() !=
11689               VectorType::AltiVecBool))
11690       break;
11691     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11692              Opc == UO_Plus &&
11693              resultType->isPointerType())
11694       break;
11695 
11696     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11697       << resultType << Input.get()->getSourceRange());
11698 
11699   case UO_Not: // bitwise complement
11700     Input = UsualUnaryConversions(Input.get());
11701     if (Input.isInvalid())
11702       return ExprError();
11703     resultType = Input.get()->getType();
11704     if (resultType->isDependentType())
11705       break;
11706     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11707     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11708       // C99 does not support '~' for complex conjugation.
11709       Diag(OpLoc, diag::ext_integer_complement_complex)
11710           << resultType << Input.get()->getSourceRange();
11711     else if (resultType->hasIntegerRepresentation())
11712       break;
11713     else if (resultType->isExtVectorType()) {
11714       if (Context.getLangOpts().OpenCL) {
11715         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11716         // on vector float types.
11717         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11718         if (!T->isIntegerType())
11719           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11720                            << resultType << Input.get()->getSourceRange());
11721       }
11722       break;
11723     } else {
11724       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11725                        << resultType << Input.get()->getSourceRange());
11726     }
11727     break;
11728 
11729   case UO_LNot: // logical negation
11730     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11731     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11732     if (Input.isInvalid()) return ExprError();
11733     resultType = Input.get()->getType();
11734 
11735     // Though we still have to promote half FP to float...
11736     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11737       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11738       resultType = Context.FloatTy;
11739     }
11740 
11741     if (resultType->isDependentType())
11742       break;
11743     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11744       // C99 6.5.3.3p1: ok, fallthrough;
11745       if (Context.getLangOpts().CPlusPlus) {
11746         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11747         // operand contextually converted to bool.
11748         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11749                                   ScalarTypeToBooleanCastKind(resultType));
11750       } else if (Context.getLangOpts().OpenCL &&
11751                  Context.getLangOpts().OpenCLVersion < 120) {
11752         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11753         // operate on scalar float types.
11754         if (!resultType->isIntegerType() && !resultType->isPointerType())
11755           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11756                            << resultType << Input.get()->getSourceRange());
11757       }
11758     } else if (resultType->isExtVectorType()) {
11759       if (Context.getLangOpts().OpenCL &&
11760           Context.getLangOpts().OpenCLVersion < 120) {
11761         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11762         // operate on vector float types.
11763         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11764         if (!T->isIntegerType())
11765           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11766                            << resultType << Input.get()->getSourceRange());
11767       }
11768       // Vector logical not returns the signed variant of the operand type.
11769       resultType = GetSignedVectorType(resultType);
11770       break;
11771     } else {
11772       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11773         << resultType << Input.get()->getSourceRange());
11774     }
11775 
11776     // LNot always has type int. C99 6.5.3.3p5.
11777     // In C++, it's bool. C++ 5.3.1p8
11778     resultType = Context.getLogicalOperationType();
11779     break;
11780   case UO_Real:
11781   case UO_Imag:
11782     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11783     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11784     // complex l-values to ordinary l-values and all other values to r-values.
11785     if (Input.isInvalid()) return ExprError();
11786     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11787       if (Input.get()->getValueKind() != VK_RValue &&
11788           Input.get()->getObjectKind() == OK_Ordinary)
11789         VK = Input.get()->getValueKind();
11790     } else if (!getLangOpts().CPlusPlus) {
11791       // In C, a volatile scalar is read by __imag. In C++, it is not.
11792       Input = DefaultLvalueConversion(Input.get());
11793     }
11794     break;
11795   case UO_Extension:
11796   case UO_Coawait:
11797     resultType = Input.get()->getType();
11798     VK = Input.get()->getValueKind();
11799     OK = Input.get()->getObjectKind();
11800     break;
11801   }
11802   if (resultType.isNull() || Input.isInvalid())
11803     return ExprError();
11804 
11805   // Check for array bounds violations in the operand of the UnaryOperator,
11806   // except for the '*' and '&' operators that have to be handled specially
11807   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11808   // that are explicitly defined as valid by the standard).
11809   if (Opc != UO_AddrOf && Opc != UO_Deref)
11810     CheckArrayAccess(Input.get());
11811 
11812   return new (Context)
11813       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11814 }
11815 
11816 /// \brief Determine whether the given expression is a qualified member
11817 /// access expression, of a form that could be turned into a pointer to member
11818 /// with the address-of operator.
11819 static bool isQualifiedMemberAccess(Expr *E) {
11820   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11821     if (!DRE->getQualifier())
11822       return false;
11823 
11824     ValueDecl *VD = DRE->getDecl();
11825     if (!VD->isCXXClassMember())
11826       return false;
11827 
11828     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11829       return true;
11830     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11831       return Method->isInstance();
11832 
11833     return false;
11834   }
11835 
11836   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11837     if (!ULE->getQualifier())
11838       return false;
11839 
11840     for (NamedDecl *D : ULE->decls()) {
11841       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11842         if (Method->isInstance())
11843           return true;
11844       } else {
11845         // Overload set does not contain methods.
11846         break;
11847       }
11848     }
11849 
11850     return false;
11851   }
11852 
11853   return false;
11854 }
11855 
11856 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11857                               UnaryOperatorKind Opc, Expr *Input) {
11858   // First things first: handle placeholders so that the
11859   // overloaded-operator check considers the right type.
11860   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11861     // Increment and decrement of pseudo-object references.
11862     if (pty->getKind() == BuiltinType::PseudoObject &&
11863         UnaryOperator::isIncrementDecrementOp(Opc))
11864       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11865 
11866     // extension is always a builtin operator.
11867     if (Opc == UO_Extension)
11868       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11869 
11870     // & gets special logic for several kinds of placeholder.
11871     // The builtin code knows what to do.
11872     if (Opc == UO_AddrOf &&
11873         (pty->getKind() == BuiltinType::Overload ||
11874          pty->getKind() == BuiltinType::UnknownAny ||
11875          pty->getKind() == BuiltinType::BoundMember))
11876       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11877 
11878     // Anything else needs to be handled now.
11879     ExprResult Result = CheckPlaceholderExpr(Input);
11880     if (Result.isInvalid()) return ExprError();
11881     Input = Result.get();
11882   }
11883 
11884   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11885       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11886       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11887     // Find all of the overloaded operators visible from this
11888     // point. We perform both an operator-name lookup from the local
11889     // scope and an argument-dependent lookup based on the types of
11890     // the arguments.
11891     UnresolvedSet<16> Functions;
11892     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11893     if (S && OverOp != OO_None)
11894       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11895                                    Functions);
11896 
11897     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11898   }
11899 
11900   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11901 }
11902 
11903 // Unary Operators.  'Tok' is the token for the operator.
11904 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11905                               tok::TokenKind Op, Expr *Input) {
11906   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11907 }
11908 
11909 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11910 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11911                                 LabelDecl *TheDecl) {
11912   TheDecl->markUsed(Context);
11913   // Create the AST node.  The address of a label always has type 'void*'.
11914   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11915                                      Context.getPointerType(Context.VoidTy));
11916 }
11917 
11918 /// Given the last statement in a statement-expression, check whether
11919 /// the result is a producing expression (like a call to an
11920 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11921 /// release out of the full-expression.  Otherwise, return null.
11922 /// Cannot fail.
11923 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11924   // Should always be wrapped with one of these.
11925   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11926   if (!cleanups) return nullptr;
11927 
11928   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11929   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11930     return nullptr;
11931 
11932   // Splice out the cast.  This shouldn't modify any interesting
11933   // features of the statement.
11934   Expr *producer = cast->getSubExpr();
11935   assert(producer->getType() == cast->getType());
11936   assert(producer->getValueKind() == cast->getValueKind());
11937   cleanups->setSubExpr(producer);
11938   return cleanups;
11939 }
11940 
11941 void Sema::ActOnStartStmtExpr() {
11942   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11943 }
11944 
11945 void Sema::ActOnStmtExprError() {
11946   // Note that function is also called by TreeTransform when leaving a
11947   // StmtExpr scope without rebuilding anything.
11948 
11949   DiscardCleanupsInEvaluationContext();
11950   PopExpressionEvaluationContext();
11951 }
11952 
11953 ExprResult
11954 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11955                     SourceLocation RPLoc) { // "({..})"
11956   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11957   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11958 
11959   if (hasAnyUnrecoverableErrorsInThisFunction())
11960     DiscardCleanupsInEvaluationContext();
11961   assert(!Cleanup.exprNeedsCleanups() &&
11962          "cleanups within StmtExpr not correctly bound!");
11963   PopExpressionEvaluationContext();
11964 
11965   // FIXME: there are a variety of strange constraints to enforce here, for
11966   // example, it is not possible to goto into a stmt expression apparently.
11967   // More semantic analysis is needed.
11968 
11969   // If there are sub-stmts in the compound stmt, take the type of the last one
11970   // as the type of the stmtexpr.
11971   QualType Ty = Context.VoidTy;
11972   bool StmtExprMayBindToTemp = false;
11973   if (!Compound->body_empty()) {
11974     Stmt *LastStmt = Compound->body_back();
11975     LabelStmt *LastLabelStmt = nullptr;
11976     // If LastStmt is a label, skip down through into the body.
11977     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11978       LastLabelStmt = Label;
11979       LastStmt = Label->getSubStmt();
11980     }
11981 
11982     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11983       // Do function/array conversion on the last expression, but not
11984       // lvalue-to-rvalue.  However, initialize an unqualified type.
11985       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11986       if (LastExpr.isInvalid())
11987         return ExprError();
11988       Ty = LastExpr.get()->getType().getUnqualifiedType();
11989 
11990       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11991         // In ARC, if the final expression ends in a consume, splice
11992         // the consume out and bind it later.  In the alternate case
11993         // (when dealing with a retainable type), the result
11994         // initialization will create a produce.  In both cases the
11995         // result will be +1, and we'll need to balance that out with
11996         // a bind.
11997         if (Expr *rebuiltLastStmt
11998               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11999           LastExpr = rebuiltLastStmt;
12000         } else {
12001           LastExpr = PerformCopyInitialization(
12002                             InitializedEntity::InitializeResult(LPLoc,
12003                                                                 Ty,
12004                                                                 false),
12005                                                    SourceLocation(),
12006                                                LastExpr);
12007         }
12008 
12009         if (LastExpr.isInvalid())
12010           return ExprError();
12011         if (LastExpr.get() != nullptr) {
12012           if (!LastLabelStmt)
12013             Compound->setLastStmt(LastExpr.get());
12014           else
12015             LastLabelStmt->setSubStmt(LastExpr.get());
12016           StmtExprMayBindToTemp = true;
12017         }
12018       }
12019     }
12020   }
12021 
12022   // FIXME: Check that expression type is complete/non-abstract; statement
12023   // expressions are not lvalues.
12024   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12025   if (StmtExprMayBindToTemp)
12026     return MaybeBindToTemporary(ResStmtExpr);
12027   return ResStmtExpr;
12028 }
12029 
12030 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12031                                       TypeSourceInfo *TInfo,
12032                                       ArrayRef<OffsetOfComponent> Components,
12033                                       SourceLocation RParenLoc) {
12034   QualType ArgTy = TInfo->getType();
12035   bool Dependent = ArgTy->isDependentType();
12036   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12037 
12038   // We must have at least one component that refers to the type, and the first
12039   // one is known to be a field designator.  Verify that the ArgTy represents
12040   // a struct/union/class.
12041   if (!Dependent && !ArgTy->isRecordType())
12042     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12043                        << ArgTy << TypeRange);
12044 
12045   // Type must be complete per C99 7.17p3 because a declaring a variable
12046   // with an incomplete type would be ill-formed.
12047   if (!Dependent
12048       && RequireCompleteType(BuiltinLoc, ArgTy,
12049                              diag::err_offsetof_incomplete_type, TypeRange))
12050     return ExprError();
12051 
12052   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12053   // GCC extension, diagnose them.
12054   // FIXME: This diagnostic isn't actually visible because the location is in
12055   // a system header!
12056   if (Components.size() != 1)
12057     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12058       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12059 
12060   bool DidWarnAboutNonPOD = false;
12061   QualType CurrentType = ArgTy;
12062   SmallVector<OffsetOfNode, 4> Comps;
12063   SmallVector<Expr*, 4> Exprs;
12064   for (const OffsetOfComponent &OC : Components) {
12065     if (OC.isBrackets) {
12066       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12067       if (!CurrentType->isDependentType()) {
12068         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12069         if(!AT)
12070           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12071                            << CurrentType);
12072         CurrentType = AT->getElementType();
12073       } else
12074         CurrentType = Context.DependentTy;
12075 
12076       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12077       if (IdxRval.isInvalid())
12078         return ExprError();
12079       Expr *Idx = IdxRval.get();
12080 
12081       // The expression must be an integral expression.
12082       // FIXME: An integral constant expression?
12083       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12084           !Idx->getType()->isIntegerType())
12085         return ExprError(Diag(Idx->getLocStart(),
12086                               diag::err_typecheck_subscript_not_integer)
12087                          << Idx->getSourceRange());
12088 
12089       // Record this array index.
12090       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12091       Exprs.push_back(Idx);
12092       continue;
12093     }
12094 
12095     // Offset of a field.
12096     if (CurrentType->isDependentType()) {
12097       // We have the offset of a field, but we can't look into the dependent
12098       // type. Just record the identifier of the field.
12099       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12100       CurrentType = Context.DependentTy;
12101       continue;
12102     }
12103 
12104     // We need to have a complete type to look into.
12105     if (RequireCompleteType(OC.LocStart, CurrentType,
12106                             diag::err_offsetof_incomplete_type))
12107       return ExprError();
12108 
12109     // Look for the designated field.
12110     const RecordType *RC = CurrentType->getAs<RecordType>();
12111     if (!RC)
12112       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12113                        << CurrentType);
12114     RecordDecl *RD = RC->getDecl();
12115 
12116     // C++ [lib.support.types]p5:
12117     //   The macro offsetof accepts a restricted set of type arguments in this
12118     //   International Standard. type shall be a POD structure or a POD union
12119     //   (clause 9).
12120     // C++11 [support.types]p4:
12121     //   If type is not a standard-layout class (Clause 9), the results are
12122     //   undefined.
12123     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12124       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12125       unsigned DiagID =
12126         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12127                             : diag::ext_offsetof_non_pod_type;
12128 
12129       if (!IsSafe && !DidWarnAboutNonPOD &&
12130           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12131                               PDiag(DiagID)
12132                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12133                               << CurrentType))
12134         DidWarnAboutNonPOD = true;
12135     }
12136 
12137     // Look for the field.
12138     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12139     LookupQualifiedName(R, RD);
12140     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12141     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12142     if (!MemberDecl) {
12143       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12144         MemberDecl = IndirectMemberDecl->getAnonField();
12145     }
12146 
12147     if (!MemberDecl)
12148       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12149                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12150                                                               OC.LocEnd));
12151 
12152     // C99 7.17p3:
12153     //   (If the specified member is a bit-field, the behavior is undefined.)
12154     //
12155     // We diagnose this as an error.
12156     if (MemberDecl->isBitField()) {
12157       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12158         << MemberDecl->getDeclName()
12159         << SourceRange(BuiltinLoc, RParenLoc);
12160       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12161       return ExprError();
12162     }
12163 
12164     RecordDecl *Parent = MemberDecl->getParent();
12165     if (IndirectMemberDecl)
12166       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12167 
12168     // If the member was found in a base class, introduce OffsetOfNodes for
12169     // the base class indirections.
12170     CXXBasePaths Paths;
12171     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12172                       Paths)) {
12173       if (Paths.getDetectedVirtual()) {
12174         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12175           << MemberDecl->getDeclName()
12176           << SourceRange(BuiltinLoc, RParenLoc);
12177         return ExprError();
12178       }
12179 
12180       CXXBasePath &Path = Paths.front();
12181       for (const CXXBasePathElement &B : Path)
12182         Comps.push_back(OffsetOfNode(B.Base));
12183     }
12184 
12185     if (IndirectMemberDecl) {
12186       for (auto *FI : IndirectMemberDecl->chain()) {
12187         assert(isa<FieldDecl>(FI));
12188         Comps.push_back(OffsetOfNode(OC.LocStart,
12189                                      cast<FieldDecl>(FI), OC.LocEnd));
12190       }
12191     } else
12192       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12193 
12194     CurrentType = MemberDecl->getType().getNonReferenceType();
12195   }
12196 
12197   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12198                               Comps, Exprs, RParenLoc);
12199 }
12200 
12201 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12202                                       SourceLocation BuiltinLoc,
12203                                       SourceLocation TypeLoc,
12204                                       ParsedType ParsedArgTy,
12205                                       ArrayRef<OffsetOfComponent> Components,
12206                                       SourceLocation RParenLoc) {
12207 
12208   TypeSourceInfo *ArgTInfo;
12209   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12210   if (ArgTy.isNull())
12211     return ExprError();
12212 
12213   if (!ArgTInfo)
12214     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12215 
12216   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12217 }
12218 
12219 
12220 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12221                                  Expr *CondExpr,
12222                                  Expr *LHSExpr, Expr *RHSExpr,
12223                                  SourceLocation RPLoc) {
12224   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12225 
12226   ExprValueKind VK = VK_RValue;
12227   ExprObjectKind OK = OK_Ordinary;
12228   QualType resType;
12229   bool ValueDependent = false;
12230   bool CondIsTrue = false;
12231   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12232     resType = Context.DependentTy;
12233     ValueDependent = true;
12234   } else {
12235     // The conditional expression is required to be a constant expression.
12236     llvm::APSInt condEval(32);
12237     ExprResult CondICE
12238       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12239           diag::err_typecheck_choose_expr_requires_constant, false);
12240     if (CondICE.isInvalid())
12241       return ExprError();
12242     CondExpr = CondICE.get();
12243     CondIsTrue = condEval.getZExtValue();
12244 
12245     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12246     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12247 
12248     resType = ActiveExpr->getType();
12249     ValueDependent = ActiveExpr->isValueDependent();
12250     VK = ActiveExpr->getValueKind();
12251     OK = ActiveExpr->getObjectKind();
12252   }
12253 
12254   return new (Context)
12255       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12256                  CondIsTrue, resType->isDependentType(), ValueDependent);
12257 }
12258 
12259 //===----------------------------------------------------------------------===//
12260 // Clang Extensions.
12261 //===----------------------------------------------------------------------===//
12262 
12263 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12264 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12265   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12266 
12267   if (LangOpts.CPlusPlus) {
12268     Decl *ManglingContextDecl;
12269     if (MangleNumberingContext *MCtx =
12270             getCurrentMangleNumberContext(Block->getDeclContext(),
12271                                           ManglingContextDecl)) {
12272       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12273       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12274     }
12275   }
12276 
12277   PushBlockScope(CurScope, Block);
12278   CurContext->addDecl(Block);
12279   if (CurScope)
12280     PushDeclContext(CurScope, Block);
12281   else
12282     CurContext = Block;
12283 
12284   getCurBlock()->HasImplicitReturnType = true;
12285 
12286   // Enter a new evaluation context to insulate the block from any
12287   // cleanups from the enclosing full-expression.
12288   PushExpressionEvaluationContext(
12289       ExpressionEvaluationContext::PotentiallyEvaluated);
12290 }
12291 
12292 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12293                                Scope *CurScope) {
12294   assert(ParamInfo.getIdentifier() == nullptr &&
12295          "block-id should have no identifier!");
12296   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12297   BlockScopeInfo *CurBlock = getCurBlock();
12298 
12299   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12300   QualType T = Sig->getType();
12301 
12302   // FIXME: We should allow unexpanded parameter packs here, but that would,
12303   // in turn, make the block expression contain unexpanded parameter packs.
12304   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12305     // Drop the parameters.
12306     FunctionProtoType::ExtProtoInfo EPI;
12307     EPI.HasTrailingReturn = false;
12308     EPI.TypeQuals |= DeclSpec::TQ_const;
12309     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12310     Sig = Context.getTrivialTypeSourceInfo(T);
12311   }
12312 
12313   // GetTypeForDeclarator always produces a function type for a block
12314   // literal signature.  Furthermore, it is always a FunctionProtoType
12315   // unless the function was written with a typedef.
12316   assert(T->isFunctionType() &&
12317          "GetTypeForDeclarator made a non-function block signature");
12318 
12319   // Look for an explicit signature in that function type.
12320   FunctionProtoTypeLoc ExplicitSignature;
12321 
12322   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12323   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12324 
12325     // Check whether that explicit signature was synthesized by
12326     // GetTypeForDeclarator.  If so, don't save that as part of the
12327     // written signature.
12328     if (ExplicitSignature.getLocalRangeBegin() ==
12329         ExplicitSignature.getLocalRangeEnd()) {
12330       // This would be much cheaper if we stored TypeLocs instead of
12331       // TypeSourceInfos.
12332       TypeLoc Result = ExplicitSignature.getReturnLoc();
12333       unsigned Size = Result.getFullDataSize();
12334       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12335       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12336 
12337       ExplicitSignature = FunctionProtoTypeLoc();
12338     }
12339   }
12340 
12341   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12342   CurBlock->FunctionType = T;
12343 
12344   const FunctionType *Fn = T->getAs<FunctionType>();
12345   QualType RetTy = Fn->getReturnType();
12346   bool isVariadic =
12347     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12348 
12349   CurBlock->TheDecl->setIsVariadic(isVariadic);
12350 
12351   // Context.DependentTy is used as a placeholder for a missing block
12352   // return type.  TODO:  what should we do with declarators like:
12353   //   ^ * { ... }
12354   // If the answer is "apply template argument deduction"....
12355   if (RetTy != Context.DependentTy) {
12356     CurBlock->ReturnType = RetTy;
12357     CurBlock->TheDecl->setBlockMissingReturnType(false);
12358     CurBlock->HasImplicitReturnType = false;
12359   }
12360 
12361   // Push block parameters from the declarator if we had them.
12362   SmallVector<ParmVarDecl*, 8> Params;
12363   if (ExplicitSignature) {
12364     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12365       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12366       if (Param->getIdentifier() == nullptr &&
12367           !Param->isImplicit() &&
12368           !Param->isInvalidDecl() &&
12369           !getLangOpts().CPlusPlus)
12370         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12371       Params.push_back(Param);
12372     }
12373 
12374   // Fake up parameter variables if we have a typedef, like
12375   //   ^ fntype { ... }
12376   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12377     for (const auto &I : Fn->param_types()) {
12378       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12379           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12380       Params.push_back(Param);
12381     }
12382   }
12383 
12384   // Set the parameters on the block decl.
12385   if (!Params.empty()) {
12386     CurBlock->TheDecl->setParams(Params);
12387     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12388                              /*CheckParameterNames=*/false);
12389   }
12390 
12391   // Finally we can process decl attributes.
12392   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12393 
12394   // Put the parameter variables in scope.
12395   for (auto AI : CurBlock->TheDecl->parameters()) {
12396     AI->setOwningFunction(CurBlock->TheDecl);
12397 
12398     // If this has an identifier, add it to the scope stack.
12399     if (AI->getIdentifier()) {
12400       CheckShadow(CurBlock->TheScope, AI);
12401 
12402       PushOnScopeChains(AI, CurBlock->TheScope);
12403     }
12404   }
12405 }
12406 
12407 /// ActOnBlockError - If there is an error parsing a block, this callback
12408 /// is invoked to pop the information about the block from the action impl.
12409 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12410   // Leave the expression-evaluation context.
12411   DiscardCleanupsInEvaluationContext();
12412   PopExpressionEvaluationContext();
12413 
12414   // Pop off CurBlock, handle nested blocks.
12415   PopDeclContext();
12416   PopFunctionScopeInfo();
12417 }
12418 
12419 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12420 /// literal was successfully completed.  ^(int x){...}
12421 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12422                                     Stmt *Body, Scope *CurScope) {
12423   // If blocks are disabled, emit an error.
12424   if (!LangOpts.Blocks)
12425     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12426 
12427   // Leave the expression-evaluation context.
12428   if (hasAnyUnrecoverableErrorsInThisFunction())
12429     DiscardCleanupsInEvaluationContext();
12430   assert(!Cleanup.exprNeedsCleanups() &&
12431          "cleanups within block not correctly bound!");
12432   PopExpressionEvaluationContext();
12433 
12434   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12435 
12436   if (BSI->HasImplicitReturnType)
12437     deduceClosureReturnType(*BSI);
12438 
12439   PopDeclContext();
12440 
12441   QualType RetTy = Context.VoidTy;
12442   if (!BSI->ReturnType.isNull())
12443     RetTy = BSI->ReturnType;
12444 
12445   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12446   QualType BlockTy;
12447 
12448   // Set the captured variables on the block.
12449   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12450   SmallVector<BlockDecl::Capture, 4> Captures;
12451   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12452     if (Cap.isThisCapture())
12453       continue;
12454     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12455                               Cap.isNested(), Cap.getInitExpr());
12456     Captures.push_back(NewCap);
12457   }
12458   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12459 
12460   // If the user wrote a function type in some form, try to use that.
12461   if (!BSI->FunctionType.isNull()) {
12462     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12463 
12464     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12465     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12466 
12467     // Turn protoless block types into nullary block types.
12468     if (isa<FunctionNoProtoType>(FTy)) {
12469       FunctionProtoType::ExtProtoInfo EPI;
12470       EPI.ExtInfo = Ext;
12471       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12472 
12473     // Otherwise, if we don't need to change anything about the function type,
12474     // preserve its sugar structure.
12475     } else if (FTy->getReturnType() == RetTy &&
12476                (!NoReturn || FTy->getNoReturnAttr())) {
12477       BlockTy = BSI->FunctionType;
12478 
12479     // Otherwise, make the minimal modifications to the function type.
12480     } else {
12481       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12482       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12483       EPI.TypeQuals = 0; // FIXME: silently?
12484       EPI.ExtInfo = Ext;
12485       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12486     }
12487 
12488   // If we don't have a function type, just build one from nothing.
12489   } else {
12490     FunctionProtoType::ExtProtoInfo EPI;
12491     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12492     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12493   }
12494 
12495   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12496   BlockTy = Context.getBlockPointerType(BlockTy);
12497 
12498   // If needed, diagnose invalid gotos and switches in the block.
12499   if (getCurFunction()->NeedsScopeChecking() &&
12500       !PP.isCodeCompletionEnabled())
12501     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12502 
12503   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12504 
12505   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12506     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12507 
12508   // Try to apply the named return value optimization. We have to check again
12509   // if we can do this, though, because blocks keep return statements around
12510   // to deduce an implicit return type.
12511   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12512       !BSI->TheDecl->isDependentContext())
12513     computeNRVO(Body, BSI);
12514 
12515   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12516   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12517   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12518 
12519   // If the block isn't obviously global, i.e. it captures anything at
12520   // all, then we need to do a few things in the surrounding context:
12521   if (Result->getBlockDecl()->hasCaptures()) {
12522     // First, this expression has a new cleanup object.
12523     ExprCleanupObjects.push_back(Result->getBlockDecl());
12524     Cleanup.setExprNeedsCleanups(true);
12525 
12526     // It also gets a branch-protected scope if any of the captured
12527     // variables needs destruction.
12528     for (const auto &CI : Result->getBlockDecl()->captures()) {
12529       const VarDecl *var = CI.getVariable();
12530       if (var->getType().isDestructedType() != QualType::DK_none) {
12531         getCurFunction()->setHasBranchProtectedScope();
12532         break;
12533       }
12534     }
12535   }
12536 
12537   return Result;
12538 }
12539 
12540 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12541                             SourceLocation RPLoc) {
12542   TypeSourceInfo *TInfo;
12543   GetTypeFromParser(Ty, &TInfo);
12544   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12545 }
12546 
12547 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12548                                 Expr *E, TypeSourceInfo *TInfo,
12549                                 SourceLocation RPLoc) {
12550   Expr *OrigExpr = E;
12551   bool IsMS = false;
12552 
12553   // CUDA device code does not support varargs.
12554   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12555     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12556       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12557       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12558         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12559     }
12560   }
12561 
12562   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12563   // as Microsoft ABI on an actual Microsoft platform, where
12564   // __builtin_ms_va_list and __builtin_va_list are the same.)
12565   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12566       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12567     QualType MSVaListType = Context.getBuiltinMSVaListType();
12568     if (Context.hasSameType(MSVaListType, E->getType())) {
12569       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12570         return ExprError();
12571       IsMS = true;
12572     }
12573   }
12574 
12575   // Get the va_list type
12576   QualType VaListType = Context.getBuiltinVaListType();
12577   if (!IsMS) {
12578     if (VaListType->isArrayType()) {
12579       // Deal with implicit array decay; for example, on x86-64,
12580       // va_list is an array, but it's supposed to decay to
12581       // a pointer for va_arg.
12582       VaListType = Context.getArrayDecayedType(VaListType);
12583       // Make sure the input expression also decays appropriately.
12584       ExprResult Result = UsualUnaryConversions(E);
12585       if (Result.isInvalid())
12586         return ExprError();
12587       E = Result.get();
12588     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12589       // If va_list is a record type and we are compiling in C++ mode,
12590       // check the argument using reference binding.
12591       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12592           Context, Context.getLValueReferenceType(VaListType), false);
12593       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12594       if (Init.isInvalid())
12595         return ExprError();
12596       E = Init.getAs<Expr>();
12597     } else {
12598       // Otherwise, the va_list argument must be an l-value because
12599       // it is modified by va_arg.
12600       if (!E->isTypeDependent() &&
12601           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12602         return ExprError();
12603     }
12604   }
12605 
12606   if (!IsMS && !E->isTypeDependent() &&
12607       !Context.hasSameType(VaListType, E->getType()))
12608     return ExprError(Diag(E->getLocStart(),
12609                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12610       << OrigExpr->getType() << E->getSourceRange());
12611 
12612   if (!TInfo->getType()->isDependentType()) {
12613     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12614                             diag::err_second_parameter_to_va_arg_incomplete,
12615                             TInfo->getTypeLoc()))
12616       return ExprError();
12617 
12618     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12619                                TInfo->getType(),
12620                                diag::err_second_parameter_to_va_arg_abstract,
12621                                TInfo->getTypeLoc()))
12622       return ExprError();
12623 
12624     if (!TInfo->getType().isPODType(Context)) {
12625       Diag(TInfo->getTypeLoc().getBeginLoc(),
12626            TInfo->getType()->isObjCLifetimeType()
12627              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12628              : diag::warn_second_parameter_to_va_arg_not_pod)
12629         << TInfo->getType()
12630         << TInfo->getTypeLoc().getSourceRange();
12631     }
12632 
12633     // Check for va_arg where arguments of the given type will be promoted
12634     // (i.e. this va_arg is guaranteed to have undefined behavior).
12635     QualType PromoteType;
12636     if (TInfo->getType()->isPromotableIntegerType()) {
12637       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12638       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12639         PromoteType = QualType();
12640     }
12641     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12642       PromoteType = Context.DoubleTy;
12643     if (!PromoteType.isNull())
12644       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12645                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12646                           << TInfo->getType()
12647                           << PromoteType
12648                           << TInfo->getTypeLoc().getSourceRange());
12649   }
12650 
12651   QualType T = TInfo->getType().getNonLValueExprType(Context);
12652   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12653 }
12654 
12655 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12656   // The type of __null will be int or long, depending on the size of
12657   // pointers on the target.
12658   QualType Ty;
12659   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12660   if (pw == Context.getTargetInfo().getIntWidth())
12661     Ty = Context.IntTy;
12662   else if (pw == Context.getTargetInfo().getLongWidth())
12663     Ty = Context.LongTy;
12664   else if (pw == Context.getTargetInfo().getLongLongWidth())
12665     Ty = Context.LongLongTy;
12666   else {
12667     llvm_unreachable("I don't know size of pointer!");
12668   }
12669 
12670   return new (Context) GNUNullExpr(Ty, TokenLoc);
12671 }
12672 
12673 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12674                                               bool Diagnose) {
12675   if (!getLangOpts().ObjC1)
12676     return false;
12677 
12678   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12679   if (!PT)
12680     return false;
12681 
12682   if (!PT->isObjCIdType()) {
12683     // Check if the destination is the 'NSString' interface.
12684     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12685     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12686       return false;
12687   }
12688 
12689   // Ignore any parens, implicit casts (should only be
12690   // array-to-pointer decays), and not-so-opaque values.  The last is
12691   // important for making this trigger for property assignments.
12692   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12693   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12694     if (OV->getSourceExpr())
12695       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12696 
12697   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12698   if (!SL || !SL->isAscii())
12699     return false;
12700   if (Diagnose) {
12701     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12702       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12703     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12704   }
12705   return true;
12706 }
12707 
12708 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12709                                               const Expr *SrcExpr) {
12710   if (!DstType->isFunctionPointerType() ||
12711       !SrcExpr->getType()->isFunctionType())
12712     return false;
12713 
12714   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12715   if (!DRE)
12716     return false;
12717 
12718   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12719   if (!FD)
12720     return false;
12721 
12722   return !S.checkAddressOfFunctionIsAvailable(FD,
12723                                               /*Complain=*/true,
12724                                               SrcExpr->getLocStart());
12725 }
12726 
12727 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12728                                     SourceLocation Loc,
12729                                     QualType DstType, QualType SrcType,
12730                                     Expr *SrcExpr, AssignmentAction Action,
12731                                     bool *Complained) {
12732   if (Complained)
12733     *Complained = false;
12734 
12735   // Decode the result (notice that AST's are still created for extensions).
12736   bool CheckInferredResultType = false;
12737   bool isInvalid = false;
12738   unsigned DiagKind = 0;
12739   FixItHint Hint;
12740   ConversionFixItGenerator ConvHints;
12741   bool MayHaveConvFixit = false;
12742   bool MayHaveFunctionDiff = false;
12743   const ObjCInterfaceDecl *IFace = nullptr;
12744   const ObjCProtocolDecl *PDecl = nullptr;
12745 
12746   switch (ConvTy) {
12747   case Compatible:
12748       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12749       return false;
12750 
12751   case PointerToInt:
12752     DiagKind = diag::ext_typecheck_convert_pointer_int;
12753     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12754     MayHaveConvFixit = true;
12755     break;
12756   case IntToPointer:
12757     DiagKind = diag::ext_typecheck_convert_int_pointer;
12758     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12759     MayHaveConvFixit = true;
12760     break;
12761   case IncompatiblePointer:
12762     if (Action == AA_Passing_CFAudited)
12763       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12764     else if (SrcType->isFunctionPointerType() &&
12765              DstType->isFunctionPointerType())
12766       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12767     else
12768       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12769 
12770     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12771       SrcType->isObjCObjectPointerType();
12772     if (Hint.isNull() && !CheckInferredResultType) {
12773       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12774     }
12775     else if (CheckInferredResultType) {
12776       SrcType = SrcType.getUnqualifiedType();
12777       DstType = DstType.getUnqualifiedType();
12778     }
12779     MayHaveConvFixit = true;
12780     break;
12781   case IncompatiblePointerSign:
12782     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12783     break;
12784   case FunctionVoidPointer:
12785     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12786     break;
12787   case IncompatiblePointerDiscardsQualifiers: {
12788     // Perform array-to-pointer decay if necessary.
12789     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12790 
12791     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12792     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12793     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12794       DiagKind = diag::err_typecheck_incompatible_address_space;
12795       break;
12796 
12797 
12798     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12799       DiagKind = diag::err_typecheck_incompatible_ownership;
12800       break;
12801     }
12802 
12803     llvm_unreachable("unknown error case for discarding qualifiers!");
12804     // fallthrough
12805   }
12806   case CompatiblePointerDiscardsQualifiers:
12807     // If the qualifiers lost were because we were applying the
12808     // (deprecated) C++ conversion from a string literal to a char*
12809     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12810     // Ideally, this check would be performed in
12811     // checkPointerTypesForAssignment. However, that would require a
12812     // bit of refactoring (so that the second argument is an
12813     // expression, rather than a type), which should be done as part
12814     // of a larger effort to fix checkPointerTypesForAssignment for
12815     // C++ semantics.
12816     if (getLangOpts().CPlusPlus &&
12817         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12818       return false;
12819     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12820     break;
12821   case IncompatibleNestedPointerQualifiers:
12822     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12823     break;
12824   case IntToBlockPointer:
12825     DiagKind = diag::err_int_to_block_pointer;
12826     break;
12827   case IncompatibleBlockPointer:
12828     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12829     break;
12830   case IncompatibleObjCQualifiedId: {
12831     if (SrcType->isObjCQualifiedIdType()) {
12832       const ObjCObjectPointerType *srcOPT =
12833                 SrcType->getAs<ObjCObjectPointerType>();
12834       for (auto *srcProto : srcOPT->quals()) {
12835         PDecl = srcProto;
12836         break;
12837       }
12838       if (const ObjCInterfaceType *IFaceT =
12839             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12840         IFace = IFaceT->getDecl();
12841     }
12842     else if (DstType->isObjCQualifiedIdType()) {
12843       const ObjCObjectPointerType *dstOPT =
12844         DstType->getAs<ObjCObjectPointerType>();
12845       for (auto *dstProto : dstOPT->quals()) {
12846         PDecl = dstProto;
12847         break;
12848       }
12849       if (const ObjCInterfaceType *IFaceT =
12850             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12851         IFace = IFaceT->getDecl();
12852     }
12853     DiagKind = diag::warn_incompatible_qualified_id;
12854     break;
12855   }
12856   case IncompatibleVectors:
12857     DiagKind = diag::warn_incompatible_vectors;
12858     break;
12859   case IncompatibleObjCWeakRef:
12860     DiagKind = diag::err_arc_weak_unavailable_assign;
12861     break;
12862   case Incompatible:
12863     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12864       if (Complained)
12865         *Complained = true;
12866       return true;
12867     }
12868 
12869     DiagKind = diag::err_typecheck_convert_incompatible;
12870     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12871     MayHaveConvFixit = true;
12872     isInvalid = true;
12873     MayHaveFunctionDiff = true;
12874     break;
12875   }
12876 
12877   QualType FirstType, SecondType;
12878   switch (Action) {
12879   case AA_Assigning:
12880   case AA_Initializing:
12881     // The destination type comes first.
12882     FirstType = DstType;
12883     SecondType = SrcType;
12884     break;
12885 
12886   case AA_Returning:
12887   case AA_Passing:
12888   case AA_Passing_CFAudited:
12889   case AA_Converting:
12890   case AA_Sending:
12891   case AA_Casting:
12892     // The source type comes first.
12893     FirstType = SrcType;
12894     SecondType = DstType;
12895     break;
12896   }
12897 
12898   PartialDiagnostic FDiag = PDiag(DiagKind);
12899   if (Action == AA_Passing_CFAudited)
12900     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12901   else
12902     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12903 
12904   // If we can fix the conversion, suggest the FixIts.
12905   assert(ConvHints.isNull() || Hint.isNull());
12906   if (!ConvHints.isNull()) {
12907     for (FixItHint &H : ConvHints.Hints)
12908       FDiag << H;
12909   } else {
12910     FDiag << Hint;
12911   }
12912   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12913 
12914   if (MayHaveFunctionDiff)
12915     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12916 
12917   Diag(Loc, FDiag);
12918   if (DiagKind == diag::warn_incompatible_qualified_id &&
12919       PDecl && IFace && !IFace->hasDefinition())
12920       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12921         << IFace->getName() << PDecl->getName();
12922 
12923   if (SecondType == Context.OverloadTy)
12924     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12925                               FirstType, /*TakingAddress=*/true);
12926 
12927   if (CheckInferredResultType)
12928     EmitRelatedResultTypeNote(SrcExpr);
12929 
12930   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12931     EmitRelatedResultTypeNoteForReturn(DstType);
12932 
12933   if (Complained)
12934     *Complained = true;
12935   return isInvalid;
12936 }
12937 
12938 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12939                                                  llvm::APSInt *Result) {
12940   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12941   public:
12942     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12943       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12944     }
12945   } Diagnoser;
12946 
12947   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12948 }
12949 
12950 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12951                                                  llvm::APSInt *Result,
12952                                                  unsigned DiagID,
12953                                                  bool AllowFold) {
12954   class IDDiagnoser : public VerifyICEDiagnoser {
12955     unsigned DiagID;
12956 
12957   public:
12958     IDDiagnoser(unsigned DiagID)
12959       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12960 
12961     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12962       S.Diag(Loc, DiagID) << SR;
12963     }
12964   } Diagnoser(DiagID);
12965 
12966   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12967 }
12968 
12969 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12970                                             SourceRange SR) {
12971   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12972 }
12973 
12974 ExprResult
12975 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12976                                       VerifyICEDiagnoser &Diagnoser,
12977                                       bool AllowFold) {
12978   SourceLocation DiagLoc = E->getLocStart();
12979 
12980   if (getLangOpts().CPlusPlus11) {
12981     // C++11 [expr.const]p5:
12982     //   If an expression of literal class type is used in a context where an
12983     //   integral constant expression is required, then that class type shall
12984     //   have a single non-explicit conversion function to an integral or
12985     //   unscoped enumeration type
12986     ExprResult Converted;
12987     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12988     public:
12989       CXX11ConvertDiagnoser(bool Silent)
12990           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12991                                 Silent, true) {}
12992 
12993       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12994                                            QualType T) override {
12995         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12996       }
12997 
12998       SemaDiagnosticBuilder diagnoseIncomplete(
12999           Sema &S, SourceLocation Loc, QualType T) override {
13000         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13001       }
13002 
13003       SemaDiagnosticBuilder diagnoseExplicitConv(
13004           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13005         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13006       }
13007 
13008       SemaDiagnosticBuilder noteExplicitConv(
13009           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13010         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13011                  << ConvTy->isEnumeralType() << ConvTy;
13012       }
13013 
13014       SemaDiagnosticBuilder diagnoseAmbiguous(
13015           Sema &S, SourceLocation Loc, QualType T) override {
13016         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13017       }
13018 
13019       SemaDiagnosticBuilder noteAmbiguous(
13020           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13021         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13022                  << ConvTy->isEnumeralType() << ConvTy;
13023       }
13024 
13025       SemaDiagnosticBuilder diagnoseConversion(
13026           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13027         llvm_unreachable("conversion functions are permitted");
13028       }
13029     } ConvertDiagnoser(Diagnoser.Suppress);
13030 
13031     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13032                                                     ConvertDiagnoser);
13033     if (Converted.isInvalid())
13034       return Converted;
13035     E = Converted.get();
13036     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13037       return ExprError();
13038   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13039     // An ICE must be of integral or unscoped enumeration type.
13040     if (!Diagnoser.Suppress)
13041       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13042     return ExprError();
13043   }
13044 
13045   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13046   // in the non-ICE case.
13047   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13048     if (Result)
13049       *Result = E->EvaluateKnownConstInt(Context);
13050     return E;
13051   }
13052 
13053   Expr::EvalResult EvalResult;
13054   SmallVector<PartialDiagnosticAt, 8> Notes;
13055   EvalResult.Diag = &Notes;
13056 
13057   // Try to evaluate the expression, and produce diagnostics explaining why it's
13058   // not a constant expression as a side-effect.
13059   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13060                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13061 
13062   // In C++11, we can rely on diagnostics being produced for any expression
13063   // which is not a constant expression. If no diagnostics were produced, then
13064   // this is a constant expression.
13065   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13066     if (Result)
13067       *Result = EvalResult.Val.getInt();
13068     return E;
13069   }
13070 
13071   // If our only note is the usual "invalid subexpression" note, just point
13072   // the caret at its location rather than producing an essentially
13073   // redundant note.
13074   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13075         diag::note_invalid_subexpr_in_const_expr) {
13076     DiagLoc = Notes[0].first;
13077     Notes.clear();
13078   }
13079 
13080   if (!Folded || !AllowFold) {
13081     if (!Diagnoser.Suppress) {
13082       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13083       for (const PartialDiagnosticAt &Note : Notes)
13084         Diag(Note.first, Note.second);
13085     }
13086 
13087     return ExprError();
13088   }
13089 
13090   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13091   for (const PartialDiagnosticAt &Note : Notes)
13092     Diag(Note.first, Note.second);
13093 
13094   if (Result)
13095     *Result = EvalResult.Val.getInt();
13096   return E;
13097 }
13098 
13099 namespace {
13100   // Handle the case where we conclude a expression which we speculatively
13101   // considered to be unevaluated is actually evaluated.
13102   class TransformToPE : public TreeTransform<TransformToPE> {
13103     typedef TreeTransform<TransformToPE> BaseTransform;
13104 
13105   public:
13106     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13107 
13108     // Make sure we redo semantic analysis
13109     bool AlwaysRebuild() { return true; }
13110 
13111     // Make sure we handle LabelStmts correctly.
13112     // FIXME: This does the right thing, but maybe we need a more general
13113     // fix to TreeTransform?
13114     StmtResult TransformLabelStmt(LabelStmt *S) {
13115       S->getDecl()->setStmt(nullptr);
13116       return BaseTransform::TransformLabelStmt(S);
13117     }
13118 
13119     // We need to special-case DeclRefExprs referring to FieldDecls which
13120     // are not part of a member pointer formation; normal TreeTransforming
13121     // doesn't catch this case because of the way we represent them in the AST.
13122     // FIXME: This is a bit ugly; is it really the best way to handle this
13123     // case?
13124     //
13125     // Error on DeclRefExprs referring to FieldDecls.
13126     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13127       if (isa<FieldDecl>(E->getDecl()) &&
13128           !SemaRef.isUnevaluatedContext())
13129         return SemaRef.Diag(E->getLocation(),
13130                             diag::err_invalid_non_static_member_use)
13131             << E->getDecl() << E->getSourceRange();
13132 
13133       return BaseTransform::TransformDeclRefExpr(E);
13134     }
13135 
13136     // Exception: filter out member pointer formation
13137     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13138       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13139         return E;
13140 
13141       return BaseTransform::TransformUnaryOperator(E);
13142     }
13143 
13144     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13145       // Lambdas never need to be transformed.
13146       return E;
13147     }
13148   };
13149 }
13150 
13151 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13152   assert(isUnevaluatedContext() &&
13153          "Should only transform unevaluated expressions");
13154   ExprEvalContexts.back().Context =
13155       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13156   if (isUnevaluatedContext())
13157     return E;
13158   return TransformToPE(*this).TransformExpr(E);
13159 }
13160 
13161 void
13162 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13163                                       Decl *LambdaContextDecl,
13164                                       bool IsDecltype) {
13165   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13166                                 LambdaContextDecl, IsDecltype);
13167   Cleanup.reset();
13168   if (!MaybeODRUseExprs.empty())
13169     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13170 }
13171 
13172 void
13173 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13174                                       ReuseLambdaContextDecl_t,
13175                                       bool IsDecltype) {
13176   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13177   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13178 }
13179 
13180 void Sema::PopExpressionEvaluationContext() {
13181   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13182   unsigned NumTypos = Rec.NumTypos;
13183 
13184   if (!Rec.Lambdas.empty()) {
13185     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13186       unsigned D;
13187       if (Rec.isUnevaluated()) {
13188         // C++11 [expr.prim.lambda]p2:
13189         //   A lambda-expression shall not appear in an unevaluated operand
13190         //   (Clause 5).
13191         D = diag::err_lambda_unevaluated_operand;
13192       } else {
13193         // C++1y [expr.const]p2:
13194         //   A conditional-expression e is a core constant expression unless the
13195         //   evaluation of e, following the rules of the abstract machine, would
13196         //   evaluate [...] a lambda-expression.
13197         D = diag::err_lambda_in_constant_expression;
13198       }
13199 
13200       // C++1z allows lambda expressions as core constant expressions.
13201       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13202       // 1607) from appearing within template-arguments and array-bounds that
13203       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13204       // unevaluated contexts) might lift some of these restrictions in a
13205       // future version.
13206       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13207         for (const auto *L : Rec.Lambdas)
13208           Diag(L->getLocStart(), D);
13209     } else {
13210       // Mark the capture expressions odr-used. This was deferred
13211       // during lambda expression creation.
13212       for (auto *Lambda : Rec.Lambdas) {
13213         for (auto *C : Lambda->capture_inits())
13214           MarkDeclarationsReferencedInExpr(C);
13215       }
13216     }
13217   }
13218 
13219   // When are coming out of an unevaluated context, clear out any
13220   // temporaries that we may have created as part of the evaluation of
13221   // the expression in that context: they aren't relevant because they
13222   // will never be constructed.
13223   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13224     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13225                              ExprCleanupObjects.end());
13226     Cleanup = Rec.ParentCleanup;
13227     CleanupVarDeclMarking();
13228     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13229   // Otherwise, merge the contexts together.
13230   } else {
13231     Cleanup.mergeFrom(Rec.ParentCleanup);
13232     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13233                             Rec.SavedMaybeODRUseExprs.end());
13234   }
13235 
13236   // Pop the current expression evaluation context off the stack.
13237   ExprEvalContexts.pop_back();
13238 
13239   if (!ExprEvalContexts.empty())
13240     ExprEvalContexts.back().NumTypos += NumTypos;
13241   else
13242     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13243                             "last ExpressionEvaluationContextRecord");
13244 }
13245 
13246 void Sema::DiscardCleanupsInEvaluationContext() {
13247   ExprCleanupObjects.erase(
13248          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13249          ExprCleanupObjects.end());
13250   Cleanup.reset();
13251   MaybeODRUseExprs.clear();
13252 }
13253 
13254 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13255   if (!E->getType()->isVariablyModifiedType())
13256     return E;
13257   return TransformToPotentiallyEvaluated(E);
13258 }
13259 
13260 /// Are we within a context in which some evaluation could be performed (be it
13261 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13262 /// captured by C++'s idea of an "unevaluated context".
13263 static bool isEvaluatableContext(Sema &SemaRef) {
13264   switch (SemaRef.ExprEvalContexts.back().Context) {
13265     case Sema::ExpressionEvaluationContext::Unevaluated:
13266     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13267     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13268       // Expressions in this context are never evaluated.
13269       return false;
13270 
13271     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13272     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13273     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13274       // Expressions in this context could be evaluated.
13275       return true;
13276 
13277     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13278       // Referenced declarations will only be used if the construct in the
13279       // containing expression is used, at which point we'll be given another
13280       // turn to mark them.
13281       return false;
13282   }
13283   llvm_unreachable("Invalid context");
13284 }
13285 
13286 /// Are we within a context in which references to resolved functions or to
13287 /// variables result in odr-use?
13288 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13289   // An expression in a template is not really an expression until it's been
13290   // instantiated, so it doesn't trigger odr-use.
13291   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13292     return false;
13293 
13294   switch (SemaRef.ExprEvalContexts.back().Context) {
13295     case Sema::ExpressionEvaluationContext::Unevaluated:
13296     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13297     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13298     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13299       return false;
13300 
13301     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13302     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13303       return true;
13304 
13305     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13306       return false;
13307   }
13308   llvm_unreachable("Invalid context");
13309 }
13310 
13311 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13312   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13313   return Func->isConstexpr() &&
13314          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13315 }
13316 
13317 /// \brief Mark a function referenced, and check whether it is odr-used
13318 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13319 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13320                                   bool MightBeOdrUse) {
13321   assert(Func && "No function?");
13322 
13323   Func->setReferenced();
13324 
13325   // C++11 [basic.def.odr]p3:
13326   //   A function whose name appears as a potentially-evaluated expression is
13327   //   odr-used if it is the unique lookup result or the selected member of a
13328   //   set of overloaded functions [...].
13329   //
13330   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13331   // can just check that here.
13332   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13333 
13334   // Determine whether we require a function definition to exist, per
13335   // C++11 [temp.inst]p3:
13336   //   Unless a function template specialization has been explicitly
13337   //   instantiated or explicitly specialized, the function template
13338   //   specialization is implicitly instantiated when the specialization is
13339   //   referenced in a context that requires a function definition to exist.
13340   //
13341   // That is either when this is an odr-use, or when a usage of a constexpr
13342   // function occurs within an evaluatable context.
13343   bool NeedDefinition =
13344       OdrUse || (isEvaluatableContext(*this) &&
13345                  isImplicitlyDefinableConstexprFunction(Func));
13346 
13347   // C++14 [temp.expl.spec]p6:
13348   //   If a template [...] is explicitly specialized then that specialization
13349   //   shall be declared before the first use of that specialization that would
13350   //   cause an implicit instantiation to take place, in every translation unit
13351   //   in which such a use occurs
13352   if (NeedDefinition &&
13353       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13354        Func->getMemberSpecializationInfo()))
13355     checkSpecializationVisibility(Loc, Func);
13356 
13357   // C++14 [except.spec]p17:
13358   //   An exception-specification is considered to be needed when:
13359   //   - the function is odr-used or, if it appears in an unevaluated operand,
13360   //     would be odr-used if the expression were potentially-evaluated;
13361   //
13362   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13363   // function is a pure virtual function we're calling, and in that case the
13364   // function was selected by overload resolution and we need to resolve its
13365   // exception specification for a different reason.
13366   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13367   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13368     ResolveExceptionSpec(Loc, FPT);
13369 
13370   // If we don't need to mark the function as used, and we don't need to
13371   // try to provide a definition, there's nothing more to do.
13372   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13373       (!NeedDefinition || Func->getBody()))
13374     return;
13375 
13376   // Note that this declaration has been used.
13377   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13378     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13379     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13380       if (Constructor->isDefaultConstructor()) {
13381         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13382           return;
13383         DefineImplicitDefaultConstructor(Loc, Constructor);
13384       } else if (Constructor->isCopyConstructor()) {
13385         DefineImplicitCopyConstructor(Loc, Constructor);
13386       } else if (Constructor->isMoveConstructor()) {
13387         DefineImplicitMoveConstructor(Loc, Constructor);
13388       }
13389     } else if (Constructor->getInheritedConstructor()) {
13390       DefineInheritingConstructor(Loc, Constructor);
13391     }
13392   } else if (CXXDestructorDecl *Destructor =
13393                  dyn_cast<CXXDestructorDecl>(Func)) {
13394     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13395     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13396       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13397         return;
13398       DefineImplicitDestructor(Loc, Destructor);
13399     }
13400     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13401       MarkVTableUsed(Loc, Destructor->getParent());
13402   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13403     if (MethodDecl->isOverloadedOperator() &&
13404         MethodDecl->getOverloadedOperator() == OO_Equal) {
13405       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13406       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13407         if (MethodDecl->isCopyAssignmentOperator())
13408           DefineImplicitCopyAssignment(Loc, MethodDecl);
13409         else if (MethodDecl->isMoveAssignmentOperator())
13410           DefineImplicitMoveAssignment(Loc, MethodDecl);
13411       }
13412     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13413                MethodDecl->getParent()->isLambda()) {
13414       CXXConversionDecl *Conversion =
13415           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13416       if (Conversion->isLambdaToBlockPointerConversion())
13417         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13418       else
13419         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13420     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13421       MarkVTableUsed(Loc, MethodDecl->getParent());
13422   }
13423 
13424   // Recursive functions should be marked when used from another function.
13425   // FIXME: Is this really right?
13426   if (CurContext == Func) return;
13427 
13428   // Implicit instantiation of function templates and member functions of
13429   // class templates.
13430   if (Func->isImplicitlyInstantiable()) {
13431     bool AlreadyInstantiated = false;
13432     SourceLocation PointOfInstantiation = Loc;
13433     if (FunctionTemplateSpecializationInfo *SpecInfo
13434                               = Func->getTemplateSpecializationInfo()) {
13435       if (SpecInfo->getPointOfInstantiation().isInvalid())
13436         SpecInfo->setPointOfInstantiation(Loc);
13437       else if (SpecInfo->getTemplateSpecializationKind()
13438                  == TSK_ImplicitInstantiation) {
13439         AlreadyInstantiated = true;
13440         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13441       }
13442     } else if (MemberSpecializationInfo *MSInfo
13443                                 = Func->getMemberSpecializationInfo()) {
13444       if (MSInfo->getPointOfInstantiation().isInvalid())
13445         MSInfo->setPointOfInstantiation(Loc);
13446       else if (MSInfo->getTemplateSpecializationKind()
13447                  == TSK_ImplicitInstantiation) {
13448         AlreadyInstantiated = true;
13449         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13450       }
13451     }
13452 
13453     if (!AlreadyInstantiated || Func->isConstexpr()) {
13454       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13455           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13456           CodeSynthesisContexts.size())
13457         PendingLocalImplicitInstantiations.push_back(
13458             std::make_pair(Func, PointOfInstantiation));
13459       else if (Func->isConstexpr())
13460         // Do not defer instantiations of constexpr functions, to avoid the
13461         // expression evaluator needing to call back into Sema if it sees a
13462         // call to such a function.
13463         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13464       else {
13465         PendingInstantiations.push_back(std::make_pair(Func,
13466                                                        PointOfInstantiation));
13467         // Notify the consumer that a function was implicitly instantiated.
13468         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13469       }
13470     }
13471   } else {
13472     // Walk redefinitions, as some of them may be instantiable.
13473     for (auto i : Func->redecls()) {
13474       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13475         MarkFunctionReferenced(Loc, i, OdrUse);
13476     }
13477   }
13478 
13479   if (!OdrUse) return;
13480 
13481   // Keep track of used but undefined functions.
13482   if (!Func->isDefined()) {
13483     if (mightHaveNonExternalLinkage(Func))
13484       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13485     else if (Func->getMostRecentDecl()->isInlined() &&
13486              !LangOpts.GNUInline &&
13487              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13488       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13489   }
13490 
13491   Func->markUsed(Context);
13492 }
13493 
13494 static void
13495 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13496                                    ValueDecl *var, DeclContext *DC) {
13497   DeclContext *VarDC = var->getDeclContext();
13498 
13499   //  If the parameter still belongs to the translation unit, then
13500   //  we're actually just using one parameter in the declaration of
13501   //  the next.
13502   if (isa<ParmVarDecl>(var) &&
13503       isa<TranslationUnitDecl>(VarDC))
13504     return;
13505 
13506   // For C code, don't diagnose about capture if we're not actually in code
13507   // right now; it's impossible to write a non-constant expression outside of
13508   // function context, so we'll get other (more useful) diagnostics later.
13509   //
13510   // For C++, things get a bit more nasty... it would be nice to suppress this
13511   // diagnostic for certain cases like using a local variable in an array bound
13512   // for a member of a local class, but the correct predicate is not obvious.
13513   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13514     return;
13515 
13516   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13517   unsigned ContextKind = 3; // unknown
13518   if (isa<CXXMethodDecl>(VarDC) &&
13519       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13520     ContextKind = 2;
13521   } else if (isa<FunctionDecl>(VarDC)) {
13522     ContextKind = 0;
13523   } else if (isa<BlockDecl>(VarDC)) {
13524     ContextKind = 1;
13525   }
13526 
13527   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13528     << var << ValueKind << ContextKind << VarDC;
13529   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13530       << var;
13531 
13532   // FIXME: Add additional diagnostic info about class etc. which prevents
13533   // capture.
13534 }
13535 
13536 
13537 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13538                                       bool &SubCapturesAreNested,
13539                                       QualType &CaptureType,
13540                                       QualType &DeclRefType) {
13541    // Check whether we've already captured it.
13542   if (CSI->CaptureMap.count(Var)) {
13543     // If we found a capture, any subcaptures are nested.
13544     SubCapturesAreNested = true;
13545 
13546     // Retrieve the capture type for this variable.
13547     CaptureType = CSI->getCapture(Var).getCaptureType();
13548 
13549     // Compute the type of an expression that refers to this variable.
13550     DeclRefType = CaptureType.getNonReferenceType();
13551 
13552     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13553     // are mutable in the sense that user can change their value - they are
13554     // private instances of the captured declarations.
13555     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13556     if (Cap.isCopyCapture() &&
13557         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13558         !(isa<CapturedRegionScopeInfo>(CSI) &&
13559           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13560       DeclRefType.addConst();
13561     return true;
13562   }
13563   return false;
13564 }
13565 
13566 // Only block literals, captured statements, and lambda expressions can
13567 // capture; other scopes don't work.
13568 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13569                                  SourceLocation Loc,
13570                                  const bool Diagnose, Sema &S) {
13571   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13572     return getLambdaAwareParentOfDeclContext(DC);
13573   else if (Var->hasLocalStorage()) {
13574     if (Diagnose)
13575        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13576   }
13577   return nullptr;
13578 }
13579 
13580 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13581 // certain types of variables (unnamed, variably modified types etc.)
13582 // so check for eligibility.
13583 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13584                                  SourceLocation Loc,
13585                                  const bool Diagnose, Sema &S) {
13586 
13587   bool IsBlock = isa<BlockScopeInfo>(CSI);
13588   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13589 
13590   // Lambdas are not allowed to capture unnamed variables
13591   // (e.g. anonymous unions).
13592   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13593   // assuming that's the intent.
13594   if (IsLambda && !Var->getDeclName()) {
13595     if (Diagnose) {
13596       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13597       S.Diag(Var->getLocation(), diag::note_declared_at);
13598     }
13599     return false;
13600   }
13601 
13602   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13603   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13604     if (Diagnose) {
13605       S.Diag(Loc, diag::err_ref_vm_type);
13606       S.Diag(Var->getLocation(), diag::note_previous_decl)
13607         << Var->getDeclName();
13608     }
13609     return false;
13610   }
13611   // Prohibit structs with flexible array members too.
13612   // We cannot capture what is in the tail end of the struct.
13613   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13614     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13615       if (Diagnose) {
13616         if (IsBlock)
13617           S.Diag(Loc, diag::err_ref_flexarray_type);
13618         else
13619           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13620             << Var->getDeclName();
13621         S.Diag(Var->getLocation(), diag::note_previous_decl)
13622           << Var->getDeclName();
13623       }
13624       return false;
13625     }
13626   }
13627   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13628   // Lambdas and captured statements are not allowed to capture __block
13629   // variables; they don't support the expected semantics.
13630   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13631     if (Diagnose) {
13632       S.Diag(Loc, diag::err_capture_block_variable)
13633         << Var->getDeclName() << !IsLambda;
13634       S.Diag(Var->getLocation(), diag::note_previous_decl)
13635         << Var->getDeclName();
13636     }
13637     return false;
13638   }
13639   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13640   if (S.getLangOpts().OpenCL && IsBlock &&
13641       Var->getType()->isBlockPointerType()) {
13642     if (Diagnose)
13643       S.Diag(Loc, diag::err_opencl_block_ref_block);
13644     return false;
13645   }
13646 
13647   return true;
13648 }
13649 
13650 // Returns true if the capture by block was successful.
13651 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13652                                  SourceLocation Loc,
13653                                  const bool BuildAndDiagnose,
13654                                  QualType &CaptureType,
13655                                  QualType &DeclRefType,
13656                                  const bool Nested,
13657                                  Sema &S) {
13658   Expr *CopyExpr = nullptr;
13659   bool ByRef = false;
13660 
13661   // Blocks are not allowed to capture arrays.
13662   if (CaptureType->isArrayType()) {
13663     if (BuildAndDiagnose) {
13664       S.Diag(Loc, diag::err_ref_array_type);
13665       S.Diag(Var->getLocation(), diag::note_previous_decl)
13666       << Var->getDeclName();
13667     }
13668     return false;
13669   }
13670 
13671   // Forbid the block-capture of autoreleasing variables.
13672   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13673     if (BuildAndDiagnose) {
13674       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13675         << /*block*/ 0;
13676       S.Diag(Var->getLocation(), diag::note_previous_decl)
13677         << Var->getDeclName();
13678     }
13679     return false;
13680   }
13681 
13682   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13683   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13684     // This function finds out whether there is an AttributedType of kind
13685     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13686     // attr_objc_ownership implies __autoreleasing was explicitly specified
13687     // rather than being added implicitly by the compiler.
13688     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13689       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13690         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13691           return true;
13692 
13693         // Peel off AttributedTypes that are not of kind objc_ownership.
13694         Ty = AttrTy->getModifiedType();
13695       }
13696 
13697       return false;
13698     };
13699 
13700     QualType PointeeTy = PT->getPointeeType();
13701 
13702     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13703         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13704         !IsObjCOwnershipAttributedType(PointeeTy)) {
13705       if (BuildAndDiagnose) {
13706         SourceLocation VarLoc = Var->getLocation();
13707         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13708         {
13709           auto AddAutoreleaseNote =
13710               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13711           // Provide a fix-it for the '__autoreleasing' keyword at the
13712           // appropriate location in the variable's type.
13713           if (const auto *TSI = Var->getTypeSourceInfo()) {
13714             PointerTypeLoc PTL =
13715                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13716             if (PTL) {
13717               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13718               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13719                                                S.getLangOpts());
13720               if (Loc.isValid()) {
13721                 StringRef CharAtLoc = Lexer::getSourceText(
13722                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13723                     S.getSourceManager(), S.getLangOpts());
13724                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13725                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13726                              ? " __autoreleasing "
13727                              : " __autoreleasing");
13728               }
13729             }
13730           }
13731         }
13732         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13733       }
13734     }
13735   }
13736 
13737   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13738   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13739       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13740     // Block capture by reference does not change the capture or
13741     // declaration reference types.
13742     ByRef = true;
13743   } else {
13744     // Block capture by copy introduces 'const'.
13745     CaptureType = CaptureType.getNonReferenceType().withConst();
13746     DeclRefType = CaptureType;
13747 
13748     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13749       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13750         // The capture logic needs the destructor, so make sure we mark it.
13751         // Usually this is unnecessary because most local variables have
13752         // their destructors marked at declaration time, but parameters are
13753         // an exception because it's technically only the call site that
13754         // actually requires the destructor.
13755         if (isa<ParmVarDecl>(Var))
13756           S.FinalizeVarWithDestructor(Var, Record);
13757 
13758         // Enter a new evaluation context to insulate the copy
13759         // full-expression.
13760         EnterExpressionEvaluationContext scope(
13761             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13762 
13763         // According to the blocks spec, the capture of a variable from
13764         // the stack requires a const copy constructor.  This is not true
13765         // of the copy/move done to move a __block variable to the heap.
13766         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13767                                                   DeclRefType.withConst(),
13768                                                   VK_LValue, Loc);
13769 
13770         ExprResult Result
13771           = S.PerformCopyInitialization(
13772               InitializedEntity::InitializeBlock(Var->getLocation(),
13773                                                   CaptureType, false),
13774               Loc, DeclRef);
13775 
13776         // Build a full-expression copy expression if initialization
13777         // succeeded and used a non-trivial constructor.  Recover from
13778         // errors by pretending that the copy isn't necessary.
13779         if (!Result.isInvalid() &&
13780             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13781                 ->isTrivial()) {
13782           Result = S.MaybeCreateExprWithCleanups(Result);
13783           CopyExpr = Result.get();
13784         }
13785       }
13786     }
13787   }
13788 
13789   // Actually capture the variable.
13790   if (BuildAndDiagnose)
13791     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13792                     SourceLocation(), CaptureType, CopyExpr);
13793 
13794   return true;
13795 
13796 }
13797 
13798 
13799 /// \brief Capture the given variable in the captured region.
13800 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13801                                     VarDecl *Var,
13802                                     SourceLocation Loc,
13803                                     const bool BuildAndDiagnose,
13804                                     QualType &CaptureType,
13805                                     QualType &DeclRefType,
13806                                     const bool RefersToCapturedVariable,
13807                                     Sema &S) {
13808   // By default, capture variables by reference.
13809   bool ByRef = true;
13810   // Using an LValue reference type is consistent with Lambdas (see below).
13811   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13812     if (S.IsOpenMPCapturedDecl(Var))
13813       DeclRefType = DeclRefType.getUnqualifiedType();
13814     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13815   }
13816 
13817   if (ByRef)
13818     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13819   else
13820     CaptureType = DeclRefType;
13821 
13822   Expr *CopyExpr = nullptr;
13823   if (BuildAndDiagnose) {
13824     // The current implementation assumes that all variables are captured
13825     // by references. Since there is no capture by copy, no expression
13826     // evaluation will be needed.
13827     RecordDecl *RD = RSI->TheRecordDecl;
13828 
13829     FieldDecl *Field
13830       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13831                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13832                           nullptr, false, ICIS_NoInit);
13833     Field->setImplicit(true);
13834     Field->setAccess(AS_private);
13835     RD->addDecl(Field);
13836 
13837     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13838                                             DeclRefType, VK_LValue, Loc);
13839     Var->setReferenced(true);
13840     Var->markUsed(S.Context);
13841   }
13842 
13843   // Actually capture the variable.
13844   if (BuildAndDiagnose)
13845     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13846                     SourceLocation(), CaptureType, CopyExpr);
13847 
13848 
13849   return true;
13850 }
13851 
13852 /// \brief Create a field within the lambda class for the variable
13853 /// being captured.
13854 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13855                                     QualType FieldType, QualType DeclRefType,
13856                                     SourceLocation Loc,
13857                                     bool RefersToCapturedVariable) {
13858   CXXRecordDecl *Lambda = LSI->Lambda;
13859 
13860   // Build the non-static data member.
13861   FieldDecl *Field
13862     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13863                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13864                         nullptr, false, ICIS_NoInit);
13865   Field->setImplicit(true);
13866   Field->setAccess(AS_private);
13867   Lambda->addDecl(Field);
13868 }
13869 
13870 /// \brief Capture the given variable in the lambda.
13871 static bool captureInLambda(LambdaScopeInfo *LSI,
13872                             VarDecl *Var,
13873                             SourceLocation Loc,
13874                             const bool BuildAndDiagnose,
13875                             QualType &CaptureType,
13876                             QualType &DeclRefType,
13877                             const bool RefersToCapturedVariable,
13878                             const Sema::TryCaptureKind Kind,
13879                             SourceLocation EllipsisLoc,
13880                             const bool IsTopScope,
13881                             Sema &S) {
13882 
13883   // Determine whether we are capturing by reference or by value.
13884   bool ByRef = false;
13885   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13886     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13887   } else {
13888     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13889   }
13890 
13891   // Compute the type of the field that will capture this variable.
13892   if (ByRef) {
13893     // C++11 [expr.prim.lambda]p15:
13894     //   An entity is captured by reference if it is implicitly or
13895     //   explicitly captured but not captured by copy. It is
13896     //   unspecified whether additional unnamed non-static data
13897     //   members are declared in the closure type for entities
13898     //   captured by reference.
13899     //
13900     // FIXME: It is not clear whether we want to build an lvalue reference
13901     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13902     // to do the former, while EDG does the latter. Core issue 1249 will
13903     // clarify, but for now we follow GCC because it's a more permissive and
13904     // easily defensible position.
13905     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13906   } else {
13907     // C++11 [expr.prim.lambda]p14:
13908     //   For each entity captured by copy, an unnamed non-static
13909     //   data member is declared in the closure type. The
13910     //   declaration order of these members is unspecified. The type
13911     //   of such a data member is the type of the corresponding
13912     //   captured entity if the entity is not a reference to an
13913     //   object, or the referenced type otherwise. [Note: If the
13914     //   captured entity is a reference to a function, the
13915     //   corresponding data member is also a reference to a
13916     //   function. - end note ]
13917     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13918       if (!RefType->getPointeeType()->isFunctionType())
13919         CaptureType = RefType->getPointeeType();
13920     }
13921 
13922     // Forbid the lambda copy-capture of autoreleasing variables.
13923     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13924       if (BuildAndDiagnose) {
13925         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13926         S.Diag(Var->getLocation(), diag::note_previous_decl)
13927           << Var->getDeclName();
13928       }
13929       return false;
13930     }
13931 
13932     // Make sure that by-copy captures are of a complete and non-abstract type.
13933     if (BuildAndDiagnose) {
13934       if (!CaptureType->isDependentType() &&
13935           S.RequireCompleteType(Loc, CaptureType,
13936                                 diag::err_capture_of_incomplete_type,
13937                                 Var->getDeclName()))
13938         return false;
13939 
13940       if (S.RequireNonAbstractType(Loc, CaptureType,
13941                                    diag::err_capture_of_abstract_type))
13942         return false;
13943     }
13944   }
13945 
13946   // Capture this variable in the lambda.
13947   if (BuildAndDiagnose)
13948     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13949                             RefersToCapturedVariable);
13950 
13951   // Compute the type of a reference to this captured variable.
13952   if (ByRef)
13953     DeclRefType = CaptureType.getNonReferenceType();
13954   else {
13955     // C++ [expr.prim.lambda]p5:
13956     //   The closure type for a lambda-expression has a public inline
13957     //   function call operator [...]. This function call operator is
13958     //   declared const (9.3.1) if and only if the lambda-expression's
13959     //   parameter-declaration-clause is not followed by mutable.
13960     DeclRefType = CaptureType.getNonReferenceType();
13961     if (!LSI->Mutable && !CaptureType->isReferenceType())
13962       DeclRefType.addConst();
13963   }
13964 
13965   // Add the capture.
13966   if (BuildAndDiagnose)
13967     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13968                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13969 
13970   return true;
13971 }
13972 
13973 bool Sema::tryCaptureVariable(
13974     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13975     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13976     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13977   // An init-capture is notionally from the context surrounding its
13978   // declaration, but its parent DC is the lambda class.
13979   DeclContext *VarDC = Var->getDeclContext();
13980   if (Var->isInitCapture())
13981     VarDC = VarDC->getParent();
13982 
13983   DeclContext *DC = CurContext;
13984   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13985       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13986   // We need to sync up the Declaration Context with the
13987   // FunctionScopeIndexToStopAt
13988   if (FunctionScopeIndexToStopAt) {
13989     unsigned FSIndex = FunctionScopes.size() - 1;
13990     while (FSIndex != MaxFunctionScopesIndex) {
13991       DC = getLambdaAwareParentOfDeclContext(DC);
13992       --FSIndex;
13993     }
13994   }
13995 
13996 
13997   // If the variable is declared in the current context, there is no need to
13998   // capture it.
13999   if (VarDC == DC) return true;
14000 
14001   // Capture global variables if it is required to use private copy of this
14002   // variable.
14003   bool IsGlobal = !Var->hasLocalStorage();
14004   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14005     return true;
14006 
14007   // Walk up the stack to determine whether we can capture the variable,
14008   // performing the "simple" checks that don't depend on type. We stop when
14009   // we've either hit the declared scope of the variable or find an existing
14010   // capture of that variable.  We start from the innermost capturing-entity
14011   // (the DC) and ensure that all intervening capturing-entities
14012   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14013   // declcontext can either capture the variable or have already captured
14014   // the variable.
14015   CaptureType = Var->getType();
14016   DeclRefType = CaptureType.getNonReferenceType();
14017   bool Nested = false;
14018   bool Explicit = (Kind != TryCapture_Implicit);
14019   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14020   do {
14021     // Only block literals, captured statements, and lambda expressions can
14022     // capture; other scopes don't work.
14023     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14024                                                               ExprLoc,
14025                                                               BuildAndDiagnose,
14026                                                               *this);
14027     // We need to check for the parent *first* because, if we *have*
14028     // private-captured a global variable, we need to recursively capture it in
14029     // intermediate blocks, lambdas, etc.
14030     if (!ParentDC) {
14031       if (IsGlobal) {
14032         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14033         break;
14034       }
14035       return true;
14036     }
14037 
14038     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14039     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14040 
14041 
14042     // Check whether we've already captured it.
14043     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14044                                              DeclRefType)) {
14045       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14046       break;
14047     }
14048     // If we are instantiating a generic lambda call operator body,
14049     // we do not want to capture new variables.  What was captured
14050     // during either a lambdas transformation or initial parsing
14051     // should be used.
14052     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14053       if (BuildAndDiagnose) {
14054         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14055         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14056           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14057           Diag(Var->getLocation(), diag::note_previous_decl)
14058              << Var->getDeclName();
14059           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14060         } else
14061           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14062       }
14063       return true;
14064     }
14065     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14066     // certain types of variables (unnamed, variably modified types etc.)
14067     // so check for eligibility.
14068     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14069        return true;
14070 
14071     // Try to capture variable-length arrays types.
14072     if (Var->getType()->isVariablyModifiedType()) {
14073       // We're going to walk down into the type and look for VLA
14074       // expressions.
14075       QualType QTy = Var->getType();
14076       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14077         QTy = PVD->getOriginalType();
14078       captureVariablyModifiedType(Context, QTy, CSI);
14079     }
14080 
14081     if (getLangOpts().OpenMP) {
14082       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14083         // OpenMP private variables should not be captured in outer scope, so
14084         // just break here. Similarly, global variables that are captured in a
14085         // target region should not be captured outside the scope of the region.
14086         if (RSI->CapRegionKind == CR_OpenMP) {
14087           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14088           // When we detect target captures we are looking from inside the
14089           // target region, therefore we need to propagate the capture from the
14090           // enclosing region. Therefore, the capture is not initially nested.
14091           if (IsTargetCap)
14092             FunctionScopesIndex--;
14093 
14094           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14095             Nested = !IsTargetCap;
14096             DeclRefType = DeclRefType.getUnqualifiedType();
14097             CaptureType = Context.getLValueReferenceType(DeclRefType);
14098             break;
14099           }
14100         }
14101       }
14102     }
14103     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14104       // No capture-default, and this is not an explicit capture
14105       // so cannot capture this variable.
14106       if (BuildAndDiagnose) {
14107         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14108         Diag(Var->getLocation(), diag::note_previous_decl)
14109           << Var->getDeclName();
14110         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14111           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14112                diag::note_lambda_decl);
14113         // FIXME: If we error out because an outer lambda can not implicitly
14114         // capture a variable that an inner lambda explicitly captures, we
14115         // should have the inner lambda do the explicit capture - because
14116         // it makes for cleaner diagnostics later.  This would purely be done
14117         // so that the diagnostic does not misleadingly claim that a variable
14118         // can not be captured by a lambda implicitly even though it is captured
14119         // explicitly.  Suggestion:
14120         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14121         //    at the function head
14122         //  - cache the StartingDeclContext - this must be a lambda
14123         //  - captureInLambda in the innermost lambda the variable.
14124       }
14125       return true;
14126     }
14127 
14128     FunctionScopesIndex--;
14129     DC = ParentDC;
14130     Explicit = false;
14131   } while (!VarDC->Equals(DC));
14132 
14133   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14134   // computing the type of the capture at each step, checking type-specific
14135   // requirements, and adding captures if requested.
14136   // If the variable had already been captured previously, we start capturing
14137   // at the lambda nested within that one.
14138   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14139        ++I) {
14140     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14141 
14142     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14143       if (!captureInBlock(BSI, Var, ExprLoc,
14144                           BuildAndDiagnose, CaptureType,
14145                           DeclRefType, Nested, *this))
14146         return true;
14147       Nested = true;
14148     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14149       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14150                                    BuildAndDiagnose, CaptureType,
14151                                    DeclRefType, Nested, *this))
14152         return true;
14153       Nested = true;
14154     } else {
14155       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14156       if (!captureInLambda(LSI, Var, ExprLoc,
14157                            BuildAndDiagnose, CaptureType,
14158                            DeclRefType, Nested, Kind, EllipsisLoc,
14159                             /*IsTopScope*/I == N - 1, *this))
14160         return true;
14161       Nested = true;
14162     }
14163   }
14164   return false;
14165 }
14166 
14167 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14168                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14169   QualType CaptureType;
14170   QualType DeclRefType;
14171   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14172                             /*BuildAndDiagnose=*/true, CaptureType,
14173                             DeclRefType, nullptr);
14174 }
14175 
14176 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14177   QualType CaptureType;
14178   QualType DeclRefType;
14179   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14180                              /*BuildAndDiagnose=*/false, CaptureType,
14181                              DeclRefType, nullptr);
14182 }
14183 
14184 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14185   QualType CaptureType;
14186   QualType DeclRefType;
14187 
14188   // Determine whether we can capture this variable.
14189   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14190                          /*BuildAndDiagnose=*/false, CaptureType,
14191                          DeclRefType, nullptr))
14192     return QualType();
14193 
14194   return DeclRefType;
14195 }
14196 
14197 
14198 
14199 // If either the type of the variable or the initializer is dependent,
14200 // return false. Otherwise, determine whether the variable is a constant
14201 // expression. Use this if you need to know if a variable that might or
14202 // might not be dependent is truly a constant expression.
14203 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14204     ASTContext &Context) {
14205 
14206   if (Var->getType()->isDependentType())
14207     return false;
14208   const VarDecl *DefVD = nullptr;
14209   Var->getAnyInitializer(DefVD);
14210   if (!DefVD)
14211     return false;
14212   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14213   Expr *Init = cast<Expr>(Eval->Value);
14214   if (Init->isValueDependent())
14215     return false;
14216   return IsVariableAConstantExpression(Var, Context);
14217 }
14218 
14219 
14220 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14221   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14222   // an object that satisfies the requirements for appearing in a
14223   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14224   // is immediately applied."  This function handles the lvalue-to-rvalue
14225   // conversion part.
14226   MaybeODRUseExprs.erase(E->IgnoreParens());
14227 
14228   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14229   // to a variable that is a constant expression, and if so, identify it as
14230   // a reference to a variable that does not involve an odr-use of that
14231   // variable.
14232   if (LambdaScopeInfo *LSI = getCurLambda()) {
14233     Expr *SansParensExpr = E->IgnoreParens();
14234     VarDecl *Var = nullptr;
14235     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14236       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14237     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14238       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14239 
14240     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14241       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14242   }
14243 }
14244 
14245 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14246   Res = CorrectDelayedTyposInExpr(Res);
14247 
14248   if (!Res.isUsable())
14249     return Res;
14250 
14251   // If a constant-expression is a reference to a variable where we delay
14252   // deciding whether it is an odr-use, just assume we will apply the
14253   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14254   // (a non-type template argument), we have special handling anyway.
14255   UpdateMarkingForLValueToRValue(Res.get());
14256   return Res;
14257 }
14258 
14259 void Sema::CleanupVarDeclMarking() {
14260   for (Expr *E : MaybeODRUseExprs) {
14261     VarDecl *Var;
14262     SourceLocation Loc;
14263     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14264       Var = cast<VarDecl>(DRE->getDecl());
14265       Loc = DRE->getLocation();
14266     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14267       Var = cast<VarDecl>(ME->getMemberDecl());
14268       Loc = ME->getMemberLoc();
14269     } else {
14270       llvm_unreachable("Unexpected expression");
14271     }
14272 
14273     MarkVarDeclODRUsed(Var, Loc, *this,
14274                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14275   }
14276 
14277   MaybeODRUseExprs.clear();
14278 }
14279 
14280 
14281 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14282                                     VarDecl *Var, Expr *E) {
14283   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14284          "Invalid Expr argument to DoMarkVarDeclReferenced");
14285   Var->setReferenced();
14286 
14287   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14288 
14289   bool OdrUseContext = isOdrUseContext(SemaRef);
14290   bool NeedDefinition =
14291       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14292                         Var->isUsableInConstantExpressions(SemaRef.Context));
14293 
14294   VarTemplateSpecializationDecl *VarSpec =
14295       dyn_cast<VarTemplateSpecializationDecl>(Var);
14296   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14297          "Can't instantiate a partial template specialization.");
14298 
14299   // If this might be a member specialization of a static data member, check
14300   // the specialization is visible. We already did the checks for variable
14301   // template specializations when we created them.
14302   if (NeedDefinition && TSK != TSK_Undeclared &&
14303       !isa<VarTemplateSpecializationDecl>(Var))
14304     SemaRef.checkSpecializationVisibility(Loc, Var);
14305 
14306   // Perform implicit instantiation of static data members, static data member
14307   // templates of class templates, and variable template specializations. Delay
14308   // instantiations of variable templates, except for those that could be used
14309   // in a constant expression.
14310   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14311     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14312 
14313     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14314       if (Var->getPointOfInstantiation().isInvalid()) {
14315         // This is a modification of an existing AST node. Notify listeners.
14316         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14317           L->StaticDataMemberInstantiated(Var);
14318       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14319         // Don't bother trying to instantiate it again, unless we might need
14320         // its initializer before we get to the end of the TU.
14321         TryInstantiating = false;
14322     }
14323 
14324     if (Var->getPointOfInstantiation().isInvalid())
14325       Var->setTemplateSpecializationKind(TSK, Loc);
14326 
14327     if (TryInstantiating) {
14328       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14329       bool InstantiationDependent = false;
14330       bool IsNonDependent =
14331           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14332                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14333                   : true;
14334 
14335       // Do not instantiate specializations that are still type-dependent.
14336       if (IsNonDependent) {
14337         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14338           // Do not defer instantiations of variables which could be used in a
14339           // constant expression.
14340           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14341         } else {
14342           SemaRef.PendingInstantiations
14343               .push_back(std::make_pair(Var, PointOfInstantiation));
14344         }
14345       }
14346     }
14347   }
14348 
14349   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14350   // the requirements for appearing in a constant expression (5.19) and, if
14351   // it is an object, the lvalue-to-rvalue conversion (4.1)
14352   // is immediately applied."  We check the first part here, and
14353   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14354   // Note that we use the C++11 definition everywhere because nothing in
14355   // C++03 depends on whether we get the C++03 version correct. The second
14356   // part does not apply to references, since they are not objects.
14357   if (OdrUseContext && E &&
14358       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14359     // A reference initialized by a constant expression can never be
14360     // odr-used, so simply ignore it.
14361     if (!Var->getType()->isReferenceType())
14362       SemaRef.MaybeODRUseExprs.insert(E);
14363   } else if (OdrUseContext) {
14364     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14365                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14366   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14367     // If this is a dependent context, we don't need to mark variables as
14368     // odr-used, but we may still need to track them for lambda capture.
14369     // FIXME: Do we also need to do this inside dependent typeid expressions
14370     // (which are modeled as unevaluated at this point)?
14371     const bool RefersToEnclosingScope =
14372         (SemaRef.CurContext != Var->getDeclContext() &&
14373          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14374     if (RefersToEnclosingScope) {
14375       LambdaScopeInfo *const LSI =
14376           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14377       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14378         // If a variable could potentially be odr-used, defer marking it so
14379         // until we finish analyzing the full expression for any
14380         // lvalue-to-rvalue
14381         // or discarded value conversions that would obviate odr-use.
14382         // Add it to the list of potential captures that will be analyzed
14383         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14384         // unless the variable is a reference that was initialized by a constant
14385         // expression (this will never need to be captured or odr-used).
14386         assert(E && "Capture variable should be used in an expression.");
14387         if (!Var->getType()->isReferenceType() ||
14388             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14389           LSI->addPotentialCapture(E->IgnoreParens());
14390       }
14391     }
14392   }
14393 }
14394 
14395 /// \brief Mark a variable referenced, and check whether it is odr-used
14396 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14397 /// used directly for normal expressions referring to VarDecl.
14398 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14399   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14400 }
14401 
14402 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14403                                Decl *D, Expr *E, bool MightBeOdrUse) {
14404   if (SemaRef.isInOpenMPDeclareTargetContext())
14405     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14406 
14407   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14408     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14409     return;
14410   }
14411 
14412   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14413 
14414   // If this is a call to a method via a cast, also mark the method in the
14415   // derived class used in case codegen can devirtualize the call.
14416   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14417   if (!ME)
14418     return;
14419   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14420   if (!MD)
14421     return;
14422   // Only attempt to devirtualize if this is truly a virtual call.
14423   bool IsVirtualCall = MD->isVirtual() &&
14424                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14425   if (!IsVirtualCall)
14426     return;
14427   const Expr *Base = ME->getBase();
14428   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14429   if (!MostDerivedClassDecl)
14430     return;
14431   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14432   if (!DM || DM->isPure())
14433     return;
14434   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14435 }
14436 
14437 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14438 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14439   // TODO: update this with DR# once a defect report is filed.
14440   // C++11 defect. The address of a pure member should not be an ODR use, even
14441   // if it's a qualified reference.
14442   bool OdrUse = true;
14443   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14444     if (Method->isVirtual())
14445       OdrUse = false;
14446   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14447 }
14448 
14449 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14450 void Sema::MarkMemberReferenced(MemberExpr *E) {
14451   // C++11 [basic.def.odr]p2:
14452   //   A non-overloaded function whose name appears as a potentially-evaluated
14453   //   expression or a member of a set of candidate functions, if selected by
14454   //   overload resolution when referred to from a potentially-evaluated
14455   //   expression, is odr-used, unless it is a pure virtual function and its
14456   //   name is not explicitly qualified.
14457   bool MightBeOdrUse = true;
14458   if (E->performsVirtualDispatch(getLangOpts())) {
14459     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14460       if (Method->isPure())
14461         MightBeOdrUse = false;
14462   }
14463   SourceLocation Loc = E->getMemberLoc().isValid() ?
14464                             E->getMemberLoc() : E->getLocStart();
14465   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14466 }
14467 
14468 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14469 /// marks the declaration referenced, and performs odr-use checking for
14470 /// functions and variables. This method should not be used when building a
14471 /// normal expression which refers to a variable.
14472 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14473                                  bool MightBeOdrUse) {
14474   if (MightBeOdrUse) {
14475     if (auto *VD = dyn_cast<VarDecl>(D)) {
14476       MarkVariableReferenced(Loc, VD);
14477       return;
14478     }
14479   }
14480   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14481     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14482     return;
14483   }
14484   D->setReferenced();
14485 }
14486 
14487 namespace {
14488   // Mark all of the declarations used by a type as referenced.
14489   // FIXME: Not fully implemented yet! We need to have a better understanding
14490   // of when we're entering a context we should not recurse into.
14491   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14492   // TreeTransforms rebuilding the type in a new context. Rather than
14493   // duplicating the TreeTransform logic, we should consider reusing it here.
14494   // Currently that causes problems when rebuilding LambdaExprs.
14495   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14496     Sema &S;
14497     SourceLocation Loc;
14498 
14499   public:
14500     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14501 
14502     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14503 
14504     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14505   };
14506 }
14507 
14508 bool MarkReferencedDecls::TraverseTemplateArgument(
14509     const TemplateArgument &Arg) {
14510   {
14511     // A non-type template argument is a constant-evaluated context.
14512     EnterExpressionEvaluationContext Evaluated(
14513         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14514     if (Arg.getKind() == TemplateArgument::Declaration) {
14515       if (Decl *D = Arg.getAsDecl())
14516         S.MarkAnyDeclReferenced(Loc, D, true);
14517     } else if (Arg.getKind() == TemplateArgument::Expression) {
14518       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14519     }
14520   }
14521 
14522   return Inherited::TraverseTemplateArgument(Arg);
14523 }
14524 
14525 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14526   MarkReferencedDecls Marker(*this, Loc);
14527   Marker.TraverseType(T);
14528 }
14529 
14530 namespace {
14531   /// \brief Helper class that marks all of the declarations referenced by
14532   /// potentially-evaluated subexpressions as "referenced".
14533   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14534     Sema &S;
14535     bool SkipLocalVariables;
14536 
14537   public:
14538     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14539 
14540     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14541       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14542 
14543     void VisitDeclRefExpr(DeclRefExpr *E) {
14544       // If we were asked not to visit local variables, don't.
14545       if (SkipLocalVariables) {
14546         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14547           if (VD->hasLocalStorage())
14548             return;
14549       }
14550 
14551       S.MarkDeclRefReferenced(E);
14552     }
14553 
14554     void VisitMemberExpr(MemberExpr *E) {
14555       S.MarkMemberReferenced(E);
14556       Inherited::VisitMemberExpr(E);
14557     }
14558 
14559     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14560       S.MarkFunctionReferenced(E->getLocStart(),
14561             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14562       Visit(E->getSubExpr());
14563     }
14564 
14565     void VisitCXXNewExpr(CXXNewExpr *E) {
14566       if (E->getOperatorNew())
14567         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14568       if (E->getOperatorDelete())
14569         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14570       Inherited::VisitCXXNewExpr(E);
14571     }
14572 
14573     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14574       if (E->getOperatorDelete())
14575         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14576       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14577       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14578         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14579         S.MarkFunctionReferenced(E->getLocStart(),
14580                                     S.LookupDestructor(Record));
14581       }
14582 
14583       Inherited::VisitCXXDeleteExpr(E);
14584     }
14585 
14586     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14587       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14588       Inherited::VisitCXXConstructExpr(E);
14589     }
14590 
14591     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14592       Visit(E->getExpr());
14593     }
14594 
14595     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14596       Inherited::VisitImplicitCastExpr(E);
14597 
14598       if (E->getCastKind() == CK_LValueToRValue)
14599         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14600     }
14601   };
14602 }
14603 
14604 /// \brief Mark any declarations that appear within this expression or any
14605 /// potentially-evaluated subexpressions as "referenced".
14606 ///
14607 /// \param SkipLocalVariables If true, don't mark local variables as
14608 /// 'referenced'.
14609 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14610                                             bool SkipLocalVariables) {
14611   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14612 }
14613 
14614 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14615 /// of the program being compiled.
14616 ///
14617 /// This routine emits the given diagnostic when the code currently being
14618 /// type-checked is "potentially evaluated", meaning that there is a
14619 /// possibility that the code will actually be executable. Code in sizeof()
14620 /// expressions, code used only during overload resolution, etc., are not
14621 /// potentially evaluated. This routine will suppress such diagnostics or,
14622 /// in the absolutely nutty case of potentially potentially evaluated
14623 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14624 /// later.
14625 ///
14626 /// This routine should be used for all diagnostics that describe the run-time
14627 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14628 /// Failure to do so will likely result in spurious diagnostics or failures
14629 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14630 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14631                                const PartialDiagnostic &PD) {
14632   switch (ExprEvalContexts.back().Context) {
14633   case ExpressionEvaluationContext::Unevaluated:
14634   case ExpressionEvaluationContext::UnevaluatedList:
14635   case ExpressionEvaluationContext::UnevaluatedAbstract:
14636   case ExpressionEvaluationContext::DiscardedStatement:
14637     // The argument will never be evaluated, so don't complain.
14638     break;
14639 
14640   case ExpressionEvaluationContext::ConstantEvaluated:
14641     // Relevant diagnostics should be produced by constant evaluation.
14642     break;
14643 
14644   case ExpressionEvaluationContext::PotentiallyEvaluated:
14645   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14646     if (Statement && getCurFunctionOrMethodDecl()) {
14647       FunctionScopes.back()->PossiblyUnreachableDiags.
14648         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14649     }
14650     else
14651       Diag(Loc, PD);
14652 
14653     return true;
14654   }
14655 
14656   return false;
14657 }
14658 
14659 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14660                                CallExpr *CE, FunctionDecl *FD) {
14661   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14662     return false;
14663 
14664   // If we're inside a decltype's expression, don't check for a valid return
14665   // type or construct temporaries until we know whether this is the last call.
14666   if (ExprEvalContexts.back().IsDecltype) {
14667     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14668     return false;
14669   }
14670 
14671   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14672     FunctionDecl *FD;
14673     CallExpr *CE;
14674 
14675   public:
14676     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14677       : FD(FD), CE(CE) { }
14678 
14679     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14680       if (!FD) {
14681         S.Diag(Loc, diag::err_call_incomplete_return)
14682           << T << CE->getSourceRange();
14683         return;
14684       }
14685 
14686       S.Diag(Loc, diag::err_call_function_incomplete_return)
14687         << CE->getSourceRange() << FD->getDeclName() << T;
14688       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14689           << FD->getDeclName();
14690     }
14691   } Diagnoser(FD, CE);
14692 
14693   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14694     return true;
14695 
14696   return false;
14697 }
14698 
14699 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14700 // will prevent this condition from triggering, which is what we want.
14701 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14702   SourceLocation Loc;
14703 
14704   unsigned diagnostic = diag::warn_condition_is_assignment;
14705   bool IsOrAssign = false;
14706 
14707   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14708     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14709       return;
14710 
14711     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14712 
14713     // Greylist some idioms by putting them into a warning subcategory.
14714     if (ObjCMessageExpr *ME
14715           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14716       Selector Sel = ME->getSelector();
14717 
14718       // self = [<foo> init...]
14719       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14720         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14721 
14722       // <foo> = [<bar> nextObject]
14723       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14724         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14725     }
14726 
14727     Loc = Op->getOperatorLoc();
14728   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14729     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14730       return;
14731 
14732     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14733     Loc = Op->getOperatorLoc();
14734   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14735     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14736   else {
14737     // Not an assignment.
14738     return;
14739   }
14740 
14741   Diag(Loc, diagnostic) << E->getSourceRange();
14742 
14743   SourceLocation Open = E->getLocStart();
14744   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14745   Diag(Loc, diag::note_condition_assign_silence)
14746         << FixItHint::CreateInsertion(Open, "(")
14747         << FixItHint::CreateInsertion(Close, ")");
14748 
14749   if (IsOrAssign)
14750     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14751       << FixItHint::CreateReplacement(Loc, "!=");
14752   else
14753     Diag(Loc, diag::note_condition_assign_to_comparison)
14754       << FixItHint::CreateReplacement(Loc, "==");
14755 }
14756 
14757 /// \brief Redundant parentheses over an equality comparison can indicate
14758 /// that the user intended an assignment used as condition.
14759 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14760   // Don't warn if the parens came from a macro.
14761   SourceLocation parenLoc = ParenE->getLocStart();
14762   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14763     return;
14764   // Don't warn for dependent expressions.
14765   if (ParenE->isTypeDependent())
14766     return;
14767 
14768   Expr *E = ParenE->IgnoreParens();
14769 
14770   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14771     if (opE->getOpcode() == BO_EQ &&
14772         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14773                                                            == Expr::MLV_Valid) {
14774       SourceLocation Loc = opE->getOperatorLoc();
14775 
14776       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14777       SourceRange ParenERange = ParenE->getSourceRange();
14778       Diag(Loc, diag::note_equality_comparison_silence)
14779         << FixItHint::CreateRemoval(ParenERange.getBegin())
14780         << FixItHint::CreateRemoval(ParenERange.getEnd());
14781       Diag(Loc, diag::note_equality_comparison_to_assign)
14782         << FixItHint::CreateReplacement(Loc, "=");
14783     }
14784 }
14785 
14786 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14787                                        bool IsConstexpr) {
14788   DiagnoseAssignmentAsCondition(E);
14789   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14790     DiagnoseEqualityWithExtraParens(parenE);
14791 
14792   ExprResult result = CheckPlaceholderExpr(E);
14793   if (result.isInvalid()) return ExprError();
14794   E = result.get();
14795 
14796   if (!E->isTypeDependent()) {
14797     if (getLangOpts().CPlusPlus)
14798       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14799 
14800     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14801     if (ERes.isInvalid())
14802       return ExprError();
14803     E = ERes.get();
14804 
14805     QualType T = E->getType();
14806     if (!T->isScalarType()) { // C99 6.8.4.1p1
14807       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14808         << T << E->getSourceRange();
14809       return ExprError();
14810     }
14811     CheckBoolLikeConversion(E, Loc);
14812   }
14813 
14814   return E;
14815 }
14816 
14817 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14818                                            Expr *SubExpr, ConditionKind CK) {
14819   // Empty conditions are valid in for-statements.
14820   if (!SubExpr)
14821     return ConditionResult();
14822 
14823   ExprResult Cond;
14824   switch (CK) {
14825   case ConditionKind::Boolean:
14826     Cond = CheckBooleanCondition(Loc, SubExpr);
14827     break;
14828 
14829   case ConditionKind::ConstexprIf:
14830     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14831     break;
14832 
14833   case ConditionKind::Switch:
14834     Cond = CheckSwitchCondition(Loc, SubExpr);
14835     break;
14836   }
14837   if (Cond.isInvalid())
14838     return ConditionError();
14839 
14840   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14841   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14842   if (!FullExpr.get())
14843     return ConditionError();
14844 
14845   return ConditionResult(*this, nullptr, FullExpr,
14846                          CK == ConditionKind::ConstexprIf);
14847 }
14848 
14849 namespace {
14850   /// A visitor for rebuilding a call to an __unknown_any expression
14851   /// to have an appropriate type.
14852   struct RebuildUnknownAnyFunction
14853     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14854 
14855     Sema &S;
14856 
14857     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14858 
14859     ExprResult VisitStmt(Stmt *S) {
14860       llvm_unreachable("unexpected statement!");
14861     }
14862 
14863     ExprResult VisitExpr(Expr *E) {
14864       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14865         << E->getSourceRange();
14866       return ExprError();
14867     }
14868 
14869     /// Rebuild an expression which simply semantically wraps another
14870     /// expression which it shares the type and value kind of.
14871     template <class T> ExprResult rebuildSugarExpr(T *E) {
14872       ExprResult SubResult = Visit(E->getSubExpr());
14873       if (SubResult.isInvalid()) return ExprError();
14874 
14875       Expr *SubExpr = SubResult.get();
14876       E->setSubExpr(SubExpr);
14877       E->setType(SubExpr->getType());
14878       E->setValueKind(SubExpr->getValueKind());
14879       assert(E->getObjectKind() == OK_Ordinary);
14880       return E;
14881     }
14882 
14883     ExprResult VisitParenExpr(ParenExpr *E) {
14884       return rebuildSugarExpr(E);
14885     }
14886 
14887     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14888       return rebuildSugarExpr(E);
14889     }
14890 
14891     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14892       ExprResult SubResult = Visit(E->getSubExpr());
14893       if (SubResult.isInvalid()) return ExprError();
14894 
14895       Expr *SubExpr = SubResult.get();
14896       E->setSubExpr(SubExpr);
14897       E->setType(S.Context.getPointerType(SubExpr->getType()));
14898       assert(E->getValueKind() == VK_RValue);
14899       assert(E->getObjectKind() == OK_Ordinary);
14900       return E;
14901     }
14902 
14903     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14904       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14905 
14906       E->setType(VD->getType());
14907 
14908       assert(E->getValueKind() == VK_RValue);
14909       if (S.getLangOpts().CPlusPlus &&
14910           !(isa<CXXMethodDecl>(VD) &&
14911             cast<CXXMethodDecl>(VD)->isInstance()))
14912         E->setValueKind(VK_LValue);
14913 
14914       return E;
14915     }
14916 
14917     ExprResult VisitMemberExpr(MemberExpr *E) {
14918       return resolveDecl(E, E->getMemberDecl());
14919     }
14920 
14921     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14922       return resolveDecl(E, E->getDecl());
14923     }
14924   };
14925 }
14926 
14927 /// Given a function expression of unknown-any type, try to rebuild it
14928 /// to have a function type.
14929 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14930   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14931   if (Result.isInvalid()) return ExprError();
14932   return S.DefaultFunctionArrayConversion(Result.get());
14933 }
14934 
14935 namespace {
14936   /// A visitor for rebuilding an expression of type __unknown_anytype
14937   /// into one which resolves the type directly on the referring
14938   /// expression.  Strict preservation of the original source
14939   /// structure is not a goal.
14940   struct RebuildUnknownAnyExpr
14941     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14942 
14943     Sema &S;
14944 
14945     /// The current destination type.
14946     QualType DestType;
14947 
14948     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14949       : S(S), DestType(CastType) {}
14950 
14951     ExprResult VisitStmt(Stmt *S) {
14952       llvm_unreachable("unexpected statement!");
14953     }
14954 
14955     ExprResult VisitExpr(Expr *E) {
14956       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14957         << E->getSourceRange();
14958       return ExprError();
14959     }
14960 
14961     ExprResult VisitCallExpr(CallExpr *E);
14962     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14963 
14964     /// Rebuild an expression which simply semantically wraps another
14965     /// expression which it shares the type and value kind of.
14966     template <class T> ExprResult rebuildSugarExpr(T *E) {
14967       ExprResult SubResult = Visit(E->getSubExpr());
14968       if (SubResult.isInvalid()) return ExprError();
14969       Expr *SubExpr = SubResult.get();
14970       E->setSubExpr(SubExpr);
14971       E->setType(SubExpr->getType());
14972       E->setValueKind(SubExpr->getValueKind());
14973       assert(E->getObjectKind() == OK_Ordinary);
14974       return E;
14975     }
14976 
14977     ExprResult VisitParenExpr(ParenExpr *E) {
14978       return rebuildSugarExpr(E);
14979     }
14980 
14981     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14982       return rebuildSugarExpr(E);
14983     }
14984 
14985     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14986       const PointerType *Ptr = DestType->getAs<PointerType>();
14987       if (!Ptr) {
14988         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14989           << E->getSourceRange();
14990         return ExprError();
14991       }
14992 
14993       if (isa<CallExpr>(E->getSubExpr())) {
14994         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14995           << E->getSourceRange();
14996         return ExprError();
14997       }
14998 
14999       assert(E->getValueKind() == VK_RValue);
15000       assert(E->getObjectKind() == OK_Ordinary);
15001       E->setType(DestType);
15002 
15003       // Build the sub-expression as if it were an object of the pointee type.
15004       DestType = Ptr->getPointeeType();
15005       ExprResult SubResult = Visit(E->getSubExpr());
15006       if (SubResult.isInvalid()) return ExprError();
15007       E->setSubExpr(SubResult.get());
15008       return E;
15009     }
15010 
15011     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15012 
15013     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15014 
15015     ExprResult VisitMemberExpr(MemberExpr *E) {
15016       return resolveDecl(E, E->getMemberDecl());
15017     }
15018 
15019     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15020       return resolveDecl(E, E->getDecl());
15021     }
15022   };
15023 }
15024 
15025 /// Rebuilds a call expression which yielded __unknown_anytype.
15026 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15027   Expr *CalleeExpr = E->getCallee();
15028 
15029   enum FnKind {
15030     FK_MemberFunction,
15031     FK_FunctionPointer,
15032     FK_BlockPointer
15033   };
15034 
15035   FnKind Kind;
15036   QualType CalleeType = CalleeExpr->getType();
15037   if (CalleeType == S.Context.BoundMemberTy) {
15038     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15039     Kind = FK_MemberFunction;
15040     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15041   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15042     CalleeType = Ptr->getPointeeType();
15043     Kind = FK_FunctionPointer;
15044   } else {
15045     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15046     Kind = FK_BlockPointer;
15047   }
15048   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15049 
15050   // Verify that this is a legal result type of a function.
15051   if (DestType->isArrayType() || DestType->isFunctionType()) {
15052     unsigned diagID = diag::err_func_returning_array_function;
15053     if (Kind == FK_BlockPointer)
15054       diagID = diag::err_block_returning_array_function;
15055 
15056     S.Diag(E->getExprLoc(), diagID)
15057       << DestType->isFunctionType() << DestType;
15058     return ExprError();
15059   }
15060 
15061   // Otherwise, go ahead and set DestType as the call's result.
15062   E->setType(DestType.getNonLValueExprType(S.Context));
15063   E->setValueKind(Expr::getValueKindForType(DestType));
15064   assert(E->getObjectKind() == OK_Ordinary);
15065 
15066   // Rebuild the function type, replacing the result type with DestType.
15067   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15068   if (Proto) {
15069     // __unknown_anytype(...) is a special case used by the debugger when
15070     // it has no idea what a function's signature is.
15071     //
15072     // We want to build this call essentially under the K&R
15073     // unprototyped rules, but making a FunctionNoProtoType in C++
15074     // would foul up all sorts of assumptions.  However, we cannot
15075     // simply pass all arguments as variadic arguments, nor can we
15076     // portably just call the function under a non-variadic type; see
15077     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15078     // However, it turns out that in practice it is generally safe to
15079     // call a function declared as "A foo(B,C,D);" under the prototype
15080     // "A foo(B,C,D,...);".  The only known exception is with the
15081     // Windows ABI, where any variadic function is implicitly cdecl
15082     // regardless of its normal CC.  Therefore we change the parameter
15083     // types to match the types of the arguments.
15084     //
15085     // This is a hack, but it is far superior to moving the
15086     // corresponding target-specific code from IR-gen to Sema/AST.
15087 
15088     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15089     SmallVector<QualType, 8> ArgTypes;
15090     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15091       ArgTypes.reserve(E->getNumArgs());
15092       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15093         Expr *Arg = E->getArg(i);
15094         QualType ArgType = Arg->getType();
15095         if (E->isLValue()) {
15096           ArgType = S.Context.getLValueReferenceType(ArgType);
15097         } else if (E->isXValue()) {
15098           ArgType = S.Context.getRValueReferenceType(ArgType);
15099         }
15100         ArgTypes.push_back(ArgType);
15101       }
15102       ParamTypes = ArgTypes;
15103     }
15104     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15105                                          Proto->getExtProtoInfo());
15106   } else {
15107     DestType = S.Context.getFunctionNoProtoType(DestType,
15108                                                 FnType->getExtInfo());
15109   }
15110 
15111   // Rebuild the appropriate pointer-to-function type.
15112   switch (Kind) {
15113   case FK_MemberFunction:
15114     // Nothing to do.
15115     break;
15116 
15117   case FK_FunctionPointer:
15118     DestType = S.Context.getPointerType(DestType);
15119     break;
15120 
15121   case FK_BlockPointer:
15122     DestType = S.Context.getBlockPointerType(DestType);
15123     break;
15124   }
15125 
15126   // Finally, we can recurse.
15127   ExprResult CalleeResult = Visit(CalleeExpr);
15128   if (!CalleeResult.isUsable()) return ExprError();
15129   E->setCallee(CalleeResult.get());
15130 
15131   // Bind a temporary if necessary.
15132   return S.MaybeBindToTemporary(E);
15133 }
15134 
15135 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15136   // Verify that this is a legal result type of a call.
15137   if (DestType->isArrayType() || DestType->isFunctionType()) {
15138     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15139       << DestType->isFunctionType() << DestType;
15140     return ExprError();
15141   }
15142 
15143   // Rewrite the method result type if available.
15144   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15145     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15146     Method->setReturnType(DestType);
15147   }
15148 
15149   // Change the type of the message.
15150   E->setType(DestType.getNonReferenceType());
15151   E->setValueKind(Expr::getValueKindForType(DestType));
15152 
15153   return S.MaybeBindToTemporary(E);
15154 }
15155 
15156 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15157   // The only case we should ever see here is a function-to-pointer decay.
15158   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15159     assert(E->getValueKind() == VK_RValue);
15160     assert(E->getObjectKind() == OK_Ordinary);
15161 
15162     E->setType(DestType);
15163 
15164     // Rebuild the sub-expression as the pointee (function) type.
15165     DestType = DestType->castAs<PointerType>()->getPointeeType();
15166 
15167     ExprResult Result = Visit(E->getSubExpr());
15168     if (!Result.isUsable()) return ExprError();
15169 
15170     E->setSubExpr(Result.get());
15171     return E;
15172   } else if (E->getCastKind() == CK_LValueToRValue) {
15173     assert(E->getValueKind() == VK_RValue);
15174     assert(E->getObjectKind() == OK_Ordinary);
15175 
15176     assert(isa<BlockPointerType>(E->getType()));
15177 
15178     E->setType(DestType);
15179 
15180     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15181     DestType = S.Context.getLValueReferenceType(DestType);
15182 
15183     ExprResult Result = Visit(E->getSubExpr());
15184     if (!Result.isUsable()) return ExprError();
15185 
15186     E->setSubExpr(Result.get());
15187     return E;
15188   } else {
15189     llvm_unreachable("Unhandled cast type!");
15190   }
15191 }
15192 
15193 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15194   ExprValueKind ValueKind = VK_LValue;
15195   QualType Type = DestType;
15196 
15197   // We know how to make this work for certain kinds of decls:
15198 
15199   //  - functions
15200   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15201     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15202       DestType = Ptr->getPointeeType();
15203       ExprResult Result = resolveDecl(E, VD);
15204       if (Result.isInvalid()) return ExprError();
15205       return S.ImpCastExprToType(Result.get(), Type,
15206                                  CK_FunctionToPointerDecay, VK_RValue);
15207     }
15208 
15209     if (!Type->isFunctionType()) {
15210       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15211         << VD << E->getSourceRange();
15212       return ExprError();
15213     }
15214     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15215       // We must match the FunctionDecl's type to the hack introduced in
15216       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15217       // type. See the lengthy commentary in that routine.
15218       QualType FDT = FD->getType();
15219       const FunctionType *FnType = FDT->castAs<FunctionType>();
15220       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15221       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15222       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15223         SourceLocation Loc = FD->getLocation();
15224         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15225                                       FD->getDeclContext(),
15226                                       Loc, Loc, FD->getNameInfo().getName(),
15227                                       DestType, FD->getTypeSourceInfo(),
15228                                       SC_None, false/*isInlineSpecified*/,
15229                                       FD->hasPrototype(),
15230                                       false/*isConstexprSpecified*/);
15231 
15232         if (FD->getQualifier())
15233           NewFD->setQualifierInfo(FD->getQualifierLoc());
15234 
15235         SmallVector<ParmVarDecl*, 16> Params;
15236         for (const auto &AI : FT->param_types()) {
15237           ParmVarDecl *Param =
15238             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15239           Param->setScopeInfo(0, Params.size());
15240           Params.push_back(Param);
15241         }
15242         NewFD->setParams(Params);
15243         DRE->setDecl(NewFD);
15244         VD = DRE->getDecl();
15245       }
15246     }
15247 
15248     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15249       if (MD->isInstance()) {
15250         ValueKind = VK_RValue;
15251         Type = S.Context.BoundMemberTy;
15252       }
15253 
15254     // Function references aren't l-values in C.
15255     if (!S.getLangOpts().CPlusPlus)
15256       ValueKind = VK_RValue;
15257 
15258   //  - variables
15259   } else if (isa<VarDecl>(VD)) {
15260     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15261       Type = RefTy->getPointeeType();
15262     } else if (Type->isFunctionType()) {
15263       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15264         << VD << E->getSourceRange();
15265       return ExprError();
15266     }
15267 
15268   //  - nothing else
15269   } else {
15270     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15271       << VD << E->getSourceRange();
15272     return ExprError();
15273   }
15274 
15275   // Modifying the declaration like this is friendly to IR-gen but
15276   // also really dangerous.
15277   VD->setType(DestType);
15278   E->setType(Type);
15279   E->setValueKind(ValueKind);
15280   return E;
15281 }
15282 
15283 /// Check a cast of an unknown-any type.  We intentionally only
15284 /// trigger this for C-style casts.
15285 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15286                                      Expr *CastExpr, CastKind &CastKind,
15287                                      ExprValueKind &VK, CXXCastPath &Path) {
15288   // The type we're casting to must be either void or complete.
15289   if (!CastType->isVoidType() &&
15290       RequireCompleteType(TypeRange.getBegin(), CastType,
15291                           diag::err_typecheck_cast_to_incomplete))
15292     return ExprError();
15293 
15294   // Rewrite the casted expression from scratch.
15295   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15296   if (!result.isUsable()) return ExprError();
15297 
15298   CastExpr = result.get();
15299   VK = CastExpr->getValueKind();
15300   CastKind = CK_NoOp;
15301 
15302   return CastExpr;
15303 }
15304 
15305 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15306   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15307 }
15308 
15309 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15310                                     Expr *arg, QualType &paramType) {
15311   // If the syntactic form of the argument is not an explicit cast of
15312   // any sort, just do default argument promotion.
15313   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15314   if (!castArg) {
15315     ExprResult result = DefaultArgumentPromotion(arg);
15316     if (result.isInvalid()) return ExprError();
15317     paramType = result.get()->getType();
15318     return result;
15319   }
15320 
15321   // Otherwise, use the type that was written in the explicit cast.
15322   assert(!arg->hasPlaceholderType());
15323   paramType = castArg->getTypeAsWritten();
15324 
15325   // Copy-initialize a parameter of that type.
15326   InitializedEntity entity =
15327     InitializedEntity::InitializeParameter(Context, paramType,
15328                                            /*consumed*/ false);
15329   return PerformCopyInitialization(entity, callLoc, arg);
15330 }
15331 
15332 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15333   Expr *orig = E;
15334   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15335   while (true) {
15336     E = E->IgnoreParenImpCasts();
15337     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15338       E = call->getCallee();
15339       diagID = diag::err_uncasted_call_of_unknown_any;
15340     } else {
15341       break;
15342     }
15343   }
15344 
15345   SourceLocation loc;
15346   NamedDecl *d;
15347   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15348     loc = ref->getLocation();
15349     d = ref->getDecl();
15350   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15351     loc = mem->getMemberLoc();
15352     d = mem->getMemberDecl();
15353   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15354     diagID = diag::err_uncasted_call_of_unknown_any;
15355     loc = msg->getSelectorStartLoc();
15356     d = msg->getMethodDecl();
15357     if (!d) {
15358       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15359         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15360         << orig->getSourceRange();
15361       return ExprError();
15362     }
15363   } else {
15364     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15365       << E->getSourceRange();
15366     return ExprError();
15367   }
15368 
15369   S.Diag(loc, diagID) << d << orig->getSourceRange();
15370 
15371   // Never recoverable.
15372   return ExprError();
15373 }
15374 
15375 /// Check for operands with placeholder types and complain if found.
15376 /// Returns true if there was an error and no recovery was possible.
15377 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15378   if (!getLangOpts().CPlusPlus) {
15379     // C cannot handle TypoExpr nodes on either side of a binop because it
15380     // doesn't handle dependent types properly, so make sure any TypoExprs have
15381     // been dealt with before checking the operands.
15382     ExprResult Result = CorrectDelayedTyposInExpr(E);
15383     if (!Result.isUsable()) return ExprError();
15384     E = Result.get();
15385   }
15386 
15387   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15388   if (!placeholderType) return E;
15389 
15390   switch (placeholderType->getKind()) {
15391 
15392   // Overloaded expressions.
15393   case BuiltinType::Overload: {
15394     // Try to resolve a single function template specialization.
15395     // This is obligatory.
15396     ExprResult Result = E;
15397     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15398       return Result;
15399 
15400     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15401     // leaves Result unchanged on failure.
15402     Result = E;
15403     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15404       return Result;
15405 
15406     // If that failed, try to recover with a call.
15407     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15408                          /*complain*/ true);
15409     return Result;
15410   }
15411 
15412   // Bound member functions.
15413   case BuiltinType::BoundMember: {
15414     ExprResult result = E;
15415     const Expr *BME = E->IgnoreParens();
15416     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15417     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15418     if (isa<CXXPseudoDestructorExpr>(BME)) {
15419       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15420     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15421       if (ME->getMemberNameInfo().getName().getNameKind() ==
15422           DeclarationName::CXXDestructorName)
15423         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15424     }
15425     tryToRecoverWithCall(result, PD,
15426                          /*complain*/ true);
15427     return result;
15428   }
15429 
15430   // ARC unbridged casts.
15431   case BuiltinType::ARCUnbridgedCast: {
15432     Expr *realCast = stripARCUnbridgedCast(E);
15433     diagnoseARCUnbridgedCast(realCast);
15434     return realCast;
15435   }
15436 
15437   // Expressions of unknown type.
15438   case BuiltinType::UnknownAny:
15439     return diagnoseUnknownAnyExpr(*this, E);
15440 
15441   // Pseudo-objects.
15442   case BuiltinType::PseudoObject:
15443     return checkPseudoObjectRValue(E);
15444 
15445   case BuiltinType::BuiltinFn: {
15446     // Accept __noop without parens by implicitly converting it to a call expr.
15447     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15448     if (DRE) {
15449       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15450       if (FD->getBuiltinID() == Builtin::BI__noop) {
15451         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15452                               CK_BuiltinFnToFnPtr).get();
15453         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15454                                       VK_RValue, SourceLocation());
15455       }
15456     }
15457 
15458     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15459     return ExprError();
15460   }
15461 
15462   // Expressions of unknown type.
15463   case BuiltinType::OMPArraySection:
15464     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15465     return ExprError();
15466 
15467   // Everything else should be impossible.
15468 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15469   case BuiltinType::Id:
15470 #include "clang/Basic/OpenCLImageTypes.def"
15471 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15472 #define PLACEHOLDER_TYPE(Id, SingletonId)
15473 #include "clang/AST/BuiltinTypes.def"
15474     break;
15475   }
15476 
15477   llvm_unreachable("invalid placeholder type!");
15478 }
15479 
15480 bool Sema::CheckCaseExpression(Expr *E) {
15481   if (E->isTypeDependent())
15482     return true;
15483   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15484     return E->getType()->isIntegralOrEnumerationType();
15485   return false;
15486 }
15487 
15488 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15489 ExprResult
15490 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15491   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15492          "Unknown Objective-C Boolean value!");
15493   QualType BoolT = Context.ObjCBuiltinBoolTy;
15494   if (!Context.getBOOLDecl()) {
15495     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15496                         Sema::LookupOrdinaryName);
15497     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15498       NamedDecl *ND = Result.getFoundDecl();
15499       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15500         Context.setBOOLDecl(TD);
15501     }
15502   }
15503   if (Context.getBOOLDecl())
15504     BoolT = Context.getBOOLType();
15505   return new (Context)
15506       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15507 }
15508 
15509 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15510     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15511     SourceLocation RParen) {
15512 
15513   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15514 
15515   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15516                            [&](const AvailabilitySpec &Spec) {
15517                              return Spec.getPlatform() == Platform;
15518                            });
15519 
15520   VersionTuple Version;
15521   if (Spec != AvailSpecs.end())
15522     Version = Spec->getVersion();
15523 
15524   return new (Context)
15525       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15526 }
15527