1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97 
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105 
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message);
109 
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message);
117         continue;
118       }
119     }
120     break;
121   }
122 
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message);
128     }
129   }
130 
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message);
136     }
137 
138   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142 
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158 
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161 
162   return Result;
163 }
164 
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173 
174     if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
175       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
176       return;
177     }
178 
179     const ObjCPropertyDecl *ObjCPDecl = nullptr;
180     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183         if (PDeclResult == Result)
184           ObjCPDecl = PD;
185       }
186     }
187 
188     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189                               ObjCPDecl, ObjCPropertyAccess);
190   }
191 }
192 
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195   assert(Decl->isDeleted());
196 
197   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
198 
199   if (Method && Method->isDeleted() && Method->isDefaulted()) {
200     // If the method was explicitly defaulted, point at that declaration.
201     if (!Method->isImplicit())
202       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
203 
204     // Try to diagnose why this special member function was implicitly
205     // deleted. This might fail, if that reason no longer applies.
206     CXXSpecialMember CSM = getSpecialMember(Method);
207     if (CSM != CXXInvalid)
208       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
209 
210     return;
211   }
212 
213   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214   if (Ctor && Ctor->isInheritingConstructor())
215     return NoteDeletedInheritingConstructor(Ctor);
216 
217   Diag(Decl->getLocation(), diag::note_availability_specified_here)
218     << Decl << true;
219 }
220 
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224   for (auto I : D->redecls()) {
225     if (I->getStorageClass() != SC_None)
226       return true;
227   }
228   return false;
229 }
230 
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
233 ///
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
240                                                       const NamedDecl *D,
241                                                       SourceLocation Loc) {
242   // This is disabled under C++; there are too many ways for this to fire in
243   // contexts where the warning is a false positive, or where it is technically
244   // correct but benign.
245   if (S.getLangOpts().CPlusPlus)
246     return;
247 
248   // Check if this is an inlined function or method.
249   FunctionDecl *Current = S.getCurFunctionDecl();
250   if (!Current)
251     return;
252   if (!Current->isInlined())
253     return;
254   if (!Current->isExternallyVisible())
255     return;
256 
257   // Check if the decl has internal linkage.
258   if (D->getFormalLinkage() != InternalLinkage)
259     return;
260 
261   // Downgrade from ExtWarn to Extension if
262   //  (1) the supposedly external inline function is in the main file,
263   //      and probably won't be included anywhere else.
264   //  (2) the thing we're referencing is a pure function.
265   //  (3) the thing we're referencing is another inline function.
266   // This last can give us false negatives, but it's better than warning on
267   // wrappers for simple C library functions.
268   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270   if (!DowngradeWarning && UsedFn)
271     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
272 
273   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274                                : diag::ext_internal_in_extern_inline)
275     << /*IsVar=*/!UsedFn << D;
276 
277   S.MaybeSuggestAddingStaticToDecl(Current);
278 
279   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
280       << D;
281 }
282 
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284   const FunctionDecl *First = Cur->getFirstDecl();
285 
286   // Suggest "static" on the function, if possible.
287   if (!hasAnyExplicitStorageClass(First)) {
288     SourceLocation DeclBegin = First->getSourceRange().getBegin();
289     Diag(DeclBegin, diag::note_convert_inline_to_static)
290       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
291   }
292 }
293 
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
296 ///
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
302 ///
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
305 ///
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307                              const ObjCInterfaceDecl *UnknownObjCClass,
308                              bool ObjCPropertyAccess) {
309   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310     // If there were any diagnostics suppressed by template argument deduction,
311     // emit them now.
312     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313     if (Pos != SuppressedDiagnostics.end()) {
314       for (const PartialDiagnosticAt &Suppressed : Pos->second)
315         Diag(Suppressed.first, Suppressed.second);
316 
317       // Clear out the list of suppressed diagnostics, so that we don't emit
318       // them again for this specialization. However, we don't obsolete this
319       // entry from the table, because we want to avoid ever emitting these
320       // diagnostics again.
321       Pos->second.clear();
322     }
323 
324     // C++ [basic.start.main]p3:
325     //   The function 'main' shall not be used within a program.
326     if (cast<FunctionDecl>(D)->isMain())
327       Diag(Loc, diag::ext_main_used);
328   }
329 
330   // See if this is an auto-typed variable whose initializer we are parsing.
331   if (ParsingInitForAutoVars.count(D)) {
332     if (isa<BindingDecl>(D)) {
333       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
334         << D->getDeclName();
335     } else {
336       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
337 
338       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339         << D->getDeclName() << (unsigned)AT->getKeyword();
340     }
341     return true;
342   }
343 
344   // See if this is a deleted function.
345   SmallVector<DiagnoseIfAttr *, 4> DiagnoseIfWarnings;
346   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
347     if (FD->isDeleted()) {
348       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
349       if (Ctor && Ctor->isInheritingConstructor())
350         Diag(Loc, diag::err_deleted_inherited_ctor_use)
351             << Ctor->getParent()
352             << Ctor->getInheritedConstructor().getConstructor()->getParent();
353       else
354         Diag(Loc, diag::err_deleted_function_use);
355       NoteDeletedFunction(FD);
356       return true;
357     }
358 
359     // If the function has a deduced return type, and we can't deduce it,
360     // then we can't use it either.
361     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
362         DeduceReturnType(FD, Loc))
363       return true;
364 
365     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
366       return true;
367 
368     if (const DiagnoseIfAttr *A =
369             checkArgIndependentDiagnoseIf(FD, DiagnoseIfWarnings)) {
370       emitDiagnoseIfDiagnostic(Loc, A);
371       return true;
372     }
373   }
374 
375   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
376   // Only the variables omp_in and omp_out are allowed in the combiner.
377   // Only the variables omp_priv and omp_orig are allowed in the
378   // initializer-clause.
379   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
380   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
381       isa<VarDecl>(D)) {
382     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
383         << getCurFunction()->HasOMPDeclareReductionCombiner;
384     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
385     return true;
386   }
387 
388   for (const auto *W : DiagnoseIfWarnings)
389     emitDiagnoseIfDiagnostic(Loc, W);
390 
391   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
392                              ObjCPropertyAccess);
393 
394   DiagnoseUnusedOfDecl(*this, D, Loc);
395 
396   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
397 
398   return false;
399 }
400 
401 /// \brief Retrieve the message suffix that should be added to a
402 /// diagnostic complaining about the given function being deleted or
403 /// unavailable.
404 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
405   std::string Message;
406   if (FD->getAvailability(&Message))
407     return ": " + Message;
408 
409   return std::string();
410 }
411 
412 /// DiagnoseSentinelCalls - This routine checks whether a call or
413 /// message-send is to a declaration with the sentinel attribute, and
414 /// if so, it checks that the requirements of the sentinel are
415 /// satisfied.
416 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
417                                  ArrayRef<Expr *> Args) {
418   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
419   if (!attr)
420     return;
421 
422   // The number of formal parameters of the declaration.
423   unsigned numFormalParams;
424 
425   // The kind of declaration.  This is also an index into a %select in
426   // the diagnostic.
427   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
428 
429   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
430     numFormalParams = MD->param_size();
431     calleeType = CT_Method;
432   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433     numFormalParams = FD->param_size();
434     calleeType = CT_Function;
435   } else if (isa<VarDecl>(D)) {
436     QualType type = cast<ValueDecl>(D)->getType();
437     const FunctionType *fn = nullptr;
438     if (const PointerType *ptr = type->getAs<PointerType>()) {
439       fn = ptr->getPointeeType()->getAs<FunctionType>();
440       if (!fn) return;
441       calleeType = CT_Function;
442     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
443       fn = ptr->getPointeeType()->castAs<FunctionType>();
444       calleeType = CT_Block;
445     } else {
446       return;
447     }
448 
449     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
450       numFormalParams = proto->getNumParams();
451     } else {
452       numFormalParams = 0;
453     }
454   } else {
455     return;
456   }
457 
458   // "nullPos" is the number of formal parameters at the end which
459   // effectively count as part of the variadic arguments.  This is
460   // useful if you would prefer to not have *any* formal parameters,
461   // but the language forces you to have at least one.
462   unsigned nullPos = attr->getNullPos();
463   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
464   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
465 
466   // The number of arguments which should follow the sentinel.
467   unsigned numArgsAfterSentinel = attr->getSentinel();
468 
469   // If there aren't enough arguments for all the formal parameters,
470   // the sentinel, and the args after the sentinel, complain.
471   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
472     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
474     return;
475   }
476 
477   // Otherwise, find the sentinel expression.
478   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
479   if (!sentinelExpr) return;
480   if (sentinelExpr->isValueDependent()) return;
481   if (Context.isSentinelNullExpr(sentinelExpr)) return;
482 
483   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
484   // or 'NULL' if those are actually defined in the context.  Only use
485   // 'nil' for ObjC methods, where it's much more likely that the
486   // variadic arguments form a list of object pointers.
487   SourceLocation MissingNilLoc
488     = getLocForEndOfToken(sentinelExpr->getLocEnd());
489   std::string NullValue;
490   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
491     NullValue = "nil";
492   else if (getLangOpts().CPlusPlus11)
493     NullValue = "nullptr";
494   else if (PP.isMacroDefined("NULL"))
495     NullValue = "NULL";
496   else
497     NullValue = "(void*) 0";
498 
499   if (MissingNilLoc.isInvalid())
500     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
501   else
502     Diag(MissingNilLoc, diag::warn_missing_sentinel)
503       << int(calleeType)
504       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
505   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
506 }
507 
508 SourceRange Sema::getExprRange(Expr *E) const {
509   return E ? E->getSourceRange() : SourceRange();
510 }
511 
512 //===----------------------------------------------------------------------===//
513 //  Standard Promotions and Conversions
514 //===----------------------------------------------------------------------===//
515 
516 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
518   // Handle any placeholder expressions which made it here.
519   if (E->getType()->isPlaceholderType()) {
520     ExprResult result = CheckPlaceholderExpr(E);
521     if (result.isInvalid()) return ExprError();
522     E = result.get();
523   }
524 
525   QualType Ty = E->getType();
526   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
527 
528   if (Ty->isFunctionType()) {
529     // If we are here, we are not calling a function but taking
530     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
531     if (getLangOpts().OpenCL) {
532       if (Diagnose)
533         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
534       return ExprError();
535     }
536 
537     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
538       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
539         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
540           return ExprError();
541 
542     E = ImpCastExprToType(E, Context.getPointerType(Ty),
543                           CK_FunctionToPointerDecay).get();
544   } else if (Ty->isArrayType()) {
545     // In C90 mode, arrays only promote to pointers if the array expression is
546     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
547     // type 'array of type' is converted to an expression that has type 'pointer
548     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
549     // that has type 'array of type' ...".  The relevant change is "an lvalue"
550     // (C90) to "an expression" (C99).
551     //
552     // C++ 4.2p1:
553     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
554     // T" can be converted to an rvalue of type "pointer to T".
555     //
556     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
557       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
558                             CK_ArrayToPointerDecay).get();
559   }
560   return E;
561 }
562 
563 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
564   // Check to see if we are dereferencing a null pointer.  If so,
565   // and if not volatile-qualified, this is undefined behavior that the
566   // optimizer will delete, so warn about it.  People sometimes try to use this
567   // to get a deterministic trap and are surprised by clang's behavior.  This
568   // only handles the pattern "*null", which is a very syntactic check.
569   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
570     if (UO->getOpcode() == UO_Deref &&
571         UO->getSubExpr()->IgnoreParenCasts()->
572           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
573         !UO->getType().isVolatileQualified()) {
574     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575                           S.PDiag(diag::warn_indirection_through_null)
576                             << UO->getSubExpr()->getSourceRange());
577     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578                         S.PDiag(diag::note_indirection_through_null));
579   }
580 }
581 
582 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
583                                     SourceLocation AssignLoc,
584                                     const Expr* RHS) {
585   const ObjCIvarDecl *IV = OIRE->getDecl();
586   if (!IV)
587     return;
588 
589   DeclarationName MemberName = IV->getDeclName();
590   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
591   if (!Member || !Member->isStr("isa"))
592     return;
593 
594   const Expr *Base = OIRE->getBase();
595   QualType BaseType = Base->getType();
596   if (OIRE->isArrow())
597     BaseType = BaseType->getPointeeType();
598   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
599     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
600       ObjCInterfaceDecl *ClassDeclared = nullptr;
601       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
602       if (!ClassDeclared->getSuperClass()
603           && (*ClassDeclared->ivar_begin()) == IV) {
604         if (RHS) {
605           NamedDecl *ObjectSetClass =
606             S.LookupSingleName(S.TUScope,
607                                &S.Context.Idents.get("object_setClass"),
608                                SourceLocation(), S.LookupOrdinaryName);
609           if (ObjectSetClass) {
610             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
611             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
612             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
613             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
614                                                      AssignLoc), ",") <<
615             FixItHint::CreateInsertion(RHSLocEnd, ")");
616           }
617           else
618             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
619         } else {
620           NamedDecl *ObjectGetClass =
621             S.LookupSingleName(S.TUScope,
622                                &S.Context.Idents.get("object_getClass"),
623                                SourceLocation(), S.LookupOrdinaryName);
624           if (ObjectGetClass)
625             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
626             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
627             FixItHint::CreateReplacement(
628                                          SourceRange(OIRE->getOpLoc(),
629                                                      OIRE->getLocEnd()), ")");
630           else
631             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
632         }
633         S.Diag(IV->getLocation(), diag::note_ivar_decl);
634       }
635     }
636 }
637 
638 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
639   // Handle any placeholder expressions which made it here.
640   if (E->getType()->isPlaceholderType()) {
641     ExprResult result = CheckPlaceholderExpr(E);
642     if (result.isInvalid()) return ExprError();
643     E = result.get();
644   }
645 
646   // C++ [conv.lval]p1:
647   //   A glvalue of a non-function, non-array type T can be
648   //   converted to a prvalue.
649   if (!E->isGLValue()) return E;
650 
651   QualType T = E->getType();
652   assert(!T.isNull() && "r-value conversion on typeless expression?");
653 
654   // We don't want to throw lvalue-to-rvalue casts on top of
655   // expressions of certain types in C++.
656   if (getLangOpts().CPlusPlus &&
657       (E->getType() == Context.OverloadTy ||
658        T->isDependentType() ||
659        T->isRecordType()))
660     return E;
661 
662   // The C standard is actually really unclear on this point, and
663   // DR106 tells us what the result should be but not why.  It's
664   // generally best to say that void types just doesn't undergo
665   // lvalue-to-rvalue at all.  Note that expressions of unqualified
666   // 'void' type are never l-values, but qualified void can be.
667   if (T->isVoidType())
668     return E;
669 
670   // OpenCL usually rejects direct accesses to values of 'half' type.
671   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
672       T->isHalfType()) {
673     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
674       << 0 << T;
675     return ExprError();
676   }
677 
678   CheckForNullPointerDereference(*this, E);
679   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
680     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
681                                      &Context.Idents.get("object_getClass"),
682                                      SourceLocation(), LookupOrdinaryName);
683     if (ObjectGetClass)
684       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
685         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
686         FixItHint::CreateReplacement(
687                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
688     else
689       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
690   }
691   else if (const ObjCIvarRefExpr *OIRE =
692             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
693     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
694 
695   // C++ [conv.lval]p1:
696   //   [...] If T is a non-class type, the type of the prvalue is the
697   //   cv-unqualified version of T. Otherwise, the type of the
698   //   rvalue is T.
699   //
700   // C99 6.3.2.1p2:
701   //   If the lvalue has qualified type, the value has the unqualified
702   //   version of the type of the lvalue; otherwise, the value has the
703   //   type of the lvalue.
704   if (T.hasQualifiers())
705     T = T.getUnqualifiedType();
706 
707   // Under the MS ABI, lock down the inheritance model now.
708   if (T->isMemberPointerType() &&
709       Context.getTargetInfo().getCXXABI().isMicrosoft())
710     (void)isCompleteType(E->getExprLoc(), T);
711 
712   UpdateMarkingForLValueToRValue(E);
713 
714   // Loading a __weak object implicitly retains the value, so we need a cleanup to
715   // balance that.
716   if (getLangOpts().ObjCAutoRefCount &&
717       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
718     Cleanup.setExprNeedsCleanups(true);
719 
720   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
721                                             nullptr, VK_RValue);
722 
723   // C11 6.3.2.1p2:
724   //   ... if the lvalue has atomic type, the value has the non-atomic version
725   //   of the type of the lvalue ...
726   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
727     T = Atomic->getValueType().getUnqualifiedType();
728     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
729                                    nullptr, VK_RValue);
730   }
731 
732   return Res;
733 }
734 
735 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
736   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
737   if (Res.isInvalid())
738     return ExprError();
739   Res = DefaultLvalueConversion(Res.get());
740   if (Res.isInvalid())
741     return ExprError();
742   return Res;
743 }
744 
745 /// CallExprUnaryConversions - a special case of an unary conversion
746 /// performed on a function designator of a call expression.
747 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
748   QualType Ty = E->getType();
749   ExprResult Res = E;
750   // Only do implicit cast for a function type, but not for a pointer
751   // to function type.
752   if (Ty->isFunctionType()) {
753     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
754                             CK_FunctionToPointerDecay).get();
755     if (Res.isInvalid())
756       return ExprError();
757   }
758   Res = DefaultLvalueConversion(Res.get());
759   if (Res.isInvalid())
760     return ExprError();
761   return Res.get();
762 }
763 
764 /// UsualUnaryConversions - Performs various conversions that are common to most
765 /// operators (C99 6.3). The conversions of array and function types are
766 /// sometimes suppressed. For example, the array->pointer conversion doesn't
767 /// apply if the array is an argument to the sizeof or address (&) operators.
768 /// In these instances, this routine should *not* be called.
769 ExprResult Sema::UsualUnaryConversions(Expr *E) {
770   // First, convert to an r-value.
771   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
772   if (Res.isInvalid())
773     return ExprError();
774   E = Res.get();
775 
776   QualType Ty = E->getType();
777   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
778 
779   // Half FP have to be promoted to float unless it is natively supported
780   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
781     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
782 
783   // Try to perform integral promotions if the object has a theoretically
784   // promotable type.
785   if (Ty->isIntegralOrUnscopedEnumerationType()) {
786     // C99 6.3.1.1p2:
787     //
788     //   The following may be used in an expression wherever an int or
789     //   unsigned int may be used:
790     //     - an object or expression with an integer type whose integer
791     //       conversion rank is less than or equal to the rank of int
792     //       and unsigned int.
793     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
794     //
795     //   If an int can represent all values of the original type, the
796     //   value is converted to an int; otherwise, it is converted to an
797     //   unsigned int. These are called the integer promotions. All
798     //   other types are unchanged by the integer promotions.
799 
800     QualType PTy = Context.isPromotableBitField(E);
801     if (!PTy.isNull()) {
802       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
803       return E;
804     }
805     if (Ty->isPromotableIntegerType()) {
806       QualType PT = Context.getPromotedIntegerType(Ty);
807       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
808       return E;
809     }
810   }
811   return E;
812 }
813 
814 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
815 /// do not have a prototype. Arguments that have type float or __fp16
816 /// are promoted to double. All other argument types are converted by
817 /// UsualUnaryConversions().
818 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
819   QualType Ty = E->getType();
820   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
821 
822   ExprResult Res = UsualUnaryConversions(E);
823   if (Res.isInvalid())
824     return ExprError();
825   E = Res.get();
826 
827   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
828   // double.
829   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
830   if (BTy && (BTy->getKind() == BuiltinType::Half ||
831               BTy->getKind() == BuiltinType::Float)) {
832     if (getLangOpts().OpenCL &&
833         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
834         if (BTy->getKind() == BuiltinType::Half) {
835             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
836         }
837     } else {
838       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
839     }
840   }
841 
842   // C++ performs lvalue-to-rvalue conversion as a default argument
843   // promotion, even on class types, but note:
844   //   C++11 [conv.lval]p2:
845   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
846   //     operand or a subexpression thereof the value contained in the
847   //     referenced object is not accessed. Otherwise, if the glvalue
848   //     has a class type, the conversion copy-initializes a temporary
849   //     of type T from the glvalue and the result of the conversion
850   //     is a prvalue for the temporary.
851   // FIXME: add some way to gate this entire thing for correctness in
852   // potentially potentially evaluated contexts.
853   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
854     ExprResult Temp = PerformCopyInitialization(
855                        InitializedEntity::InitializeTemporary(E->getType()),
856                                                 E->getExprLoc(), E);
857     if (Temp.isInvalid())
858       return ExprError();
859     E = Temp.get();
860   }
861 
862   return E;
863 }
864 
865 /// Determine the degree of POD-ness for an expression.
866 /// Incomplete types are considered POD, since this check can be performed
867 /// when we're in an unevaluated context.
868 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
869   if (Ty->isIncompleteType()) {
870     // C++11 [expr.call]p7:
871     //   After these conversions, if the argument does not have arithmetic,
872     //   enumeration, pointer, pointer to member, or class type, the program
873     //   is ill-formed.
874     //
875     // Since we've already performed array-to-pointer and function-to-pointer
876     // decay, the only such type in C++ is cv void. This also handles
877     // initializer lists as variadic arguments.
878     if (Ty->isVoidType())
879       return VAK_Invalid;
880 
881     if (Ty->isObjCObjectType())
882       return VAK_Invalid;
883     return VAK_Valid;
884   }
885 
886   if (Ty.isCXX98PODType(Context))
887     return VAK_Valid;
888 
889   // C++11 [expr.call]p7:
890   //   Passing a potentially-evaluated argument of class type (Clause 9)
891   //   having a non-trivial copy constructor, a non-trivial move constructor,
892   //   or a non-trivial destructor, with no corresponding parameter,
893   //   is conditionally-supported with implementation-defined semantics.
894   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
895     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
896       if (!Record->hasNonTrivialCopyConstructor() &&
897           !Record->hasNonTrivialMoveConstructor() &&
898           !Record->hasNonTrivialDestructor())
899         return VAK_ValidInCXX11;
900 
901   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
902     return VAK_Valid;
903 
904   if (Ty->isObjCObjectType())
905     return VAK_Invalid;
906 
907   if (getLangOpts().MSVCCompat)
908     return VAK_MSVCUndefined;
909 
910   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
911   // permitted to reject them. We should consider doing so.
912   return VAK_Undefined;
913 }
914 
915 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
916   // Don't allow one to pass an Objective-C interface to a vararg.
917   const QualType &Ty = E->getType();
918   VarArgKind VAK = isValidVarArgType(Ty);
919 
920   // Complain about passing non-POD types through varargs.
921   switch (VAK) {
922   case VAK_ValidInCXX11:
923     DiagRuntimeBehavior(
924         E->getLocStart(), nullptr,
925         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
926           << Ty << CT);
927     // Fall through.
928   case VAK_Valid:
929     if (Ty->isRecordType()) {
930       // This is unlikely to be what the user intended. If the class has a
931       // 'c_str' member function, the user probably meant to call that.
932       DiagRuntimeBehavior(E->getLocStart(), nullptr,
933                           PDiag(diag::warn_pass_class_arg_to_vararg)
934                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
935     }
936     break;
937 
938   case VAK_Undefined:
939   case VAK_MSVCUndefined:
940     DiagRuntimeBehavior(
941         E->getLocStart(), nullptr,
942         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
943           << getLangOpts().CPlusPlus11 << Ty << CT);
944     break;
945 
946   case VAK_Invalid:
947     if (Ty->isObjCObjectType())
948       DiagRuntimeBehavior(
949           E->getLocStart(), nullptr,
950           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
951             << Ty << CT);
952     else
953       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
954         << isa<InitListExpr>(E) << Ty << CT;
955     break;
956   }
957 }
958 
959 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
960 /// will create a trap if the resulting type is not a POD type.
961 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
962                                                   FunctionDecl *FDecl) {
963   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
964     // Strip the unbridged-cast placeholder expression off, if applicable.
965     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
966         (CT == VariadicMethod ||
967          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
968       E = stripARCUnbridgedCast(E);
969 
970     // Otherwise, do normal placeholder checking.
971     } else {
972       ExprResult ExprRes = CheckPlaceholderExpr(E);
973       if (ExprRes.isInvalid())
974         return ExprError();
975       E = ExprRes.get();
976     }
977   }
978 
979   ExprResult ExprRes = DefaultArgumentPromotion(E);
980   if (ExprRes.isInvalid())
981     return ExprError();
982   E = ExprRes.get();
983 
984   // Diagnostics regarding non-POD argument types are
985   // emitted along with format string checking in Sema::CheckFunctionCall().
986   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
987     // Turn this into a trap.
988     CXXScopeSpec SS;
989     SourceLocation TemplateKWLoc;
990     UnqualifiedId Name;
991     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
992                        E->getLocStart());
993     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
994                                           Name, true, false);
995     if (TrapFn.isInvalid())
996       return ExprError();
997 
998     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
999                                     E->getLocStart(), None,
1000                                     E->getLocEnd());
1001     if (Call.isInvalid())
1002       return ExprError();
1003 
1004     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1005                                   Call.get(), E);
1006     if (Comma.isInvalid())
1007       return ExprError();
1008     return Comma.get();
1009   }
1010 
1011   if (!getLangOpts().CPlusPlus &&
1012       RequireCompleteType(E->getExprLoc(), E->getType(),
1013                           diag::err_call_incomplete_argument))
1014     return ExprError();
1015 
1016   return E;
1017 }
1018 
1019 /// \brief Converts an integer to complex float type.  Helper function of
1020 /// UsualArithmeticConversions()
1021 ///
1022 /// \return false if the integer expression is an integer type and is
1023 /// successfully converted to the complex type.
1024 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1025                                                   ExprResult &ComplexExpr,
1026                                                   QualType IntTy,
1027                                                   QualType ComplexTy,
1028                                                   bool SkipCast) {
1029   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1030   if (SkipCast) return false;
1031   if (IntTy->isIntegerType()) {
1032     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1033     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1034     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1035                                   CK_FloatingRealToComplex);
1036   } else {
1037     assert(IntTy->isComplexIntegerType());
1038     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1039                                   CK_IntegralComplexToFloatingComplex);
1040   }
1041   return false;
1042 }
1043 
1044 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1045 /// UsualArithmeticConversions()
1046 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1047                                              ExprResult &RHS, QualType LHSType,
1048                                              QualType RHSType,
1049                                              bool IsCompAssign) {
1050   // if we have an integer operand, the result is the complex type.
1051   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1052                                              /*skipCast*/false))
1053     return LHSType;
1054   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1055                                              /*skipCast*/IsCompAssign))
1056     return RHSType;
1057 
1058   // This handles complex/complex, complex/float, or float/complex.
1059   // When both operands are complex, the shorter operand is converted to the
1060   // type of the longer, and that is the type of the result. This corresponds
1061   // to what is done when combining two real floating-point operands.
1062   // The fun begins when size promotion occur across type domains.
1063   // From H&S 6.3.4: When one operand is complex and the other is a real
1064   // floating-point type, the less precise type is converted, within it's
1065   // real or complex domain, to the precision of the other type. For example,
1066   // when combining a "long double" with a "double _Complex", the
1067   // "double _Complex" is promoted to "long double _Complex".
1068 
1069   // Compute the rank of the two types, regardless of whether they are complex.
1070   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1071 
1072   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1073   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1074   QualType LHSElementType =
1075       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1076   QualType RHSElementType =
1077       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1078 
1079   QualType ResultType = S.Context.getComplexType(LHSElementType);
1080   if (Order < 0) {
1081     // Promote the precision of the LHS if not an assignment.
1082     ResultType = S.Context.getComplexType(RHSElementType);
1083     if (!IsCompAssign) {
1084       if (LHSComplexType)
1085         LHS =
1086             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1087       else
1088         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1089     }
1090   } else if (Order > 0) {
1091     // Promote the precision of the RHS.
1092     if (RHSComplexType)
1093       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1094     else
1095       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1096   }
1097   return ResultType;
1098 }
1099 
1100 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1101 /// of UsualArithmeticConversions()
1102 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1103                                            ExprResult &IntExpr,
1104                                            QualType FloatTy, QualType IntTy,
1105                                            bool ConvertFloat, bool ConvertInt) {
1106   if (IntTy->isIntegerType()) {
1107     if (ConvertInt)
1108       // Convert intExpr to the lhs floating point type.
1109       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1110                                     CK_IntegralToFloating);
1111     return FloatTy;
1112   }
1113 
1114   // Convert both sides to the appropriate complex float.
1115   assert(IntTy->isComplexIntegerType());
1116   QualType result = S.Context.getComplexType(FloatTy);
1117 
1118   // _Complex int -> _Complex float
1119   if (ConvertInt)
1120     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1121                                   CK_IntegralComplexToFloatingComplex);
1122 
1123   // float -> _Complex float
1124   if (ConvertFloat)
1125     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1126                                     CK_FloatingRealToComplex);
1127 
1128   return result;
1129 }
1130 
1131 /// \brief Handle arithmethic conversion with floating point types.  Helper
1132 /// function of UsualArithmeticConversions()
1133 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1134                                       ExprResult &RHS, QualType LHSType,
1135                                       QualType RHSType, bool IsCompAssign) {
1136   bool LHSFloat = LHSType->isRealFloatingType();
1137   bool RHSFloat = RHSType->isRealFloatingType();
1138 
1139   // If we have two real floating types, convert the smaller operand
1140   // to the bigger result.
1141   if (LHSFloat && RHSFloat) {
1142     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1143     if (order > 0) {
1144       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1145       return LHSType;
1146     }
1147 
1148     assert(order < 0 && "illegal float comparison");
1149     if (!IsCompAssign)
1150       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1151     return RHSType;
1152   }
1153 
1154   if (LHSFloat) {
1155     // Half FP has to be promoted to float unless it is natively supported
1156     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1157       LHSType = S.Context.FloatTy;
1158 
1159     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1160                                       /*convertFloat=*/!IsCompAssign,
1161                                       /*convertInt=*/ true);
1162   }
1163   assert(RHSFloat);
1164   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1165                                     /*convertInt=*/ true,
1166                                     /*convertFloat=*/!IsCompAssign);
1167 }
1168 
1169 /// \brief Diagnose attempts to convert between __float128 and long double if
1170 /// there is no support for such conversion. Helper function of
1171 /// UsualArithmeticConversions().
1172 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1173                                       QualType RHSType) {
1174   /*  No issue converting if at least one of the types is not a floating point
1175       type or the two types have the same rank.
1176   */
1177   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1178       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1179     return false;
1180 
1181   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1182          "The remaining types must be floating point types.");
1183 
1184   auto *LHSComplex = LHSType->getAs<ComplexType>();
1185   auto *RHSComplex = RHSType->getAs<ComplexType>();
1186 
1187   QualType LHSElemType = LHSComplex ?
1188     LHSComplex->getElementType() : LHSType;
1189   QualType RHSElemType = RHSComplex ?
1190     RHSComplex->getElementType() : RHSType;
1191 
1192   // No issue if the two types have the same representation
1193   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1194       &S.Context.getFloatTypeSemantics(RHSElemType))
1195     return false;
1196 
1197   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1198                                 RHSElemType == S.Context.LongDoubleTy);
1199   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1200                             RHSElemType == S.Context.Float128Ty);
1201 
1202   /* We've handled the situation where __float128 and long double have the same
1203      representation. The only other allowable conversion is if long double is
1204      really just double.
1205   */
1206   return Float128AndLongDouble &&
1207     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1208      &llvm::APFloat::IEEEdouble());
1209 }
1210 
1211 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1212 
1213 namespace {
1214 /// These helper callbacks are placed in an anonymous namespace to
1215 /// permit their use as function template parameters.
1216 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1217   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1218 }
1219 
1220 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1221   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1222                              CK_IntegralComplexCast);
1223 }
1224 }
1225 
1226 /// \brief Handle integer arithmetic conversions.  Helper function of
1227 /// UsualArithmeticConversions()
1228 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1229 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1230                                         ExprResult &RHS, QualType LHSType,
1231                                         QualType RHSType, bool IsCompAssign) {
1232   // The rules for this case are in C99 6.3.1.8
1233   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1234   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1235   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1236   if (LHSSigned == RHSSigned) {
1237     // Same signedness; use the higher-ranked type
1238     if (order >= 0) {
1239       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240       return LHSType;
1241     } else if (!IsCompAssign)
1242       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243     return RHSType;
1244   } else if (order != (LHSSigned ? 1 : -1)) {
1245     // The unsigned type has greater than or equal rank to the
1246     // signed type, so use the unsigned type
1247     if (RHSSigned) {
1248       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1249       return LHSType;
1250     } else if (!IsCompAssign)
1251       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1252     return RHSType;
1253   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1254     // The two types are different widths; if we are here, that
1255     // means the signed type is larger than the unsigned type, so
1256     // use the signed type.
1257     if (LHSSigned) {
1258       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1259       return LHSType;
1260     } else if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1262     return RHSType;
1263   } else {
1264     // The signed type is higher-ranked than the unsigned type,
1265     // but isn't actually any bigger (like unsigned int and long
1266     // on most 32-bit systems).  Use the unsigned type corresponding
1267     // to the signed type.
1268     QualType result =
1269       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1270     RHS = (*doRHSCast)(S, RHS.get(), result);
1271     if (!IsCompAssign)
1272       LHS = (*doLHSCast)(S, LHS.get(), result);
1273     return result;
1274   }
1275 }
1276 
1277 /// \brief Handle conversions with GCC complex int extension.  Helper function
1278 /// of UsualArithmeticConversions()
1279 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1280                                            ExprResult &RHS, QualType LHSType,
1281                                            QualType RHSType,
1282                                            bool IsCompAssign) {
1283   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1284   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1285 
1286   if (LHSComplexInt && RHSComplexInt) {
1287     QualType LHSEltType = LHSComplexInt->getElementType();
1288     QualType RHSEltType = RHSComplexInt->getElementType();
1289     QualType ScalarType =
1290       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1291         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1292 
1293     return S.Context.getComplexType(ScalarType);
1294   }
1295 
1296   if (LHSComplexInt) {
1297     QualType LHSEltType = LHSComplexInt->getElementType();
1298     QualType ScalarType =
1299       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1300         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1301     QualType ComplexType = S.Context.getComplexType(ScalarType);
1302     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1303                               CK_IntegralRealToComplex);
1304 
1305     return ComplexType;
1306   }
1307 
1308   assert(RHSComplexInt);
1309 
1310   QualType RHSEltType = RHSComplexInt->getElementType();
1311   QualType ScalarType =
1312     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1313       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1314   QualType ComplexType = S.Context.getComplexType(ScalarType);
1315 
1316   if (!IsCompAssign)
1317     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1318                               CK_IntegralRealToComplex);
1319   return ComplexType;
1320 }
1321 
1322 /// UsualArithmeticConversions - Performs various conversions that are common to
1323 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1324 /// routine returns the first non-arithmetic type found. The client is
1325 /// responsible for emitting appropriate error diagnostics.
1326 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1327                                           bool IsCompAssign) {
1328   if (!IsCompAssign) {
1329     LHS = UsualUnaryConversions(LHS.get());
1330     if (LHS.isInvalid())
1331       return QualType();
1332   }
1333 
1334   RHS = UsualUnaryConversions(RHS.get());
1335   if (RHS.isInvalid())
1336     return QualType();
1337 
1338   // For conversion purposes, we ignore any qualifiers.
1339   // For example, "const float" and "float" are equivalent.
1340   QualType LHSType =
1341     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1342   QualType RHSType =
1343     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1344 
1345   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1346   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1347     LHSType = AtomicLHS->getValueType();
1348 
1349   // If both types are identical, no conversion is needed.
1350   if (LHSType == RHSType)
1351     return LHSType;
1352 
1353   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1354   // The caller can deal with this (e.g. pointer + int).
1355   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1356     return QualType();
1357 
1358   // Apply unary and bitfield promotions to the LHS's type.
1359   QualType LHSUnpromotedType = LHSType;
1360   if (LHSType->isPromotableIntegerType())
1361     LHSType = Context.getPromotedIntegerType(LHSType);
1362   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1363   if (!LHSBitfieldPromoteTy.isNull())
1364     LHSType = LHSBitfieldPromoteTy;
1365   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1366     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1367 
1368   // If both types are identical, no conversion is needed.
1369   if (LHSType == RHSType)
1370     return LHSType;
1371 
1372   // At this point, we have two different arithmetic types.
1373 
1374   // Diagnose attempts to convert between __float128 and long double where
1375   // such conversions currently can't be handled.
1376   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1377     return QualType();
1378 
1379   // Handle complex types first (C99 6.3.1.8p1).
1380   if (LHSType->isComplexType() || RHSType->isComplexType())
1381     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1382                                         IsCompAssign);
1383 
1384   // Now handle "real" floating types (i.e. float, double, long double).
1385   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1386     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1387                                  IsCompAssign);
1388 
1389   // Handle GCC complex int extension.
1390   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1391     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1392                                       IsCompAssign);
1393 
1394   // Finally, we have two differing integer types.
1395   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1396            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1397 }
1398 
1399 
1400 //===----------------------------------------------------------------------===//
1401 //  Semantic Analysis for various Expression Types
1402 //===----------------------------------------------------------------------===//
1403 
1404 
1405 ExprResult
1406 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1407                                 SourceLocation DefaultLoc,
1408                                 SourceLocation RParenLoc,
1409                                 Expr *ControllingExpr,
1410                                 ArrayRef<ParsedType> ArgTypes,
1411                                 ArrayRef<Expr *> ArgExprs) {
1412   unsigned NumAssocs = ArgTypes.size();
1413   assert(NumAssocs == ArgExprs.size());
1414 
1415   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1416   for (unsigned i = 0; i < NumAssocs; ++i) {
1417     if (ArgTypes[i])
1418       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1419     else
1420       Types[i] = nullptr;
1421   }
1422 
1423   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1424                                              ControllingExpr,
1425                                              llvm::makeArrayRef(Types, NumAssocs),
1426                                              ArgExprs);
1427   delete [] Types;
1428   return ER;
1429 }
1430 
1431 ExprResult
1432 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1433                                  SourceLocation DefaultLoc,
1434                                  SourceLocation RParenLoc,
1435                                  Expr *ControllingExpr,
1436                                  ArrayRef<TypeSourceInfo *> Types,
1437                                  ArrayRef<Expr *> Exprs) {
1438   unsigned NumAssocs = Types.size();
1439   assert(NumAssocs == Exprs.size());
1440 
1441   // Decay and strip qualifiers for the controlling expression type, and handle
1442   // placeholder type replacement. See committee discussion from WG14 DR423.
1443   {
1444     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1445     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1446     if (R.isInvalid())
1447       return ExprError();
1448     ControllingExpr = R.get();
1449   }
1450 
1451   // The controlling expression is an unevaluated operand, so side effects are
1452   // likely unintended.
1453   if (ActiveTemplateInstantiations.empty() &&
1454       ControllingExpr->HasSideEffects(Context, false))
1455     Diag(ControllingExpr->getExprLoc(),
1456          diag::warn_side_effects_unevaluated_context);
1457 
1458   bool TypeErrorFound = false,
1459        IsResultDependent = ControllingExpr->isTypeDependent(),
1460        ContainsUnexpandedParameterPack
1461          = ControllingExpr->containsUnexpandedParameterPack();
1462 
1463   for (unsigned i = 0; i < NumAssocs; ++i) {
1464     if (Exprs[i]->containsUnexpandedParameterPack())
1465       ContainsUnexpandedParameterPack = true;
1466 
1467     if (Types[i]) {
1468       if (Types[i]->getType()->containsUnexpandedParameterPack())
1469         ContainsUnexpandedParameterPack = true;
1470 
1471       if (Types[i]->getType()->isDependentType()) {
1472         IsResultDependent = true;
1473       } else {
1474         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1475         // complete object type other than a variably modified type."
1476         unsigned D = 0;
1477         if (Types[i]->getType()->isIncompleteType())
1478           D = diag::err_assoc_type_incomplete;
1479         else if (!Types[i]->getType()->isObjectType())
1480           D = diag::err_assoc_type_nonobject;
1481         else if (Types[i]->getType()->isVariablyModifiedType())
1482           D = diag::err_assoc_type_variably_modified;
1483 
1484         if (D != 0) {
1485           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1486             << Types[i]->getTypeLoc().getSourceRange()
1487             << Types[i]->getType();
1488           TypeErrorFound = true;
1489         }
1490 
1491         // C11 6.5.1.1p2 "No two generic associations in the same generic
1492         // selection shall specify compatible types."
1493         for (unsigned j = i+1; j < NumAssocs; ++j)
1494           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1495               Context.typesAreCompatible(Types[i]->getType(),
1496                                          Types[j]->getType())) {
1497             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1498                  diag::err_assoc_compatible_types)
1499               << Types[j]->getTypeLoc().getSourceRange()
1500               << Types[j]->getType()
1501               << Types[i]->getType();
1502             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1503                  diag::note_compat_assoc)
1504               << Types[i]->getTypeLoc().getSourceRange()
1505               << Types[i]->getType();
1506             TypeErrorFound = true;
1507           }
1508       }
1509     }
1510   }
1511   if (TypeErrorFound)
1512     return ExprError();
1513 
1514   // If we determined that the generic selection is result-dependent, don't
1515   // try to compute the result expression.
1516   if (IsResultDependent)
1517     return new (Context) GenericSelectionExpr(
1518         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1519         ContainsUnexpandedParameterPack);
1520 
1521   SmallVector<unsigned, 1> CompatIndices;
1522   unsigned DefaultIndex = -1U;
1523   for (unsigned i = 0; i < NumAssocs; ++i) {
1524     if (!Types[i])
1525       DefaultIndex = i;
1526     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1527                                         Types[i]->getType()))
1528       CompatIndices.push_back(i);
1529   }
1530 
1531   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1532   // type compatible with at most one of the types named in its generic
1533   // association list."
1534   if (CompatIndices.size() > 1) {
1535     // We strip parens here because the controlling expression is typically
1536     // parenthesized in macro definitions.
1537     ControllingExpr = ControllingExpr->IgnoreParens();
1538     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1539       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1540       << (unsigned) CompatIndices.size();
1541     for (unsigned I : CompatIndices) {
1542       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1543            diag::note_compat_assoc)
1544         << Types[I]->getTypeLoc().getSourceRange()
1545         << Types[I]->getType();
1546     }
1547     return ExprError();
1548   }
1549 
1550   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1551   // its controlling expression shall have type compatible with exactly one of
1552   // the types named in its generic association list."
1553   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1554     // We strip parens here because the controlling expression is typically
1555     // parenthesized in macro definitions.
1556     ControllingExpr = ControllingExpr->IgnoreParens();
1557     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1558       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1559     return ExprError();
1560   }
1561 
1562   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1563   // type name that is compatible with the type of the controlling expression,
1564   // then the result expression of the generic selection is the expression
1565   // in that generic association. Otherwise, the result expression of the
1566   // generic selection is the expression in the default generic association."
1567   unsigned ResultIndex =
1568     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1569 
1570   return new (Context) GenericSelectionExpr(
1571       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1572       ContainsUnexpandedParameterPack, ResultIndex);
1573 }
1574 
1575 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1576 /// location of the token and the offset of the ud-suffix within it.
1577 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1578                                      unsigned Offset) {
1579   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1580                                         S.getLangOpts());
1581 }
1582 
1583 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1584 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1585 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1586                                                  IdentifierInfo *UDSuffix,
1587                                                  SourceLocation UDSuffixLoc,
1588                                                  ArrayRef<Expr*> Args,
1589                                                  SourceLocation LitEndLoc) {
1590   assert(Args.size() <= 2 && "too many arguments for literal operator");
1591 
1592   QualType ArgTy[2];
1593   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1594     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1595     if (ArgTy[ArgIdx]->isArrayType())
1596       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1597   }
1598 
1599   DeclarationName OpName =
1600     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1601   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1602   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1603 
1604   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1605   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1606                               /*AllowRaw*/false, /*AllowTemplate*/false,
1607                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1608     return ExprError();
1609 
1610   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1611 }
1612 
1613 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1614 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1615 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1616 /// multiple tokens.  However, the common case is that StringToks points to one
1617 /// string.
1618 ///
1619 ExprResult
1620 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1621   assert(!StringToks.empty() && "Must have at least one string!");
1622 
1623   StringLiteralParser Literal(StringToks, PP);
1624   if (Literal.hadError)
1625     return ExprError();
1626 
1627   SmallVector<SourceLocation, 4> StringTokLocs;
1628   for (const Token &Tok : StringToks)
1629     StringTokLocs.push_back(Tok.getLocation());
1630 
1631   QualType CharTy = Context.CharTy;
1632   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1633   if (Literal.isWide()) {
1634     CharTy = Context.getWideCharType();
1635     Kind = StringLiteral::Wide;
1636   } else if (Literal.isUTF8()) {
1637     Kind = StringLiteral::UTF8;
1638   } else if (Literal.isUTF16()) {
1639     CharTy = Context.Char16Ty;
1640     Kind = StringLiteral::UTF16;
1641   } else if (Literal.isUTF32()) {
1642     CharTy = Context.Char32Ty;
1643     Kind = StringLiteral::UTF32;
1644   } else if (Literal.isPascal()) {
1645     CharTy = Context.UnsignedCharTy;
1646   }
1647 
1648   QualType CharTyConst = CharTy;
1649   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1650   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1651     CharTyConst.addConst();
1652 
1653   // Get an array type for the string, according to C99 6.4.5.  This includes
1654   // the nul terminator character as well as the string length for pascal
1655   // strings.
1656   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1657                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1658                                  ArrayType::Normal, 0);
1659 
1660   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1661   if (getLangOpts().OpenCL) {
1662     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1663   }
1664 
1665   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1666   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1667                                              Kind, Literal.Pascal, StrTy,
1668                                              &StringTokLocs[0],
1669                                              StringTokLocs.size());
1670   if (Literal.getUDSuffix().empty())
1671     return Lit;
1672 
1673   // We're building a user-defined literal.
1674   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1675   SourceLocation UDSuffixLoc =
1676     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1677                    Literal.getUDSuffixOffset());
1678 
1679   // Make sure we're allowed user-defined literals here.
1680   if (!UDLScope)
1681     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1682 
1683   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1684   //   operator "" X (str, len)
1685   QualType SizeType = Context.getSizeType();
1686 
1687   DeclarationName OpName =
1688     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1689   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1690   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1691 
1692   QualType ArgTy[] = {
1693     Context.getArrayDecayedType(StrTy), SizeType
1694   };
1695 
1696   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1697   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1698                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1699                                 /*AllowStringTemplate*/true)) {
1700 
1701   case LOLR_Cooked: {
1702     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1703     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1704                                                     StringTokLocs[0]);
1705     Expr *Args[] = { Lit, LenArg };
1706 
1707     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1708   }
1709 
1710   case LOLR_StringTemplate: {
1711     TemplateArgumentListInfo ExplicitArgs;
1712 
1713     unsigned CharBits = Context.getIntWidth(CharTy);
1714     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1715     llvm::APSInt Value(CharBits, CharIsUnsigned);
1716 
1717     TemplateArgument TypeArg(CharTy);
1718     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1719     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1720 
1721     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1722       Value = Lit->getCodeUnit(I);
1723       TemplateArgument Arg(Context, Value, CharTy);
1724       TemplateArgumentLocInfo ArgInfo;
1725       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1726     }
1727     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1728                                     &ExplicitArgs);
1729   }
1730   case LOLR_Raw:
1731   case LOLR_Template:
1732     llvm_unreachable("unexpected literal operator lookup result");
1733   case LOLR_Error:
1734     return ExprError();
1735   }
1736   llvm_unreachable("unexpected literal operator lookup result");
1737 }
1738 
1739 ExprResult
1740 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1741                        SourceLocation Loc,
1742                        const CXXScopeSpec *SS) {
1743   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1744   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1745 }
1746 
1747 /// BuildDeclRefExpr - Build an expression that references a
1748 /// declaration that does not require a closure capture.
1749 ExprResult
1750 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1751                        const DeclarationNameInfo &NameInfo,
1752                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1753                        const TemplateArgumentListInfo *TemplateArgs) {
1754   bool RefersToCapturedVariable =
1755       isa<VarDecl>(D) &&
1756       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1757 
1758   DeclRefExpr *E;
1759   if (isa<VarTemplateSpecializationDecl>(D)) {
1760     VarTemplateSpecializationDecl *VarSpec =
1761         cast<VarTemplateSpecializationDecl>(D);
1762 
1763     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1764                                         : NestedNameSpecifierLoc(),
1765                             VarSpec->getTemplateKeywordLoc(), D,
1766                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1767                             FoundD, TemplateArgs);
1768   } else {
1769     assert(!TemplateArgs && "No template arguments for non-variable"
1770                             " template specialization references");
1771     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1772                                         : NestedNameSpecifierLoc(),
1773                             SourceLocation(), D, RefersToCapturedVariable,
1774                             NameInfo, Ty, VK, FoundD);
1775   }
1776 
1777   MarkDeclRefReferenced(E);
1778 
1779   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1780       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1781       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1782       recordUseOfEvaluatedWeak(E);
1783 
1784   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1785     UnusedPrivateFields.remove(FD);
1786     // Just in case we're building an illegal pointer-to-member.
1787     if (FD->isBitField())
1788       E->setObjectKind(OK_BitField);
1789   }
1790 
1791   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1792   // designates a bit-field.
1793   if (auto *BD = dyn_cast<BindingDecl>(D))
1794     if (auto *BE = BD->getBinding())
1795       E->setObjectKind(BE->getObjectKind());
1796 
1797   return E;
1798 }
1799 
1800 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1801 /// possibly a list of template arguments.
1802 ///
1803 /// If this produces template arguments, it is permitted to call
1804 /// DecomposeTemplateName.
1805 ///
1806 /// This actually loses a lot of source location information for
1807 /// non-standard name kinds; we should consider preserving that in
1808 /// some way.
1809 void
1810 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1811                              TemplateArgumentListInfo &Buffer,
1812                              DeclarationNameInfo &NameInfo,
1813                              const TemplateArgumentListInfo *&TemplateArgs) {
1814   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1815     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1816     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1817 
1818     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1819                                        Id.TemplateId->NumArgs);
1820     translateTemplateArguments(TemplateArgsPtr, Buffer);
1821 
1822     TemplateName TName = Id.TemplateId->Template.get();
1823     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1824     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1825     TemplateArgs = &Buffer;
1826   } else {
1827     NameInfo = GetNameFromUnqualifiedId(Id);
1828     TemplateArgs = nullptr;
1829   }
1830 }
1831 
1832 static void emitEmptyLookupTypoDiagnostic(
1833     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1834     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1835     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1836   DeclContext *Ctx =
1837       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1838   if (!TC) {
1839     // Emit a special diagnostic for failed member lookups.
1840     // FIXME: computing the declaration context might fail here (?)
1841     if (Ctx)
1842       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1843                                                  << SS.getRange();
1844     else
1845       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1846     return;
1847   }
1848 
1849   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1850   bool DroppedSpecifier =
1851       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1852   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1853                         ? diag::note_implicit_param_decl
1854                         : diag::note_previous_decl;
1855   if (!Ctx)
1856     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1857                          SemaRef.PDiag(NoteID));
1858   else
1859     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1860                                  << Typo << Ctx << DroppedSpecifier
1861                                  << SS.getRange(),
1862                          SemaRef.PDiag(NoteID));
1863 }
1864 
1865 /// Diagnose an empty lookup.
1866 ///
1867 /// \return false if new lookup candidates were found
1868 bool
1869 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1870                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1871                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1872                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1873   DeclarationName Name = R.getLookupName();
1874 
1875   unsigned diagnostic = diag::err_undeclared_var_use;
1876   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1877   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1878       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1879       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1880     diagnostic = diag::err_undeclared_use;
1881     diagnostic_suggest = diag::err_undeclared_use_suggest;
1882   }
1883 
1884   // If the original lookup was an unqualified lookup, fake an
1885   // unqualified lookup.  This is useful when (for example) the
1886   // original lookup would not have found something because it was a
1887   // dependent name.
1888   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1889   while (DC) {
1890     if (isa<CXXRecordDecl>(DC)) {
1891       LookupQualifiedName(R, DC);
1892 
1893       if (!R.empty()) {
1894         // Don't give errors about ambiguities in this lookup.
1895         R.suppressDiagnostics();
1896 
1897         // During a default argument instantiation the CurContext points
1898         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1899         // function parameter list, hence add an explicit check.
1900         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1901                               ActiveTemplateInstantiations.back().Kind ==
1902             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1903         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1904         bool isInstance = CurMethod &&
1905                           CurMethod->isInstance() &&
1906                           DC == CurMethod->getParent() && !isDefaultArgument;
1907 
1908         // Give a code modification hint to insert 'this->'.
1909         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1910         // Actually quite difficult!
1911         if (getLangOpts().MSVCCompat)
1912           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1913         if (isInstance) {
1914           Diag(R.getNameLoc(), diagnostic) << Name
1915             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1916           CheckCXXThisCapture(R.getNameLoc());
1917         } else {
1918           Diag(R.getNameLoc(), diagnostic) << Name;
1919         }
1920 
1921         // Do we really want to note all of these?
1922         for (NamedDecl *D : R)
1923           Diag(D->getLocation(), diag::note_dependent_var_use);
1924 
1925         // Return true if we are inside a default argument instantiation
1926         // and the found name refers to an instance member function, otherwise
1927         // the function calling DiagnoseEmptyLookup will try to create an
1928         // implicit member call and this is wrong for default argument.
1929         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1930           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1931           return true;
1932         }
1933 
1934         // Tell the callee to try to recover.
1935         return false;
1936       }
1937 
1938       R.clear();
1939     }
1940 
1941     // In Microsoft mode, if we are performing lookup from within a friend
1942     // function definition declared at class scope then we must set
1943     // DC to the lexical parent to be able to search into the parent
1944     // class.
1945     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1946         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1947         DC->getLexicalParent()->isRecord())
1948       DC = DC->getLexicalParent();
1949     else
1950       DC = DC->getParent();
1951   }
1952 
1953   // We didn't find anything, so try to correct for a typo.
1954   TypoCorrection Corrected;
1955   if (S && Out) {
1956     SourceLocation TypoLoc = R.getNameLoc();
1957     assert(!ExplicitTemplateArgs &&
1958            "Diagnosing an empty lookup with explicit template args!");
1959     *Out = CorrectTypoDelayed(
1960         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1961         [=](const TypoCorrection &TC) {
1962           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1963                                         diagnostic, diagnostic_suggest);
1964         },
1965         nullptr, CTK_ErrorRecovery);
1966     if (*Out)
1967       return true;
1968   } else if (S && (Corrected =
1969                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1970                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1971     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1972     bool DroppedSpecifier =
1973         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1974     R.setLookupName(Corrected.getCorrection());
1975 
1976     bool AcceptableWithRecovery = false;
1977     bool AcceptableWithoutRecovery = false;
1978     NamedDecl *ND = Corrected.getFoundDecl();
1979     if (ND) {
1980       if (Corrected.isOverloaded()) {
1981         OverloadCandidateSet OCS(R.getNameLoc(),
1982                                  OverloadCandidateSet::CSK_Normal);
1983         OverloadCandidateSet::iterator Best;
1984         for (NamedDecl *CD : Corrected) {
1985           if (FunctionTemplateDecl *FTD =
1986                    dyn_cast<FunctionTemplateDecl>(CD))
1987             AddTemplateOverloadCandidate(
1988                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1989                 Args, OCS);
1990           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1991             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1992               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1993                                    Args, OCS);
1994         }
1995         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1996         case OR_Success:
1997           ND = Best->FoundDecl;
1998           Corrected.setCorrectionDecl(ND);
1999           break;
2000         default:
2001           // FIXME: Arbitrarily pick the first declaration for the note.
2002           Corrected.setCorrectionDecl(ND);
2003           break;
2004         }
2005       }
2006       R.addDecl(ND);
2007       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2008         CXXRecordDecl *Record = nullptr;
2009         if (Corrected.getCorrectionSpecifier()) {
2010           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2011           Record = Ty->getAsCXXRecordDecl();
2012         }
2013         if (!Record)
2014           Record = cast<CXXRecordDecl>(
2015               ND->getDeclContext()->getRedeclContext());
2016         R.setNamingClass(Record);
2017       }
2018 
2019       auto *UnderlyingND = ND->getUnderlyingDecl();
2020       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2021                                isa<FunctionTemplateDecl>(UnderlyingND);
2022       // FIXME: If we ended up with a typo for a type name or
2023       // Objective-C class name, we're in trouble because the parser
2024       // is in the wrong place to recover. Suggest the typo
2025       // correction, but don't make it a fix-it since we're not going
2026       // to recover well anyway.
2027       AcceptableWithoutRecovery =
2028           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2029     } else {
2030       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2031       // because we aren't able to recover.
2032       AcceptableWithoutRecovery = true;
2033     }
2034 
2035     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2036       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2037                             ? diag::note_implicit_param_decl
2038                             : diag::note_previous_decl;
2039       if (SS.isEmpty())
2040         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2041                      PDiag(NoteID), AcceptableWithRecovery);
2042       else
2043         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2044                                   << Name << computeDeclContext(SS, false)
2045                                   << DroppedSpecifier << SS.getRange(),
2046                      PDiag(NoteID), AcceptableWithRecovery);
2047 
2048       // Tell the callee whether to try to recover.
2049       return !AcceptableWithRecovery;
2050     }
2051   }
2052   R.clear();
2053 
2054   // Emit a special diagnostic for failed member lookups.
2055   // FIXME: computing the declaration context might fail here (?)
2056   if (!SS.isEmpty()) {
2057     Diag(R.getNameLoc(), diag::err_no_member)
2058       << Name << computeDeclContext(SS, false)
2059       << SS.getRange();
2060     return true;
2061   }
2062 
2063   // Give up, we can't recover.
2064   Diag(R.getNameLoc(), diagnostic) << Name;
2065   return true;
2066 }
2067 
2068 /// In Microsoft mode, if we are inside a template class whose parent class has
2069 /// dependent base classes, and we can't resolve an unqualified identifier, then
2070 /// assume the identifier is a member of a dependent base class.  We can only
2071 /// recover successfully in static methods, instance methods, and other contexts
2072 /// where 'this' is available.  This doesn't precisely match MSVC's
2073 /// instantiation model, but it's close enough.
2074 static Expr *
2075 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2076                                DeclarationNameInfo &NameInfo,
2077                                SourceLocation TemplateKWLoc,
2078                                const TemplateArgumentListInfo *TemplateArgs) {
2079   // Only try to recover from lookup into dependent bases in static methods or
2080   // contexts where 'this' is available.
2081   QualType ThisType = S.getCurrentThisType();
2082   const CXXRecordDecl *RD = nullptr;
2083   if (!ThisType.isNull())
2084     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2085   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2086     RD = MD->getParent();
2087   if (!RD || !RD->hasAnyDependentBases())
2088     return nullptr;
2089 
2090   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2091   // is available, suggest inserting 'this->' as a fixit.
2092   SourceLocation Loc = NameInfo.getLoc();
2093   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2094   DB << NameInfo.getName() << RD;
2095 
2096   if (!ThisType.isNull()) {
2097     DB << FixItHint::CreateInsertion(Loc, "this->");
2098     return CXXDependentScopeMemberExpr::Create(
2099         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2100         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2101         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2102   }
2103 
2104   // Synthesize a fake NNS that points to the derived class.  This will
2105   // perform name lookup during template instantiation.
2106   CXXScopeSpec SS;
2107   auto *NNS =
2108       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2109   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2110   return DependentScopeDeclRefExpr::Create(
2111       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2112       TemplateArgs);
2113 }
2114 
2115 ExprResult
2116 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2117                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2118                         bool HasTrailingLParen, bool IsAddressOfOperand,
2119                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2120                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2121   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2122          "cannot be direct & operand and have a trailing lparen");
2123   if (SS.isInvalid())
2124     return ExprError();
2125 
2126   TemplateArgumentListInfo TemplateArgsBuffer;
2127 
2128   // Decompose the UnqualifiedId into the following data.
2129   DeclarationNameInfo NameInfo;
2130   const TemplateArgumentListInfo *TemplateArgs;
2131   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2132 
2133   DeclarationName Name = NameInfo.getName();
2134   IdentifierInfo *II = Name.getAsIdentifierInfo();
2135   SourceLocation NameLoc = NameInfo.getLoc();
2136 
2137   // C++ [temp.dep.expr]p3:
2138   //   An id-expression is type-dependent if it contains:
2139   //     -- an identifier that was declared with a dependent type,
2140   //        (note: handled after lookup)
2141   //     -- a template-id that is dependent,
2142   //        (note: handled in BuildTemplateIdExpr)
2143   //     -- a conversion-function-id that specifies a dependent type,
2144   //     -- a nested-name-specifier that contains a class-name that
2145   //        names a dependent type.
2146   // Determine whether this is a member of an unknown specialization;
2147   // we need to handle these differently.
2148   bool DependentID = false;
2149   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2150       Name.getCXXNameType()->isDependentType()) {
2151     DependentID = true;
2152   } else if (SS.isSet()) {
2153     if (DeclContext *DC = computeDeclContext(SS, false)) {
2154       if (RequireCompleteDeclContext(SS, DC))
2155         return ExprError();
2156     } else {
2157       DependentID = true;
2158     }
2159   }
2160 
2161   if (DependentID)
2162     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2163                                       IsAddressOfOperand, TemplateArgs);
2164 
2165   // Perform the required lookup.
2166   LookupResult R(*this, NameInfo,
2167                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2168                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2169   if (TemplateArgs) {
2170     // Lookup the template name again to correctly establish the context in
2171     // which it was found. This is really unfortunate as we already did the
2172     // lookup to determine that it was a template name in the first place. If
2173     // this becomes a performance hit, we can work harder to preserve those
2174     // results until we get here but it's likely not worth it.
2175     bool MemberOfUnknownSpecialization;
2176     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2177                        MemberOfUnknownSpecialization);
2178 
2179     if (MemberOfUnknownSpecialization ||
2180         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2181       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2182                                         IsAddressOfOperand, TemplateArgs);
2183   } else {
2184     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2185     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2186 
2187     // If the result might be in a dependent base class, this is a dependent
2188     // id-expression.
2189     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2190       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2191                                         IsAddressOfOperand, TemplateArgs);
2192 
2193     // If this reference is in an Objective-C method, then we need to do
2194     // some special Objective-C lookup, too.
2195     if (IvarLookupFollowUp) {
2196       ExprResult E(LookupInObjCMethod(R, S, II, true));
2197       if (E.isInvalid())
2198         return ExprError();
2199 
2200       if (Expr *Ex = E.getAs<Expr>())
2201         return Ex;
2202     }
2203   }
2204 
2205   if (R.isAmbiguous())
2206     return ExprError();
2207 
2208   // This could be an implicitly declared function reference (legal in C90,
2209   // extension in C99, forbidden in C++).
2210   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2211     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2212     if (D) R.addDecl(D);
2213   }
2214 
2215   // Determine whether this name might be a candidate for
2216   // argument-dependent lookup.
2217   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2218 
2219   if (R.empty() && !ADL) {
2220     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2221       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2222                                                    TemplateKWLoc, TemplateArgs))
2223         return E;
2224     }
2225 
2226     // Don't diagnose an empty lookup for inline assembly.
2227     if (IsInlineAsmIdentifier)
2228       return ExprError();
2229 
2230     // If this name wasn't predeclared and if this is not a function
2231     // call, diagnose the problem.
2232     TypoExpr *TE = nullptr;
2233     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2234         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2235     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2236     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2237            "Typo correction callback misconfigured");
2238     if (CCC) {
2239       // Make sure the callback knows what the typo being diagnosed is.
2240       CCC->setTypoName(II);
2241       if (SS.isValid())
2242         CCC->setTypoNNS(SS.getScopeRep());
2243     }
2244     if (DiagnoseEmptyLookup(S, SS, R,
2245                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2246                             nullptr, None, &TE)) {
2247       if (TE && KeywordReplacement) {
2248         auto &State = getTypoExprState(TE);
2249         auto BestTC = State.Consumer->getNextCorrection();
2250         if (BestTC.isKeyword()) {
2251           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2252           if (State.DiagHandler)
2253             State.DiagHandler(BestTC);
2254           KeywordReplacement->startToken();
2255           KeywordReplacement->setKind(II->getTokenID());
2256           KeywordReplacement->setIdentifierInfo(II);
2257           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2258           // Clean up the state associated with the TypoExpr, since it has
2259           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2260           clearDelayedTypo(TE);
2261           // Signal that a correction to a keyword was performed by returning a
2262           // valid-but-null ExprResult.
2263           return (Expr*)nullptr;
2264         }
2265         State.Consumer->resetCorrectionStream();
2266       }
2267       return TE ? TE : ExprError();
2268     }
2269 
2270     assert(!R.empty() &&
2271            "DiagnoseEmptyLookup returned false but added no results");
2272 
2273     // If we found an Objective-C instance variable, let
2274     // LookupInObjCMethod build the appropriate expression to
2275     // reference the ivar.
2276     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2277       R.clear();
2278       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2279       // In a hopelessly buggy code, Objective-C instance variable
2280       // lookup fails and no expression will be built to reference it.
2281       if (!E.isInvalid() && !E.get())
2282         return ExprError();
2283       return E;
2284     }
2285   }
2286 
2287   // This is guaranteed from this point on.
2288   assert(!R.empty() || ADL);
2289 
2290   // Check whether this might be a C++ implicit instance member access.
2291   // C++ [class.mfct.non-static]p3:
2292   //   When an id-expression that is not part of a class member access
2293   //   syntax and not used to form a pointer to member is used in the
2294   //   body of a non-static member function of class X, if name lookup
2295   //   resolves the name in the id-expression to a non-static non-type
2296   //   member of some class C, the id-expression is transformed into a
2297   //   class member access expression using (*this) as the
2298   //   postfix-expression to the left of the . operator.
2299   //
2300   // But we don't actually need to do this for '&' operands if R
2301   // resolved to a function or overloaded function set, because the
2302   // expression is ill-formed if it actually works out to be a
2303   // non-static member function:
2304   //
2305   // C++ [expr.ref]p4:
2306   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2307   //   [t]he expression can be used only as the left-hand operand of a
2308   //   member function call.
2309   //
2310   // There are other safeguards against such uses, but it's important
2311   // to get this right here so that we don't end up making a
2312   // spuriously dependent expression if we're inside a dependent
2313   // instance method.
2314   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2315     bool MightBeImplicitMember;
2316     if (!IsAddressOfOperand)
2317       MightBeImplicitMember = true;
2318     else if (!SS.isEmpty())
2319       MightBeImplicitMember = false;
2320     else if (R.isOverloadedResult())
2321       MightBeImplicitMember = false;
2322     else if (R.isUnresolvableResult())
2323       MightBeImplicitMember = true;
2324     else
2325       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2326                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2327                               isa<MSPropertyDecl>(R.getFoundDecl());
2328 
2329     if (MightBeImplicitMember)
2330       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2331                                              R, TemplateArgs, S);
2332   }
2333 
2334   if (TemplateArgs || TemplateKWLoc.isValid()) {
2335 
2336     // In C++1y, if this is a variable template id, then check it
2337     // in BuildTemplateIdExpr().
2338     // The single lookup result must be a variable template declaration.
2339     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2340         Id.TemplateId->Kind == TNK_Var_template) {
2341       assert(R.getAsSingle<VarTemplateDecl>() &&
2342              "There should only be one declaration found.");
2343     }
2344 
2345     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2346   }
2347 
2348   return BuildDeclarationNameExpr(SS, R, ADL);
2349 }
2350 
2351 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2352 /// declaration name, generally during template instantiation.
2353 /// There's a large number of things which don't need to be done along
2354 /// this path.
2355 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2356     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2357     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2358   DeclContext *DC = computeDeclContext(SS, false);
2359   if (!DC)
2360     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2361                                      NameInfo, /*TemplateArgs=*/nullptr);
2362 
2363   if (RequireCompleteDeclContext(SS, DC))
2364     return ExprError();
2365 
2366   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2367   LookupQualifiedName(R, DC);
2368 
2369   if (R.isAmbiguous())
2370     return ExprError();
2371 
2372   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2373     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2374                                      NameInfo, /*TemplateArgs=*/nullptr);
2375 
2376   if (R.empty()) {
2377     Diag(NameInfo.getLoc(), diag::err_no_member)
2378       << NameInfo.getName() << DC << SS.getRange();
2379     return ExprError();
2380   }
2381 
2382   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2383     // Diagnose a missing typename if this resolved unambiguously to a type in
2384     // a dependent context.  If we can recover with a type, downgrade this to
2385     // a warning in Microsoft compatibility mode.
2386     unsigned DiagID = diag::err_typename_missing;
2387     if (RecoveryTSI && getLangOpts().MSVCCompat)
2388       DiagID = diag::ext_typename_missing;
2389     SourceLocation Loc = SS.getBeginLoc();
2390     auto D = Diag(Loc, DiagID);
2391     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2392       << SourceRange(Loc, NameInfo.getEndLoc());
2393 
2394     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2395     // context.
2396     if (!RecoveryTSI)
2397       return ExprError();
2398 
2399     // Only issue the fixit if we're prepared to recover.
2400     D << FixItHint::CreateInsertion(Loc, "typename ");
2401 
2402     // Recover by pretending this was an elaborated type.
2403     QualType Ty = Context.getTypeDeclType(TD);
2404     TypeLocBuilder TLB;
2405     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2406 
2407     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2408     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2409     QTL.setElaboratedKeywordLoc(SourceLocation());
2410     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2411 
2412     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2413 
2414     return ExprEmpty();
2415   }
2416 
2417   // Defend against this resolving to an implicit member access. We usually
2418   // won't get here if this might be a legitimate a class member (we end up in
2419   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2420   // a pointer-to-member or in an unevaluated context in C++11.
2421   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2422     return BuildPossibleImplicitMemberExpr(SS,
2423                                            /*TemplateKWLoc=*/SourceLocation(),
2424                                            R, /*TemplateArgs=*/nullptr, S);
2425 
2426   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2427 }
2428 
2429 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2430 /// detected that we're currently inside an ObjC method.  Perform some
2431 /// additional lookup.
2432 ///
2433 /// Ideally, most of this would be done by lookup, but there's
2434 /// actually quite a lot of extra work involved.
2435 ///
2436 /// Returns a null sentinel to indicate trivial success.
2437 ExprResult
2438 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2439                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2440   SourceLocation Loc = Lookup.getNameLoc();
2441   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2442 
2443   // Check for error condition which is already reported.
2444   if (!CurMethod)
2445     return ExprError();
2446 
2447   // There are two cases to handle here.  1) scoped lookup could have failed,
2448   // in which case we should look for an ivar.  2) scoped lookup could have
2449   // found a decl, but that decl is outside the current instance method (i.e.
2450   // a global variable).  In these two cases, we do a lookup for an ivar with
2451   // this name, if the lookup sucedes, we replace it our current decl.
2452 
2453   // If we're in a class method, we don't normally want to look for
2454   // ivars.  But if we don't find anything else, and there's an
2455   // ivar, that's an error.
2456   bool IsClassMethod = CurMethod->isClassMethod();
2457 
2458   bool LookForIvars;
2459   if (Lookup.empty())
2460     LookForIvars = true;
2461   else if (IsClassMethod)
2462     LookForIvars = false;
2463   else
2464     LookForIvars = (Lookup.isSingleResult() &&
2465                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2466   ObjCInterfaceDecl *IFace = nullptr;
2467   if (LookForIvars) {
2468     IFace = CurMethod->getClassInterface();
2469     ObjCInterfaceDecl *ClassDeclared;
2470     ObjCIvarDecl *IV = nullptr;
2471     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2472       // Diagnose using an ivar in a class method.
2473       if (IsClassMethod)
2474         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2475                          << IV->getDeclName());
2476 
2477       // If we're referencing an invalid decl, just return this as a silent
2478       // error node.  The error diagnostic was already emitted on the decl.
2479       if (IV->isInvalidDecl())
2480         return ExprError();
2481 
2482       // Check if referencing a field with __attribute__((deprecated)).
2483       if (DiagnoseUseOfDecl(IV, Loc))
2484         return ExprError();
2485 
2486       // Diagnose the use of an ivar outside of the declaring class.
2487       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2488           !declaresSameEntity(ClassDeclared, IFace) &&
2489           !getLangOpts().DebuggerSupport)
2490         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2491 
2492       // FIXME: This should use a new expr for a direct reference, don't
2493       // turn this into Self->ivar, just return a BareIVarExpr or something.
2494       IdentifierInfo &II = Context.Idents.get("self");
2495       UnqualifiedId SelfName;
2496       SelfName.setIdentifier(&II, SourceLocation());
2497       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2498       CXXScopeSpec SelfScopeSpec;
2499       SourceLocation TemplateKWLoc;
2500       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2501                                               SelfName, false, false);
2502       if (SelfExpr.isInvalid())
2503         return ExprError();
2504 
2505       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2506       if (SelfExpr.isInvalid())
2507         return ExprError();
2508 
2509       MarkAnyDeclReferenced(Loc, IV, true);
2510 
2511       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2512       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2513           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2514         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2515 
2516       ObjCIvarRefExpr *Result = new (Context)
2517           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2518                           IV->getLocation(), SelfExpr.get(), true, true);
2519 
2520       if (getLangOpts().ObjCAutoRefCount) {
2521         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2522           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2523             recordUseOfEvaluatedWeak(Result);
2524         }
2525         if (CurContext->isClosure())
2526           Diag(Loc, diag::warn_implicitly_retains_self)
2527             << FixItHint::CreateInsertion(Loc, "self->");
2528       }
2529 
2530       return Result;
2531     }
2532   } else if (CurMethod->isInstanceMethod()) {
2533     // We should warn if a local variable hides an ivar.
2534     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2535       ObjCInterfaceDecl *ClassDeclared;
2536       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2537         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2538             declaresSameEntity(IFace, ClassDeclared))
2539           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2540       }
2541     }
2542   } else if (Lookup.isSingleResult() &&
2543              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2544     // If accessing a stand-alone ivar in a class method, this is an error.
2545     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2546       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2547                        << IV->getDeclName());
2548   }
2549 
2550   if (Lookup.empty() && II && AllowBuiltinCreation) {
2551     // FIXME. Consolidate this with similar code in LookupName.
2552     if (unsigned BuiltinID = II->getBuiltinID()) {
2553       if (!(getLangOpts().CPlusPlus &&
2554             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2555         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2556                                            S, Lookup.isForRedeclaration(),
2557                                            Lookup.getNameLoc());
2558         if (D) Lookup.addDecl(D);
2559       }
2560     }
2561   }
2562   // Sentinel value saying that we didn't do anything special.
2563   return ExprResult((Expr *)nullptr);
2564 }
2565 
2566 /// \brief Cast a base object to a member's actual type.
2567 ///
2568 /// Logically this happens in three phases:
2569 ///
2570 /// * First we cast from the base type to the naming class.
2571 ///   The naming class is the class into which we were looking
2572 ///   when we found the member;  it's the qualifier type if a
2573 ///   qualifier was provided, and otherwise it's the base type.
2574 ///
2575 /// * Next we cast from the naming class to the declaring class.
2576 ///   If the member we found was brought into a class's scope by
2577 ///   a using declaration, this is that class;  otherwise it's
2578 ///   the class declaring the member.
2579 ///
2580 /// * Finally we cast from the declaring class to the "true"
2581 ///   declaring class of the member.  This conversion does not
2582 ///   obey access control.
2583 ExprResult
2584 Sema::PerformObjectMemberConversion(Expr *From,
2585                                     NestedNameSpecifier *Qualifier,
2586                                     NamedDecl *FoundDecl,
2587                                     NamedDecl *Member) {
2588   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2589   if (!RD)
2590     return From;
2591 
2592   QualType DestRecordType;
2593   QualType DestType;
2594   QualType FromRecordType;
2595   QualType FromType = From->getType();
2596   bool PointerConversions = false;
2597   if (isa<FieldDecl>(Member)) {
2598     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2599 
2600     if (FromType->getAs<PointerType>()) {
2601       DestType = Context.getPointerType(DestRecordType);
2602       FromRecordType = FromType->getPointeeType();
2603       PointerConversions = true;
2604     } else {
2605       DestType = DestRecordType;
2606       FromRecordType = FromType;
2607     }
2608   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2609     if (Method->isStatic())
2610       return From;
2611 
2612     DestType = Method->getThisType(Context);
2613     DestRecordType = DestType->getPointeeType();
2614 
2615     if (FromType->getAs<PointerType>()) {
2616       FromRecordType = FromType->getPointeeType();
2617       PointerConversions = true;
2618     } else {
2619       FromRecordType = FromType;
2620       DestType = DestRecordType;
2621     }
2622   } else {
2623     // No conversion necessary.
2624     return From;
2625   }
2626 
2627   if (DestType->isDependentType() || FromType->isDependentType())
2628     return From;
2629 
2630   // If the unqualified types are the same, no conversion is necessary.
2631   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2632     return From;
2633 
2634   SourceRange FromRange = From->getSourceRange();
2635   SourceLocation FromLoc = FromRange.getBegin();
2636 
2637   ExprValueKind VK = From->getValueKind();
2638 
2639   // C++ [class.member.lookup]p8:
2640   //   [...] Ambiguities can often be resolved by qualifying a name with its
2641   //   class name.
2642   //
2643   // If the member was a qualified name and the qualified referred to a
2644   // specific base subobject type, we'll cast to that intermediate type
2645   // first and then to the object in which the member is declared. That allows
2646   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2647   //
2648   //   class Base { public: int x; };
2649   //   class Derived1 : public Base { };
2650   //   class Derived2 : public Base { };
2651   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2652   //
2653   //   void VeryDerived::f() {
2654   //     x = 17; // error: ambiguous base subobjects
2655   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2656   //   }
2657   if (Qualifier && Qualifier->getAsType()) {
2658     QualType QType = QualType(Qualifier->getAsType(), 0);
2659     assert(QType->isRecordType() && "lookup done with non-record type");
2660 
2661     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2662 
2663     // In C++98, the qualifier type doesn't actually have to be a base
2664     // type of the object type, in which case we just ignore it.
2665     // Otherwise build the appropriate casts.
2666     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2667       CXXCastPath BasePath;
2668       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2669                                        FromLoc, FromRange, &BasePath))
2670         return ExprError();
2671 
2672       if (PointerConversions)
2673         QType = Context.getPointerType(QType);
2674       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2675                                VK, &BasePath).get();
2676 
2677       FromType = QType;
2678       FromRecordType = QRecordType;
2679 
2680       // If the qualifier type was the same as the destination type,
2681       // we're done.
2682       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2683         return From;
2684     }
2685   }
2686 
2687   bool IgnoreAccess = false;
2688 
2689   // If we actually found the member through a using declaration, cast
2690   // down to the using declaration's type.
2691   //
2692   // Pointer equality is fine here because only one declaration of a
2693   // class ever has member declarations.
2694   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2695     assert(isa<UsingShadowDecl>(FoundDecl));
2696     QualType URecordType = Context.getTypeDeclType(
2697                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2698 
2699     // We only need to do this if the naming-class to declaring-class
2700     // conversion is non-trivial.
2701     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2702       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2703       CXXCastPath BasePath;
2704       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2705                                        FromLoc, FromRange, &BasePath))
2706         return ExprError();
2707 
2708       QualType UType = URecordType;
2709       if (PointerConversions)
2710         UType = Context.getPointerType(UType);
2711       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2712                                VK, &BasePath).get();
2713       FromType = UType;
2714       FromRecordType = URecordType;
2715     }
2716 
2717     // We don't do access control for the conversion from the
2718     // declaring class to the true declaring class.
2719     IgnoreAccess = true;
2720   }
2721 
2722   CXXCastPath BasePath;
2723   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2724                                    FromLoc, FromRange, &BasePath,
2725                                    IgnoreAccess))
2726     return ExprError();
2727 
2728   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2729                            VK, &BasePath);
2730 }
2731 
2732 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2733                                       const LookupResult &R,
2734                                       bool HasTrailingLParen) {
2735   // Only when used directly as the postfix-expression of a call.
2736   if (!HasTrailingLParen)
2737     return false;
2738 
2739   // Never if a scope specifier was provided.
2740   if (SS.isSet())
2741     return false;
2742 
2743   // Only in C++ or ObjC++.
2744   if (!getLangOpts().CPlusPlus)
2745     return false;
2746 
2747   // Turn off ADL when we find certain kinds of declarations during
2748   // normal lookup:
2749   for (NamedDecl *D : R) {
2750     // C++0x [basic.lookup.argdep]p3:
2751     //     -- a declaration of a class member
2752     // Since using decls preserve this property, we check this on the
2753     // original decl.
2754     if (D->isCXXClassMember())
2755       return false;
2756 
2757     // C++0x [basic.lookup.argdep]p3:
2758     //     -- a block-scope function declaration that is not a
2759     //        using-declaration
2760     // NOTE: we also trigger this for function templates (in fact, we
2761     // don't check the decl type at all, since all other decl types
2762     // turn off ADL anyway).
2763     if (isa<UsingShadowDecl>(D))
2764       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2765     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2766       return false;
2767 
2768     // C++0x [basic.lookup.argdep]p3:
2769     //     -- a declaration that is neither a function or a function
2770     //        template
2771     // And also for builtin functions.
2772     if (isa<FunctionDecl>(D)) {
2773       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2774 
2775       // But also builtin functions.
2776       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2777         return false;
2778     } else if (!isa<FunctionTemplateDecl>(D))
2779       return false;
2780   }
2781 
2782   return true;
2783 }
2784 
2785 
2786 /// Diagnoses obvious problems with the use of the given declaration
2787 /// as an expression.  This is only actually called for lookups that
2788 /// were not overloaded, and it doesn't promise that the declaration
2789 /// will in fact be used.
2790 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2791   if (D->isInvalidDecl())
2792     return true;
2793 
2794   if (isa<TypedefNameDecl>(D)) {
2795     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2796     return true;
2797   }
2798 
2799   if (isa<ObjCInterfaceDecl>(D)) {
2800     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2801     return true;
2802   }
2803 
2804   if (isa<NamespaceDecl>(D)) {
2805     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2806     return true;
2807   }
2808 
2809   return false;
2810 }
2811 
2812 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2813                                           LookupResult &R, bool NeedsADL,
2814                                           bool AcceptInvalidDecl) {
2815   // If this is a single, fully-resolved result and we don't need ADL,
2816   // just build an ordinary singleton decl ref.
2817   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2818     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2819                                     R.getRepresentativeDecl(), nullptr,
2820                                     AcceptInvalidDecl);
2821 
2822   // We only need to check the declaration if there's exactly one
2823   // result, because in the overloaded case the results can only be
2824   // functions and function templates.
2825   if (R.isSingleResult() &&
2826       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2827     return ExprError();
2828 
2829   // Otherwise, just build an unresolved lookup expression.  Suppress
2830   // any lookup-related diagnostics; we'll hash these out later, when
2831   // we've picked a target.
2832   R.suppressDiagnostics();
2833 
2834   UnresolvedLookupExpr *ULE
2835     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2836                                    SS.getWithLocInContext(Context),
2837                                    R.getLookupNameInfo(),
2838                                    NeedsADL, R.isOverloadedResult(),
2839                                    R.begin(), R.end());
2840 
2841   return ULE;
2842 }
2843 
2844 static void
2845 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2846                                    ValueDecl *var, DeclContext *DC);
2847 
2848 /// \brief Complete semantic analysis for a reference to the given declaration.
2849 ExprResult Sema::BuildDeclarationNameExpr(
2850     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2851     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2852     bool AcceptInvalidDecl) {
2853   assert(D && "Cannot refer to a NULL declaration");
2854   assert(!isa<FunctionTemplateDecl>(D) &&
2855          "Cannot refer unambiguously to a function template");
2856 
2857   SourceLocation Loc = NameInfo.getLoc();
2858   if (CheckDeclInExpr(*this, Loc, D))
2859     return ExprError();
2860 
2861   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2862     // Specifically diagnose references to class templates that are missing
2863     // a template argument list.
2864     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2865                                            << Template << SS.getRange();
2866     Diag(Template->getLocation(), diag::note_template_decl_here);
2867     return ExprError();
2868   }
2869 
2870   // Make sure that we're referring to a value.
2871   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2872   if (!VD) {
2873     Diag(Loc, diag::err_ref_non_value)
2874       << D << SS.getRange();
2875     Diag(D->getLocation(), diag::note_declared_at);
2876     return ExprError();
2877   }
2878 
2879   // Check whether this declaration can be used. Note that we suppress
2880   // this check when we're going to perform argument-dependent lookup
2881   // on this function name, because this might not be the function
2882   // that overload resolution actually selects.
2883   if (DiagnoseUseOfDecl(VD, Loc))
2884     return ExprError();
2885 
2886   // Only create DeclRefExpr's for valid Decl's.
2887   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2888     return ExprError();
2889 
2890   // Handle members of anonymous structs and unions.  If we got here,
2891   // and the reference is to a class member indirect field, then this
2892   // must be the subject of a pointer-to-member expression.
2893   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2894     if (!indirectField->isCXXClassMember())
2895       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2896                                                       indirectField);
2897 
2898   {
2899     QualType type = VD->getType();
2900     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2901       // C++ [except.spec]p17:
2902       //   An exception-specification is considered to be needed when:
2903       //   - in an expression, the function is the unique lookup result or
2904       //     the selected member of a set of overloaded functions.
2905       ResolveExceptionSpec(Loc, FPT);
2906       type = VD->getType();
2907     }
2908     ExprValueKind valueKind = VK_RValue;
2909 
2910     switch (D->getKind()) {
2911     // Ignore all the non-ValueDecl kinds.
2912 #define ABSTRACT_DECL(kind)
2913 #define VALUE(type, base)
2914 #define DECL(type, base) \
2915     case Decl::type:
2916 #include "clang/AST/DeclNodes.inc"
2917       llvm_unreachable("invalid value decl kind");
2918 
2919     // These shouldn't make it here.
2920     case Decl::ObjCAtDefsField:
2921     case Decl::ObjCIvar:
2922       llvm_unreachable("forming non-member reference to ivar?");
2923 
2924     // Enum constants are always r-values and never references.
2925     // Unresolved using declarations are dependent.
2926     case Decl::EnumConstant:
2927     case Decl::UnresolvedUsingValue:
2928     case Decl::OMPDeclareReduction:
2929       valueKind = VK_RValue;
2930       break;
2931 
2932     // Fields and indirect fields that got here must be for
2933     // pointer-to-member expressions; we just call them l-values for
2934     // internal consistency, because this subexpression doesn't really
2935     // exist in the high-level semantics.
2936     case Decl::Field:
2937     case Decl::IndirectField:
2938       assert(getLangOpts().CPlusPlus &&
2939              "building reference to field in C?");
2940 
2941       // These can't have reference type in well-formed programs, but
2942       // for internal consistency we do this anyway.
2943       type = type.getNonReferenceType();
2944       valueKind = VK_LValue;
2945       break;
2946 
2947     // Non-type template parameters are either l-values or r-values
2948     // depending on the type.
2949     case Decl::NonTypeTemplateParm: {
2950       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2951         type = reftype->getPointeeType();
2952         valueKind = VK_LValue; // even if the parameter is an r-value reference
2953         break;
2954       }
2955 
2956       // For non-references, we need to strip qualifiers just in case
2957       // the template parameter was declared as 'const int' or whatever.
2958       valueKind = VK_RValue;
2959       type = type.getUnqualifiedType();
2960       break;
2961     }
2962 
2963     case Decl::Var:
2964     case Decl::VarTemplateSpecialization:
2965     case Decl::VarTemplatePartialSpecialization:
2966     case Decl::Decomposition:
2967     case Decl::OMPCapturedExpr:
2968       // In C, "extern void blah;" is valid and is an r-value.
2969       if (!getLangOpts().CPlusPlus &&
2970           !type.hasQualifiers() &&
2971           type->isVoidType()) {
2972         valueKind = VK_RValue;
2973         break;
2974       }
2975       // fallthrough
2976 
2977     case Decl::ImplicitParam:
2978     case Decl::ParmVar: {
2979       // These are always l-values.
2980       valueKind = VK_LValue;
2981       type = type.getNonReferenceType();
2982 
2983       // FIXME: Does the addition of const really only apply in
2984       // potentially-evaluated contexts? Since the variable isn't actually
2985       // captured in an unevaluated context, it seems that the answer is no.
2986       if (!isUnevaluatedContext()) {
2987         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2988         if (!CapturedType.isNull())
2989           type = CapturedType;
2990       }
2991 
2992       break;
2993     }
2994 
2995     case Decl::Binding: {
2996       // These are always lvalues.
2997       valueKind = VK_LValue;
2998       type = type.getNonReferenceType();
2999       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3000       // decides how that's supposed to work.
3001       auto *BD = cast<BindingDecl>(VD);
3002       if (BD->getDeclContext()->isFunctionOrMethod() &&
3003           BD->getDeclContext() != CurContext)
3004         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3005       break;
3006     }
3007 
3008     case Decl::Function: {
3009       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3010         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3011           type = Context.BuiltinFnTy;
3012           valueKind = VK_RValue;
3013           break;
3014         }
3015       }
3016 
3017       const FunctionType *fty = type->castAs<FunctionType>();
3018 
3019       // If we're referring to a function with an __unknown_anytype
3020       // result type, make the entire expression __unknown_anytype.
3021       if (fty->getReturnType() == Context.UnknownAnyTy) {
3022         type = Context.UnknownAnyTy;
3023         valueKind = VK_RValue;
3024         break;
3025       }
3026 
3027       // Functions are l-values in C++.
3028       if (getLangOpts().CPlusPlus) {
3029         valueKind = VK_LValue;
3030         break;
3031       }
3032 
3033       // C99 DR 316 says that, if a function type comes from a
3034       // function definition (without a prototype), that type is only
3035       // used for checking compatibility. Therefore, when referencing
3036       // the function, we pretend that we don't have the full function
3037       // type.
3038       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3039           isa<FunctionProtoType>(fty))
3040         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3041                                               fty->getExtInfo());
3042 
3043       // Functions are r-values in C.
3044       valueKind = VK_RValue;
3045       break;
3046     }
3047 
3048     case Decl::MSProperty:
3049       valueKind = VK_LValue;
3050       break;
3051 
3052     case Decl::CXXMethod:
3053       // If we're referring to a method with an __unknown_anytype
3054       // result type, make the entire expression __unknown_anytype.
3055       // This should only be possible with a type written directly.
3056       if (const FunctionProtoType *proto
3057             = dyn_cast<FunctionProtoType>(VD->getType()))
3058         if (proto->getReturnType() == Context.UnknownAnyTy) {
3059           type = Context.UnknownAnyTy;
3060           valueKind = VK_RValue;
3061           break;
3062         }
3063 
3064       // C++ methods are l-values if static, r-values if non-static.
3065       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3066         valueKind = VK_LValue;
3067         break;
3068       }
3069       // fallthrough
3070 
3071     case Decl::CXXConversion:
3072     case Decl::CXXDestructor:
3073     case Decl::CXXConstructor:
3074       valueKind = VK_RValue;
3075       break;
3076     }
3077 
3078     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3079                             TemplateArgs);
3080   }
3081 }
3082 
3083 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3084                                     SmallString<32> &Target) {
3085   Target.resize(CharByteWidth * (Source.size() + 1));
3086   char *ResultPtr = &Target[0];
3087   const llvm::UTF8 *ErrorPtr;
3088   bool success =
3089       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3090   (void)success;
3091   assert(success);
3092   Target.resize(ResultPtr - &Target[0]);
3093 }
3094 
3095 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3096                                      PredefinedExpr::IdentType IT) {
3097   // Pick the current block, lambda, captured statement or function.
3098   Decl *currentDecl = nullptr;
3099   if (const BlockScopeInfo *BSI = getCurBlock())
3100     currentDecl = BSI->TheDecl;
3101   else if (const LambdaScopeInfo *LSI = getCurLambda())
3102     currentDecl = LSI->CallOperator;
3103   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3104     currentDecl = CSI->TheCapturedDecl;
3105   else
3106     currentDecl = getCurFunctionOrMethodDecl();
3107 
3108   if (!currentDecl) {
3109     Diag(Loc, diag::ext_predef_outside_function);
3110     currentDecl = Context.getTranslationUnitDecl();
3111   }
3112 
3113   QualType ResTy;
3114   StringLiteral *SL = nullptr;
3115   if (cast<DeclContext>(currentDecl)->isDependentContext())
3116     ResTy = Context.DependentTy;
3117   else {
3118     // Pre-defined identifiers are of type char[x], where x is the length of
3119     // the string.
3120     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3121     unsigned Length = Str.length();
3122 
3123     llvm::APInt LengthI(32, Length + 1);
3124     if (IT == PredefinedExpr::LFunction) {
3125       ResTy = Context.WideCharTy.withConst();
3126       SmallString<32> RawChars;
3127       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3128                               Str, RawChars);
3129       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3130                                            /*IndexTypeQuals*/ 0);
3131       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3132                                  /*Pascal*/ false, ResTy, Loc);
3133     } else {
3134       ResTy = Context.CharTy.withConst();
3135       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3136                                            /*IndexTypeQuals*/ 0);
3137       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3138                                  /*Pascal*/ false, ResTy, Loc);
3139     }
3140   }
3141 
3142   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3143 }
3144 
3145 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3146   PredefinedExpr::IdentType IT;
3147 
3148   switch (Kind) {
3149   default: llvm_unreachable("Unknown simple primary expr!");
3150   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3151   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3152   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3153   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3154   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3155   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3156   }
3157 
3158   return BuildPredefinedExpr(Loc, IT);
3159 }
3160 
3161 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3162   SmallString<16> CharBuffer;
3163   bool Invalid = false;
3164   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3165   if (Invalid)
3166     return ExprError();
3167 
3168   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3169                             PP, Tok.getKind());
3170   if (Literal.hadError())
3171     return ExprError();
3172 
3173   QualType Ty;
3174   if (Literal.isWide())
3175     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3176   else if (Literal.isUTF16())
3177     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3178   else if (Literal.isUTF32())
3179     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3180   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3181     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3182   else
3183     Ty = Context.CharTy;  // 'x' -> char in C++
3184 
3185   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3186   if (Literal.isWide())
3187     Kind = CharacterLiteral::Wide;
3188   else if (Literal.isUTF16())
3189     Kind = CharacterLiteral::UTF16;
3190   else if (Literal.isUTF32())
3191     Kind = CharacterLiteral::UTF32;
3192   else if (Literal.isUTF8())
3193     Kind = CharacterLiteral::UTF8;
3194 
3195   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3196                                              Tok.getLocation());
3197 
3198   if (Literal.getUDSuffix().empty())
3199     return Lit;
3200 
3201   // We're building a user-defined literal.
3202   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3203   SourceLocation UDSuffixLoc =
3204     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3205 
3206   // Make sure we're allowed user-defined literals here.
3207   if (!UDLScope)
3208     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3209 
3210   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3211   //   operator "" X (ch)
3212   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3213                                         Lit, Tok.getLocation());
3214 }
3215 
3216 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3217   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3218   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3219                                 Context.IntTy, Loc);
3220 }
3221 
3222 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3223                                   QualType Ty, SourceLocation Loc) {
3224   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3225 
3226   using llvm::APFloat;
3227   APFloat Val(Format);
3228 
3229   APFloat::opStatus result = Literal.GetFloatValue(Val);
3230 
3231   // Overflow is always an error, but underflow is only an error if
3232   // we underflowed to zero (APFloat reports denormals as underflow).
3233   if ((result & APFloat::opOverflow) ||
3234       ((result & APFloat::opUnderflow) && Val.isZero())) {
3235     unsigned diagnostic;
3236     SmallString<20> buffer;
3237     if (result & APFloat::opOverflow) {
3238       diagnostic = diag::warn_float_overflow;
3239       APFloat::getLargest(Format).toString(buffer);
3240     } else {
3241       diagnostic = diag::warn_float_underflow;
3242       APFloat::getSmallest(Format).toString(buffer);
3243     }
3244 
3245     S.Diag(Loc, diagnostic)
3246       << Ty
3247       << StringRef(buffer.data(), buffer.size());
3248   }
3249 
3250   bool isExact = (result == APFloat::opOK);
3251   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3252 }
3253 
3254 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3255   assert(E && "Invalid expression");
3256 
3257   if (E->isValueDependent())
3258     return false;
3259 
3260   QualType QT = E->getType();
3261   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3262     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3263     return true;
3264   }
3265 
3266   llvm::APSInt ValueAPS;
3267   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3268 
3269   if (R.isInvalid())
3270     return true;
3271 
3272   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3273   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3274     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3275         << ValueAPS.toString(10) << ValueIsPositive;
3276     return true;
3277   }
3278 
3279   return false;
3280 }
3281 
3282 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3283   // Fast path for a single digit (which is quite common).  A single digit
3284   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3285   if (Tok.getLength() == 1) {
3286     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3287     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3288   }
3289 
3290   SmallString<128> SpellingBuffer;
3291   // NumericLiteralParser wants to overread by one character.  Add padding to
3292   // the buffer in case the token is copied to the buffer.  If getSpelling()
3293   // returns a StringRef to the memory buffer, it should have a null char at
3294   // the EOF, so it is also safe.
3295   SpellingBuffer.resize(Tok.getLength() + 1);
3296 
3297   // Get the spelling of the token, which eliminates trigraphs, etc.
3298   bool Invalid = false;
3299   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3300   if (Invalid)
3301     return ExprError();
3302 
3303   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3304   if (Literal.hadError)
3305     return ExprError();
3306 
3307   if (Literal.hasUDSuffix()) {
3308     // We're building a user-defined literal.
3309     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3310     SourceLocation UDSuffixLoc =
3311       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3312 
3313     // Make sure we're allowed user-defined literals here.
3314     if (!UDLScope)
3315       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3316 
3317     QualType CookedTy;
3318     if (Literal.isFloatingLiteral()) {
3319       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3320       // long double, the literal is treated as a call of the form
3321       //   operator "" X (f L)
3322       CookedTy = Context.LongDoubleTy;
3323     } else {
3324       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3325       // unsigned long long, the literal is treated as a call of the form
3326       //   operator "" X (n ULL)
3327       CookedTy = Context.UnsignedLongLongTy;
3328     }
3329 
3330     DeclarationName OpName =
3331       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3332     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3333     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3334 
3335     SourceLocation TokLoc = Tok.getLocation();
3336 
3337     // Perform literal operator lookup to determine if we're building a raw
3338     // literal or a cooked one.
3339     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3340     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3341                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3342                                   /*AllowStringTemplate*/false)) {
3343     case LOLR_Error:
3344       return ExprError();
3345 
3346     case LOLR_Cooked: {
3347       Expr *Lit;
3348       if (Literal.isFloatingLiteral()) {
3349         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3350       } else {
3351         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3352         if (Literal.GetIntegerValue(ResultVal))
3353           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3354               << /* Unsigned */ 1;
3355         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3356                                      Tok.getLocation());
3357       }
3358       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3359     }
3360 
3361     case LOLR_Raw: {
3362       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3363       // literal is treated as a call of the form
3364       //   operator "" X ("n")
3365       unsigned Length = Literal.getUDSuffixOffset();
3366       QualType StrTy = Context.getConstantArrayType(
3367           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3368           ArrayType::Normal, 0);
3369       Expr *Lit = StringLiteral::Create(
3370           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3371           /*Pascal*/false, StrTy, &TokLoc, 1);
3372       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3373     }
3374 
3375     case LOLR_Template: {
3376       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3377       // template), L is treated as a call fo the form
3378       //   operator "" X <'c1', 'c2', ... 'ck'>()
3379       // where n is the source character sequence c1 c2 ... ck.
3380       TemplateArgumentListInfo ExplicitArgs;
3381       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3382       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3383       llvm::APSInt Value(CharBits, CharIsUnsigned);
3384       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3385         Value = TokSpelling[I];
3386         TemplateArgument Arg(Context, Value, Context.CharTy);
3387         TemplateArgumentLocInfo ArgInfo;
3388         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3389       }
3390       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3391                                       &ExplicitArgs);
3392     }
3393     case LOLR_StringTemplate:
3394       llvm_unreachable("unexpected literal operator lookup result");
3395     }
3396   }
3397 
3398   Expr *Res;
3399 
3400   if (Literal.isFloatingLiteral()) {
3401     QualType Ty;
3402     if (Literal.isHalf){
3403       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3404         Ty = Context.HalfTy;
3405       else {
3406         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3407         return ExprError();
3408       }
3409     } else if (Literal.isFloat)
3410       Ty = Context.FloatTy;
3411     else if (Literal.isLong)
3412       Ty = Context.LongDoubleTy;
3413     else if (Literal.isFloat128)
3414       Ty = Context.Float128Ty;
3415     else
3416       Ty = Context.DoubleTy;
3417 
3418     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3419 
3420     if (Ty == Context.DoubleTy) {
3421       if (getLangOpts().SinglePrecisionConstants) {
3422         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3423         if (BTy->getKind() != BuiltinType::Float) {
3424           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3425         }
3426       } else if (getLangOpts().OpenCL &&
3427                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3428         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3429         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3430         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3431       }
3432     }
3433   } else if (!Literal.isIntegerLiteral()) {
3434     return ExprError();
3435   } else {
3436     QualType Ty;
3437 
3438     // 'long long' is a C99 or C++11 feature.
3439     if (!getLangOpts().C99 && Literal.isLongLong) {
3440       if (getLangOpts().CPlusPlus)
3441         Diag(Tok.getLocation(),
3442              getLangOpts().CPlusPlus11 ?
3443              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3444       else
3445         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3446     }
3447 
3448     // Get the value in the widest-possible width.
3449     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3450     llvm::APInt ResultVal(MaxWidth, 0);
3451 
3452     if (Literal.GetIntegerValue(ResultVal)) {
3453       // If this value didn't fit into uintmax_t, error and force to ull.
3454       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3455           << /* Unsigned */ 1;
3456       Ty = Context.UnsignedLongLongTy;
3457       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3458              "long long is not intmax_t?");
3459     } else {
3460       // If this value fits into a ULL, try to figure out what else it fits into
3461       // according to the rules of C99 6.4.4.1p5.
3462 
3463       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3464       // be an unsigned int.
3465       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3466 
3467       // Check from smallest to largest, picking the smallest type we can.
3468       unsigned Width = 0;
3469 
3470       // Microsoft specific integer suffixes are explicitly sized.
3471       if (Literal.MicrosoftInteger) {
3472         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3473           Width = 8;
3474           Ty = Context.CharTy;
3475         } else {
3476           Width = Literal.MicrosoftInteger;
3477           Ty = Context.getIntTypeForBitwidth(Width,
3478                                              /*Signed=*/!Literal.isUnsigned);
3479         }
3480       }
3481 
3482       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3483         // Are int/unsigned possibilities?
3484         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3485 
3486         // Does it fit in a unsigned int?
3487         if (ResultVal.isIntN(IntSize)) {
3488           // Does it fit in a signed int?
3489           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3490             Ty = Context.IntTy;
3491           else if (AllowUnsigned)
3492             Ty = Context.UnsignedIntTy;
3493           Width = IntSize;
3494         }
3495       }
3496 
3497       // Are long/unsigned long possibilities?
3498       if (Ty.isNull() && !Literal.isLongLong) {
3499         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3500 
3501         // Does it fit in a unsigned long?
3502         if (ResultVal.isIntN(LongSize)) {
3503           // Does it fit in a signed long?
3504           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3505             Ty = Context.LongTy;
3506           else if (AllowUnsigned)
3507             Ty = Context.UnsignedLongTy;
3508           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3509           // is compatible.
3510           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3511             const unsigned LongLongSize =
3512                 Context.getTargetInfo().getLongLongWidth();
3513             Diag(Tok.getLocation(),
3514                  getLangOpts().CPlusPlus
3515                      ? Literal.isLong
3516                            ? diag::warn_old_implicitly_unsigned_long_cxx
3517                            : /*C++98 UB*/ diag::
3518                                  ext_old_implicitly_unsigned_long_cxx
3519                      : diag::warn_old_implicitly_unsigned_long)
3520                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3521                                             : /*will be ill-formed*/ 1);
3522             Ty = Context.UnsignedLongTy;
3523           }
3524           Width = LongSize;
3525         }
3526       }
3527 
3528       // Check long long if needed.
3529       if (Ty.isNull()) {
3530         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3531 
3532         // Does it fit in a unsigned long long?
3533         if (ResultVal.isIntN(LongLongSize)) {
3534           // Does it fit in a signed long long?
3535           // To be compatible with MSVC, hex integer literals ending with the
3536           // LL or i64 suffix are always signed in Microsoft mode.
3537           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3538               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3539             Ty = Context.LongLongTy;
3540           else if (AllowUnsigned)
3541             Ty = Context.UnsignedLongLongTy;
3542           Width = LongLongSize;
3543         }
3544       }
3545 
3546       // If we still couldn't decide a type, we probably have something that
3547       // does not fit in a signed long long, but has no U suffix.
3548       if (Ty.isNull()) {
3549         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3550         Ty = Context.UnsignedLongLongTy;
3551         Width = Context.getTargetInfo().getLongLongWidth();
3552       }
3553 
3554       if (ResultVal.getBitWidth() != Width)
3555         ResultVal = ResultVal.trunc(Width);
3556     }
3557     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3558   }
3559 
3560   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3561   if (Literal.isImaginary)
3562     Res = new (Context) ImaginaryLiteral(Res,
3563                                         Context.getComplexType(Res->getType()));
3564 
3565   return Res;
3566 }
3567 
3568 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3569   assert(E && "ActOnParenExpr() missing expr");
3570   return new (Context) ParenExpr(L, R, E);
3571 }
3572 
3573 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3574                                          SourceLocation Loc,
3575                                          SourceRange ArgRange) {
3576   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3577   // scalar or vector data type argument..."
3578   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3579   // type (C99 6.2.5p18) or void.
3580   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3581     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3582       << T << ArgRange;
3583     return true;
3584   }
3585 
3586   assert((T->isVoidType() || !T->isIncompleteType()) &&
3587          "Scalar types should always be complete");
3588   return false;
3589 }
3590 
3591 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3592                                            SourceLocation Loc,
3593                                            SourceRange ArgRange,
3594                                            UnaryExprOrTypeTrait TraitKind) {
3595   // Invalid types must be hard errors for SFINAE in C++.
3596   if (S.LangOpts.CPlusPlus)
3597     return true;
3598 
3599   // C99 6.5.3.4p1:
3600   if (T->isFunctionType() &&
3601       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3602     // sizeof(function)/alignof(function) is allowed as an extension.
3603     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3604       << TraitKind << ArgRange;
3605     return false;
3606   }
3607 
3608   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3609   // this is an error (OpenCL v1.1 s6.3.k)
3610   if (T->isVoidType()) {
3611     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3612                                         : diag::ext_sizeof_alignof_void_type;
3613     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3614     return false;
3615   }
3616 
3617   return true;
3618 }
3619 
3620 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3621                                              SourceLocation Loc,
3622                                              SourceRange ArgRange,
3623                                              UnaryExprOrTypeTrait TraitKind) {
3624   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3625   // runtime doesn't allow it.
3626   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3627     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3628       << T << (TraitKind == UETT_SizeOf)
3629       << ArgRange;
3630     return true;
3631   }
3632 
3633   return false;
3634 }
3635 
3636 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3637 /// pointer type is equal to T) and emit a warning if it is.
3638 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3639                                      Expr *E) {
3640   // Don't warn if the operation changed the type.
3641   if (T != E->getType())
3642     return;
3643 
3644   // Now look for array decays.
3645   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3646   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3647     return;
3648 
3649   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3650                                              << ICE->getType()
3651                                              << ICE->getSubExpr()->getType();
3652 }
3653 
3654 /// \brief Check the constraints on expression operands to unary type expression
3655 /// and type traits.
3656 ///
3657 /// Completes any types necessary and validates the constraints on the operand
3658 /// expression. The logic mostly mirrors the type-based overload, but may modify
3659 /// the expression as it completes the type for that expression through template
3660 /// instantiation, etc.
3661 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3662                                             UnaryExprOrTypeTrait ExprKind) {
3663   QualType ExprTy = E->getType();
3664   assert(!ExprTy->isReferenceType());
3665 
3666   if (ExprKind == UETT_VecStep)
3667     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3668                                         E->getSourceRange());
3669 
3670   // Whitelist some types as extensions
3671   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3672                                       E->getSourceRange(), ExprKind))
3673     return false;
3674 
3675   // 'alignof' applied to an expression only requires the base element type of
3676   // the expression to be complete. 'sizeof' requires the expression's type to
3677   // be complete (and will attempt to complete it if it's an array of unknown
3678   // bound).
3679   if (ExprKind == UETT_AlignOf) {
3680     if (RequireCompleteType(E->getExprLoc(),
3681                             Context.getBaseElementType(E->getType()),
3682                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3683                             E->getSourceRange()))
3684       return true;
3685   } else {
3686     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3687                                 ExprKind, E->getSourceRange()))
3688       return true;
3689   }
3690 
3691   // Completing the expression's type may have changed it.
3692   ExprTy = E->getType();
3693   assert(!ExprTy->isReferenceType());
3694 
3695   if (ExprTy->isFunctionType()) {
3696     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3697       << ExprKind << E->getSourceRange();
3698     return true;
3699   }
3700 
3701   // The operand for sizeof and alignof is in an unevaluated expression context,
3702   // so side effects could result in unintended consequences.
3703   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3704       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3705     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3706 
3707   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3708                                        E->getSourceRange(), ExprKind))
3709     return true;
3710 
3711   if (ExprKind == UETT_SizeOf) {
3712     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3713       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3714         QualType OType = PVD->getOriginalType();
3715         QualType Type = PVD->getType();
3716         if (Type->isPointerType() && OType->isArrayType()) {
3717           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3718             << Type << OType;
3719           Diag(PVD->getLocation(), diag::note_declared_at);
3720         }
3721       }
3722     }
3723 
3724     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3725     // decays into a pointer and returns an unintended result. This is most
3726     // likely a typo for "sizeof(array) op x".
3727     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3728       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3729                                BO->getLHS());
3730       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3731                                BO->getRHS());
3732     }
3733   }
3734 
3735   return false;
3736 }
3737 
3738 /// \brief Check the constraints on operands to unary expression and type
3739 /// traits.
3740 ///
3741 /// This will complete any types necessary, and validate the various constraints
3742 /// on those operands.
3743 ///
3744 /// The UsualUnaryConversions() function is *not* called by this routine.
3745 /// C99 6.3.2.1p[2-4] all state:
3746 ///   Except when it is the operand of the sizeof operator ...
3747 ///
3748 /// C++ [expr.sizeof]p4
3749 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3750 ///   standard conversions are not applied to the operand of sizeof.
3751 ///
3752 /// This policy is followed for all of the unary trait expressions.
3753 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3754                                             SourceLocation OpLoc,
3755                                             SourceRange ExprRange,
3756                                             UnaryExprOrTypeTrait ExprKind) {
3757   if (ExprType->isDependentType())
3758     return false;
3759 
3760   // C++ [expr.sizeof]p2:
3761   //     When applied to a reference or a reference type, the result
3762   //     is the size of the referenced type.
3763   // C++11 [expr.alignof]p3:
3764   //     When alignof is applied to a reference type, the result
3765   //     shall be the alignment of the referenced type.
3766   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3767     ExprType = Ref->getPointeeType();
3768 
3769   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3770   //   When alignof or _Alignof is applied to an array type, the result
3771   //   is the alignment of the element type.
3772   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3773     ExprType = Context.getBaseElementType(ExprType);
3774 
3775   if (ExprKind == UETT_VecStep)
3776     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3777 
3778   // Whitelist some types as extensions
3779   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3780                                       ExprKind))
3781     return false;
3782 
3783   if (RequireCompleteType(OpLoc, ExprType,
3784                           diag::err_sizeof_alignof_incomplete_type,
3785                           ExprKind, ExprRange))
3786     return true;
3787 
3788   if (ExprType->isFunctionType()) {
3789     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3790       << ExprKind << ExprRange;
3791     return true;
3792   }
3793 
3794   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3795                                        ExprKind))
3796     return true;
3797 
3798   return false;
3799 }
3800 
3801 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3802   E = E->IgnoreParens();
3803 
3804   // Cannot know anything else if the expression is dependent.
3805   if (E->isTypeDependent())
3806     return false;
3807 
3808   if (E->getObjectKind() == OK_BitField) {
3809     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3810        << 1 << E->getSourceRange();
3811     return true;
3812   }
3813 
3814   ValueDecl *D = nullptr;
3815   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3816     D = DRE->getDecl();
3817   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3818     D = ME->getMemberDecl();
3819   }
3820 
3821   // If it's a field, require the containing struct to have a
3822   // complete definition so that we can compute the layout.
3823   //
3824   // This can happen in C++11 onwards, either by naming the member
3825   // in a way that is not transformed into a member access expression
3826   // (in an unevaluated operand, for instance), or by naming the member
3827   // in a trailing-return-type.
3828   //
3829   // For the record, since __alignof__ on expressions is a GCC
3830   // extension, GCC seems to permit this but always gives the
3831   // nonsensical answer 0.
3832   //
3833   // We don't really need the layout here --- we could instead just
3834   // directly check for all the appropriate alignment-lowing
3835   // attributes --- but that would require duplicating a lot of
3836   // logic that just isn't worth duplicating for such a marginal
3837   // use-case.
3838   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3839     // Fast path this check, since we at least know the record has a
3840     // definition if we can find a member of it.
3841     if (!FD->getParent()->isCompleteDefinition()) {
3842       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3843         << E->getSourceRange();
3844       return true;
3845     }
3846 
3847     // Otherwise, if it's a field, and the field doesn't have
3848     // reference type, then it must have a complete type (or be a
3849     // flexible array member, which we explicitly want to
3850     // white-list anyway), which makes the following checks trivial.
3851     if (!FD->getType()->isReferenceType())
3852       return false;
3853   }
3854 
3855   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3856 }
3857 
3858 bool Sema::CheckVecStepExpr(Expr *E) {
3859   E = E->IgnoreParens();
3860 
3861   // Cannot know anything else if the expression is dependent.
3862   if (E->isTypeDependent())
3863     return false;
3864 
3865   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3866 }
3867 
3868 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3869                                         CapturingScopeInfo *CSI) {
3870   assert(T->isVariablyModifiedType());
3871   assert(CSI != nullptr);
3872 
3873   // We're going to walk down into the type and look for VLA expressions.
3874   do {
3875     const Type *Ty = T.getTypePtr();
3876     switch (Ty->getTypeClass()) {
3877 #define TYPE(Class, Base)
3878 #define ABSTRACT_TYPE(Class, Base)
3879 #define NON_CANONICAL_TYPE(Class, Base)
3880 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3881 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3882 #include "clang/AST/TypeNodes.def"
3883       T = QualType();
3884       break;
3885     // These types are never variably-modified.
3886     case Type::Builtin:
3887     case Type::Complex:
3888     case Type::Vector:
3889     case Type::ExtVector:
3890     case Type::Record:
3891     case Type::Enum:
3892     case Type::Elaborated:
3893     case Type::TemplateSpecialization:
3894     case Type::ObjCObject:
3895     case Type::ObjCInterface:
3896     case Type::ObjCObjectPointer:
3897     case Type::ObjCTypeParam:
3898     case Type::Pipe:
3899       llvm_unreachable("type class is never variably-modified!");
3900     case Type::Adjusted:
3901       T = cast<AdjustedType>(Ty)->getOriginalType();
3902       break;
3903     case Type::Decayed:
3904       T = cast<DecayedType>(Ty)->getPointeeType();
3905       break;
3906     case Type::Pointer:
3907       T = cast<PointerType>(Ty)->getPointeeType();
3908       break;
3909     case Type::BlockPointer:
3910       T = cast<BlockPointerType>(Ty)->getPointeeType();
3911       break;
3912     case Type::LValueReference:
3913     case Type::RValueReference:
3914       T = cast<ReferenceType>(Ty)->getPointeeType();
3915       break;
3916     case Type::MemberPointer:
3917       T = cast<MemberPointerType>(Ty)->getPointeeType();
3918       break;
3919     case Type::ConstantArray:
3920     case Type::IncompleteArray:
3921       // Losing element qualification here is fine.
3922       T = cast<ArrayType>(Ty)->getElementType();
3923       break;
3924     case Type::VariableArray: {
3925       // Losing element qualification here is fine.
3926       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3927 
3928       // Unknown size indication requires no size computation.
3929       // Otherwise, evaluate and record it.
3930       if (auto Size = VAT->getSizeExpr()) {
3931         if (!CSI->isVLATypeCaptured(VAT)) {
3932           RecordDecl *CapRecord = nullptr;
3933           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3934             CapRecord = LSI->Lambda;
3935           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3936             CapRecord = CRSI->TheRecordDecl;
3937           }
3938           if (CapRecord) {
3939             auto ExprLoc = Size->getExprLoc();
3940             auto SizeType = Context.getSizeType();
3941             // Build the non-static data member.
3942             auto Field =
3943                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3944                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3945                                   /*BW*/ nullptr, /*Mutable*/ false,
3946                                   /*InitStyle*/ ICIS_NoInit);
3947             Field->setImplicit(true);
3948             Field->setAccess(AS_private);
3949             Field->setCapturedVLAType(VAT);
3950             CapRecord->addDecl(Field);
3951 
3952             CSI->addVLATypeCapture(ExprLoc, SizeType);
3953           }
3954         }
3955       }
3956       T = VAT->getElementType();
3957       break;
3958     }
3959     case Type::FunctionProto:
3960     case Type::FunctionNoProto:
3961       T = cast<FunctionType>(Ty)->getReturnType();
3962       break;
3963     case Type::Paren:
3964     case Type::TypeOf:
3965     case Type::UnaryTransform:
3966     case Type::Attributed:
3967     case Type::SubstTemplateTypeParm:
3968     case Type::PackExpansion:
3969       // Keep walking after single level desugaring.
3970       T = T.getSingleStepDesugaredType(Context);
3971       break;
3972     case Type::Typedef:
3973       T = cast<TypedefType>(Ty)->desugar();
3974       break;
3975     case Type::Decltype:
3976       T = cast<DecltypeType>(Ty)->desugar();
3977       break;
3978     case Type::Auto:
3979       T = cast<AutoType>(Ty)->getDeducedType();
3980       break;
3981     case Type::TypeOfExpr:
3982       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3983       break;
3984     case Type::Atomic:
3985       T = cast<AtomicType>(Ty)->getValueType();
3986       break;
3987     }
3988   } while (!T.isNull() && T->isVariablyModifiedType());
3989 }
3990 
3991 /// \brief Build a sizeof or alignof expression given a type operand.
3992 ExprResult
3993 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3994                                      SourceLocation OpLoc,
3995                                      UnaryExprOrTypeTrait ExprKind,
3996                                      SourceRange R) {
3997   if (!TInfo)
3998     return ExprError();
3999 
4000   QualType T = TInfo->getType();
4001 
4002   if (!T->isDependentType() &&
4003       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4004     return ExprError();
4005 
4006   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4007     if (auto *TT = T->getAs<TypedefType>()) {
4008       for (auto I = FunctionScopes.rbegin(),
4009                 E = std::prev(FunctionScopes.rend());
4010            I != E; ++I) {
4011         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4012         if (CSI == nullptr)
4013           break;
4014         DeclContext *DC = nullptr;
4015         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4016           DC = LSI->CallOperator;
4017         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4018           DC = CRSI->TheCapturedDecl;
4019         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4020           DC = BSI->TheDecl;
4021         if (DC) {
4022           if (DC->containsDecl(TT->getDecl()))
4023             break;
4024           captureVariablyModifiedType(Context, T, CSI);
4025         }
4026       }
4027     }
4028   }
4029 
4030   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4031   return new (Context) UnaryExprOrTypeTraitExpr(
4032       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4033 }
4034 
4035 /// \brief Build a sizeof or alignof expression given an expression
4036 /// operand.
4037 ExprResult
4038 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4039                                      UnaryExprOrTypeTrait ExprKind) {
4040   ExprResult PE = CheckPlaceholderExpr(E);
4041   if (PE.isInvalid())
4042     return ExprError();
4043 
4044   E = PE.get();
4045 
4046   // Verify that the operand is valid.
4047   bool isInvalid = false;
4048   if (E->isTypeDependent()) {
4049     // Delay type-checking for type-dependent expressions.
4050   } else if (ExprKind == UETT_AlignOf) {
4051     isInvalid = CheckAlignOfExpr(*this, E);
4052   } else if (ExprKind == UETT_VecStep) {
4053     isInvalid = CheckVecStepExpr(E);
4054   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4055       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4056       isInvalid = true;
4057   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4058     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4059     isInvalid = true;
4060   } else {
4061     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4062   }
4063 
4064   if (isInvalid)
4065     return ExprError();
4066 
4067   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4068     PE = TransformToPotentiallyEvaluated(E);
4069     if (PE.isInvalid()) return ExprError();
4070     E = PE.get();
4071   }
4072 
4073   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4074   return new (Context) UnaryExprOrTypeTraitExpr(
4075       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4076 }
4077 
4078 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4079 /// expr and the same for @c alignof and @c __alignof
4080 /// Note that the ArgRange is invalid if isType is false.
4081 ExprResult
4082 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4083                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4084                                     void *TyOrEx, SourceRange ArgRange) {
4085   // If error parsing type, ignore.
4086   if (!TyOrEx) return ExprError();
4087 
4088   if (IsType) {
4089     TypeSourceInfo *TInfo;
4090     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4091     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4092   }
4093 
4094   Expr *ArgEx = (Expr *)TyOrEx;
4095   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4096   return Result;
4097 }
4098 
4099 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4100                                      bool IsReal) {
4101   if (V.get()->isTypeDependent())
4102     return S.Context.DependentTy;
4103 
4104   // _Real and _Imag are only l-values for normal l-values.
4105   if (V.get()->getObjectKind() != OK_Ordinary) {
4106     V = S.DefaultLvalueConversion(V.get());
4107     if (V.isInvalid())
4108       return QualType();
4109   }
4110 
4111   // These operators return the element type of a complex type.
4112   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4113     return CT->getElementType();
4114 
4115   // Otherwise they pass through real integer and floating point types here.
4116   if (V.get()->getType()->isArithmeticType())
4117     return V.get()->getType();
4118 
4119   // Test for placeholders.
4120   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4121   if (PR.isInvalid()) return QualType();
4122   if (PR.get() != V.get()) {
4123     V = PR;
4124     return CheckRealImagOperand(S, V, Loc, IsReal);
4125   }
4126 
4127   // Reject anything else.
4128   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4129     << (IsReal ? "__real" : "__imag");
4130   return QualType();
4131 }
4132 
4133 
4134 
4135 ExprResult
4136 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4137                           tok::TokenKind Kind, Expr *Input) {
4138   UnaryOperatorKind Opc;
4139   switch (Kind) {
4140   default: llvm_unreachable("Unknown unary op!");
4141   case tok::plusplus:   Opc = UO_PostInc; break;
4142   case tok::minusminus: Opc = UO_PostDec; break;
4143   }
4144 
4145   // Since this might is a postfix expression, get rid of ParenListExprs.
4146   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4147   if (Result.isInvalid()) return ExprError();
4148   Input = Result.get();
4149 
4150   return BuildUnaryOp(S, OpLoc, Opc, Input);
4151 }
4152 
4153 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4154 ///
4155 /// \return true on error
4156 static bool checkArithmeticOnObjCPointer(Sema &S,
4157                                          SourceLocation opLoc,
4158                                          Expr *op) {
4159   assert(op->getType()->isObjCObjectPointerType());
4160   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4161       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4162     return false;
4163 
4164   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4165     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4166     << op->getSourceRange();
4167   return true;
4168 }
4169 
4170 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4171   auto *BaseNoParens = Base->IgnoreParens();
4172   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4173     return MSProp->getPropertyDecl()->getType()->isArrayType();
4174   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4175 }
4176 
4177 ExprResult
4178 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4179                               Expr *idx, SourceLocation rbLoc) {
4180   if (base && !base->getType().isNull() &&
4181       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4182     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4183                                     /*Length=*/nullptr, rbLoc);
4184 
4185   // Since this might be a postfix expression, get rid of ParenListExprs.
4186   if (isa<ParenListExpr>(base)) {
4187     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4188     if (result.isInvalid()) return ExprError();
4189     base = result.get();
4190   }
4191 
4192   // Handle any non-overload placeholder types in the base and index
4193   // expressions.  We can't handle overloads here because the other
4194   // operand might be an overloadable type, in which case the overload
4195   // resolution for the operator overload should get the first crack
4196   // at the overload.
4197   bool IsMSPropertySubscript = false;
4198   if (base->getType()->isNonOverloadPlaceholderType()) {
4199     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4200     if (!IsMSPropertySubscript) {
4201       ExprResult result = CheckPlaceholderExpr(base);
4202       if (result.isInvalid())
4203         return ExprError();
4204       base = result.get();
4205     }
4206   }
4207   if (idx->getType()->isNonOverloadPlaceholderType()) {
4208     ExprResult result = CheckPlaceholderExpr(idx);
4209     if (result.isInvalid()) return ExprError();
4210     idx = result.get();
4211   }
4212 
4213   // Build an unanalyzed expression if either operand is type-dependent.
4214   if (getLangOpts().CPlusPlus &&
4215       (base->isTypeDependent() || idx->isTypeDependent())) {
4216     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4217                                             VK_LValue, OK_Ordinary, rbLoc);
4218   }
4219 
4220   // MSDN, property (C++)
4221   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4222   // This attribute can also be used in the declaration of an empty array in a
4223   // class or structure definition. For example:
4224   // __declspec(property(get=GetX, put=PutX)) int x[];
4225   // The above statement indicates that x[] can be used with one or more array
4226   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4227   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4228   if (IsMSPropertySubscript) {
4229     // Build MS property subscript expression if base is MS property reference
4230     // or MS property subscript.
4231     return new (Context) MSPropertySubscriptExpr(
4232         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4233   }
4234 
4235   // Use C++ overloaded-operator rules if either operand has record
4236   // type.  The spec says to do this if either type is *overloadable*,
4237   // but enum types can't declare subscript operators or conversion
4238   // operators, so there's nothing interesting for overload resolution
4239   // to do if there aren't any record types involved.
4240   //
4241   // ObjC pointers have their own subscripting logic that is not tied
4242   // to overload resolution and so should not take this path.
4243   if (getLangOpts().CPlusPlus &&
4244       (base->getType()->isRecordType() ||
4245        (!base->getType()->isObjCObjectPointerType() &&
4246         idx->getType()->isRecordType()))) {
4247     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4248   }
4249 
4250   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4251 }
4252 
4253 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4254                                           Expr *LowerBound,
4255                                           SourceLocation ColonLoc, Expr *Length,
4256                                           SourceLocation RBLoc) {
4257   if (Base->getType()->isPlaceholderType() &&
4258       !Base->getType()->isSpecificPlaceholderType(
4259           BuiltinType::OMPArraySection)) {
4260     ExprResult Result = CheckPlaceholderExpr(Base);
4261     if (Result.isInvalid())
4262       return ExprError();
4263     Base = Result.get();
4264   }
4265   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4266     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4267     if (Result.isInvalid())
4268       return ExprError();
4269     Result = DefaultLvalueConversion(Result.get());
4270     if (Result.isInvalid())
4271       return ExprError();
4272     LowerBound = Result.get();
4273   }
4274   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4275     ExprResult Result = CheckPlaceholderExpr(Length);
4276     if (Result.isInvalid())
4277       return ExprError();
4278     Result = DefaultLvalueConversion(Result.get());
4279     if (Result.isInvalid())
4280       return ExprError();
4281     Length = Result.get();
4282   }
4283 
4284   // Build an unanalyzed expression if either operand is type-dependent.
4285   if (Base->isTypeDependent() ||
4286       (LowerBound &&
4287        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4288       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4289     return new (Context)
4290         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4291                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4292   }
4293 
4294   // Perform default conversions.
4295   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4296   QualType ResultTy;
4297   if (OriginalTy->isAnyPointerType()) {
4298     ResultTy = OriginalTy->getPointeeType();
4299   } else if (OriginalTy->isArrayType()) {
4300     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4301   } else {
4302     return ExprError(
4303         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4304         << Base->getSourceRange());
4305   }
4306   // C99 6.5.2.1p1
4307   if (LowerBound) {
4308     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4309                                                       LowerBound);
4310     if (Res.isInvalid())
4311       return ExprError(Diag(LowerBound->getExprLoc(),
4312                             diag::err_omp_typecheck_section_not_integer)
4313                        << 0 << LowerBound->getSourceRange());
4314     LowerBound = Res.get();
4315 
4316     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4317         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4318       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4319           << 0 << LowerBound->getSourceRange();
4320   }
4321   if (Length) {
4322     auto Res =
4323         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4324     if (Res.isInvalid())
4325       return ExprError(Diag(Length->getExprLoc(),
4326                             diag::err_omp_typecheck_section_not_integer)
4327                        << 1 << Length->getSourceRange());
4328     Length = Res.get();
4329 
4330     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4331         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4332       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4333           << 1 << Length->getSourceRange();
4334   }
4335 
4336   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4337   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4338   // type. Note that functions are not objects, and that (in C99 parlance)
4339   // incomplete types are not object types.
4340   if (ResultTy->isFunctionType()) {
4341     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4342         << ResultTy << Base->getSourceRange();
4343     return ExprError();
4344   }
4345 
4346   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4347                           diag::err_omp_section_incomplete_type, Base))
4348     return ExprError();
4349 
4350   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4351     llvm::APSInt LowerBoundValue;
4352     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4353       // OpenMP 4.5, [2.4 Array Sections]
4354       // The array section must be a subset of the original array.
4355       if (LowerBoundValue.isNegative()) {
4356         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4357             << LowerBound->getSourceRange();
4358         return ExprError();
4359       }
4360     }
4361   }
4362 
4363   if (Length) {
4364     llvm::APSInt LengthValue;
4365     if (Length->EvaluateAsInt(LengthValue, Context)) {
4366       // OpenMP 4.5, [2.4 Array Sections]
4367       // The length must evaluate to non-negative integers.
4368       if (LengthValue.isNegative()) {
4369         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4370             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4371             << Length->getSourceRange();
4372         return ExprError();
4373       }
4374     }
4375   } else if (ColonLoc.isValid() &&
4376              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4377                                       !OriginalTy->isVariableArrayType()))) {
4378     // OpenMP 4.5, [2.4 Array Sections]
4379     // When the size of the array dimension is not known, the length must be
4380     // specified explicitly.
4381     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4382         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4383     return ExprError();
4384   }
4385 
4386   if (!Base->getType()->isSpecificPlaceholderType(
4387           BuiltinType::OMPArraySection)) {
4388     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4389     if (Result.isInvalid())
4390       return ExprError();
4391     Base = Result.get();
4392   }
4393   return new (Context)
4394       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4395                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4396 }
4397 
4398 ExprResult
4399 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4400                                       Expr *Idx, SourceLocation RLoc) {
4401   Expr *LHSExp = Base;
4402   Expr *RHSExp = Idx;
4403 
4404   ExprValueKind VK = VK_LValue;
4405   ExprObjectKind OK = OK_Ordinary;
4406 
4407   // Per C++ core issue 1213, the result is an xvalue if either operand is
4408   // a non-lvalue array, and an lvalue otherwise.
4409   if (getLangOpts().CPlusPlus11 &&
4410       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4411        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4412     VK = VK_XValue;
4413 
4414   // Perform default conversions.
4415   if (!LHSExp->getType()->getAs<VectorType>()) {
4416     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4417     if (Result.isInvalid())
4418       return ExprError();
4419     LHSExp = Result.get();
4420   }
4421   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4422   if (Result.isInvalid())
4423     return ExprError();
4424   RHSExp = Result.get();
4425 
4426   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4427 
4428   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4429   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4430   // in the subscript position. As a result, we need to derive the array base
4431   // and index from the expression types.
4432   Expr *BaseExpr, *IndexExpr;
4433   QualType ResultType;
4434   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4435     BaseExpr = LHSExp;
4436     IndexExpr = RHSExp;
4437     ResultType = Context.DependentTy;
4438   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4439     BaseExpr = LHSExp;
4440     IndexExpr = RHSExp;
4441     ResultType = PTy->getPointeeType();
4442   } else if (const ObjCObjectPointerType *PTy =
4443                LHSTy->getAs<ObjCObjectPointerType>()) {
4444     BaseExpr = LHSExp;
4445     IndexExpr = RHSExp;
4446 
4447     // Use custom logic if this should be the pseudo-object subscript
4448     // expression.
4449     if (!LangOpts.isSubscriptPointerArithmetic())
4450       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4451                                           nullptr);
4452 
4453     ResultType = PTy->getPointeeType();
4454   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4455      // Handle the uncommon case of "123[Ptr]".
4456     BaseExpr = RHSExp;
4457     IndexExpr = LHSExp;
4458     ResultType = PTy->getPointeeType();
4459   } else if (const ObjCObjectPointerType *PTy =
4460                RHSTy->getAs<ObjCObjectPointerType>()) {
4461      // Handle the uncommon case of "123[Ptr]".
4462     BaseExpr = RHSExp;
4463     IndexExpr = LHSExp;
4464     ResultType = PTy->getPointeeType();
4465     if (!LangOpts.isSubscriptPointerArithmetic()) {
4466       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4467         << ResultType << BaseExpr->getSourceRange();
4468       return ExprError();
4469     }
4470   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4471     BaseExpr = LHSExp;    // vectors: V[123]
4472     IndexExpr = RHSExp;
4473     VK = LHSExp->getValueKind();
4474     if (VK != VK_RValue)
4475       OK = OK_VectorComponent;
4476 
4477     // FIXME: need to deal with const...
4478     ResultType = VTy->getElementType();
4479   } else if (LHSTy->isArrayType()) {
4480     // If we see an array that wasn't promoted by
4481     // DefaultFunctionArrayLvalueConversion, it must be an array that
4482     // wasn't promoted because of the C90 rule that doesn't
4483     // allow promoting non-lvalue arrays.  Warn, then
4484     // force the promotion here.
4485     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4486         LHSExp->getSourceRange();
4487     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4488                                CK_ArrayToPointerDecay).get();
4489     LHSTy = LHSExp->getType();
4490 
4491     BaseExpr = LHSExp;
4492     IndexExpr = RHSExp;
4493     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4494   } else if (RHSTy->isArrayType()) {
4495     // Same as previous, except for 123[f().a] case
4496     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4497         RHSExp->getSourceRange();
4498     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4499                                CK_ArrayToPointerDecay).get();
4500     RHSTy = RHSExp->getType();
4501 
4502     BaseExpr = RHSExp;
4503     IndexExpr = LHSExp;
4504     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4505   } else {
4506     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4507        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4508   }
4509   // C99 6.5.2.1p1
4510   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4511     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4512                      << IndexExpr->getSourceRange());
4513 
4514   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4515        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4516          && !IndexExpr->isTypeDependent())
4517     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4518 
4519   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4520   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4521   // type. Note that Functions are not objects, and that (in C99 parlance)
4522   // incomplete types are not object types.
4523   if (ResultType->isFunctionType()) {
4524     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4525       << ResultType << BaseExpr->getSourceRange();
4526     return ExprError();
4527   }
4528 
4529   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4530     // GNU extension: subscripting on pointer to void
4531     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4532       << BaseExpr->getSourceRange();
4533 
4534     // C forbids expressions of unqualified void type from being l-values.
4535     // See IsCForbiddenLValueType.
4536     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4537   } else if (!ResultType->isDependentType() &&
4538       RequireCompleteType(LLoc, ResultType,
4539                           diag::err_subscript_incomplete_type, BaseExpr))
4540     return ExprError();
4541 
4542   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4543          !ResultType.isCForbiddenLValueType());
4544 
4545   return new (Context)
4546       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4547 }
4548 
4549 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4550                                   ParmVarDecl *Param) {
4551   if (Param->hasUnparsedDefaultArg()) {
4552     Diag(CallLoc,
4553          diag::err_use_of_default_argument_to_function_declared_later) <<
4554       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4555     Diag(UnparsedDefaultArgLocs[Param],
4556          diag::note_default_argument_declared_here);
4557     return true;
4558   }
4559 
4560   if (Param->hasUninstantiatedDefaultArg()) {
4561     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4562 
4563     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4564                                                  Param);
4565 
4566     // Instantiate the expression.
4567     MultiLevelTemplateArgumentList MutiLevelArgList
4568       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4569 
4570     InstantiatingTemplate Inst(*this, CallLoc, Param,
4571                                MutiLevelArgList.getInnermost());
4572     if (Inst.isInvalid())
4573       return true;
4574     if (Inst.isAlreadyInstantiating()) {
4575       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4576       Param->setInvalidDecl();
4577       return true;
4578     }
4579 
4580     ExprResult Result;
4581     {
4582       // C++ [dcl.fct.default]p5:
4583       //   The names in the [default argument] expression are bound, and
4584       //   the semantic constraints are checked, at the point where the
4585       //   default argument expression appears.
4586       ContextRAII SavedContext(*this, FD);
4587       LocalInstantiationScope Local(*this);
4588       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4589                                 /*DirectInit*/false);
4590     }
4591     if (Result.isInvalid())
4592       return true;
4593 
4594     // Check the expression as an initializer for the parameter.
4595     InitializedEntity Entity
4596       = InitializedEntity::InitializeParameter(Context, Param);
4597     InitializationKind Kind
4598       = InitializationKind::CreateCopy(Param->getLocation(),
4599              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4600     Expr *ResultE = Result.getAs<Expr>();
4601 
4602     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4603     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4604     if (Result.isInvalid())
4605       return true;
4606 
4607     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4608                                  Param->getOuterLocStart());
4609     if (Result.isInvalid())
4610       return true;
4611 
4612     // Remember the instantiated default argument.
4613     Param->setDefaultArg(Result.getAs<Expr>());
4614     if (ASTMutationListener *L = getASTMutationListener()) {
4615       L->DefaultArgumentInstantiated(Param);
4616     }
4617   }
4618 
4619   // If the default argument expression is not set yet, we are building it now.
4620   if (!Param->hasInit()) {
4621     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4622     Param->setInvalidDecl();
4623     return true;
4624   }
4625 
4626   // If the default expression creates temporaries, we need to
4627   // push them to the current stack of expression temporaries so they'll
4628   // be properly destroyed.
4629   // FIXME: We should really be rebuilding the default argument with new
4630   // bound temporaries; see the comment in PR5810.
4631   // We don't need to do that with block decls, though, because
4632   // blocks in default argument expression can never capture anything.
4633   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4634     // Set the "needs cleanups" bit regardless of whether there are
4635     // any explicit objects.
4636     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4637 
4638     // Append all the objects to the cleanup list.  Right now, this
4639     // should always be a no-op, because blocks in default argument
4640     // expressions should never be able to capture anything.
4641     assert(!Init->getNumObjects() &&
4642            "default argument expression has capturing blocks?");
4643   }
4644 
4645   // We already type-checked the argument, so we know it works.
4646   // Just mark all of the declarations in this potentially-evaluated expression
4647   // as being "referenced".
4648   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4649                                    /*SkipLocalVariables=*/true);
4650   return false;
4651 }
4652 
4653 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4654                                         FunctionDecl *FD, ParmVarDecl *Param) {
4655   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4656     return ExprError();
4657   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4658 }
4659 
4660 Sema::VariadicCallType
4661 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4662                           Expr *Fn) {
4663   if (Proto && Proto->isVariadic()) {
4664     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4665       return VariadicConstructor;
4666     else if (Fn && Fn->getType()->isBlockPointerType())
4667       return VariadicBlock;
4668     else if (FDecl) {
4669       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4670         if (Method->isInstance())
4671           return VariadicMethod;
4672     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4673       return VariadicMethod;
4674     return VariadicFunction;
4675   }
4676   return VariadicDoesNotApply;
4677 }
4678 
4679 namespace {
4680 class FunctionCallCCC : public FunctionCallFilterCCC {
4681 public:
4682   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4683                   unsigned NumArgs, MemberExpr *ME)
4684       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4685         FunctionName(FuncName) {}
4686 
4687   bool ValidateCandidate(const TypoCorrection &candidate) override {
4688     if (!candidate.getCorrectionSpecifier() ||
4689         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4690       return false;
4691     }
4692 
4693     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4694   }
4695 
4696 private:
4697   const IdentifierInfo *const FunctionName;
4698 };
4699 }
4700 
4701 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4702                                                FunctionDecl *FDecl,
4703                                                ArrayRef<Expr *> Args) {
4704   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4705   DeclarationName FuncName = FDecl->getDeclName();
4706   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4707 
4708   if (TypoCorrection Corrected = S.CorrectTypo(
4709           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4710           S.getScopeForContext(S.CurContext), nullptr,
4711           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4712                                              Args.size(), ME),
4713           Sema::CTK_ErrorRecovery)) {
4714     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4715       if (Corrected.isOverloaded()) {
4716         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4717         OverloadCandidateSet::iterator Best;
4718         for (NamedDecl *CD : Corrected) {
4719           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4720             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4721                                    OCS);
4722         }
4723         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4724         case OR_Success:
4725           ND = Best->FoundDecl;
4726           Corrected.setCorrectionDecl(ND);
4727           break;
4728         default:
4729           break;
4730         }
4731       }
4732       ND = ND->getUnderlyingDecl();
4733       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4734         return Corrected;
4735     }
4736   }
4737   return TypoCorrection();
4738 }
4739 
4740 /// ConvertArgumentsForCall - Converts the arguments specified in
4741 /// Args/NumArgs to the parameter types of the function FDecl with
4742 /// function prototype Proto. Call is the call expression itself, and
4743 /// Fn is the function expression. For a C++ member function, this
4744 /// routine does not attempt to convert the object argument. Returns
4745 /// true if the call is ill-formed.
4746 bool
4747 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4748                               FunctionDecl *FDecl,
4749                               const FunctionProtoType *Proto,
4750                               ArrayRef<Expr *> Args,
4751                               SourceLocation RParenLoc,
4752                               bool IsExecConfig) {
4753   // Bail out early if calling a builtin with custom typechecking.
4754   if (FDecl)
4755     if (unsigned ID = FDecl->getBuiltinID())
4756       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4757         return false;
4758 
4759   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4760   // assignment, to the types of the corresponding parameter, ...
4761   unsigned NumParams = Proto->getNumParams();
4762   bool Invalid = false;
4763   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4764   unsigned FnKind = Fn->getType()->isBlockPointerType()
4765                        ? 1 /* block */
4766                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4767                                        : 0 /* function */);
4768 
4769   // If too few arguments are available (and we don't have default
4770   // arguments for the remaining parameters), don't make the call.
4771   if (Args.size() < NumParams) {
4772     if (Args.size() < MinArgs) {
4773       TypoCorrection TC;
4774       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4775         unsigned diag_id =
4776             MinArgs == NumParams && !Proto->isVariadic()
4777                 ? diag::err_typecheck_call_too_few_args_suggest
4778                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4779         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4780                                         << static_cast<unsigned>(Args.size())
4781                                         << TC.getCorrectionRange());
4782       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4783         Diag(RParenLoc,
4784              MinArgs == NumParams && !Proto->isVariadic()
4785                  ? diag::err_typecheck_call_too_few_args_one
4786                  : diag::err_typecheck_call_too_few_args_at_least_one)
4787             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4788       else
4789         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4790                             ? diag::err_typecheck_call_too_few_args
4791                             : diag::err_typecheck_call_too_few_args_at_least)
4792             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4793             << Fn->getSourceRange();
4794 
4795       // Emit the location of the prototype.
4796       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4797         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4798           << FDecl;
4799 
4800       return true;
4801     }
4802     Call->setNumArgs(Context, NumParams);
4803   }
4804 
4805   // If too many are passed and not variadic, error on the extras and drop
4806   // them.
4807   if (Args.size() > NumParams) {
4808     if (!Proto->isVariadic()) {
4809       TypoCorrection TC;
4810       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4811         unsigned diag_id =
4812             MinArgs == NumParams && !Proto->isVariadic()
4813                 ? diag::err_typecheck_call_too_many_args_suggest
4814                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4815         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4816                                         << static_cast<unsigned>(Args.size())
4817                                         << TC.getCorrectionRange());
4818       } else if (NumParams == 1 && FDecl &&
4819                  FDecl->getParamDecl(0)->getDeclName())
4820         Diag(Args[NumParams]->getLocStart(),
4821              MinArgs == NumParams
4822                  ? diag::err_typecheck_call_too_many_args_one
4823                  : diag::err_typecheck_call_too_many_args_at_most_one)
4824             << FnKind << FDecl->getParamDecl(0)
4825             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4826             << SourceRange(Args[NumParams]->getLocStart(),
4827                            Args.back()->getLocEnd());
4828       else
4829         Diag(Args[NumParams]->getLocStart(),
4830              MinArgs == NumParams
4831                  ? diag::err_typecheck_call_too_many_args
4832                  : diag::err_typecheck_call_too_many_args_at_most)
4833             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4834             << Fn->getSourceRange()
4835             << SourceRange(Args[NumParams]->getLocStart(),
4836                            Args.back()->getLocEnd());
4837 
4838       // Emit the location of the prototype.
4839       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4840         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4841           << FDecl;
4842 
4843       // This deletes the extra arguments.
4844       Call->setNumArgs(Context, NumParams);
4845       return true;
4846     }
4847   }
4848   SmallVector<Expr *, 8> AllArgs;
4849   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4850 
4851   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4852                                    Proto, 0, Args, AllArgs, CallType);
4853   if (Invalid)
4854     return true;
4855   unsigned TotalNumArgs = AllArgs.size();
4856   for (unsigned i = 0; i < TotalNumArgs; ++i)
4857     Call->setArg(i, AllArgs[i]);
4858 
4859   return false;
4860 }
4861 
4862 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4863                                   const FunctionProtoType *Proto,
4864                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4865                                   SmallVectorImpl<Expr *> &AllArgs,
4866                                   VariadicCallType CallType, bool AllowExplicit,
4867                                   bool IsListInitialization) {
4868   unsigned NumParams = Proto->getNumParams();
4869   bool Invalid = false;
4870   size_t ArgIx = 0;
4871   // Continue to check argument types (even if we have too few/many args).
4872   for (unsigned i = FirstParam; i < NumParams; i++) {
4873     QualType ProtoArgType = Proto->getParamType(i);
4874 
4875     Expr *Arg;
4876     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4877     if (ArgIx < Args.size()) {
4878       Arg = Args[ArgIx++];
4879 
4880       if (RequireCompleteType(Arg->getLocStart(),
4881                               ProtoArgType,
4882                               diag::err_call_incomplete_argument, Arg))
4883         return true;
4884 
4885       // Strip the unbridged-cast placeholder expression off, if applicable.
4886       bool CFAudited = false;
4887       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4888           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4889           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4890         Arg = stripARCUnbridgedCast(Arg);
4891       else if (getLangOpts().ObjCAutoRefCount &&
4892                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4893                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4894         CFAudited = true;
4895 
4896       InitializedEntity Entity =
4897           Param ? InitializedEntity::InitializeParameter(Context, Param,
4898                                                          ProtoArgType)
4899                 : InitializedEntity::InitializeParameter(
4900                       Context, ProtoArgType, Proto->isParamConsumed(i));
4901 
4902       // Remember that parameter belongs to a CF audited API.
4903       if (CFAudited)
4904         Entity.setParameterCFAudited();
4905 
4906       ExprResult ArgE = PerformCopyInitialization(
4907           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4908       if (ArgE.isInvalid())
4909         return true;
4910 
4911       Arg = ArgE.getAs<Expr>();
4912     } else {
4913       assert(Param && "can't use default arguments without a known callee");
4914 
4915       ExprResult ArgExpr =
4916         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4917       if (ArgExpr.isInvalid())
4918         return true;
4919 
4920       Arg = ArgExpr.getAs<Expr>();
4921     }
4922 
4923     // Check for array bounds violations for each argument to the call. This
4924     // check only triggers warnings when the argument isn't a more complex Expr
4925     // with its own checking, such as a BinaryOperator.
4926     CheckArrayAccess(Arg);
4927 
4928     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4929     CheckStaticArrayArgument(CallLoc, Param, Arg);
4930 
4931     AllArgs.push_back(Arg);
4932   }
4933 
4934   // If this is a variadic call, handle args passed through "...".
4935   if (CallType != VariadicDoesNotApply) {
4936     // Assume that extern "C" functions with variadic arguments that
4937     // return __unknown_anytype aren't *really* variadic.
4938     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4939         FDecl->isExternC()) {
4940       for (Expr *A : Args.slice(ArgIx)) {
4941         QualType paramType; // ignored
4942         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4943         Invalid |= arg.isInvalid();
4944         AllArgs.push_back(arg.get());
4945       }
4946 
4947     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4948     } else {
4949       for (Expr *A : Args.slice(ArgIx)) {
4950         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4951         Invalid |= Arg.isInvalid();
4952         AllArgs.push_back(Arg.get());
4953       }
4954     }
4955 
4956     // Check for array bounds violations.
4957     for (Expr *A : Args.slice(ArgIx))
4958       CheckArrayAccess(A);
4959   }
4960   return Invalid;
4961 }
4962 
4963 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4964   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4965   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4966     TL = DTL.getOriginalLoc();
4967   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4968     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4969       << ATL.getLocalSourceRange();
4970 }
4971 
4972 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4973 /// array parameter, check that it is non-null, and that if it is formed by
4974 /// array-to-pointer decay, the underlying array is sufficiently large.
4975 ///
4976 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4977 /// array type derivation, then for each call to the function, the value of the
4978 /// corresponding actual argument shall provide access to the first element of
4979 /// an array with at least as many elements as specified by the size expression.
4980 void
4981 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4982                                ParmVarDecl *Param,
4983                                const Expr *ArgExpr) {
4984   // Static array parameters are not supported in C++.
4985   if (!Param || getLangOpts().CPlusPlus)
4986     return;
4987 
4988   QualType OrigTy = Param->getOriginalType();
4989 
4990   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4991   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4992     return;
4993 
4994   if (ArgExpr->isNullPointerConstant(Context,
4995                                      Expr::NPC_NeverValueDependent)) {
4996     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4997     DiagnoseCalleeStaticArrayParam(*this, Param);
4998     return;
4999   }
5000 
5001   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5002   if (!CAT)
5003     return;
5004 
5005   const ConstantArrayType *ArgCAT =
5006     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5007   if (!ArgCAT)
5008     return;
5009 
5010   if (ArgCAT->getSize().ult(CAT->getSize())) {
5011     Diag(CallLoc, diag::warn_static_array_too_small)
5012       << ArgExpr->getSourceRange()
5013       << (unsigned) ArgCAT->getSize().getZExtValue()
5014       << (unsigned) CAT->getSize().getZExtValue();
5015     DiagnoseCalleeStaticArrayParam(*this, Param);
5016   }
5017 }
5018 
5019 /// Given a function expression of unknown-any type, try to rebuild it
5020 /// to have a function type.
5021 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5022 
5023 /// Is the given type a placeholder that we need to lower out
5024 /// immediately during argument processing?
5025 static bool isPlaceholderToRemoveAsArg(QualType type) {
5026   // Placeholders are never sugared.
5027   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5028   if (!placeholder) return false;
5029 
5030   switch (placeholder->getKind()) {
5031   // Ignore all the non-placeholder types.
5032 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5033   case BuiltinType::Id:
5034 #include "clang/Basic/OpenCLImageTypes.def"
5035 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5036 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5037 #include "clang/AST/BuiltinTypes.def"
5038     return false;
5039 
5040   // We cannot lower out overload sets; they might validly be resolved
5041   // by the call machinery.
5042   case BuiltinType::Overload:
5043     return false;
5044 
5045   // Unbridged casts in ARC can be handled in some call positions and
5046   // should be left in place.
5047   case BuiltinType::ARCUnbridgedCast:
5048     return false;
5049 
5050   // Pseudo-objects should be converted as soon as possible.
5051   case BuiltinType::PseudoObject:
5052     return true;
5053 
5054   // The debugger mode could theoretically but currently does not try
5055   // to resolve unknown-typed arguments based on known parameter types.
5056   case BuiltinType::UnknownAny:
5057     return true;
5058 
5059   // These are always invalid as call arguments and should be reported.
5060   case BuiltinType::BoundMember:
5061   case BuiltinType::BuiltinFn:
5062   case BuiltinType::OMPArraySection:
5063     return true;
5064 
5065   }
5066   llvm_unreachable("bad builtin type kind");
5067 }
5068 
5069 /// Check an argument list for placeholders that we won't try to
5070 /// handle later.
5071 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5072   // Apply this processing to all the arguments at once instead of
5073   // dying at the first failure.
5074   bool hasInvalid = false;
5075   for (size_t i = 0, e = args.size(); i != e; i++) {
5076     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5077       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5078       if (result.isInvalid()) hasInvalid = true;
5079       else args[i] = result.get();
5080     } else if (hasInvalid) {
5081       (void)S.CorrectDelayedTyposInExpr(args[i]);
5082     }
5083   }
5084   return hasInvalid;
5085 }
5086 
5087 /// If a builtin function has a pointer argument with no explicit address
5088 /// space, then it should be able to accept a pointer to any address
5089 /// space as input.  In order to do this, we need to replace the
5090 /// standard builtin declaration with one that uses the same address space
5091 /// as the call.
5092 ///
5093 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5094 ///                  it does not contain any pointer arguments without
5095 ///                  an address space qualifer.  Otherwise the rewritten
5096 ///                  FunctionDecl is returned.
5097 /// TODO: Handle pointer return types.
5098 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5099                                                 const FunctionDecl *FDecl,
5100                                                 MultiExprArg ArgExprs) {
5101 
5102   QualType DeclType = FDecl->getType();
5103   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5104 
5105   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5106       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5107     return nullptr;
5108 
5109   bool NeedsNewDecl = false;
5110   unsigned i = 0;
5111   SmallVector<QualType, 8> OverloadParams;
5112 
5113   for (QualType ParamType : FT->param_types()) {
5114 
5115     // Convert array arguments to pointer to simplify type lookup.
5116     ExprResult ArgRes =
5117         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5118     if (ArgRes.isInvalid())
5119       return nullptr;
5120     Expr *Arg = ArgRes.get();
5121     QualType ArgType = Arg->getType();
5122     if (!ParamType->isPointerType() ||
5123         ParamType.getQualifiers().hasAddressSpace() ||
5124         !ArgType->isPointerType() ||
5125         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5126       OverloadParams.push_back(ParamType);
5127       continue;
5128     }
5129 
5130     NeedsNewDecl = true;
5131     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5132 
5133     QualType PointeeType = ParamType->getPointeeType();
5134     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5135     OverloadParams.push_back(Context.getPointerType(PointeeType));
5136   }
5137 
5138   if (!NeedsNewDecl)
5139     return nullptr;
5140 
5141   FunctionProtoType::ExtProtoInfo EPI;
5142   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5143                                                 OverloadParams, EPI);
5144   DeclContext *Parent = Context.getTranslationUnitDecl();
5145   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5146                                                     FDecl->getLocation(),
5147                                                     FDecl->getLocation(),
5148                                                     FDecl->getIdentifier(),
5149                                                     OverloadTy,
5150                                                     /*TInfo=*/nullptr,
5151                                                     SC_Extern, false,
5152                                                     /*hasPrototype=*/true);
5153   SmallVector<ParmVarDecl*, 16> Params;
5154   FT = cast<FunctionProtoType>(OverloadTy);
5155   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5156     QualType ParamType = FT->getParamType(i);
5157     ParmVarDecl *Parm =
5158         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5159                                 SourceLocation(), nullptr, ParamType,
5160                                 /*TInfo=*/nullptr, SC_None, nullptr);
5161     Parm->setScopeInfo(0, i);
5162     Params.push_back(Parm);
5163   }
5164   OverloadDecl->setParams(Params);
5165   return OverloadDecl;
5166 }
5167 
5168 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5169                                     FunctionDecl *Callee,
5170                                     MultiExprArg ArgExprs) {
5171   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5172   // similar attributes) really don't like it when functions are called with an
5173   // invalid number of args.
5174   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5175                          /*PartialOverloading=*/false) &&
5176       !Callee->isVariadic())
5177     return;
5178   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5179     return;
5180 
5181   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5182     S.Diag(Fn->getLocStart(),
5183            isa<CXXMethodDecl>(Callee)
5184                ? diag::err_ovl_no_viable_member_function_in_call
5185                : diag::err_ovl_no_viable_function_in_call)
5186         << Callee << Callee->getSourceRange();
5187     S.Diag(Callee->getLocation(),
5188            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5189         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5190     return;
5191   }
5192 
5193   SmallVector<DiagnoseIfAttr *, 4> Nonfatal;
5194   if (const DiagnoseIfAttr *Attr = S.checkArgDependentDiagnoseIf(
5195           Callee, ArgExprs, Nonfatal, /*MissingImplicitThis=*/true)) {
5196     S.emitDiagnoseIfDiagnostic(Fn->getLocStart(), Attr);
5197     return;
5198   }
5199 
5200   for (const auto *W : Nonfatal)
5201     S.emitDiagnoseIfDiagnostic(Fn->getLocStart(), W);
5202 }
5203 
5204 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5205 /// This provides the location of the left/right parens and a list of comma
5206 /// locations.
5207 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5208                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5209                                Expr *ExecConfig, bool IsExecConfig) {
5210   // Since this might be a postfix expression, get rid of ParenListExprs.
5211   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5212   if (Result.isInvalid()) return ExprError();
5213   Fn = Result.get();
5214 
5215   if (checkArgsForPlaceholders(*this, ArgExprs))
5216     return ExprError();
5217 
5218   if (getLangOpts().CPlusPlus) {
5219     // If this is a pseudo-destructor expression, build the call immediately.
5220     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5221       if (!ArgExprs.empty()) {
5222         // Pseudo-destructor calls should not have any arguments.
5223         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5224             << FixItHint::CreateRemoval(
5225                    SourceRange(ArgExprs.front()->getLocStart(),
5226                                ArgExprs.back()->getLocEnd()));
5227       }
5228 
5229       return new (Context)
5230           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5231     }
5232     if (Fn->getType() == Context.PseudoObjectTy) {
5233       ExprResult result = CheckPlaceholderExpr(Fn);
5234       if (result.isInvalid()) return ExprError();
5235       Fn = result.get();
5236     }
5237 
5238     // Determine whether this is a dependent call inside a C++ template,
5239     // in which case we won't do any semantic analysis now.
5240     bool Dependent = false;
5241     if (Fn->isTypeDependent())
5242       Dependent = true;
5243     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5244       Dependent = true;
5245 
5246     if (Dependent) {
5247       if (ExecConfig) {
5248         return new (Context) CUDAKernelCallExpr(
5249             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5250             Context.DependentTy, VK_RValue, RParenLoc);
5251       } else {
5252         return new (Context) CallExpr(
5253             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5254       }
5255     }
5256 
5257     // Determine whether this is a call to an object (C++ [over.call.object]).
5258     if (Fn->getType()->isRecordType())
5259       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5260                                           RParenLoc);
5261 
5262     if (Fn->getType() == Context.UnknownAnyTy) {
5263       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5264       if (result.isInvalid()) return ExprError();
5265       Fn = result.get();
5266     }
5267 
5268     if (Fn->getType() == Context.BoundMemberTy) {
5269       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5270                                        RParenLoc);
5271     }
5272   }
5273 
5274   // Check for overloaded calls.  This can happen even in C due to extensions.
5275   if (Fn->getType() == Context.OverloadTy) {
5276     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5277 
5278     // We aren't supposed to apply this logic for if there'Scope an '&'
5279     // involved.
5280     if (!find.HasFormOfMemberPointer) {
5281       OverloadExpr *ovl = find.Expression;
5282       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5283         return BuildOverloadedCallExpr(
5284             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5285             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5286       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5287                                        RParenLoc);
5288     }
5289   }
5290 
5291   // If we're directly calling a function, get the appropriate declaration.
5292   if (Fn->getType() == Context.UnknownAnyTy) {
5293     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5294     if (result.isInvalid()) return ExprError();
5295     Fn = result.get();
5296   }
5297 
5298   Expr *NakedFn = Fn->IgnoreParens();
5299 
5300   bool CallingNDeclIndirectly = false;
5301   NamedDecl *NDecl = nullptr;
5302   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5303     if (UnOp->getOpcode() == UO_AddrOf) {
5304       CallingNDeclIndirectly = true;
5305       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5306     }
5307   }
5308 
5309   if (isa<DeclRefExpr>(NakedFn)) {
5310     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5311 
5312     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5313     if (FDecl && FDecl->getBuiltinID()) {
5314       // Rewrite the function decl for this builtin by replacing parameters
5315       // with no explicit address space with the address space of the arguments
5316       // in ArgExprs.
5317       if ((FDecl =
5318                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5319         NDecl = FDecl;
5320         Fn = DeclRefExpr::Create(
5321             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5322             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5323       }
5324     }
5325   } else if (isa<MemberExpr>(NakedFn))
5326     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5327 
5328   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5329     if (CallingNDeclIndirectly &&
5330         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5331                                            Fn->getLocStart()))
5332       return ExprError();
5333 
5334     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5335       return ExprError();
5336 
5337     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5338   }
5339 
5340   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5341                                ExecConfig, IsExecConfig);
5342 }
5343 
5344 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5345 ///
5346 /// __builtin_astype( value, dst type )
5347 ///
5348 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5349                                  SourceLocation BuiltinLoc,
5350                                  SourceLocation RParenLoc) {
5351   ExprValueKind VK = VK_RValue;
5352   ExprObjectKind OK = OK_Ordinary;
5353   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5354   QualType SrcTy = E->getType();
5355   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5356     return ExprError(Diag(BuiltinLoc,
5357                           diag::err_invalid_astype_of_different_size)
5358                      << DstTy
5359                      << SrcTy
5360                      << E->getSourceRange());
5361   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5362 }
5363 
5364 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5365 /// provided arguments.
5366 ///
5367 /// __builtin_convertvector( value, dst type )
5368 ///
5369 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5370                                         SourceLocation BuiltinLoc,
5371                                         SourceLocation RParenLoc) {
5372   TypeSourceInfo *TInfo;
5373   GetTypeFromParser(ParsedDestTy, &TInfo);
5374   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5375 }
5376 
5377 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5378 /// i.e. an expression not of \p OverloadTy.  The expression should
5379 /// unary-convert to an expression of function-pointer or
5380 /// block-pointer type.
5381 ///
5382 /// \param NDecl the declaration being called, if available
5383 ExprResult
5384 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5385                             SourceLocation LParenLoc,
5386                             ArrayRef<Expr *> Args,
5387                             SourceLocation RParenLoc,
5388                             Expr *Config, bool IsExecConfig) {
5389   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5390   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5391 
5392   // Functions with 'interrupt' attribute cannot be called directly.
5393   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5394     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5395     return ExprError();
5396   }
5397 
5398   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5399   // so there's some risk when calling out to non-interrupt handler functions
5400   // that the callee might not preserve them. This is easy to diagnose here,
5401   // but can be very challenging to debug.
5402   if (auto *Caller = getCurFunctionDecl())
5403     if (Caller->hasAttr<ARMInterruptAttr>())
5404       if (!FDecl->hasAttr<ARMInterruptAttr>())
5405         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5406 
5407   // Promote the function operand.
5408   // We special-case function promotion here because we only allow promoting
5409   // builtin functions to function pointers in the callee of a call.
5410   ExprResult Result;
5411   if (BuiltinID &&
5412       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5413     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5414                                CK_BuiltinFnToFnPtr).get();
5415   } else {
5416     Result = CallExprUnaryConversions(Fn);
5417   }
5418   if (Result.isInvalid())
5419     return ExprError();
5420   Fn = Result.get();
5421 
5422   // Make the call expr early, before semantic checks.  This guarantees cleanup
5423   // of arguments and function on error.
5424   CallExpr *TheCall;
5425   if (Config)
5426     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5427                                                cast<CallExpr>(Config), Args,
5428                                                Context.BoolTy, VK_RValue,
5429                                                RParenLoc);
5430   else
5431     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5432                                      VK_RValue, RParenLoc);
5433 
5434   if (!getLangOpts().CPlusPlus) {
5435     // C cannot always handle TypoExpr nodes in builtin calls and direct
5436     // function calls as their argument checking don't necessarily handle
5437     // dependent types properly, so make sure any TypoExprs have been
5438     // dealt with.
5439     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5440     if (!Result.isUsable()) return ExprError();
5441     TheCall = dyn_cast<CallExpr>(Result.get());
5442     if (!TheCall) return Result;
5443     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5444   }
5445 
5446   // Bail out early if calling a builtin with custom typechecking.
5447   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5448     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5449 
5450  retry:
5451   const FunctionType *FuncT;
5452   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5453     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5454     // have type pointer to function".
5455     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5456     if (!FuncT)
5457       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5458                          << Fn->getType() << Fn->getSourceRange());
5459   } else if (const BlockPointerType *BPT =
5460                Fn->getType()->getAs<BlockPointerType>()) {
5461     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5462   } else {
5463     // Handle calls to expressions of unknown-any type.
5464     if (Fn->getType() == Context.UnknownAnyTy) {
5465       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5466       if (rewrite.isInvalid()) return ExprError();
5467       Fn = rewrite.get();
5468       TheCall->setCallee(Fn);
5469       goto retry;
5470     }
5471 
5472     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5473       << Fn->getType() << Fn->getSourceRange());
5474   }
5475 
5476   if (getLangOpts().CUDA) {
5477     if (Config) {
5478       // CUDA: Kernel calls must be to global functions
5479       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5480         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5481             << FDecl->getName() << Fn->getSourceRange());
5482 
5483       // CUDA: Kernel function must have 'void' return type
5484       if (!FuncT->getReturnType()->isVoidType())
5485         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5486             << Fn->getType() << Fn->getSourceRange());
5487     } else {
5488       // CUDA: Calls to global functions must be configured
5489       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5490         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5491             << FDecl->getName() << Fn->getSourceRange());
5492     }
5493   }
5494 
5495   // Check for a valid return type
5496   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5497                           FDecl))
5498     return ExprError();
5499 
5500   // We know the result type of the call, set it.
5501   TheCall->setType(FuncT->getCallResultType(Context));
5502   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5503 
5504   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5505   if (Proto) {
5506     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5507                                 IsExecConfig))
5508       return ExprError();
5509   } else {
5510     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5511 
5512     if (FDecl) {
5513       // Check if we have too few/too many template arguments, based
5514       // on our knowledge of the function definition.
5515       const FunctionDecl *Def = nullptr;
5516       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5517         Proto = Def->getType()->getAs<FunctionProtoType>();
5518        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5519           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5520           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5521       }
5522 
5523       // If the function we're calling isn't a function prototype, but we have
5524       // a function prototype from a prior declaratiom, use that prototype.
5525       if (!FDecl->hasPrototype())
5526         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5527     }
5528 
5529     // Promote the arguments (C99 6.5.2.2p6).
5530     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5531       Expr *Arg = Args[i];
5532 
5533       if (Proto && i < Proto->getNumParams()) {
5534         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5535             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5536         ExprResult ArgE =
5537             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5538         if (ArgE.isInvalid())
5539           return true;
5540 
5541         Arg = ArgE.getAs<Expr>();
5542 
5543       } else {
5544         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5545 
5546         if (ArgE.isInvalid())
5547           return true;
5548 
5549         Arg = ArgE.getAs<Expr>();
5550       }
5551 
5552       if (RequireCompleteType(Arg->getLocStart(),
5553                               Arg->getType(),
5554                               diag::err_call_incomplete_argument, Arg))
5555         return ExprError();
5556 
5557       TheCall->setArg(i, Arg);
5558     }
5559   }
5560 
5561   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5562     if (!Method->isStatic())
5563       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5564         << Fn->getSourceRange());
5565 
5566   // Check for sentinels
5567   if (NDecl)
5568     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5569 
5570   // Do special checking on direct calls to functions.
5571   if (FDecl) {
5572     if (CheckFunctionCall(FDecl, TheCall, Proto))
5573       return ExprError();
5574 
5575     if (BuiltinID)
5576       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5577   } else if (NDecl) {
5578     if (CheckPointerCall(NDecl, TheCall, Proto))
5579       return ExprError();
5580   } else {
5581     if (CheckOtherCall(TheCall, Proto))
5582       return ExprError();
5583   }
5584 
5585   return MaybeBindToTemporary(TheCall);
5586 }
5587 
5588 ExprResult
5589 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5590                            SourceLocation RParenLoc, Expr *InitExpr) {
5591   assert(Ty && "ActOnCompoundLiteral(): missing type");
5592   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5593 
5594   TypeSourceInfo *TInfo;
5595   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5596   if (!TInfo)
5597     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5598 
5599   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5600 }
5601 
5602 ExprResult
5603 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5604                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5605   QualType literalType = TInfo->getType();
5606 
5607   if (literalType->isArrayType()) {
5608     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5609           diag::err_illegal_decl_array_incomplete_type,
5610           SourceRange(LParenLoc,
5611                       LiteralExpr->getSourceRange().getEnd())))
5612       return ExprError();
5613     if (literalType->isVariableArrayType())
5614       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5615         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5616   } else if (!literalType->isDependentType() &&
5617              RequireCompleteType(LParenLoc, literalType,
5618                diag::err_typecheck_decl_incomplete_type,
5619                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5620     return ExprError();
5621 
5622   InitializedEntity Entity
5623     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5624   InitializationKind Kind
5625     = InitializationKind::CreateCStyleCast(LParenLoc,
5626                                            SourceRange(LParenLoc, RParenLoc),
5627                                            /*InitList=*/true);
5628   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5629   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5630                                       &literalType);
5631   if (Result.isInvalid())
5632     return ExprError();
5633   LiteralExpr = Result.get();
5634 
5635   bool isFileScope = !CurContext->isFunctionOrMethod();
5636   if (isFileScope &&
5637       !LiteralExpr->isTypeDependent() &&
5638       !LiteralExpr->isValueDependent() &&
5639       !literalType->isDependentType()) { // 6.5.2.5p3
5640     if (CheckForConstantInitializer(LiteralExpr, literalType))
5641       return ExprError();
5642   }
5643 
5644   // In C, compound literals are l-values for some reason.
5645   // For GCC compatibility, in C++, file-scope array compound literals with
5646   // constant initializers are also l-values, and compound literals are
5647   // otherwise prvalues.
5648   //
5649   // (GCC also treats C++ list-initialized file-scope array prvalues with
5650   // constant initializers as l-values, but that's non-conforming, so we don't
5651   // follow it there.)
5652   //
5653   // FIXME: It would be better to handle the lvalue cases as materializing and
5654   // lifetime-extending a temporary object, but our materialized temporaries
5655   // representation only supports lifetime extension from a variable, not "out
5656   // of thin air".
5657   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5658   // is bound to the result of applying array-to-pointer decay to the compound
5659   // literal.
5660   // FIXME: GCC supports compound literals of reference type, which should
5661   // obviously have a value kind derived from the kind of reference involved.
5662   ExprValueKind VK =
5663       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5664           ? VK_RValue
5665           : VK_LValue;
5666 
5667   return MaybeBindToTemporary(
5668       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5669                                         VK, LiteralExpr, isFileScope));
5670 }
5671 
5672 ExprResult
5673 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5674                     SourceLocation RBraceLoc) {
5675   // Immediately handle non-overload placeholders.  Overloads can be
5676   // resolved contextually, but everything else here can't.
5677   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5678     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5679       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5680 
5681       // Ignore failures; dropping the entire initializer list because
5682       // of one failure would be terrible for indexing/etc.
5683       if (result.isInvalid()) continue;
5684 
5685       InitArgList[I] = result.get();
5686     }
5687   }
5688 
5689   // Semantic analysis for initializers is done by ActOnDeclarator() and
5690   // CheckInitializer() - it requires knowledge of the object being intialized.
5691 
5692   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5693                                                RBraceLoc);
5694   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5695   return E;
5696 }
5697 
5698 /// Do an explicit extend of the given block pointer if we're in ARC.
5699 void Sema::maybeExtendBlockObject(ExprResult &E) {
5700   assert(E.get()->getType()->isBlockPointerType());
5701   assert(E.get()->isRValue());
5702 
5703   // Only do this in an r-value context.
5704   if (!getLangOpts().ObjCAutoRefCount) return;
5705 
5706   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5707                                CK_ARCExtendBlockObject, E.get(),
5708                                /*base path*/ nullptr, VK_RValue);
5709   Cleanup.setExprNeedsCleanups(true);
5710 }
5711 
5712 /// Prepare a conversion of the given expression to an ObjC object
5713 /// pointer type.
5714 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5715   QualType type = E.get()->getType();
5716   if (type->isObjCObjectPointerType()) {
5717     return CK_BitCast;
5718   } else if (type->isBlockPointerType()) {
5719     maybeExtendBlockObject(E);
5720     return CK_BlockPointerToObjCPointerCast;
5721   } else {
5722     assert(type->isPointerType());
5723     return CK_CPointerToObjCPointerCast;
5724   }
5725 }
5726 
5727 /// Prepares for a scalar cast, performing all the necessary stages
5728 /// except the final cast and returning the kind required.
5729 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5730   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5731   // Also, callers should have filtered out the invalid cases with
5732   // pointers.  Everything else should be possible.
5733 
5734   QualType SrcTy = Src.get()->getType();
5735   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5736     return CK_NoOp;
5737 
5738   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5739   case Type::STK_MemberPointer:
5740     llvm_unreachable("member pointer type in C");
5741 
5742   case Type::STK_CPointer:
5743   case Type::STK_BlockPointer:
5744   case Type::STK_ObjCObjectPointer:
5745     switch (DestTy->getScalarTypeKind()) {
5746     case Type::STK_CPointer: {
5747       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5748       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5749       if (SrcAS != DestAS)
5750         return CK_AddressSpaceConversion;
5751       return CK_BitCast;
5752     }
5753     case Type::STK_BlockPointer:
5754       return (SrcKind == Type::STK_BlockPointer
5755                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5756     case Type::STK_ObjCObjectPointer:
5757       if (SrcKind == Type::STK_ObjCObjectPointer)
5758         return CK_BitCast;
5759       if (SrcKind == Type::STK_CPointer)
5760         return CK_CPointerToObjCPointerCast;
5761       maybeExtendBlockObject(Src);
5762       return CK_BlockPointerToObjCPointerCast;
5763     case Type::STK_Bool:
5764       return CK_PointerToBoolean;
5765     case Type::STK_Integral:
5766       return CK_PointerToIntegral;
5767     case Type::STK_Floating:
5768     case Type::STK_FloatingComplex:
5769     case Type::STK_IntegralComplex:
5770     case Type::STK_MemberPointer:
5771       llvm_unreachable("illegal cast from pointer");
5772     }
5773     llvm_unreachable("Should have returned before this");
5774 
5775   case Type::STK_Bool: // casting from bool is like casting from an integer
5776   case Type::STK_Integral:
5777     switch (DestTy->getScalarTypeKind()) {
5778     case Type::STK_CPointer:
5779     case Type::STK_ObjCObjectPointer:
5780     case Type::STK_BlockPointer:
5781       if (Src.get()->isNullPointerConstant(Context,
5782                                            Expr::NPC_ValueDependentIsNull))
5783         return CK_NullToPointer;
5784       return CK_IntegralToPointer;
5785     case Type::STK_Bool:
5786       return CK_IntegralToBoolean;
5787     case Type::STK_Integral:
5788       return CK_IntegralCast;
5789     case Type::STK_Floating:
5790       return CK_IntegralToFloating;
5791     case Type::STK_IntegralComplex:
5792       Src = ImpCastExprToType(Src.get(),
5793                       DestTy->castAs<ComplexType>()->getElementType(),
5794                       CK_IntegralCast);
5795       return CK_IntegralRealToComplex;
5796     case Type::STK_FloatingComplex:
5797       Src = ImpCastExprToType(Src.get(),
5798                       DestTy->castAs<ComplexType>()->getElementType(),
5799                       CK_IntegralToFloating);
5800       return CK_FloatingRealToComplex;
5801     case Type::STK_MemberPointer:
5802       llvm_unreachable("member pointer type in C");
5803     }
5804     llvm_unreachable("Should have returned before this");
5805 
5806   case Type::STK_Floating:
5807     switch (DestTy->getScalarTypeKind()) {
5808     case Type::STK_Floating:
5809       return CK_FloatingCast;
5810     case Type::STK_Bool:
5811       return CK_FloatingToBoolean;
5812     case Type::STK_Integral:
5813       return CK_FloatingToIntegral;
5814     case Type::STK_FloatingComplex:
5815       Src = ImpCastExprToType(Src.get(),
5816                               DestTy->castAs<ComplexType>()->getElementType(),
5817                               CK_FloatingCast);
5818       return CK_FloatingRealToComplex;
5819     case Type::STK_IntegralComplex:
5820       Src = ImpCastExprToType(Src.get(),
5821                               DestTy->castAs<ComplexType>()->getElementType(),
5822                               CK_FloatingToIntegral);
5823       return CK_IntegralRealToComplex;
5824     case Type::STK_CPointer:
5825     case Type::STK_ObjCObjectPointer:
5826     case Type::STK_BlockPointer:
5827       llvm_unreachable("valid float->pointer cast?");
5828     case Type::STK_MemberPointer:
5829       llvm_unreachable("member pointer type in C");
5830     }
5831     llvm_unreachable("Should have returned before this");
5832 
5833   case Type::STK_FloatingComplex:
5834     switch (DestTy->getScalarTypeKind()) {
5835     case Type::STK_FloatingComplex:
5836       return CK_FloatingComplexCast;
5837     case Type::STK_IntegralComplex:
5838       return CK_FloatingComplexToIntegralComplex;
5839     case Type::STK_Floating: {
5840       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5841       if (Context.hasSameType(ET, DestTy))
5842         return CK_FloatingComplexToReal;
5843       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5844       return CK_FloatingCast;
5845     }
5846     case Type::STK_Bool:
5847       return CK_FloatingComplexToBoolean;
5848     case Type::STK_Integral:
5849       Src = ImpCastExprToType(Src.get(),
5850                               SrcTy->castAs<ComplexType>()->getElementType(),
5851                               CK_FloatingComplexToReal);
5852       return CK_FloatingToIntegral;
5853     case Type::STK_CPointer:
5854     case Type::STK_ObjCObjectPointer:
5855     case Type::STK_BlockPointer:
5856       llvm_unreachable("valid complex float->pointer cast?");
5857     case Type::STK_MemberPointer:
5858       llvm_unreachable("member pointer type in C");
5859     }
5860     llvm_unreachable("Should have returned before this");
5861 
5862   case Type::STK_IntegralComplex:
5863     switch (DestTy->getScalarTypeKind()) {
5864     case Type::STK_FloatingComplex:
5865       return CK_IntegralComplexToFloatingComplex;
5866     case Type::STK_IntegralComplex:
5867       return CK_IntegralComplexCast;
5868     case Type::STK_Integral: {
5869       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5870       if (Context.hasSameType(ET, DestTy))
5871         return CK_IntegralComplexToReal;
5872       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5873       return CK_IntegralCast;
5874     }
5875     case Type::STK_Bool:
5876       return CK_IntegralComplexToBoolean;
5877     case Type::STK_Floating:
5878       Src = ImpCastExprToType(Src.get(),
5879                               SrcTy->castAs<ComplexType>()->getElementType(),
5880                               CK_IntegralComplexToReal);
5881       return CK_IntegralToFloating;
5882     case Type::STK_CPointer:
5883     case Type::STK_ObjCObjectPointer:
5884     case Type::STK_BlockPointer:
5885       llvm_unreachable("valid complex int->pointer cast?");
5886     case Type::STK_MemberPointer:
5887       llvm_unreachable("member pointer type in C");
5888     }
5889     llvm_unreachable("Should have returned before this");
5890   }
5891 
5892   llvm_unreachable("Unhandled scalar cast");
5893 }
5894 
5895 static bool breakDownVectorType(QualType type, uint64_t &len,
5896                                 QualType &eltType) {
5897   // Vectors are simple.
5898   if (const VectorType *vecType = type->getAs<VectorType>()) {
5899     len = vecType->getNumElements();
5900     eltType = vecType->getElementType();
5901     assert(eltType->isScalarType());
5902     return true;
5903   }
5904 
5905   // We allow lax conversion to and from non-vector types, but only if
5906   // they're real types (i.e. non-complex, non-pointer scalar types).
5907   if (!type->isRealType()) return false;
5908 
5909   len = 1;
5910   eltType = type;
5911   return true;
5912 }
5913 
5914 /// Are the two types lax-compatible vector types?  That is, given
5915 /// that one of them is a vector, do they have equal storage sizes,
5916 /// where the storage size is the number of elements times the element
5917 /// size?
5918 ///
5919 /// This will also return false if either of the types is neither a
5920 /// vector nor a real type.
5921 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5922   assert(destTy->isVectorType() || srcTy->isVectorType());
5923 
5924   // Disallow lax conversions between scalars and ExtVectors (these
5925   // conversions are allowed for other vector types because common headers
5926   // depend on them).  Most scalar OP ExtVector cases are handled by the
5927   // splat path anyway, which does what we want (convert, not bitcast).
5928   // What this rules out for ExtVectors is crazy things like char4*float.
5929   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5930   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5931 
5932   uint64_t srcLen, destLen;
5933   QualType srcEltTy, destEltTy;
5934   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5935   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5936 
5937   // ASTContext::getTypeSize will return the size rounded up to a
5938   // power of 2, so instead of using that, we need to use the raw
5939   // element size multiplied by the element count.
5940   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5941   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5942 
5943   return (srcLen * srcEltSize == destLen * destEltSize);
5944 }
5945 
5946 /// Is this a legal conversion between two types, one of which is
5947 /// known to be a vector type?
5948 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5949   assert(destTy->isVectorType() || srcTy->isVectorType());
5950 
5951   if (!Context.getLangOpts().LaxVectorConversions)
5952     return false;
5953   return areLaxCompatibleVectorTypes(srcTy, destTy);
5954 }
5955 
5956 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5957                            CastKind &Kind) {
5958   assert(VectorTy->isVectorType() && "Not a vector type!");
5959 
5960   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5961     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5962       return Diag(R.getBegin(),
5963                   Ty->isVectorType() ?
5964                   diag::err_invalid_conversion_between_vectors :
5965                   diag::err_invalid_conversion_between_vector_and_integer)
5966         << VectorTy << Ty << R;
5967   } else
5968     return Diag(R.getBegin(),
5969                 diag::err_invalid_conversion_between_vector_and_scalar)
5970       << VectorTy << Ty << R;
5971 
5972   Kind = CK_BitCast;
5973   return false;
5974 }
5975 
5976 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5977   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5978 
5979   if (DestElemTy == SplattedExpr->getType())
5980     return SplattedExpr;
5981 
5982   assert(DestElemTy->isFloatingType() ||
5983          DestElemTy->isIntegralOrEnumerationType());
5984 
5985   CastKind CK;
5986   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5987     // OpenCL requires that we convert `true` boolean expressions to -1, but
5988     // only when splatting vectors.
5989     if (DestElemTy->isFloatingType()) {
5990       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5991       // in two steps: boolean to signed integral, then to floating.
5992       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5993                                                  CK_BooleanToSignedIntegral);
5994       SplattedExpr = CastExprRes.get();
5995       CK = CK_IntegralToFloating;
5996     } else {
5997       CK = CK_BooleanToSignedIntegral;
5998     }
5999   } else {
6000     ExprResult CastExprRes = SplattedExpr;
6001     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6002     if (CastExprRes.isInvalid())
6003       return ExprError();
6004     SplattedExpr = CastExprRes.get();
6005   }
6006   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6007 }
6008 
6009 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6010                                     Expr *CastExpr, CastKind &Kind) {
6011   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6012 
6013   QualType SrcTy = CastExpr->getType();
6014 
6015   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6016   // an ExtVectorType.
6017   // In OpenCL, casts between vectors of different types are not allowed.
6018   // (See OpenCL 6.2).
6019   if (SrcTy->isVectorType()) {
6020     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6021         || (getLangOpts().OpenCL &&
6022             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6023       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6024         << DestTy << SrcTy << R;
6025       return ExprError();
6026     }
6027     Kind = CK_BitCast;
6028     return CastExpr;
6029   }
6030 
6031   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6032   // conversion will take place first from scalar to elt type, and then
6033   // splat from elt type to vector.
6034   if (SrcTy->isPointerType())
6035     return Diag(R.getBegin(),
6036                 diag::err_invalid_conversion_between_vector_and_scalar)
6037       << DestTy << SrcTy << R;
6038 
6039   Kind = CK_VectorSplat;
6040   return prepareVectorSplat(DestTy, CastExpr);
6041 }
6042 
6043 ExprResult
6044 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6045                     Declarator &D, ParsedType &Ty,
6046                     SourceLocation RParenLoc, Expr *CastExpr) {
6047   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6048          "ActOnCastExpr(): missing type or expr");
6049 
6050   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6051   if (D.isInvalidType())
6052     return ExprError();
6053 
6054   if (getLangOpts().CPlusPlus) {
6055     // Check that there are no default arguments (C++ only).
6056     CheckExtraCXXDefaultArguments(D);
6057   } else {
6058     // Make sure any TypoExprs have been dealt with.
6059     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6060     if (!Res.isUsable())
6061       return ExprError();
6062     CastExpr = Res.get();
6063   }
6064 
6065   checkUnusedDeclAttributes(D);
6066 
6067   QualType castType = castTInfo->getType();
6068   Ty = CreateParsedType(castType, castTInfo);
6069 
6070   bool isVectorLiteral = false;
6071 
6072   // Check for an altivec or OpenCL literal,
6073   // i.e. all the elements are integer constants.
6074   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6075   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6076   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6077        && castType->isVectorType() && (PE || PLE)) {
6078     if (PLE && PLE->getNumExprs() == 0) {
6079       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6080       return ExprError();
6081     }
6082     if (PE || PLE->getNumExprs() == 1) {
6083       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6084       if (!E->getType()->isVectorType())
6085         isVectorLiteral = true;
6086     }
6087     else
6088       isVectorLiteral = true;
6089   }
6090 
6091   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6092   // then handle it as such.
6093   if (isVectorLiteral)
6094     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6095 
6096   // If the Expr being casted is a ParenListExpr, handle it specially.
6097   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6098   // sequence of BinOp comma operators.
6099   if (isa<ParenListExpr>(CastExpr)) {
6100     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6101     if (Result.isInvalid()) return ExprError();
6102     CastExpr = Result.get();
6103   }
6104 
6105   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6106       !getSourceManager().isInSystemMacro(LParenLoc))
6107     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6108 
6109   CheckTollFreeBridgeCast(castType, CastExpr);
6110 
6111   CheckObjCBridgeRelatedCast(castType, CastExpr);
6112 
6113   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6114 
6115   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6116 }
6117 
6118 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6119                                     SourceLocation RParenLoc, Expr *E,
6120                                     TypeSourceInfo *TInfo) {
6121   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6122          "Expected paren or paren list expression");
6123 
6124   Expr **exprs;
6125   unsigned numExprs;
6126   Expr *subExpr;
6127   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6128   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6129     LiteralLParenLoc = PE->getLParenLoc();
6130     LiteralRParenLoc = PE->getRParenLoc();
6131     exprs = PE->getExprs();
6132     numExprs = PE->getNumExprs();
6133   } else { // isa<ParenExpr> by assertion at function entrance
6134     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6135     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6136     subExpr = cast<ParenExpr>(E)->getSubExpr();
6137     exprs = &subExpr;
6138     numExprs = 1;
6139   }
6140 
6141   QualType Ty = TInfo->getType();
6142   assert(Ty->isVectorType() && "Expected vector type");
6143 
6144   SmallVector<Expr *, 8> initExprs;
6145   const VectorType *VTy = Ty->getAs<VectorType>();
6146   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6147 
6148   // '(...)' form of vector initialization in AltiVec: the number of
6149   // initializers must be one or must match the size of the vector.
6150   // If a single value is specified in the initializer then it will be
6151   // replicated to all the components of the vector
6152   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6153     // The number of initializers must be one or must match the size of the
6154     // vector. If a single value is specified in the initializer then it will
6155     // be replicated to all the components of the vector
6156     if (numExprs == 1) {
6157       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6158       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6159       if (Literal.isInvalid())
6160         return ExprError();
6161       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6162                                   PrepareScalarCast(Literal, ElemTy));
6163       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6164     }
6165     else if (numExprs < numElems) {
6166       Diag(E->getExprLoc(),
6167            diag::err_incorrect_number_of_vector_initializers);
6168       return ExprError();
6169     }
6170     else
6171       initExprs.append(exprs, exprs + numExprs);
6172   }
6173   else {
6174     // For OpenCL, when the number of initializers is a single value,
6175     // it will be replicated to all components of the vector.
6176     if (getLangOpts().OpenCL &&
6177         VTy->getVectorKind() == VectorType::GenericVector &&
6178         numExprs == 1) {
6179         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6180         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6181         if (Literal.isInvalid())
6182           return ExprError();
6183         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6184                                     PrepareScalarCast(Literal, ElemTy));
6185         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6186     }
6187 
6188     initExprs.append(exprs, exprs + numExprs);
6189   }
6190   // FIXME: This means that pretty-printing the final AST will produce curly
6191   // braces instead of the original commas.
6192   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6193                                                    initExprs, LiteralRParenLoc);
6194   initE->setType(Ty);
6195   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6196 }
6197 
6198 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6199 /// the ParenListExpr into a sequence of comma binary operators.
6200 ExprResult
6201 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6202   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6203   if (!E)
6204     return OrigExpr;
6205 
6206   ExprResult Result(E->getExpr(0));
6207 
6208   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6209     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6210                         E->getExpr(i));
6211 
6212   if (Result.isInvalid()) return ExprError();
6213 
6214   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6215 }
6216 
6217 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6218                                     SourceLocation R,
6219                                     MultiExprArg Val) {
6220   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6221   return expr;
6222 }
6223 
6224 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6225 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6226 /// emitted.
6227 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6228                                       SourceLocation QuestionLoc) {
6229   Expr *NullExpr = LHSExpr;
6230   Expr *NonPointerExpr = RHSExpr;
6231   Expr::NullPointerConstantKind NullKind =
6232       NullExpr->isNullPointerConstant(Context,
6233                                       Expr::NPC_ValueDependentIsNotNull);
6234 
6235   if (NullKind == Expr::NPCK_NotNull) {
6236     NullExpr = RHSExpr;
6237     NonPointerExpr = LHSExpr;
6238     NullKind =
6239         NullExpr->isNullPointerConstant(Context,
6240                                         Expr::NPC_ValueDependentIsNotNull);
6241   }
6242 
6243   if (NullKind == Expr::NPCK_NotNull)
6244     return false;
6245 
6246   if (NullKind == Expr::NPCK_ZeroExpression)
6247     return false;
6248 
6249   if (NullKind == Expr::NPCK_ZeroLiteral) {
6250     // In this case, check to make sure that we got here from a "NULL"
6251     // string in the source code.
6252     NullExpr = NullExpr->IgnoreParenImpCasts();
6253     SourceLocation loc = NullExpr->getExprLoc();
6254     if (!findMacroSpelling(loc, "NULL"))
6255       return false;
6256   }
6257 
6258   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6259   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6260       << NonPointerExpr->getType() << DiagType
6261       << NonPointerExpr->getSourceRange();
6262   return true;
6263 }
6264 
6265 /// \brief Return false if the condition expression is valid, true otherwise.
6266 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6267   QualType CondTy = Cond->getType();
6268 
6269   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6270   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6271     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6272       << CondTy << Cond->getSourceRange();
6273     return true;
6274   }
6275 
6276   // C99 6.5.15p2
6277   if (CondTy->isScalarType()) return false;
6278 
6279   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6280     << CondTy << Cond->getSourceRange();
6281   return true;
6282 }
6283 
6284 /// \brief Handle when one or both operands are void type.
6285 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6286                                          ExprResult &RHS) {
6287     Expr *LHSExpr = LHS.get();
6288     Expr *RHSExpr = RHS.get();
6289 
6290     if (!LHSExpr->getType()->isVoidType())
6291       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6292         << RHSExpr->getSourceRange();
6293     if (!RHSExpr->getType()->isVoidType())
6294       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6295         << LHSExpr->getSourceRange();
6296     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6297     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6298     return S.Context.VoidTy;
6299 }
6300 
6301 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6302 /// true otherwise.
6303 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6304                                         QualType PointerTy) {
6305   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6306       !NullExpr.get()->isNullPointerConstant(S.Context,
6307                                             Expr::NPC_ValueDependentIsNull))
6308     return true;
6309 
6310   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6311   return false;
6312 }
6313 
6314 /// \brief Checks compatibility between two pointers and return the resulting
6315 /// type.
6316 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6317                                                      ExprResult &RHS,
6318                                                      SourceLocation Loc) {
6319   QualType LHSTy = LHS.get()->getType();
6320   QualType RHSTy = RHS.get()->getType();
6321 
6322   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6323     // Two identical pointers types are always compatible.
6324     return LHSTy;
6325   }
6326 
6327   QualType lhptee, rhptee;
6328 
6329   // Get the pointee types.
6330   bool IsBlockPointer = false;
6331   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6332     lhptee = LHSBTy->getPointeeType();
6333     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6334     IsBlockPointer = true;
6335   } else {
6336     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6337     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6338   }
6339 
6340   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6341   // differently qualified versions of compatible types, the result type is
6342   // a pointer to an appropriately qualified version of the composite
6343   // type.
6344 
6345   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6346   // clause doesn't make sense for our extensions. E.g. address space 2 should
6347   // be incompatible with address space 3: they may live on different devices or
6348   // anything.
6349   Qualifiers lhQual = lhptee.getQualifiers();
6350   Qualifiers rhQual = rhptee.getQualifiers();
6351 
6352   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6353   lhQual.removeCVRQualifiers();
6354   rhQual.removeCVRQualifiers();
6355 
6356   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6357   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6358 
6359   // For OpenCL:
6360   // 1. If LHS and RHS types match exactly and:
6361   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6362   //  (b) AS overlap => generate addrspacecast
6363   //  (c) AS don't overlap => give an error
6364   // 2. if LHS and RHS types don't match:
6365   //  (a) AS match => use standard C rules, generate bitcast
6366   //  (b) AS overlap => generate addrspacecast instead of bitcast
6367   //  (c) AS don't overlap => give an error
6368 
6369   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6370   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6371 
6372   // OpenCL cases 1c, 2a, 2b, and 2c.
6373   if (CompositeTy.isNull()) {
6374     // In this situation, we assume void* type. No especially good
6375     // reason, but this is what gcc does, and we do have to pick
6376     // to get a consistent AST.
6377     QualType incompatTy;
6378     if (S.getLangOpts().OpenCL) {
6379       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6380       // spaces is disallowed.
6381       unsigned ResultAddrSpace;
6382       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6383         // Cases 2a and 2b.
6384         ResultAddrSpace = lhQual.getAddressSpace();
6385       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6386         // Cases 2a and 2b.
6387         ResultAddrSpace = rhQual.getAddressSpace();
6388       } else {
6389         // Cases 1c and 2c.
6390         S.Diag(Loc,
6391                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6392             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6393             << RHS.get()->getSourceRange();
6394         return QualType();
6395       }
6396 
6397       // Continue handling cases 2a and 2b.
6398       incompatTy = S.Context.getPointerType(
6399           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6400       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6401                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6402                                     ? CK_AddressSpaceConversion /* 2b */
6403                                     : CK_BitCast /* 2a */);
6404       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6405                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6406                                     ? CK_AddressSpaceConversion /* 2b */
6407                                     : CK_BitCast /* 2a */);
6408     } else {
6409       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6410           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6411           << RHS.get()->getSourceRange();
6412       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6413       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6414       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6415     }
6416     return incompatTy;
6417   }
6418 
6419   // The pointer types are compatible.
6420   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6421   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6422   if (IsBlockPointer)
6423     ResultTy = S.Context.getBlockPointerType(ResultTy);
6424   else {
6425     // Cases 1a and 1b for OpenCL.
6426     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6427     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6428                       ? CK_BitCast /* 1a */
6429                       : CK_AddressSpaceConversion /* 1b */;
6430     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6431                       ? CK_BitCast /* 1a */
6432                       : CK_AddressSpaceConversion /* 1b */;
6433     ResultTy = S.Context.getPointerType(ResultTy);
6434   }
6435 
6436   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6437   // if the target type does not change.
6438   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6439   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6440   return ResultTy;
6441 }
6442 
6443 /// \brief Return the resulting type when the operands are both block pointers.
6444 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6445                                                           ExprResult &LHS,
6446                                                           ExprResult &RHS,
6447                                                           SourceLocation Loc) {
6448   QualType LHSTy = LHS.get()->getType();
6449   QualType RHSTy = RHS.get()->getType();
6450 
6451   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6452     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6453       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6454       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6455       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6456       return destType;
6457     }
6458     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6459       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6460       << RHS.get()->getSourceRange();
6461     return QualType();
6462   }
6463 
6464   // We have 2 block pointer types.
6465   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6466 }
6467 
6468 /// \brief Return the resulting type when the operands are both pointers.
6469 static QualType
6470 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6471                                             ExprResult &RHS,
6472                                             SourceLocation Loc) {
6473   // get the pointer types
6474   QualType LHSTy = LHS.get()->getType();
6475   QualType RHSTy = RHS.get()->getType();
6476 
6477   // get the "pointed to" types
6478   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6479   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6480 
6481   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6482   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6483     // Figure out necessary qualifiers (C99 6.5.15p6)
6484     QualType destPointee
6485       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6486     QualType destType = S.Context.getPointerType(destPointee);
6487     // Add qualifiers if necessary.
6488     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6489     // Promote to void*.
6490     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6491     return destType;
6492   }
6493   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6494     QualType destPointee
6495       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6496     QualType destType = S.Context.getPointerType(destPointee);
6497     // Add qualifiers if necessary.
6498     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6499     // Promote to void*.
6500     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6501     return destType;
6502   }
6503 
6504   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6505 }
6506 
6507 /// \brief Return false if the first expression is not an integer and the second
6508 /// expression is not a pointer, true otherwise.
6509 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6510                                         Expr* PointerExpr, SourceLocation Loc,
6511                                         bool IsIntFirstExpr) {
6512   if (!PointerExpr->getType()->isPointerType() ||
6513       !Int.get()->getType()->isIntegerType())
6514     return false;
6515 
6516   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6517   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6518 
6519   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6520     << Expr1->getType() << Expr2->getType()
6521     << Expr1->getSourceRange() << Expr2->getSourceRange();
6522   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6523                             CK_IntegralToPointer);
6524   return true;
6525 }
6526 
6527 /// \brief Simple conversion between integer and floating point types.
6528 ///
6529 /// Used when handling the OpenCL conditional operator where the
6530 /// condition is a vector while the other operands are scalar.
6531 ///
6532 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6533 /// types are either integer or floating type. Between the two
6534 /// operands, the type with the higher rank is defined as the "result
6535 /// type". The other operand needs to be promoted to the same type. No
6536 /// other type promotion is allowed. We cannot use
6537 /// UsualArithmeticConversions() for this purpose, since it always
6538 /// promotes promotable types.
6539 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6540                                             ExprResult &RHS,
6541                                             SourceLocation QuestionLoc) {
6542   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6543   if (LHS.isInvalid())
6544     return QualType();
6545   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6546   if (RHS.isInvalid())
6547     return QualType();
6548 
6549   // For conversion purposes, we ignore any qualifiers.
6550   // For example, "const float" and "float" are equivalent.
6551   QualType LHSType =
6552     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6553   QualType RHSType =
6554     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6555 
6556   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6557     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6558       << LHSType << LHS.get()->getSourceRange();
6559     return QualType();
6560   }
6561 
6562   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6563     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6564       << RHSType << RHS.get()->getSourceRange();
6565     return QualType();
6566   }
6567 
6568   // If both types are identical, no conversion is needed.
6569   if (LHSType == RHSType)
6570     return LHSType;
6571 
6572   // Now handle "real" floating types (i.e. float, double, long double).
6573   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6574     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6575                                  /*IsCompAssign = */ false);
6576 
6577   // Finally, we have two differing integer types.
6578   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6579   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6580 }
6581 
6582 /// \brief Convert scalar operands to a vector that matches the
6583 ///        condition in length.
6584 ///
6585 /// Used when handling the OpenCL conditional operator where the
6586 /// condition is a vector while the other operands are scalar.
6587 ///
6588 /// We first compute the "result type" for the scalar operands
6589 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6590 /// into a vector of that type where the length matches the condition
6591 /// vector type. s6.11.6 requires that the element types of the result
6592 /// and the condition must have the same number of bits.
6593 static QualType
6594 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6595                               QualType CondTy, SourceLocation QuestionLoc) {
6596   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6597   if (ResTy.isNull()) return QualType();
6598 
6599   const VectorType *CV = CondTy->getAs<VectorType>();
6600   assert(CV);
6601 
6602   // Determine the vector result type
6603   unsigned NumElements = CV->getNumElements();
6604   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6605 
6606   // Ensure that all types have the same number of bits
6607   if (S.Context.getTypeSize(CV->getElementType())
6608       != S.Context.getTypeSize(ResTy)) {
6609     // Since VectorTy is created internally, it does not pretty print
6610     // with an OpenCL name. Instead, we just print a description.
6611     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6612     SmallString<64> Str;
6613     llvm::raw_svector_ostream OS(Str);
6614     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6615     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6616       << CondTy << OS.str();
6617     return QualType();
6618   }
6619 
6620   // Convert operands to the vector result type
6621   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6622   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6623 
6624   return VectorTy;
6625 }
6626 
6627 /// \brief Return false if this is a valid OpenCL condition vector
6628 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6629                                        SourceLocation QuestionLoc) {
6630   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6631   // integral type.
6632   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6633   assert(CondTy);
6634   QualType EleTy = CondTy->getElementType();
6635   if (EleTy->isIntegerType()) return false;
6636 
6637   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6638     << Cond->getType() << Cond->getSourceRange();
6639   return true;
6640 }
6641 
6642 /// \brief Return false if the vector condition type and the vector
6643 ///        result type are compatible.
6644 ///
6645 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6646 /// number of elements, and their element types have the same number
6647 /// of bits.
6648 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6649                               SourceLocation QuestionLoc) {
6650   const VectorType *CV = CondTy->getAs<VectorType>();
6651   const VectorType *RV = VecResTy->getAs<VectorType>();
6652   assert(CV && RV);
6653 
6654   if (CV->getNumElements() != RV->getNumElements()) {
6655     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6656       << CondTy << VecResTy;
6657     return true;
6658   }
6659 
6660   QualType CVE = CV->getElementType();
6661   QualType RVE = RV->getElementType();
6662 
6663   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6664     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6665       << CondTy << VecResTy;
6666     return true;
6667   }
6668 
6669   return false;
6670 }
6671 
6672 /// \brief Return the resulting type for the conditional operator in
6673 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6674 ///        s6.3.i) when the condition is a vector type.
6675 static QualType
6676 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6677                              ExprResult &LHS, ExprResult &RHS,
6678                              SourceLocation QuestionLoc) {
6679   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6680   if (Cond.isInvalid())
6681     return QualType();
6682   QualType CondTy = Cond.get()->getType();
6683 
6684   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6685     return QualType();
6686 
6687   // If either operand is a vector then find the vector type of the
6688   // result as specified in OpenCL v1.1 s6.3.i.
6689   if (LHS.get()->getType()->isVectorType() ||
6690       RHS.get()->getType()->isVectorType()) {
6691     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6692                                               /*isCompAssign*/false,
6693                                               /*AllowBothBool*/true,
6694                                               /*AllowBoolConversions*/false);
6695     if (VecResTy.isNull()) return QualType();
6696     // The result type must match the condition type as specified in
6697     // OpenCL v1.1 s6.11.6.
6698     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6699       return QualType();
6700     return VecResTy;
6701   }
6702 
6703   // Both operands are scalar.
6704   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6705 }
6706 
6707 /// \brief Return true if the Expr is block type
6708 static bool checkBlockType(Sema &S, const Expr *E) {
6709   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6710     QualType Ty = CE->getCallee()->getType();
6711     if (Ty->isBlockPointerType()) {
6712       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6713       return true;
6714     }
6715   }
6716   return false;
6717 }
6718 
6719 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6720 /// In that case, LHS = cond.
6721 /// C99 6.5.15
6722 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6723                                         ExprResult &RHS, ExprValueKind &VK,
6724                                         ExprObjectKind &OK,
6725                                         SourceLocation QuestionLoc) {
6726 
6727   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6728   if (!LHSResult.isUsable()) return QualType();
6729   LHS = LHSResult;
6730 
6731   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6732   if (!RHSResult.isUsable()) return QualType();
6733   RHS = RHSResult;
6734 
6735   // C++ is sufficiently different to merit its own checker.
6736   if (getLangOpts().CPlusPlus)
6737     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6738 
6739   VK = VK_RValue;
6740   OK = OK_Ordinary;
6741 
6742   // The OpenCL operator with a vector condition is sufficiently
6743   // different to merit its own checker.
6744   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6745     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6746 
6747   // First, check the condition.
6748   Cond = UsualUnaryConversions(Cond.get());
6749   if (Cond.isInvalid())
6750     return QualType();
6751   if (checkCondition(*this, Cond.get(), QuestionLoc))
6752     return QualType();
6753 
6754   // Now check the two expressions.
6755   if (LHS.get()->getType()->isVectorType() ||
6756       RHS.get()->getType()->isVectorType())
6757     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6758                                /*AllowBothBool*/true,
6759                                /*AllowBoolConversions*/false);
6760 
6761   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6762   if (LHS.isInvalid() || RHS.isInvalid())
6763     return QualType();
6764 
6765   QualType LHSTy = LHS.get()->getType();
6766   QualType RHSTy = RHS.get()->getType();
6767 
6768   // Diagnose attempts to convert between __float128 and long double where
6769   // such conversions currently can't be handled.
6770   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6771     Diag(QuestionLoc,
6772          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6773       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6774     return QualType();
6775   }
6776 
6777   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6778   // selection operator (?:).
6779   if (getLangOpts().OpenCL &&
6780       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6781     return QualType();
6782   }
6783 
6784   // If both operands have arithmetic type, do the usual arithmetic conversions
6785   // to find a common type: C99 6.5.15p3,5.
6786   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6787     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6788     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6789 
6790     return ResTy;
6791   }
6792 
6793   // If both operands are the same structure or union type, the result is that
6794   // type.
6795   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6796     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6797       if (LHSRT->getDecl() == RHSRT->getDecl())
6798         // "If both the operands have structure or union type, the result has
6799         // that type."  This implies that CV qualifiers are dropped.
6800         return LHSTy.getUnqualifiedType();
6801     // FIXME: Type of conditional expression must be complete in C mode.
6802   }
6803 
6804   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6805   // The following || allows only one side to be void (a GCC-ism).
6806   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6807     return checkConditionalVoidType(*this, LHS, RHS);
6808   }
6809 
6810   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6811   // the type of the other operand."
6812   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6813   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6814 
6815   // All objective-c pointer type analysis is done here.
6816   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6817                                                         QuestionLoc);
6818   if (LHS.isInvalid() || RHS.isInvalid())
6819     return QualType();
6820   if (!compositeType.isNull())
6821     return compositeType;
6822 
6823 
6824   // Handle block pointer types.
6825   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6826     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6827                                                      QuestionLoc);
6828 
6829   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6830   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6831     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6832                                                        QuestionLoc);
6833 
6834   // GCC compatibility: soften pointer/integer mismatch.  Note that
6835   // null pointers have been filtered out by this point.
6836   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6837       /*isIntFirstExpr=*/true))
6838     return RHSTy;
6839   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6840       /*isIntFirstExpr=*/false))
6841     return LHSTy;
6842 
6843   // Emit a better diagnostic if one of the expressions is a null pointer
6844   // constant and the other is not a pointer type. In this case, the user most
6845   // likely forgot to take the address of the other expression.
6846   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6847     return QualType();
6848 
6849   // Otherwise, the operands are not compatible.
6850   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6851     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6852     << RHS.get()->getSourceRange();
6853   return QualType();
6854 }
6855 
6856 /// FindCompositeObjCPointerType - Helper method to find composite type of
6857 /// two objective-c pointer types of the two input expressions.
6858 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6859                                             SourceLocation QuestionLoc) {
6860   QualType LHSTy = LHS.get()->getType();
6861   QualType RHSTy = RHS.get()->getType();
6862 
6863   // Handle things like Class and struct objc_class*.  Here we case the result
6864   // to the pseudo-builtin, because that will be implicitly cast back to the
6865   // redefinition type if an attempt is made to access its fields.
6866   if (LHSTy->isObjCClassType() &&
6867       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6868     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6869     return LHSTy;
6870   }
6871   if (RHSTy->isObjCClassType() &&
6872       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6873     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6874     return RHSTy;
6875   }
6876   // And the same for struct objc_object* / id
6877   if (LHSTy->isObjCIdType() &&
6878       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6879     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6880     return LHSTy;
6881   }
6882   if (RHSTy->isObjCIdType() &&
6883       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6884     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6885     return RHSTy;
6886   }
6887   // And the same for struct objc_selector* / SEL
6888   if (Context.isObjCSelType(LHSTy) &&
6889       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6890     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6891     return LHSTy;
6892   }
6893   if (Context.isObjCSelType(RHSTy) &&
6894       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6895     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6896     return RHSTy;
6897   }
6898   // Check constraints for Objective-C object pointers types.
6899   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6900 
6901     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6902       // Two identical object pointer types are always compatible.
6903       return LHSTy;
6904     }
6905     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6906     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6907     QualType compositeType = LHSTy;
6908 
6909     // If both operands are interfaces and either operand can be
6910     // assigned to the other, use that type as the composite
6911     // type. This allows
6912     //   xxx ? (A*) a : (B*) b
6913     // where B is a subclass of A.
6914     //
6915     // Additionally, as for assignment, if either type is 'id'
6916     // allow silent coercion. Finally, if the types are
6917     // incompatible then make sure to use 'id' as the composite
6918     // type so the result is acceptable for sending messages to.
6919 
6920     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6921     // It could return the composite type.
6922     if (!(compositeType =
6923           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6924       // Nothing more to do.
6925     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6926       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6927     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6928       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6929     } else if ((LHSTy->isObjCQualifiedIdType() ||
6930                 RHSTy->isObjCQualifiedIdType()) &&
6931                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6932       // Need to handle "id<xx>" explicitly.
6933       // GCC allows qualified id and any Objective-C type to devolve to
6934       // id. Currently localizing to here until clear this should be
6935       // part of ObjCQualifiedIdTypesAreCompatible.
6936       compositeType = Context.getObjCIdType();
6937     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6938       compositeType = Context.getObjCIdType();
6939     } else {
6940       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6941       << LHSTy << RHSTy
6942       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6943       QualType incompatTy = Context.getObjCIdType();
6944       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6945       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6946       return incompatTy;
6947     }
6948     // The object pointer types are compatible.
6949     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6950     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6951     return compositeType;
6952   }
6953   // Check Objective-C object pointer types and 'void *'
6954   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6955     if (getLangOpts().ObjCAutoRefCount) {
6956       // ARC forbids the implicit conversion of object pointers to 'void *',
6957       // so these types are not compatible.
6958       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6959           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6960       LHS = RHS = true;
6961       return QualType();
6962     }
6963     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6964     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6965     QualType destPointee
6966     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6967     QualType destType = Context.getPointerType(destPointee);
6968     // Add qualifiers if necessary.
6969     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6970     // Promote to void*.
6971     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6972     return destType;
6973   }
6974   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6975     if (getLangOpts().ObjCAutoRefCount) {
6976       // ARC forbids the implicit conversion of object pointers to 'void *',
6977       // so these types are not compatible.
6978       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6979           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6980       LHS = RHS = true;
6981       return QualType();
6982     }
6983     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6984     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6985     QualType destPointee
6986     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6987     QualType destType = Context.getPointerType(destPointee);
6988     // Add qualifiers if necessary.
6989     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6990     // Promote to void*.
6991     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6992     return destType;
6993   }
6994   return QualType();
6995 }
6996 
6997 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6998 /// ParenRange in parentheses.
6999 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7000                                const PartialDiagnostic &Note,
7001                                SourceRange ParenRange) {
7002   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7003   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7004       EndLoc.isValid()) {
7005     Self.Diag(Loc, Note)
7006       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7007       << FixItHint::CreateInsertion(EndLoc, ")");
7008   } else {
7009     // We can't display the parentheses, so just show the bare note.
7010     Self.Diag(Loc, Note) << ParenRange;
7011   }
7012 }
7013 
7014 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7015   return BinaryOperator::isAdditiveOp(Opc) ||
7016          BinaryOperator::isMultiplicativeOp(Opc) ||
7017          BinaryOperator::isShiftOp(Opc);
7018 }
7019 
7020 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7021 /// expression, either using a built-in or overloaded operator,
7022 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7023 /// expression.
7024 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7025                                    Expr **RHSExprs) {
7026   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7027   E = E->IgnoreImpCasts();
7028   E = E->IgnoreConversionOperator();
7029   E = E->IgnoreImpCasts();
7030 
7031   // Built-in binary operator.
7032   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7033     if (IsArithmeticOp(OP->getOpcode())) {
7034       *Opcode = OP->getOpcode();
7035       *RHSExprs = OP->getRHS();
7036       return true;
7037     }
7038   }
7039 
7040   // Overloaded operator.
7041   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7042     if (Call->getNumArgs() != 2)
7043       return false;
7044 
7045     // Make sure this is really a binary operator that is safe to pass into
7046     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7047     OverloadedOperatorKind OO = Call->getOperator();
7048     if (OO < OO_Plus || OO > OO_Arrow ||
7049         OO == OO_PlusPlus || OO == OO_MinusMinus)
7050       return false;
7051 
7052     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7053     if (IsArithmeticOp(OpKind)) {
7054       *Opcode = OpKind;
7055       *RHSExprs = Call->getArg(1);
7056       return true;
7057     }
7058   }
7059 
7060   return false;
7061 }
7062 
7063 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7064 /// or is a logical expression such as (x==y) which has int type, but is
7065 /// commonly interpreted as boolean.
7066 static bool ExprLooksBoolean(Expr *E) {
7067   E = E->IgnoreParenImpCasts();
7068 
7069   if (E->getType()->isBooleanType())
7070     return true;
7071   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7072     return OP->isComparisonOp() || OP->isLogicalOp();
7073   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7074     return OP->getOpcode() == UO_LNot;
7075   if (E->getType()->isPointerType())
7076     return true;
7077 
7078   return false;
7079 }
7080 
7081 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7082 /// and binary operator are mixed in a way that suggests the programmer assumed
7083 /// the conditional operator has higher precedence, for example:
7084 /// "int x = a + someBinaryCondition ? 1 : 2".
7085 static void DiagnoseConditionalPrecedence(Sema &Self,
7086                                           SourceLocation OpLoc,
7087                                           Expr *Condition,
7088                                           Expr *LHSExpr,
7089                                           Expr *RHSExpr) {
7090   BinaryOperatorKind CondOpcode;
7091   Expr *CondRHS;
7092 
7093   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7094     return;
7095   if (!ExprLooksBoolean(CondRHS))
7096     return;
7097 
7098   // The condition is an arithmetic binary expression, with a right-
7099   // hand side that looks boolean, so warn.
7100 
7101   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7102       << Condition->getSourceRange()
7103       << BinaryOperator::getOpcodeStr(CondOpcode);
7104 
7105   SuggestParentheses(Self, OpLoc,
7106     Self.PDiag(diag::note_precedence_silence)
7107       << BinaryOperator::getOpcodeStr(CondOpcode),
7108     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7109 
7110   SuggestParentheses(Self, OpLoc,
7111     Self.PDiag(diag::note_precedence_conditional_first),
7112     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7113 }
7114 
7115 /// Compute the nullability of a conditional expression.
7116 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7117                                               QualType LHSTy, QualType RHSTy,
7118                                               ASTContext &Ctx) {
7119   if (!ResTy->isAnyPointerType())
7120     return ResTy;
7121 
7122   auto GetNullability = [&Ctx](QualType Ty) {
7123     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7124     if (Kind)
7125       return *Kind;
7126     return NullabilityKind::Unspecified;
7127   };
7128 
7129   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7130   NullabilityKind MergedKind;
7131 
7132   // Compute nullability of a binary conditional expression.
7133   if (IsBin) {
7134     if (LHSKind == NullabilityKind::NonNull)
7135       MergedKind = NullabilityKind::NonNull;
7136     else
7137       MergedKind = RHSKind;
7138   // Compute nullability of a normal conditional expression.
7139   } else {
7140     if (LHSKind == NullabilityKind::Nullable ||
7141         RHSKind == NullabilityKind::Nullable)
7142       MergedKind = NullabilityKind::Nullable;
7143     else if (LHSKind == NullabilityKind::NonNull)
7144       MergedKind = RHSKind;
7145     else if (RHSKind == NullabilityKind::NonNull)
7146       MergedKind = LHSKind;
7147     else
7148       MergedKind = NullabilityKind::Unspecified;
7149   }
7150 
7151   // Return if ResTy already has the correct nullability.
7152   if (GetNullability(ResTy) == MergedKind)
7153     return ResTy;
7154 
7155   // Strip all nullability from ResTy.
7156   while (ResTy->getNullability(Ctx))
7157     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7158 
7159   // Create a new AttributedType with the new nullability kind.
7160   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7161   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7162 }
7163 
7164 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7165 /// in the case of a the GNU conditional expr extension.
7166 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7167                                     SourceLocation ColonLoc,
7168                                     Expr *CondExpr, Expr *LHSExpr,
7169                                     Expr *RHSExpr) {
7170   if (!getLangOpts().CPlusPlus) {
7171     // C cannot handle TypoExpr nodes in the condition because it
7172     // doesn't handle dependent types properly, so make sure any TypoExprs have
7173     // been dealt with before checking the operands.
7174     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7175     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7176     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7177 
7178     if (!CondResult.isUsable())
7179       return ExprError();
7180 
7181     if (LHSExpr) {
7182       if (!LHSResult.isUsable())
7183         return ExprError();
7184     }
7185 
7186     if (!RHSResult.isUsable())
7187       return ExprError();
7188 
7189     CondExpr = CondResult.get();
7190     LHSExpr = LHSResult.get();
7191     RHSExpr = RHSResult.get();
7192   }
7193 
7194   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7195   // was the condition.
7196   OpaqueValueExpr *opaqueValue = nullptr;
7197   Expr *commonExpr = nullptr;
7198   if (!LHSExpr) {
7199     commonExpr = CondExpr;
7200     // Lower out placeholder types first.  This is important so that we don't
7201     // try to capture a placeholder. This happens in few cases in C++; such
7202     // as Objective-C++'s dictionary subscripting syntax.
7203     if (commonExpr->hasPlaceholderType()) {
7204       ExprResult result = CheckPlaceholderExpr(commonExpr);
7205       if (!result.isUsable()) return ExprError();
7206       commonExpr = result.get();
7207     }
7208     // We usually want to apply unary conversions *before* saving, except
7209     // in the special case of a C++ l-value conditional.
7210     if (!(getLangOpts().CPlusPlus
7211           && !commonExpr->isTypeDependent()
7212           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7213           && commonExpr->isGLValue()
7214           && commonExpr->isOrdinaryOrBitFieldObject()
7215           && RHSExpr->isOrdinaryOrBitFieldObject()
7216           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7217       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7218       if (commonRes.isInvalid())
7219         return ExprError();
7220       commonExpr = commonRes.get();
7221     }
7222 
7223     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7224                                                 commonExpr->getType(),
7225                                                 commonExpr->getValueKind(),
7226                                                 commonExpr->getObjectKind(),
7227                                                 commonExpr);
7228     LHSExpr = CondExpr = opaqueValue;
7229   }
7230 
7231   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7232   ExprValueKind VK = VK_RValue;
7233   ExprObjectKind OK = OK_Ordinary;
7234   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7235   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7236                                              VK, OK, QuestionLoc);
7237   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7238       RHS.isInvalid())
7239     return ExprError();
7240 
7241   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7242                                 RHS.get());
7243 
7244   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7245 
7246   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7247                                          Context);
7248 
7249   if (!commonExpr)
7250     return new (Context)
7251         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7252                             RHS.get(), result, VK, OK);
7253 
7254   return new (Context) BinaryConditionalOperator(
7255       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7256       ColonLoc, result, VK, OK);
7257 }
7258 
7259 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7260 // being closely modeled after the C99 spec:-). The odd characteristic of this
7261 // routine is it effectively iqnores the qualifiers on the top level pointee.
7262 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7263 // FIXME: add a couple examples in this comment.
7264 static Sema::AssignConvertType
7265 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7266   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7267   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7268 
7269   // get the "pointed to" type (ignoring qualifiers at the top level)
7270   const Type *lhptee, *rhptee;
7271   Qualifiers lhq, rhq;
7272   std::tie(lhptee, lhq) =
7273       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7274   std::tie(rhptee, rhq) =
7275       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7276 
7277   Sema::AssignConvertType ConvTy = Sema::Compatible;
7278 
7279   // C99 6.5.16.1p1: This following citation is common to constraints
7280   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7281   // qualifiers of the type *pointed to* by the right;
7282 
7283   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7284   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7285       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7286     // Ignore lifetime for further calculation.
7287     lhq.removeObjCLifetime();
7288     rhq.removeObjCLifetime();
7289   }
7290 
7291   if (!lhq.compatiblyIncludes(rhq)) {
7292     // Treat address-space mismatches as fatal.  TODO: address subspaces
7293     if (!lhq.isAddressSpaceSupersetOf(rhq))
7294       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7295 
7296     // It's okay to add or remove GC or lifetime qualifiers when converting to
7297     // and from void*.
7298     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7299                         .compatiblyIncludes(
7300                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7301              && (lhptee->isVoidType() || rhptee->isVoidType()))
7302       ; // keep old
7303 
7304     // Treat lifetime mismatches as fatal.
7305     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7306       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7307 
7308     // For GCC/MS compatibility, other qualifier mismatches are treated
7309     // as still compatible in C.
7310     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7311   }
7312 
7313   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7314   // incomplete type and the other is a pointer to a qualified or unqualified
7315   // version of void...
7316   if (lhptee->isVoidType()) {
7317     if (rhptee->isIncompleteOrObjectType())
7318       return ConvTy;
7319 
7320     // As an extension, we allow cast to/from void* to function pointer.
7321     assert(rhptee->isFunctionType());
7322     return Sema::FunctionVoidPointer;
7323   }
7324 
7325   if (rhptee->isVoidType()) {
7326     if (lhptee->isIncompleteOrObjectType())
7327       return ConvTy;
7328 
7329     // As an extension, we allow cast to/from void* to function pointer.
7330     assert(lhptee->isFunctionType());
7331     return Sema::FunctionVoidPointer;
7332   }
7333 
7334   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7335   // unqualified versions of compatible types, ...
7336   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7337   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7338     // Check if the pointee types are compatible ignoring the sign.
7339     // We explicitly check for char so that we catch "char" vs
7340     // "unsigned char" on systems where "char" is unsigned.
7341     if (lhptee->isCharType())
7342       ltrans = S.Context.UnsignedCharTy;
7343     else if (lhptee->hasSignedIntegerRepresentation())
7344       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7345 
7346     if (rhptee->isCharType())
7347       rtrans = S.Context.UnsignedCharTy;
7348     else if (rhptee->hasSignedIntegerRepresentation())
7349       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7350 
7351     if (ltrans == rtrans) {
7352       // Types are compatible ignoring the sign. Qualifier incompatibility
7353       // takes priority over sign incompatibility because the sign
7354       // warning can be disabled.
7355       if (ConvTy != Sema::Compatible)
7356         return ConvTy;
7357 
7358       return Sema::IncompatiblePointerSign;
7359     }
7360 
7361     // If we are a multi-level pointer, it's possible that our issue is simply
7362     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7363     // the eventual target type is the same and the pointers have the same
7364     // level of indirection, this must be the issue.
7365     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7366       do {
7367         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7368         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7369       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7370 
7371       if (lhptee == rhptee)
7372         return Sema::IncompatibleNestedPointerQualifiers;
7373     }
7374 
7375     // General pointer incompatibility takes priority over qualifiers.
7376     return Sema::IncompatiblePointer;
7377   }
7378   if (!S.getLangOpts().CPlusPlus &&
7379       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7380     return Sema::IncompatiblePointer;
7381   return ConvTy;
7382 }
7383 
7384 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7385 /// block pointer types are compatible or whether a block and normal pointer
7386 /// are compatible. It is more restrict than comparing two function pointer
7387 // types.
7388 static Sema::AssignConvertType
7389 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7390                                     QualType RHSType) {
7391   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7392   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7393 
7394   QualType lhptee, rhptee;
7395 
7396   // get the "pointed to" type (ignoring qualifiers at the top level)
7397   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7398   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7399 
7400   // In C++, the types have to match exactly.
7401   if (S.getLangOpts().CPlusPlus)
7402     return Sema::IncompatibleBlockPointer;
7403 
7404   Sema::AssignConvertType ConvTy = Sema::Compatible;
7405 
7406   // For blocks we enforce that qualifiers are identical.
7407   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7408     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7409 
7410   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7411     return Sema::IncompatibleBlockPointer;
7412 
7413   return ConvTy;
7414 }
7415 
7416 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7417 /// for assignment compatibility.
7418 static Sema::AssignConvertType
7419 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7420                                    QualType RHSType) {
7421   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7422   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7423 
7424   if (LHSType->isObjCBuiltinType()) {
7425     // Class is not compatible with ObjC object pointers.
7426     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7427         !RHSType->isObjCQualifiedClassType())
7428       return Sema::IncompatiblePointer;
7429     return Sema::Compatible;
7430   }
7431   if (RHSType->isObjCBuiltinType()) {
7432     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7433         !LHSType->isObjCQualifiedClassType())
7434       return Sema::IncompatiblePointer;
7435     return Sema::Compatible;
7436   }
7437   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7438   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7439 
7440   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7441       // make an exception for id<P>
7442       !LHSType->isObjCQualifiedIdType())
7443     return Sema::CompatiblePointerDiscardsQualifiers;
7444 
7445   if (S.Context.typesAreCompatible(LHSType, RHSType))
7446     return Sema::Compatible;
7447   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7448     return Sema::IncompatibleObjCQualifiedId;
7449   return Sema::IncompatiblePointer;
7450 }
7451 
7452 Sema::AssignConvertType
7453 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7454                                  QualType LHSType, QualType RHSType) {
7455   // Fake up an opaque expression.  We don't actually care about what
7456   // cast operations are required, so if CheckAssignmentConstraints
7457   // adds casts to this they'll be wasted, but fortunately that doesn't
7458   // usually happen on valid code.
7459   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7460   ExprResult RHSPtr = &RHSExpr;
7461   CastKind K = CK_Invalid;
7462 
7463   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7464 }
7465 
7466 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7467 /// has code to accommodate several GCC extensions when type checking
7468 /// pointers. Here are some objectionable examples that GCC considers warnings:
7469 ///
7470 ///  int a, *pint;
7471 ///  short *pshort;
7472 ///  struct foo *pfoo;
7473 ///
7474 ///  pint = pshort; // warning: assignment from incompatible pointer type
7475 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7476 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7477 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7478 ///
7479 /// As a result, the code for dealing with pointers is more complex than the
7480 /// C99 spec dictates.
7481 ///
7482 /// Sets 'Kind' for any result kind except Incompatible.
7483 Sema::AssignConvertType
7484 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7485                                  CastKind &Kind, bool ConvertRHS) {
7486   QualType RHSType = RHS.get()->getType();
7487   QualType OrigLHSType = LHSType;
7488 
7489   // Get canonical types.  We're not formatting these types, just comparing
7490   // them.
7491   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7492   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7493 
7494   // Common case: no conversion required.
7495   if (LHSType == RHSType) {
7496     Kind = CK_NoOp;
7497     return Compatible;
7498   }
7499 
7500   // If we have an atomic type, try a non-atomic assignment, then just add an
7501   // atomic qualification step.
7502   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7503     Sema::AssignConvertType result =
7504       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7505     if (result != Compatible)
7506       return result;
7507     if (Kind != CK_NoOp && ConvertRHS)
7508       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7509     Kind = CK_NonAtomicToAtomic;
7510     return Compatible;
7511   }
7512 
7513   // If the left-hand side is a reference type, then we are in a
7514   // (rare!) case where we've allowed the use of references in C,
7515   // e.g., as a parameter type in a built-in function. In this case,
7516   // just make sure that the type referenced is compatible with the
7517   // right-hand side type. The caller is responsible for adjusting
7518   // LHSType so that the resulting expression does not have reference
7519   // type.
7520   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7521     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7522       Kind = CK_LValueBitCast;
7523       return Compatible;
7524     }
7525     return Incompatible;
7526   }
7527 
7528   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7529   // to the same ExtVector type.
7530   if (LHSType->isExtVectorType()) {
7531     if (RHSType->isExtVectorType())
7532       return Incompatible;
7533     if (RHSType->isArithmeticType()) {
7534       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7535       if (ConvertRHS)
7536         RHS = prepareVectorSplat(LHSType, RHS.get());
7537       Kind = CK_VectorSplat;
7538       return Compatible;
7539     }
7540   }
7541 
7542   // Conversions to or from vector type.
7543   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7544     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7545       // Allow assignments of an AltiVec vector type to an equivalent GCC
7546       // vector type and vice versa
7547       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7548         Kind = CK_BitCast;
7549         return Compatible;
7550       }
7551 
7552       // If we are allowing lax vector conversions, and LHS and RHS are both
7553       // vectors, the total size only needs to be the same. This is a bitcast;
7554       // no bits are changed but the result type is different.
7555       if (isLaxVectorConversion(RHSType, LHSType)) {
7556         Kind = CK_BitCast;
7557         return IncompatibleVectors;
7558       }
7559     }
7560 
7561     // When the RHS comes from another lax conversion (e.g. binops between
7562     // scalars and vectors) the result is canonicalized as a vector. When the
7563     // LHS is also a vector, the lax is allowed by the condition above. Handle
7564     // the case where LHS is a scalar.
7565     if (LHSType->isScalarType()) {
7566       const VectorType *VecType = RHSType->getAs<VectorType>();
7567       if (VecType && VecType->getNumElements() == 1 &&
7568           isLaxVectorConversion(RHSType, LHSType)) {
7569         ExprResult *VecExpr = &RHS;
7570         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7571         Kind = CK_BitCast;
7572         return Compatible;
7573       }
7574     }
7575 
7576     return Incompatible;
7577   }
7578 
7579   // Diagnose attempts to convert between __float128 and long double where
7580   // such conversions currently can't be handled.
7581   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7582     return Incompatible;
7583 
7584   // Arithmetic conversions.
7585   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7586       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7587     if (ConvertRHS)
7588       Kind = PrepareScalarCast(RHS, LHSType);
7589     return Compatible;
7590   }
7591 
7592   // Conversions to normal pointers.
7593   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7594     // U* -> T*
7595     if (isa<PointerType>(RHSType)) {
7596       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7597       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7598       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7599       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7600     }
7601 
7602     // int -> T*
7603     if (RHSType->isIntegerType()) {
7604       Kind = CK_IntegralToPointer; // FIXME: null?
7605       return IntToPointer;
7606     }
7607 
7608     // C pointers are not compatible with ObjC object pointers,
7609     // with two exceptions:
7610     if (isa<ObjCObjectPointerType>(RHSType)) {
7611       //  - conversions to void*
7612       if (LHSPointer->getPointeeType()->isVoidType()) {
7613         Kind = CK_BitCast;
7614         return Compatible;
7615       }
7616 
7617       //  - conversions from 'Class' to the redefinition type
7618       if (RHSType->isObjCClassType() &&
7619           Context.hasSameType(LHSType,
7620                               Context.getObjCClassRedefinitionType())) {
7621         Kind = CK_BitCast;
7622         return Compatible;
7623       }
7624 
7625       Kind = CK_BitCast;
7626       return IncompatiblePointer;
7627     }
7628 
7629     // U^ -> void*
7630     if (RHSType->getAs<BlockPointerType>()) {
7631       if (LHSPointer->getPointeeType()->isVoidType()) {
7632         Kind = CK_BitCast;
7633         return Compatible;
7634       }
7635     }
7636 
7637     return Incompatible;
7638   }
7639 
7640   // Conversions to block pointers.
7641   if (isa<BlockPointerType>(LHSType)) {
7642     // U^ -> T^
7643     if (RHSType->isBlockPointerType()) {
7644       Kind = CK_BitCast;
7645       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7646     }
7647 
7648     // int or null -> T^
7649     if (RHSType->isIntegerType()) {
7650       Kind = CK_IntegralToPointer; // FIXME: null
7651       return IntToBlockPointer;
7652     }
7653 
7654     // id -> T^
7655     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7656       Kind = CK_AnyPointerToBlockPointerCast;
7657       return Compatible;
7658     }
7659 
7660     // void* -> T^
7661     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7662       if (RHSPT->getPointeeType()->isVoidType()) {
7663         Kind = CK_AnyPointerToBlockPointerCast;
7664         return Compatible;
7665       }
7666 
7667     return Incompatible;
7668   }
7669 
7670   // Conversions to Objective-C pointers.
7671   if (isa<ObjCObjectPointerType>(LHSType)) {
7672     // A* -> B*
7673     if (RHSType->isObjCObjectPointerType()) {
7674       Kind = CK_BitCast;
7675       Sema::AssignConvertType result =
7676         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7677       if (getLangOpts().ObjCAutoRefCount &&
7678           result == Compatible &&
7679           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7680         result = IncompatibleObjCWeakRef;
7681       return result;
7682     }
7683 
7684     // int or null -> A*
7685     if (RHSType->isIntegerType()) {
7686       Kind = CK_IntegralToPointer; // FIXME: null
7687       return IntToPointer;
7688     }
7689 
7690     // In general, C pointers are not compatible with ObjC object pointers,
7691     // with two exceptions:
7692     if (isa<PointerType>(RHSType)) {
7693       Kind = CK_CPointerToObjCPointerCast;
7694 
7695       //  - conversions from 'void*'
7696       if (RHSType->isVoidPointerType()) {
7697         return Compatible;
7698       }
7699 
7700       //  - conversions to 'Class' from its redefinition type
7701       if (LHSType->isObjCClassType() &&
7702           Context.hasSameType(RHSType,
7703                               Context.getObjCClassRedefinitionType())) {
7704         return Compatible;
7705       }
7706 
7707       return IncompatiblePointer;
7708     }
7709 
7710     // Only under strict condition T^ is compatible with an Objective-C pointer.
7711     if (RHSType->isBlockPointerType() &&
7712         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7713       if (ConvertRHS)
7714         maybeExtendBlockObject(RHS);
7715       Kind = CK_BlockPointerToObjCPointerCast;
7716       return Compatible;
7717     }
7718 
7719     return Incompatible;
7720   }
7721 
7722   // Conversions from pointers that are not covered by the above.
7723   if (isa<PointerType>(RHSType)) {
7724     // T* -> _Bool
7725     if (LHSType == Context.BoolTy) {
7726       Kind = CK_PointerToBoolean;
7727       return Compatible;
7728     }
7729 
7730     // T* -> int
7731     if (LHSType->isIntegerType()) {
7732       Kind = CK_PointerToIntegral;
7733       return PointerToInt;
7734     }
7735 
7736     return Incompatible;
7737   }
7738 
7739   // Conversions from Objective-C pointers that are not covered by the above.
7740   if (isa<ObjCObjectPointerType>(RHSType)) {
7741     // T* -> _Bool
7742     if (LHSType == Context.BoolTy) {
7743       Kind = CK_PointerToBoolean;
7744       return Compatible;
7745     }
7746 
7747     // T* -> int
7748     if (LHSType->isIntegerType()) {
7749       Kind = CK_PointerToIntegral;
7750       return PointerToInt;
7751     }
7752 
7753     return Incompatible;
7754   }
7755 
7756   // struct A -> struct B
7757   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7758     if (Context.typesAreCompatible(LHSType, RHSType)) {
7759       Kind = CK_NoOp;
7760       return Compatible;
7761     }
7762   }
7763 
7764   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7765     Kind = CK_IntToOCLSampler;
7766     return Compatible;
7767   }
7768 
7769   return Incompatible;
7770 }
7771 
7772 /// \brief Constructs a transparent union from an expression that is
7773 /// used to initialize the transparent union.
7774 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7775                                       ExprResult &EResult, QualType UnionType,
7776                                       FieldDecl *Field) {
7777   // Build an initializer list that designates the appropriate member
7778   // of the transparent union.
7779   Expr *E = EResult.get();
7780   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7781                                                    E, SourceLocation());
7782   Initializer->setType(UnionType);
7783   Initializer->setInitializedFieldInUnion(Field);
7784 
7785   // Build a compound literal constructing a value of the transparent
7786   // union type from this initializer list.
7787   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7788   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7789                                         VK_RValue, Initializer, false);
7790 }
7791 
7792 Sema::AssignConvertType
7793 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7794                                                ExprResult &RHS) {
7795   QualType RHSType = RHS.get()->getType();
7796 
7797   // If the ArgType is a Union type, we want to handle a potential
7798   // transparent_union GCC extension.
7799   const RecordType *UT = ArgType->getAsUnionType();
7800   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7801     return Incompatible;
7802 
7803   // The field to initialize within the transparent union.
7804   RecordDecl *UD = UT->getDecl();
7805   FieldDecl *InitField = nullptr;
7806   // It's compatible if the expression matches any of the fields.
7807   for (auto *it : UD->fields()) {
7808     if (it->getType()->isPointerType()) {
7809       // If the transparent union contains a pointer type, we allow:
7810       // 1) void pointer
7811       // 2) null pointer constant
7812       if (RHSType->isPointerType())
7813         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7814           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7815           InitField = it;
7816           break;
7817         }
7818 
7819       if (RHS.get()->isNullPointerConstant(Context,
7820                                            Expr::NPC_ValueDependentIsNull)) {
7821         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7822                                 CK_NullToPointer);
7823         InitField = it;
7824         break;
7825       }
7826     }
7827 
7828     CastKind Kind = CK_Invalid;
7829     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7830           == Compatible) {
7831       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7832       InitField = it;
7833       break;
7834     }
7835   }
7836 
7837   if (!InitField)
7838     return Incompatible;
7839 
7840   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7841   return Compatible;
7842 }
7843 
7844 Sema::AssignConvertType
7845 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7846                                        bool Diagnose,
7847                                        bool DiagnoseCFAudited,
7848                                        bool ConvertRHS) {
7849   // We need to be able to tell the caller whether we diagnosed a problem, if
7850   // they ask us to issue diagnostics.
7851   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7852 
7853   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7854   // we can't avoid *all* modifications at the moment, so we need some somewhere
7855   // to put the updated value.
7856   ExprResult LocalRHS = CallerRHS;
7857   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7858 
7859   if (getLangOpts().CPlusPlus) {
7860     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7861       // C++ 5.17p3: If the left operand is not of class type, the
7862       // expression is implicitly converted (C++ 4) to the
7863       // cv-unqualified type of the left operand.
7864       QualType RHSType = RHS.get()->getType();
7865       if (Diagnose) {
7866         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7867                                         AA_Assigning);
7868       } else {
7869         ImplicitConversionSequence ICS =
7870             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7871                                   /*SuppressUserConversions=*/false,
7872                                   /*AllowExplicit=*/false,
7873                                   /*InOverloadResolution=*/false,
7874                                   /*CStyle=*/false,
7875                                   /*AllowObjCWritebackConversion=*/false);
7876         if (ICS.isFailure())
7877           return Incompatible;
7878         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7879                                         ICS, AA_Assigning);
7880       }
7881       if (RHS.isInvalid())
7882         return Incompatible;
7883       Sema::AssignConvertType result = Compatible;
7884       if (getLangOpts().ObjCAutoRefCount &&
7885           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7886         result = IncompatibleObjCWeakRef;
7887       return result;
7888     }
7889 
7890     // FIXME: Currently, we fall through and treat C++ classes like C
7891     // structures.
7892     // FIXME: We also fall through for atomics; not sure what should
7893     // happen there, though.
7894   } else if (RHS.get()->getType() == Context.OverloadTy) {
7895     // As a set of extensions to C, we support overloading on functions. These
7896     // functions need to be resolved here.
7897     DeclAccessPair DAP;
7898     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7899             RHS.get(), LHSType, /*Complain=*/false, DAP))
7900       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7901     else
7902       return Incompatible;
7903   }
7904 
7905   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7906   // a null pointer constant.
7907   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7908        LHSType->isBlockPointerType()) &&
7909       RHS.get()->isNullPointerConstant(Context,
7910                                        Expr::NPC_ValueDependentIsNull)) {
7911     if (Diagnose || ConvertRHS) {
7912       CastKind Kind;
7913       CXXCastPath Path;
7914       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7915                              /*IgnoreBaseAccess=*/false, Diagnose);
7916       if (ConvertRHS)
7917         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7918     }
7919     return Compatible;
7920   }
7921 
7922   // This check seems unnatural, however it is necessary to ensure the proper
7923   // conversion of functions/arrays. If the conversion were done for all
7924   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7925   // expressions that suppress this implicit conversion (&, sizeof).
7926   //
7927   // Suppress this for references: C++ 8.5.3p5.
7928   if (!LHSType->isReferenceType()) {
7929     // FIXME: We potentially allocate here even if ConvertRHS is false.
7930     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7931     if (RHS.isInvalid())
7932       return Incompatible;
7933   }
7934 
7935   Expr *PRE = RHS.get()->IgnoreParenCasts();
7936   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7937     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7938     if (PDecl && !PDecl->hasDefinition()) {
7939       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7940       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7941     }
7942   }
7943 
7944   CastKind Kind = CK_Invalid;
7945   Sema::AssignConvertType result =
7946     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7947 
7948   // C99 6.5.16.1p2: The value of the right operand is converted to the
7949   // type of the assignment expression.
7950   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7951   // so that we can use references in built-in functions even in C.
7952   // The getNonReferenceType() call makes sure that the resulting expression
7953   // does not have reference type.
7954   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7955     QualType Ty = LHSType.getNonLValueExprType(Context);
7956     Expr *E = RHS.get();
7957 
7958     // Check for various Objective-C errors. If we are not reporting
7959     // diagnostics and just checking for errors, e.g., during overload
7960     // resolution, return Incompatible to indicate the failure.
7961     if (getLangOpts().ObjCAutoRefCount &&
7962         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7963                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7964       if (!Diagnose)
7965         return Incompatible;
7966     }
7967     if (getLangOpts().ObjC1 &&
7968         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7969                                            E->getType(), E, Diagnose) ||
7970          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7971       if (!Diagnose)
7972         return Incompatible;
7973       // Replace the expression with a corrected version and continue so we
7974       // can find further errors.
7975       RHS = E;
7976       return Compatible;
7977     }
7978 
7979     if (ConvertRHS)
7980       RHS = ImpCastExprToType(E, Ty, Kind);
7981   }
7982   return result;
7983 }
7984 
7985 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7986                                ExprResult &RHS) {
7987   Diag(Loc, diag::err_typecheck_invalid_operands)
7988     << LHS.get()->getType() << RHS.get()->getType()
7989     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7990   return QualType();
7991 }
7992 
7993 /// Try to convert a value of non-vector type to a vector type by converting
7994 /// the type to the element type of the vector and then performing a splat.
7995 /// If the language is OpenCL, we only use conversions that promote scalar
7996 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7997 /// for float->int.
7998 ///
7999 /// \param scalar - if non-null, actually perform the conversions
8000 /// \return true if the operation fails (but without diagnosing the failure)
8001 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8002                                      QualType scalarTy,
8003                                      QualType vectorEltTy,
8004                                      QualType vectorTy) {
8005   // The conversion to apply to the scalar before splatting it,
8006   // if necessary.
8007   CastKind scalarCast = CK_Invalid;
8008 
8009   if (vectorEltTy->isIntegralType(S.Context)) {
8010     if (!scalarTy->isIntegralType(S.Context))
8011       return true;
8012     if (S.getLangOpts().OpenCL &&
8013         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8014       return true;
8015     scalarCast = CK_IntegralCast;
8016   } else if (vectorEltTy->isRealFloatingType()) {
8017     if (scalarTy->isRealFloatingType()) {
8018       if (S.getLangOpts().OpenCL &&
8019           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8020         return true;
8021       scalarCast = CK_FloatingCast;
8022     }
8023     else if (scalarTy->isIntegralType(S.Context))
8024       scalarCast = CK_IntegralToFloating;
8025     else
8026       return true;
8027   } else {
8028     return true;
8029   }
8030 
8031   // Adjust scalar if desired.
8032   if (scalar) {
8033     if (scalarCast != CK_Invalid)
8034       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8035     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8036   }
8037   return false;
8038 }
8039 
8040 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8041                                    SourceLocation Loc, bool IsCompAssign,
8042                                    bool AllowBothBool,
8043                                    bool AllowBoolConversions) {
8044   if (!IsCompAssign) {
8045     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8046     if (LHS.isInvalid())
8047       return QualType();
8048   }
8049   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8050   if (RHS.isInvalid())
8051     return QualType();
8052 
8053   // For conversion purposes, we ignore any qualifiers.
8054   // For example, "const float" and "float" are equivalent.
8055   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8056   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8057 
8058   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8059   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8060   assert(LHSVecType || RHSVecType);
8061 
8062   // AltiVec-style "vector bool op vector bool" combinations are allowed
8063   // for some operators but not others.
8064   if (!AllowBothBool &&
8065       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8066       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8067     return InvalidOperands(Loc, LHS, RHS);
8068 
8069   // If the vector types are identical, return.
8070   if (Context.hasSameType(LHSType, RHSType))
8071     return LHSType;
8072 
8073   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8074   if (LHSVecType && RHSVecType &&
8075       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8076     if (isa<ExtVectorType>(LHSVecType)) {
8077       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8078       return LHSType;
8079     }
8080 
8081     if (!IsCompAssign)
8082       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8083     return RHSType;
8084   }
8085 
8086   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8087   // can be mixed, with the result being the non-bool type.  The non-bool
8088   // operand must have integer element type.
8089   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8090       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8091       (Context.getTypeSize(LHSVecType->getElementType()) ==
8092        Context.getTypeSize(RHSVecType->getElementType()))) {
8093     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8094         LHSVecType->getElementType()->isIntegerType() &&
8095         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8096       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8097       return LHSType;
8098     }
8099     if (!IsCompAssign &&
8100         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8101         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8102         RHSVecType->getElementType()->isIntegerType()) {
8103       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8104       return RHSType;
8105     }
8106   }
8107 
8108   // If there's an ext-vector type and a scalar, try to convert the scalar to
8109   // the vector element type and splat.
8110   // FIXME: this should also work for regular vector types as supported in GCC.
8111   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8112     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8113                                   LHSVecType->getElementType(), LHSType))
8114       return LHSType;
8115   }
8116   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8117     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8118                                   LHSType, RHSVecType->getElementType(),
8119                                   RHSType))
8120       return RHSType;
8121   }
8122 
8123   // FIXME: The code below also handles convertion between vectors and
8124   // non-scalars, we should break this down into fine grained specific checks
8125   // and emit proper diagnostics.
8126   QualType VecType = LHSVecType ? LHSType : RHSType;
8127   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8128   QualType OtherType = LHSVecType ? RHSType : LHSType;
8129   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8130   if (isLaxVectorConversion(OtherType, VecType)) {
8131     // If we're allowing lax vector conversions, only the total (data) size
8132     // needs to be the same. For non compound assignment, if one of the types is
8133     // scalar, the result is always the vector type.
8134     if (!IsCompAssign) {
8135       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8136       return VecType;
8137     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8138     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8139     // type. Note that this is already done by non-compound assignments in
8140     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8141     // <1 x T> -> T. The result is also a vector type.
8142     } else if (OtherType->isExtVectorType() ||
8143                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8144       ExprResult *RHSExpr = &RHS;
8145       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8146       return VecType;
8147     }
8148   }
8149 
8150   // Okay, the expression is invalid.
8151 
8152   // If there's a non-vector, non-real operand, diagnose that.
8153   if ((!RHSVecType && !RHSType->isRealType()) ||
8154       (!LHSVecType && !LHSType->isRealType())) {
8155     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8156       << LHSType << RHSType
8157       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8158     return QualType();
8159   }
8160 
8161   // OpenCL V1.1 6.2.6.p1:
8162   // If the operands are of more than one vector type, then an error shall
8163   // occur. Implicit conversions between vector types are not permitted, per
8164   // section 6.2.1.
8165   if (getLangOpts().OpenCL &&
8166       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8167       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8168     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8169                                                            << RHSType;
8170     return QualType();
8171   }
8172 
8173   // Otherwise, use the generic diagnostic.
8174   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8175     << LHSType << RHSType
8176     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8177   return QualType();
8178 }
8179 
8180 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8181 // expression.  These are mainly cases where the null pointer is used as an
8182 // integer instead of a pointer.
8183 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8184                                 SourceLocation Loc, bool IsCompare) {
8185   // The canonical way to check for a GNU null is with isNullPointerConstant,
8186   // but we use a bit of a hack here for speed; this is a relatively
8187   // hot path, and isNullPointerConstant is slow.
8188   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8189   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8190 
8191   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8192 
8193   // Avoid analyzing cases where the result will either be invalid (and
8194   // diagnosed as such) or entirely valid and not something to warn about.
8195   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8196       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8197     return;
8198 
8199   // Comparison operations would not make sense with a null pointer no matter
8200   // what the other expression is.
8201   if (!IsCompare) {
8202     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8203         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8204         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8205     return;
8206   }
8207 
8208   // The rest of the operations only make sense with a null pointer
8209   // if the other expression is a pointer.
8210   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8211       NonNullType->canDecayToPointerType())
8212     return;
8213 
8214   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8215       << LHSNull /* LHS is NULL */ << NonNullType
8216       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8217 }
8218 
8219 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8220                                                ExprResult &RHS,
8221                                                SourceLocation Loc, bool IsDiv) {
8222   // Check for division/remainder by zero.
8223   llvm::APSInt RHSValue;
8224   if (!RHS.get()->isValueDependent() &&
8225       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8226     S.DiagRuntimeBehavior(Loc, RHS.get(),
8227                           S.PDiag(diag::warn_remainder_division_by_zero)
8228                             << IsDiv << RHS.get()->getSourceRange());
8229 }
8230 
8231 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8232                                            SourceLocation Loc,
8233                                            bool IsCompAssign, bool IsDiv) {
8234   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8235 
8236   if (LHS.get()->getType()->isVectorType() ||
8237       RHS.get()->getType()->isVectorType())
8238     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8239                                /*AllowBothBool*/getLangOpts().AltiVec,
8240                                /*AllowBoolConversions*/false);
8241 
8242   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8243   if (LHS.isInvalid() || RHS.isInvalid())
8244     return QualType();
8245 
8246 
8247   if (compType.isNull() || !compType->isArithmeticType())
8248     return InvalidOperands(Loc, LHS, RHS);
8249   if (IsDiv)
8250     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8251   return compType;
8252 }
8253 
8254 QualType Sema::CheckRemainderOperands(
8255   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8256   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8257 
8258   if (LHS.get()->getType()->isVectorType() ||
8259       RHS.get()->getType()->isVectorType()) {
8260     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8261         RHS.get()->getType()->hasIntegerRepresentation())
8262       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8263                                  /*AllowBothBool*/getLangOpts().AltiVec,
8264                                  /*AllowBoolConversions*/false);
8265     return InvalidOperands(Loc, LHS, RHS);
8266   }
8267 
8268   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8269   if (LHS.isInvalid() || RHS.isInvalid())
8270     return QualType();
8271 
8272   if (compType.isNull() || !compType->isIntegerType())
8273     return InvalidOperands(Loc, LHS, RHS);
8274   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8275   return compType;
8276 }
8277 
8278 /// \brief Diagnose invalid arithmetic on two void pointers.
8279 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8280                                                 Expr *LHSExpr, Expr *RHSExpr) {
8281   S.Diag(Loc, S.getLangOpts().CPlusPlus
8282                 ? diag::err_typecheck_pointer_arith_void_type
8283                 : diag::ext_gnu_void_ptr)
8284     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8285                             << RHSExpr->getSourceRange();
8286 }
8287 
8288 /// \brief Diagnose invalid arithmetic on a void pointer.
8289 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8290                                             Expr *Pointer) {
8291   S.Diag(Loc, S.getLangOpts().CPlusPlus
8292                 ? diag::err_typecheck_pointer_arith_void_type
8293                 : diag::ext_gnu_void_ptr)
8294     << 0 /* one pointer */ << Pointer->getSourceRange();
8295 }
8296 
8297 /// \brief Diagnose invalid arithmetic on two function pointers.
8298 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8299                                                     Expr *LHS, Expr *RHS) {
8300   assert(LHS->getType()->isAnyPointerType());
8301   assert(RHS->getType()->isAnyPointerType());
8302   S.Diag(Loc, S.getLangOpts().CPlusPlus
8303                 ? diag::err_typecheck_pointer_arith_function_type
8304                 : diag::ext_gnu_ptr_func_arith)
8305     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8306     // We only show the second type if it differs from the first.
8307     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8308                                                    RHS->getType())
8309     << RHS->getType()->getPointeeType()
8310     << LHS->getSourceRange() << RHS->getSourceRange();
8311 }
8312 
8313 /// \brief Diagnose invalid arithmetic on a function pointer.
8314 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8315                                                 Expr *Pointer) {
8316   assert(Pointer->getType()->isAnyPointerType());
8317   S.Diag(Loc, S.getLangOpts().CPlusPlus
8318                 ? diag::err_typecheck_pointer_arith_function_type
8319                 : diag::ext_gnu_ptr_func_arith)
8320     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8321     << 0 /* one pointer, so only one type */
8322     << Pointer->getSourceRange();
8323 }
8324 
8325 /// \brief Emit error if Operand is incomplete pointer type
8326 ///
8327 /// \returns True if pointer has incomplete type
8328 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8329                                                  Expr *Operand) {
8330   QualType ResType = Operand->getType();
8331   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8332     ResType = ResAtomicType->getValueType();
8333 
8334   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8335   QualType PointeeTy = ResType->getPointeeType();
8336   return S.RequireCompleteType(Loc, PointeeTy,
8337                                diag::err_typecheck_arithmetic_incomplete_type,
8338                                PointeeTy, Operand->getSourceRange());
8339 }
8340 
8341 /// \brief Check the validity of an arithmetic pointer operand.
8342 ///
8343 /// If the operand has pointer type, this code will check for pointer types
8344 /// which are invalid in arithmetic operations. These will be diagnosed
8345 /// appropriately, including whether or not the use is supported as an
8346 /// extension.
8347 ///
8348 /// \returns True when the operand is valid to use (even if as an extension).
8349 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8350                                             Expr *Operand) {
8351   QualType ResType = Operand->getType();
8352   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8353     ResType = ResAtomicType->getValueType();
8354 
8355   if (!ResType->isAnyPointerType()) return true;
8356 
8357   QualType PointeeTy = ResType->getPointeeType();
8358   if (PointeeTy->isVoidType()) {
8359     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8360     return !S.getLangOpts().CPlusPlus;
8361   }
8362   if (PointeeTy->isFunctionType()) {
8363     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8364     return !S.getLangOpts().CPlusPlus;
8365   }
8366 
8367   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8368 
8369   return true;
8370 }
8371 
8372 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8373 /// operands.
8374 ///
8375 /// This routine will diagnose any invalid arithmetic on pointer operands much
8376 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8377 /// for emitting a single diagnostic even for operations where both LHS and RHS
8378 /// are (potentially problematic) pointers.
8379 ///
8380 /// \returns True when the operand is valid to use (even if as an extension).
8381 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8382                                                 Expr *LHSExpr, Expr *RHSExpr) {
8383   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8384   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8385   if (!isLHSPointer && !isRHSPointer) return true;
8386 
8387   QualType LHSPointeeTy, RHSPointeeTy;
8388   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8389   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8390 
8391   // if both are pointers check if operation is valid wrt address spaces
8392   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8393     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8394     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8395     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8396       S.Diag(Loc,
8397              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8398           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8399           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8400       return false;
8401     }
8402   }
8403 
8404   // Check for arithmetic on pointers to incomplete types.
8405   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8406   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8407   if (isLHSVoidPtr || isRHSVoidPtr) {
8408     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8409     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8410     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8411 
8412     return !S.getLangOpts().CPlusPlus;
8413   }
8414 
8415   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8416   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8417   if (isLHSFuncPtr || isRHSFuncPtr) {
8418     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8419     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8420                                                                 RHSExpr);
8421     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8422 
8423     return !S.getLangOpts().CPlusPlus;
8424   }
8425 
8426   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8427     return false;
8428   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8429     return false;
8430 
8431   return true;
8432 }
8433 
8434 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8435 /// literal.
8436 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8437                                   Expr *LHSExpr, Expr *RHSExpr) {
8438   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8439   Expr* IndexExpr = RHSExpr;
8440   if (!StrExpr) {
8441     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8442     IndexExpr = LHSExpr;
8443   }
8444 
8445   bool IsStringPlusInt = StrExpr &&
8446       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8447   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8448     return;
8449 
8450   llvm::APSInt index;
8451   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8452     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8453     if (index.isNonNegative() &&
8454         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8455                               index.isUnsigned()))
8456       return;
8457   }
8458 
8459   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8460   Self.Diag(OpLoc, diag::warn_string_plus_int)
8461       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8462 
8463   // Only print a fixit for "str" + int, not for int + "str".
8464   if (IndexExpr == RHSExpr) {
8465     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8466     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8467         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8468         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8469         << FixItHint::CreateInsertion(EndLoc, "]");
8470   } else
8471     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8472 }
8473 
8474 /// \brief Emit a warning when adding a char literal to a string.
8475 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8476                                    Expr *LHSExpr, Expr *RHSExpr) {
8477   const Expr *StringRefExpr = LHSExpr;
8478   const CharacterLiteral *CharExpr =
8479       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8480 
8481   if (!CharExpr) {
8482     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8483     StringRefExpr = RHSExpr;
8484   }
8485 
8486   if (!CharExpr || !StringRefExpr)
8487     return;
8488 
8489   const QualType StringType = StringRefExpr->getType();
8490 
8491   // Return if not a PointerType.
8492   if (!StringType->isAnyPointerType())
8493     return;
8494 
8495   // Return if not a CharacterType.
8496   if (!StringType->getPointeeType()->isAnyCharacterType())
8497     return;
8498 
8499   ASTContext &Ctx = Self.getASTContext();
8500   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8501 
8502   const QualType CharType = CharExpr->getType();
8503   if (!CharType->isAnyCharacterType() &&
8504       CharType->isIntegerType() &&
8505       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8506     Self.Diag(OpLoc, diag::warn_string_plus_char)
8507         << DiagRange << Ctx.CharTy;
8508   } else {
8509     Self.Diag(OpLoc, diag::warn_string_plus_char)
8510         << DiagRange << CharExpr->getType();
8511   }
8512 
8513   // Only print a fixit for str + char, not for char + str.
8514   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8515     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8516     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8517         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8518         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8519         << FixItHint::CreateInsertion(EndLoc, "]");
8520   } else {
8521     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8522   }
8523 }
8524 
8525 /// \brief Emit error when two pointers are incompatible.
8526 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8527                                            Expr *LHSExpr, Expr *RHSExpr) {
8528   assert(LHSExpr->getType()->isAnyPointerType());
8529   assert(RHSExpr->getType()->isAnyPointerType());
8530   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8531     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8532     << RHSExpr->getSourceRange();
8533 }
8534 
8535 // C99 6.5.6
8536 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8537                                      SourceLocation Loc, BinaryOperatorKind Opc,
8538                                      QualType* CompLHSTy) {
8539   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8540 
8541   if (LHS.get()->getType()->isVectorType() ||
8542       RHS.get()->getType()->isVectorType()) {
8543     QualType compType = CheckVectorOperands(
8544         LHS, RHS, Loc, CompLHSTy,
8545         /*AllowBothBool*/getLangOpts().AltiVec,
8546         /*AllowBoolConversions*/getLangOpts().ZVector);
8547     if (CompLHSTy) *CompLHSTy = compType;
8548     return compType;
8549   }
8550 
8551   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8552   if (LHS.isInvalid() || RHS.isInvalid())
8553     return QualType();
8554 
8555   // Diagnose "string literal" '+' int and string '+' "char literal".
8556   if (Opc == BO_Add) {
8557     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8558     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8559   }
8560 
8561   // handle the common case first (both operands are arithmetic).
8562   if (!compType.isNull() && compType->isArithmeticType()) {
8563     if (CompLHSTy) *CompLHSTy = compType;
8564     return compType;
8565   }
8566 
8567   // Type-checking.  Ultimately the pointer's going to be in PExp;
8568   // note that we bias towards the LHS being the pointer.
8569   Expr *PExp = LHS.get(), *IExp = RHS.get();
8570 
8571   bool isObjCPointer;
8572   if (PExp->getType()->isPointerType()) {
8573     isObjCPointer = false;
8574   } else if (PExp->getType()->isObjCObjectPointerType()) {
8575     isObjCPointer = true;
8576   } else {
8577     std::swap(PExp, IExp);
8578     if (PExp->getType()->isPointerType()) {
8579       isObjCPointer = false;
8580     } else if (PExp->getType()->isObjCObjectPointerType()) {
8581       isObjCPointer = true;
8582     } else {
8583       return InvalidOperands(Loc, LHS, RHS);
8584     }
8585   }
8586   assert(PExp->getType()->isAnyPointerType());
8587 
8588   if (!IExp->getType()->isIntegerType())
8589     return InvalidOperands(Loc, LHS, RHS);
8590 
8591   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8592     return QualType();
8593 
8594   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8595     return QualType();
8596 
8597   // Check array bounds for pointer arithemtic
8598   CheckArrayAccess(PExp, IExp);
8599 
8600   if (CompLHSTy) {
8601     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8602     if (LHSTy.isNull()) {
8603       LHSTy = LHS.get()->getType();
8604       if (LHSTy->isPromotableIntegerType())
8605         LHSTy = Context.getPromotedIntegerType(LHSTy);
8606     }
8607     *CompLHSTy = LHSTy;
8608   }
8609 
8610   return PExp->getType();
8611 }
8612 
8613 // C99 6.5.6
8614 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8615                                         SourceLocation Loc,
8616                                         QualType* CompLHSTy) {
8617   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8618 
8619   if (LHS.get()->getType()->isVectorType() ||
8620       RHS.get()->getType()->isVectorType()) {
8621     QualType compType = CheckVectorOperands(
8622         LHS, RHS, Loc, CompLHSTy,
8623         /*AllowBothBool*/getLangOpts().AltiVec,
8624         /*AllowBoolConversions*/getLangOpts().ZVector);
8625     if (CompLHSTy) *CompLHSTy = compType;
8626     return compType;
8627   }
8628 
8629   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8630   if (LHS.isInvalid() || RHS.isInvalid())
8631     return QualType();
8632 
8633   // Enforce type constraints: C99 6.5.6p3.
8634 
8635   // Handle the common case first (both operands are arithmetic).
8636   if (!compType.isNull() && compType->isArithmeticType()) {
8637     if (CompLHSTy) *CompLHSTy = compType;
8638     return compType;
8639   }
8640 
8641   // Either ptr - int   or   ptr - ptr.
8642   if (LHS.get()->getType()->isAnyPointerType()) {
8643     QualType lpointee = LHS.get()->getType()->getPointeeType();
8644 
8645     // Diagnose bad cases where we step over interface counts.
8646     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8647         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8648       return QualType();
8649 
8650     // The result type of a pointer-int computation is the pointer type.
8651     if (RHS.get()->getType()->isIntegerType()) {
8652       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8653         return QualType();
8654 
8655       // Check array bounds for pointer arithemtic
8656       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8657                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8658 
8659       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8660       return LHS.get()->getType();
8661     }
8662 
8663     // Handle pointer-pointer subtractions.
8664     if (const PointerType *RHSPTy
8665           = RHS.get()->getType()->getAs<PointerType>()) {
8666       QualType rpointee = RHSPTy->getPointeeType();
8667 
8668       if (getLangOpts().CPlusPlus) {
8669         // Pointee types must be the same: C++ [expr.add]
8670         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8671           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8672         }
8673       } else {
8674         // Pointee types must be compatible C99 6.5.6p3
8675         if (!Context.typesAreCompatible(
8676                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8677                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8678           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8679           return QualType();
8680         }
8681       }
8682 
8683       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8684                                                LHS.get(), RHS.get()))
8685         return QualType();
8686 
8687       // The pointee type may have zero size.  As an extension, a structure or
8688       // union may have zero size or an array may have zero length.  In this
8689       // case subtraction does not make sense.
8690       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8691         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8692         if (ElementSize.isZero()) {
8693           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8694             << rpointee.getUnqualifiedType()
8695             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8696         }
8697       }
8698 
8699       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8700       return Context.getPointerDiffType();
8701     }
8702   }
8703 
8704   return InvalidOperands(Loc, LHS, RHS);
8705 }
8706 
8707 static bool isScopedEnumerationType(QualType T) {
8708   if (const EnumType *ET = T->getAs<EnumType>())
8709     return ET->getDecl()->isScoped();
8710   return false;
8711 }
8712 
8713 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8714                                    SourceLocation Loc, BinaryOperatorKind Opc,
8715                                    QualType LHSType) {
8716   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8717   // so skip remaining warnings as we don't want to modify values within Sema.
8718   if (S.getLangOpts().OpenCL)
8719     return;
8720 
8721   llvm::APSInt Right;
8722   // Check right/shifter operand
8723   if (RHS.get()->isValueDependent() ||
8724       !RHS.get()->EvaluateAsInt(Right, S.Context))
8725     return;
8726 
8727   if (Right.isNegative()) {
8728     S.DiagRuntimeBehavior(Loc, RHS.get(),
8729                           S.PDiag(diag::warn_shift_negative)
8730                             << RHS.get()->getSourceRange());
8731     return;
8732   }
8733   llvm::APInt LeftBits(Right.getBitWidth(),
8734                        S.Context.getTypeSize(LHS.get()->getType()));
8735   if (Right.uge(LeftBits)) {
8736     S.DiagRuntimeBehavior(Loc, RHS.get(),
8737                           S.PDiag(diag::warn_shift_gt_typewidth)
8738                             << RHS.get()->getSourceRange());
8739     return;
8740   }
8741   if (Opc != BO_Shl)
8742     return;
8743 
8744   // When left shifting an ICE which is signed, we can check for overflow which
8745   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8746   // integers have defined behavior modulo one more than the maximum value
8747   // representable in the result type, so never warn for those.
8748   llvm::APSInt Left;
8749   if (LHS.get()->isValueDependent() ||
8750       LHSType->hasUnsignedIntegerRepresentation() ||
8751       !LHS.get()->EvaluateAsInt(Left, S.Context))
8752     return;
8753 
8754   // If LHS does not have a signed type and non-negative value
8755   // then, the behavior is undefined. Warn about it.
8756   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8757     S.DiagRuntimeBehavior(Loc, LHS.get(),
8758                           S.PDiag(diag::warn_shift_lhs_negative)
8759                             << LHS.get()->getSourceRange());
8760     return;
8761   }
8762 
8763   llvm::APInt ResultBits =
8764       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8765   if (LeftBits.uge(ResultBits))
8766     return;
8767   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8768   Result = Result.shl(Right);
8769 
8770   // Print the bit representation of the signed integer as an unsigned
8771   // hexadecimal number.
8772   SmallString<40> HexResult;
8773   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8774 
8775   // If we are only missing a sign bit, this is less likely to result in actual
8776   // bugs -- if the result is cast back to an unsigned type, it will have the
8777   // expected value. Thus we place this behind a different warning that can be
8778   // turned off separately if needed.
8779   if (LeftBits == ResultBits - 1) {
8780     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8781         << HexResult << LHSType
8782         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8783     return;
8784   }
8785 
8786   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8787     << HexResult.str() << Result.getMinSignedBits() << LHSType
8788     << Left.getBitWidth() << LHS.get()->getSourceRange()
8789     << RHS.get()->getSourceRange();
8790 }
8791 
8792 /// \brief Return the resulting type when a vector is shifted
8793 ///        by a scalar or vector shift amount.
8794 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8795                                  SourceLocation Loc, bool IsCompAssign) {
8796   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8797   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8798       !LHS.get()->getType()->isVectorType()) {
8799     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8800       << RHS.get()->getType() << LHS.get()->getType()
8801       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8802     return QualType();
8803   }
8804 
8805   if (!IsCompAssign) {
8806     LHS = S.UsualUnaryConversions(LHS.get());
8807     if (LHS.isInvalid()) return QualType();
8808   }
8809 
8810   RHS = S.UsualUnaryConversions(RHS.get());
8811   if (RHS.isInvalid()) return QualType();
8812 
8813   QualType LHSType = LHS.get()->getType();
8814   // Note that LHS might be a scalar because the routine calls not only in
8815   // OpenCL case.
8816   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8817   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8818 
8819   // Note that RHS might not be a vector.
8820   QualType RHSType = RHS.get()->getType();
8821   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8822   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8823 
8824   // The operands need to be integers.
8825   if (!LHSEleType->isIntegerType()) {
8826     S.Diag(Loc, diag::err_typecheck_expect_int)
8827       << LHS.get()->getType() << LHS.get()->getSourceRange();
8828     return QualType();
8829   }
8830 
8831   if (!RHSEleType->isIntegerType()) {
8832     S.Diag(Loc, diag::err_typecheck_expect_int)
8833       << RHS.get()->getType() << RHS.get()->getSourceRange();
8834     return QualType();
8835   }
8836 
8837   if (!LHSVecTy) {
8838     assert(RHSVecTy);
8839     if (IsCompAssign)
8840       return RHSType;
8841     if (LHSEleType != RHSEleType) {
8842       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8843       LHSEleType = RHSEleType;
8844     }
8845     QualType VecTy =
8846         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8847     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8848     LHSType = VecTy;
8849   } else if (RHSVecTy) {
8850     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8851     // are applied component-wise. So if RHS is a vector, then ensure
8852     // that the number of elements is the same as LHS...
8853     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8854       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8855         << LHS.get()->getType() << RHS.get()->getType()
8856         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8857       return QualType();
8858     }
8859     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8860       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8861       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8862       if (LHSBT != RHSBT &&
8863           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8864         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8865             << LHS.get()->getType() << RHS.get()->getType()
8866             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8867       }
8868     }
8869   } else {
8870     // ...else expand RHS to match the number of elements in LHS.
8871     QualType VecTy =
8872       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8873     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8874   }
8875 
8876   return LHSType;
8877 }
8878 
8879 // C99 6.5.7
8880 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8881                                   SourceLocation Loc, BinaryOperatorKind Opc,
8882                                   bool IsCompAssign) {
8883   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8884 
8885   // Vector shifts promote their scalar inputs to vector type.
8886   if (LHS.get()->getType()->isVectorType() ||
8887       RHS.get()->getType()->isVectorType()) {
8888     if (LangOpts.ZVector) {
8889       // The shift operators for the z vector extensions work basically
8890       // like general shifts, except that neither the LHS nor the RHS is
8891       // allowed to be a "vector bool".
8892       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8893         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8894           return InvalidOperands(Loc, LHS, RHS);
8895       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8896         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8897           return InvalidOperands(Loc, LHS, RHS);
8898     }
8899     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8900   }
8901 
8902   // Shifts don't perform usual arithmetic conversions, they just do integer
8903   // promotions on each operand. C99 6.5.7p3
8904 
8905   // For the LHS, do usual unary conversions, but then reset them away
8906   // if this is a compound assignment.
8907   ExprResult OldLHS = LHS;
8908   LHS = UsualUnaryConversions(LHS.get());
8909   if (LHS.isInvalid())
8910     return QualType();
8911   QualType LHSType = LHS.get()->getType();
8912   if (IsCompAssign) LHS = OldLHS;
8913 
8914   // The RHS is simpler.
8915   RHS = UsualUnaryConversions(RHS.get());
8916   if (RHS.isInvalid())
8917     return QualType();
8918   QualType RHSType = RHS.get()->getType();
8919 
8920   // C99 6.5.7p2: Each of the operands shall have integer type.
8921   if (!LHSType->hasIntegerRepresentation() ||
8922       !RHSType->hasIntegerRepresentation())
8923     return InvalidOperands(Loc, LHS, RHS);
8924 
8925   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8926   // hasIntegerRepresentation() above instead of this.
8927   if (isScopedEnumerationType(LHSType) ||
8928       isScopedEnumerationType(RHSType)) {
8929     return InvalidOperands(Loc, LHS, RHS);
8930   }
8931   // Sanity-check shift operands
8932   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8933 
8934   // "The type of the result is that of the promoted left operand."
8935   return LHSType;
8936 }
8937 
8938 static bool IsWithinTemplateSpecialization(Decl *D) {
8939   if (DeclContext *DC = D->getDeclContext()) {
8940     if (isa<ClassTemplateSpecializationDecl>(DC))
8941       return true;
8942     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8943       return FD->isFunctionTemplateSpecialization();
8944   }
8945   return false;
8946 }
8947 
8948 /// If two different enums are compared, raise a warning.
8949 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8950                                 Expr *RHS) {
8951   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8952   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8953 
8954   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8955   if (!LHSEnumType)
8956     return;
8957   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8958   if (!RHSEnumType)
8959     return;
8960 
8961   // Ignore anonymous enums.
8962   if (!LHSEnumType->getDecl()->getIdentifier())
8963     return;
8964   if (!RHSEnumType->getDecl()->getIdentifier())
8965     return;
8966 
8967   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8968     return;
8969 
8970   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8971       << LHSStrippedType << RHSStrippedType
8972       << LHS->getSourceRange() << RHS->getSourceRange();
8973 }
8974 
8975 /// \brief Diagnose bad pointer comparisons.
8976 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8977                                               ExprResult &LHS, ExprResult &RHS,
8978                                               bool IsError) {
8979   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8980                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8981     << LHS.get()->getType() << RHS.get()->getType()
8982     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8983 }
8984 
8985 /// \brief Returns false if the pointers are converted to a composite type,
8986 /// true otherwise.
8987 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8988                                            ExprResult &LHS, ExprResult &RHS) {
8989   // C++ [expr.rel]p2:
8990   //   [...] Pointer conversions (4.10) and qualification
8991   //   conversions (4.4) are performed on pointer operands (or on
8992   //   a pointer operand and a null pointer constant) to bring
8993   //   them to their composite pointer type. [...]
8994   //
8995   // C++ [expr.eq]p1 uses the same notion for (in)equality
8996   // comparisons of pointers.
8997 
8998   QualType LHSType = LHS.get()->getType();
8999   QualType RHSType = RHS.get()->getType();
9000   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9001          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9002 
9003   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9004   if (T.isNull()) {
9005     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9006         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9007       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9008     else
9009       S.InvalidOperands(Loc, LHS, RHS);
9010     return true;
9011   }
9012 
9013   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9014   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9015   return false;
9016 }
9017 
9018 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9019                                                     ExprResult &LHS,
9020                                                     ExprResult &RHS,
9021                                                     bool IsError) {
9022   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9023                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9024     << LHS.get()->getType() << RHS.get()->getType()
9025     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9026 }
9027 
9028 static bool isObjCObjectLiteral(ExprResult &E) {
9029   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9030   case Stmt::ObjCArrayLiteralClass:
9031   case Stmt::ObjCDictionaryLiteralClass:
9032   case Stmt::ObjCStringLiteralClass:
9033   case Stmt::ObjCBoxedExprClass:
9034     return true;
9035   default:
9036     // Note that ObjCBoolLiteral is NOT an object literal!
9037     return false;
9038   }
9039 }
9040 
9041 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9042   const ObjCObjectPointerType *Type =
9043     LHS->getType()->getAs<ObjCObjectPointerType>();
9044 
9045   // If this is not actually an Objective-C object, bail out.
9046   if (!Type)
9047     return false;
9048 
9049   // Get the LHS object's interface type.
9050   QualType InterfaceType = Type->getPointeeType();
9051 
9052   // If the RHS isn't an Objective-C object, bail out.
9053   if (!RHS->getType()->isObjCObjectPointerType())
9054     return false;
9055 
9056   // Try to find the -isEqual: method.
9057   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9058   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9059                                                       InterfaceType,
9060                                                       /*instance=*/true);
9061   if (!Method) {
9062     if (Type->isObjCIdType()) {
9063       // For 'id', just check the global pool.
9064       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9065                                                   /*receiverId=*/true);
9066     } else {
9067       // Check protocols.
9068       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9069                                              /*instance=*/true);
9070     }
9071   }
9072 
9073   if (!Method)
9074     return false;
9075 
9076   QualType T = Method->parameters()[0]->getType();
9077   if (!T->isObjCObjectPointerType())
9078     return false;
9079 
9080   QualType R = Method->getReturnType();
9081   if (!R->isScalarType())
9082     return false;
9083 
9084   return true;
9085 }
9086 
9087 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9088   FromE = FromE->IgnoreParenImpCasts();
9089   switch (FromE->getStmtClass()) {
9090     default:
9091       break;
9092     case Stmt::ObjCStringLiteralClass:
9093       // "string literal"
9094       return LK_String;
9095     case Stmt::ObjCArrayLiteralClass:
9096       // "array literal"
9097       return LK_Array;
9098     case Stmt::ObjCDictionaryLiteralClass:
9099       // "dictionary literal"
9100       return LK_Dictionary;
9101     case Stmt::BlockExprClass:
9102       return LK_Block;
9103     case Stmt::ObjCBoxedExprClass: {
9104       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9105       switch (Inner->getStmtClass()) {
9106         case Stmt::IntegerLiteralClass:
9107         case Stmt::FloatingLiteralClass:
9108         case Stmt::CharacterLiteralClass:
9109         case Stmt::ObjCBoolLiteralExprClass:
9110         case Stmt::CXXBoolLiteralExprClass:
9111           // "numeric literal"
9112           return LK_Numeric;
9113         case Stmt::ImplicitCastExprClass: {
9114           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9115           // Boolean literals can be represented by implicit casts.
9116           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9117             return LK_Numeric;
9118           break;
9119         }
9120         default:
9121           break;
9122       }
9123       return LK_Boxed;
9124     }
9125   }
9126   return LK_None;
9127 }
9128 
9129 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9130                                           ExprResult &LHS, ExprResult &RHS,
9131                                           BinaryOperator::Opcode Opc){
9132   Expr *Literal;
9133   Expr *Other;
9134   if (isObjCObjectLiteral(LHS)) {
9135     Literal = LHS.get();
9136     Other = RHS.get();
9137   } else {
9138     Literal = RHS.get();
9139     Other = LHS.get();
9140   }
9141 
9142   // Don't warn on comparisons against nil.
9143   Other = Other->IgnoreParenCasts();
9144   if (Other->isNullPointerConstant(S.getASTContext(),
9145                                    Expr::NPC_ValueDependentIsNotNull))
9146     return;
9147 
9148   // This should be kept in sync with warn_objc_literal_comparison.
9149   // LK_String should always be after the other literals, since it has its own
9150   // warning flag.
9151   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9152   assert(LiteralKind != Sema::LK_Block);
9153   if (LiteralKind == Sema::LK_None) {
9154     llvm_unreachable("Unknown Objective-C object literal kind");
9155   }
9156 
9157   if (LiteralKind == Sema::LK_String)
9158     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9159       << Literal->getSourceRange();
9160   else
9161     S.Diag(Loc, diag::warn_objc_literal_comparison)
9162       << LiteralKind << Literal->getSourceRange();
9163 
9164   if (BinaryOperator::isEqualityOp(Opc) &&
9165       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9166     SourceLocation Start = LHS.get()->getLocStart();
9167     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9168     CharSourceRange OpRange =
9169       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9170 
9171     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9172       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9173       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9174       << FixItHint::CreateInsertion(End, "]");
9175   }
9176 }
9177 
9178 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9179 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9180                                            ExprResult &RHS, SourceLocation Loc,
9181                                            BinaryOperatorKind Opc) {
9182   // Check that left hand side is !something.
9183   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9184   if (!UO || UO->getOpcode() != UO_LNot) return;
9185 
9186   // Only check if the right hand side is non-bool arithmetic type.
9187   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9188 
9189   // Make sure that the something in !something is not bool.
9190   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9191   if (SubExpr->isKnownToHaveBooleanValue()) return;
9192 
9193   // Emit warning.
9194   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9195   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9196       << Loc << IsBitwiseOp;
9197 
9198   // First note suggest !(x < y)
9199   SourceLocation FirstOpen = SubExpr->getLocStart();
9200   SourceLocation FirstClose = RHS.get()->getLocEnd();
9201   FirstClose = S.getLocForEndOfToken(FirstClose);
9202   if (FirstClose.isInvalid())
9203     FirstOpen = SourceLocation();
9204   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9205       << IsBitwiseOp
9206       << FixItHint::CreateInsertion(FirstOpen, "(")
9207       << FixItHint::CreateInsertion(FirstClose, ")");
9208 
9209   // Second note suggests (!x) < y
9210   SourceLocation SecondOpen = LHS.get()->getLocStart();
9211   SourceLocation SecondClose = LHS.get()->getLocEnd();
9212   SecondClose = S.getLocForEndOfToken(SecondClose);
9213   if (SecondClose.isInvalid())
9214     SecondOpen = SourceLocation();
9215   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9216       << FixItHint::CreateInsertion(SecondOpen, "(")
9217       << FixItHint::CreateInsertion(SecondClose, ")");
9218 }
9219 
9220 // Get the decl for a simple expression: a reference to a variable,
9221 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9222 static ValueDecl *getCompareDecl(Expr *E) {
9223   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9224     return DR->getDecl();
9225   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9226     if (Ivar->isFreeIvar())
9227       return Ivar->getDecl();
9228   }
9229   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9230     if (Mem->isImplicitAccess())
9231       return Mem->getMemberDecl();
9232   }
9233   return nullptr;
9234 }
9235 
9236 // C99 6.5.8, C++ [expr.rel]
9237 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9238                                     SourceLocation Loc, BinaryOperatorKind Opc,
9239                                     bool IsRelational) {
9240   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9241 
9242   // Handle vector comparisons separately.
9243   if (LHS.get()->getType()->isVectorType() ||
9244       RHS.get()->getType()->isVectorType())
9245     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9246 
9247   QualType LHSType = LHS.get()->getType();
9248   QualType RHSType = RHS.get()->getType();
9249 
9250   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9251   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9252 
9253   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9254   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9255 
9256   if (!LHSType->hasFloatingRepresentation() &&
9257       !(LHSType->isBlockPointerType() && IsRelational) &&
9258       !LHS.get()->getLocStart().isMacroID() &&
9259       !RHS.get()->getLocStart().isMacroID() &&
9260       ActiveTemplateInstantiations.empty()) {
9261     // For non-floating point types, check for self-comparisons of the form
9262     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9263     // often indicate logic errors in the program.
9264     //
9265     // NOTE: Don't warn about comparison expressions resulting from macro
9266     // expansion. Also don't warn about comparisons which are only self
9267     // comparisons within a template specialization. The warnings should catch
9268     // obvious cases in the definition of the template anyways. The idea is to
9269     // warn when the typed comparison operator will always evaluate to the same
9270     // result.
9271     ValueDecl *DL = getCompareDecl(LHSStripped);
9272     ValueDecl *DR = getCompareDecl(RHSStripped);
9273     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9274       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9275                           << 0 // self-
9276                           << (Opc == BO_EQ
9277                               || Opc == BO_LE
9278                               || Opc == BO_GE));
9279     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9280                !DL->getType()->isReferenceType() &&
9281                !DR->getType()->isReferenceType()) {
9282         // what is it always going to eval to?
9283         char always_evals_to;
9284         switch(Opc) {
9285         case BO_EQ: // e.g. array1 == array2
9286           always_evals_to = 0; // false
9287           break;
9288         case BO_NE: // e.g. array1 != array2
9289           always_evals_to = 1; // true
9290           break;
9291         default:
9292           // best we can say is 'a constant'
9293           always_evals_to = 2; // e.g. array1 <= array2
9294           break;
9295         }
9296         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9297                             << 1 // array
9298                             << always_evals_to);
9299     }
9300 
9301     if (isa<CastExpr>(LHSStripped))
9302       LHSStripped = LHSStripped->IgnoreParenCasts();
9303     if (isa<CastExpr>(RHSStripped))
9304       RHSStripped = RHSStripped->IgnoreParenCasts();
9305 
9306     // Warn about comparisons against a string constant (unless the other
9307     // operand is null), the user probably wants strcmp.
9308     Expr *literalString = nullptr;
9309     Expr *literalStringStripped = nullptr;
9310     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9311         !RHSStripped->isNullPointerConstant(Context,
9312                                             Expr::NPC_ValueDependentIsNull)) {
9313       literalString = LHS.get();
9314       literalStringStripped = LHSStripped;
9315     } else if ((isa<StringLiteral>(RHSStripped) ||
9316                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9317                !LHSStripped->isNullPointerConstant(Context,
9318                                             Expr::NPC_ValueDependentIsNull)) {
9319       literalString = RHS.get();
9320       literalStringStripped = RHSStripped;
9321     }
9322 
9323     if (literalString) {
9324       DiagRuntimeBehavior(Loc, nullptr,
9325         PDiag(diag::warn_stringcompare)
9326           << isa<ObjCEncodeExpr>(literalStringStripped)
9327           << literalString->getSourceRange());
9328     }
9329   }
9330 
9331   // C99 6.5.8p3 / C99 6.5.9p4
9332   UsualArithmeticConversions(LHS, RHS);
9333   if (LHS.isInvalid() || RHS.isInvalid())
9334     return QualType();
9335 
9336   LHSType = LHS.get()->getType();
9337   RHSType = RHS.get()->getType();
9338 
9339   // The result of comparisons is 'bool' in C++, 'int' in C.
9340   QualType ResultTy = Context.getLogicalOperationType();
9341 
9342   if (IsRelational) {
9343     if (LHSType->isRealType() && RHSType->isRealType())
9344       return ResultTy;
9345   } else {
9346     // Check for comparisons of floating point operands using != and ==.
9347     if (LHSType->hasFloatingRepresentation())
9348       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9349 
9350     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9351       return ResultTy;
9352   }
9353 
9354   const Expr::NullPointerConstantKind LHSNullKind =
9355       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9356   const Expr::NullPointerConstantKind RHSNullKind =
9357       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9358   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9359   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9360 
9361   if (!IsRelational && LHSIsNull != RHSIsNull) {
9362     bool IsEquality = Opc == BO_EQ;
9363     if (RHSIsNull)
9364       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9365                                    RHS.get()->getSourceRange());
9366     else
9367       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9368                                    LHS.get()->getSourceRange());
9369   }
9370 
9371   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9372       (RHSType->isIntegerType() && !RHSIsNull)) {
9373     // Skip normal pointer conversion checks in this case; we have better
9374     // diagnostics for this below.
9375   } else if (getLangOpts().CPlusPlus) {
9376     // Equality comparison of a function pointer to a void pointer is invalid,
9377     // but we allow it as an extension.
9378     // FIXME: If we really want to allow this, should it be part of composite
9379     // pointer type computation so it works in conditionals too?
9380     if (!IsRelational &&
9381         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9382          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9383       // This is a gcc extension compatibility comparison.
9384       // In a SFINAE context, we treat this as a hard error to maintain
9385       // conformance with the C++ standard.
9386       diagnoseFunctionPointerToVoidComparison(
9387           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9388 
9389       if (isSFINAEContext())
9390         return QualType();
9391 
9392       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9393       return ResultTy;
9394     }
9395 
9396     // C++ [expr.eq]p2:
9397     //   If at least one operand is a pointer [...] bring them to their
9398     //   composite pointer type.
9399     // C++ [expr.rel]p2:
9400     //   If both operands are pointers, [...] bring them to their composite
9401     //   pointer type.
9402     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9403         (IsRelational ? 2 : 1)) {
9404       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9405         return QualType();
9406       else
9407         return ResultTy;
9408     }
9409   } else if (LHSType->isPointerType() &&
9410              RHSType->isPointerType()) { // C99 6.5.8p2
9411     // All of the following pointer-related warnings are GCC extensions, except
9412     // when handling null pointer constants.
9413     QualType LCanPointeeTy =
9414       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9415     QualType RCanPointeeTy =
9416       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9417 
9418     // C99 6.5.9p2 and C99 6.5.8p2
9419     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9420                                    RCanPointeeTy.getUnqualifiedType())) {
9421       // Valid unless a relational comparison of function pointers
9422       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9423         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9424           << LHSType << RHSType << LHS.get()->getSourceRange()
9425           << RHS.get()->getSourceRange();
9426       }
9427     } else if (!IsRelational &&
9428                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9429       // Valid unless comparison between non-null pointer and function pointer
9430       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9431           && !LHSIsNull && !RHSIsNull)
9432         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9433                                                 /*isError*/false);
9434     } else {
9435       // Invalid
9436       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9437     }
9438     if (LCanPointeeTy != RCanPointeeTy) {
9439       // Treat NULL constant as a special case in OpenCL.
9440       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9441         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9442         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9443           Diag(Loc,
9444                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9445               << LHSType << RHSType << 0 /* comparison */
9446               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9447         }
9448       }
9449       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9450       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9451       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9452                                                : CK_BitCast;
9453       if (LHSIsNull && !RHSIsNull)
9454         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9455       else
9456         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9457     }
9458     return ResultTy;
9459   }
9460 
9461   if (getLangOpts().CPlusPlus) {
9462     // C++ [expr.eq]p4:
9463     //   Two operands of type std::nullptr_t or one operand of type
9464     //   std::nullptr_t and the other a null pointer constant compare equal.
9465     if (!IsRelational && LHSIsNull && RHSIsNull) {
9466       if (LHSType->isNullPtrType()) {
9467         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9468         return ResultTy;
9469       }
9470       if (RHSType->isNullPtrType()) {
9471         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9472         return ResultTy;
9473       }
9474     }
9475 
9476     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9477     // These aren't covered by the composite pointer type rules.
9478     if (!IsRelational && RHSType->isNullPtrType() &&
9479         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9480       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9481       return ResultTy;
9482     }
9483     if (!IsRelational && LHSType->isNullPtrType() &&
9484         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9485       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9486       return ResultTy;
9487     }
9488 
9489     if (IsRelational &&
9490         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9491          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9492       // HACK: Relational comparison of nullptr_t against a pointer type is
9493       // invalid per DR583, but we allow it within std::less<> and friends,
9494       // since otherwise common uses of it break.
9495       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9496       // friends to have std::nullptr_t overload candidates.
9497       DeclContext *DC = CurContext;
9498       if (isa<FunctionDecl>(DC))
9499         DC = DC->getParent();
9500       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9501         if (CTSD->isInStdNamespace() &&
9502             llvm::StringSwitch<bool>(CTSD->getName())
9503                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9504                 .Default(false)) {
9505           if (RHSType->isNullPtrType())
9506             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9507           else
9508             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9509           return ResultTy;
9510         }
9511       }
9512     }
9513 
9514     // C++ [expr.eq]p2:
9515     //   If at least one operand is a pointer to member, [...] bring them to
9516     //   their composite pointer type.
9517     if (!IsRelational &&
9518         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9519       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9520         return QualType();
9521       else
9522         return ResultTy;
9523     }
9524 
9525     // Handle scoped enumeration types specifically, since they don't promote
9526     // to integers.
9527     if (LHS.get()->getType()->isEnumeralType() &&
9528         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9529                                        RHS.get()->getType()))
9530       return ResultTy;
9531   }
9532 
9533   // Handle block pointer types.
9534   if (!IsRelational && LHSType->isBlockPointerType() &&
9535       RHSType->isBlockPointerType()) {
9536     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9537     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9538 
9539     if (!LHSIsNull && !RHSIsNull &&
9540         !Context.typesAreCompatible(lpointee, rpointee)) {
9541       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9542         << LHSType << RHSType << LHS.get()->getSourceRange()
9543         << RHS.get()->getSourceRange();
9544     }
9545     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9546     return ResultTy;
9547   }
9548 
9549   // Allow block pointers to be compared with null pointer constants.
9550   if (!IsRelational
9551       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9552           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9553     if (!LHSIsNull && !RHSIsNull) {
9554       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9555              ->getPointeeType()->isVoidType())
9556             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9557                 ->getPointeeType()->isVoidType())))
9558         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9559           << LHSType << RHSType << LHS.get()->getSourceRange()
9560           << RHS.get()->getSourceRange();
9561     }
9562     if (LHSIsNull && !RHSIsNull)
9563       LHS = ImpCastExprToType(LHS.get(), RHSType,
9564                               RHSType->isPointerType() ? CK_BitCast
9565                                 : CK_AnyPointerToBlockPointerCast);
9566     else
9567       RHS = ImpCastExprToType(RHS.get(), LHSType,
9568                               LHSType->isPointerType() ? CK_BitCast
9569                                 : CK_AnyPointerToBlockPointerCast);
9570     return ResultTy;
9571   }
9572 
9573   if (LHSType->isObjCObjectPointerType() ||
9574       RHSType->isObjCObjectPointerType()) {
9575     const PointerType *LPT = LHSType->getAs<PointerType>();
9576     const PointerType *RPT = RHSType->getAs<PointerType>();
9577     if (LPT || RPT) {
9578       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9579       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9580 
9581       if (!LPtrToVoid && !RPtrToVoid &&
9582           !Context.typesAreCompatible(LHSType, RHSType)) {
9583         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9584                                           /*isError*/false);
9585       }
9586       if (LHSIsNull && !RHSIsNull) {
9587         Expr *E = LHS.get();
9588         if (getLangOpts().ObjCAutoRefCount)
9589           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9590         LHS = ImpCastExprToType(E, RHSType,
9591                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9592       }
9593       else {
9594         Expr *E = RHS.get();
9595         if (getLangOpts().ObjCAutoRefCount)
9596           CheckObjCARCConversion(SourceRange(), LHSType, E,
9597                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9598                                  /*DiagnoseCFAudited=*/false, Opc);
9599         RHS = ImpCastExprToType(E, LHSType,
9600                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9601       }
9602       return ResultTy;
9603     }
9604     if (LHSType->isObjCObjectPointerType() &&
9605         RHSType->isObjCObjectPointerType()) {
9606       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9607         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9608                                           /*isError*/false);
9609       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9610         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9611 
9612       if (LHSIsNull && !RHSIsNull)
9613         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9614       else
9615         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9616       return ResultTy;
9617     }
9618   }
9619   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9620       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9621     unsigned DiagID = 0;
9622     bool isError = false;
9623     if (LangOpts.DebuggerSupport) {
9624       // Under a debugger, allow the comparison of pointers to integers,
9625       // since users tend to want to compare addresses.
9626     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9627                (RHSIsNull && RHSType->isIntegerType())) {
9628       if (IsRelational) {
9629         isError = getLangOpts().CPlusPlus;
9630         DiagID =
9631           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9632                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9633       }
9634     } else if (getLangOpts().CPlusPlus) {
9635       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9636       isError = true;
9637     } else if (IsRelational)
9638       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9639     else
9640       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9641 
9642     if (DiagID) {
9643       Diag(Loc, DiagID)
9644         << LHSType << RHSType << LHS.get()->getSourceRange()
9645         << RHS.get()->getSourceRange();
9646       if (isError)
9647         return QualType();
9648     }
9649 
9650     if (LHSType->isIntegerType())
9651       LHS = ImpCastExprToType(LHS.get(), RHSType,
9652                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9653     else
9654       RHS = ImpCastExprToType(RHS.get(), LHSType,
9655                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9656     return ResultTy;
9657   }
9658 
9659   // Handle block pointers.
9660   if (!IsRelational && RHSIsNull
9661       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9662     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9663     return ResultTy;
9664   }
9665   if (!IsRelational && LHSIsNull
9666       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9667     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9668     return ResultTy;
9669   }
9670 
9671   if (getLangOpts().OpenCLVersion >= 200) {
9672     if (LHSIsNull && RHSType->isQueueT()) {
9673       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9674       return ResultTy;
9675     }
9676 
9677     if (LHSType->isQueueT() && RHSIsNull) {
9678       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9679       return ResultTy;
9680     }
9681   }
9682 
9683   return InvalidOperands(Loc, LHS, RHS);
9684 }
9685 
9686 
9687 // Return a signed type that is of identical size and number of elements.
9688 // For floating point vectors, return an integer type of identical size
9689 // and number of elements.
9690 QualType Sema::GetSignedVectorType(QualType V) {
9691   const VectorType *VTy = V->getAs<VectorType>();
9692   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9693   if (TypeSize == Context.getTypeSize(Context.CharTy))
9694     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9695   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9696     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9697   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9698     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9699   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9700     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9701   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9702          "Unhandled vector element size in vector compare");
9703   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9704 }
9705 
9706 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9707 /// operates on extended vector types.  Instead of producing an IntTy result,
9708 /// like a scalar comparison, a vector comparison produces a vector of integer
9709 /// types.
9710 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9711                                           SourceLocation Loc,
9712                                           bool IsRelational) {
9713   // Check to make sure we're operating on vectors of the same type and width,
9714   // Allowing one side to be a scalar of element type.
9715   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9716                               /*AllowBothBool*/true,
9717                               /*AllowBoolConversions*/getLangOpts().ZVector);
9718   if (vType.isNull())
9719     return vType;
9720 
9721   QualType LHSType = LHS.get()->getType();
9722 
9723   // If AltiVec, the comparison results in a numeric type, i.e.
9724   // bool for C++, int for C
9725   if (getLangOpts().AltiVec &&
9726       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9727     return Context.getLogicalOperationType();
9728 
9729   // For non-floating point types, check for self-comparisons of the form
9730   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9731   // often indicate logic errors in the program.
9732   if (!LHSType->hasFloatingRepresentation() &&
9733       ActiveTemplateInstantiations.empty()) {
9734     if (DeclRefExpr* DRL
9735           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9736       if (DeclRefExpr* DRR
9737             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9738         if (DRL->getDecl() == DRR->getDecl())
9739           DiagRuntimeBehavior(Loc, nullptr,
9740                               PDiag(diag::warn_comparison_always)
9741                                 << 0 // self-
9742                                 << 2 // "a constant"
9743                               );
9744   }
9745 
9746   // Check for comparisons of floating point operands using != and ==.
9747   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9748     assert (RHS.get()->getType()->hasFloatingRepresentation());
9749     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9750   }
9751 
9752   // Return a signed type for the vector.
9753   return GetSignedVectorType(vType);
9754 }
9755 
9756 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9757                                           SourceLocation Loc) {
9758   // Ensure that either both operands are of the same vector type, or
9759   // one operand is of a vector type and the other is of its element type.
9760   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9761                                        /*AllowBothBool*/true,
9762                                        /*AllowBoolConversions*/false);
9763   if (vType.isNull())
9764     return InvalidOperands(Loc, LHS, RHS);
9765   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9766       vType->hasFloatingRepresentation())
9767     return InvalidOperands(Loc, LHS, RHS);
9768 
9769   return GetSignedVectorType(LHS.get()->getType());
9770 }
9771 
9772 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9773                                            SourceLocation Loc,
9774                                            BinaryOperatorKind Opc) {
9775   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9776 
9777   bool IsCompAssign =
9778       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9779 
9780   if (LHS.get()->getType()->isVectorType() ||
9781       RHS.get()->getType()->isVectorType()) {
9782     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9783         RHS.get()->getType()->hasIntegerRepresentation())
9784       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9785                         /*AllowBothBool*/true,
9786                         /*AllowBoolConversions*/getLangOpts().ZVector);
9787     return InvalidOperands(Loc, LHS, RHS);
9788   }
9789 
9790   if (Opc == BO_And)
9791     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9792 
9793   ExprResult LHSResult = LHS, RHSResult = RHS;
9794   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9795                                                  IsCompAssign);
9796   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9797     return QualType();
9798   LHS = LHSResult.get();
9799   RHS = RHSResult.get();
9800 
9801   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9802     return compType;
9803   return InvalidOperands(Loc, LHS, RHS);
9804 }
9805 
9806 // C99 6.5.[13,14]
9807 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9808                                            SourceLocation Loc,
9809                                            BinaryOperatorKind Opc) {
9810   // Check vector operands differently.
9811   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9812     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9813 
9814   // Diagnose cases where the user write a logical and/or but probably meant a
9815   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9816   // is a constant.
9817   if (LHS.get()->getType()->isIntegerType() &&
9818       !LHS.get()->getType()->isBooleanType() &&
9819       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9820       // Don't warn in macros or template instantiations.
9821       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9822     // If the RHS can be constant folded, and if it constant folds to something
9823     // that isn't 0 or 1 (which indicate a potential logical operation that
9824     // happened to fold to true/false) then warn.
9825     // Parens on the RHS are ignored.
9826     llvm::APSInt Result;
9827     if (RHS.get()->EvaluateAsInt(Result, Context))
9828       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9829            !RHS.get()->getExprLoc().isMacroID()) ||
9830           (Result != 0 && Result != 1)) {
9831         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9832           << RHS.get()->getSourceRange()
9833           << (Opc == BO_LAnd ? "&&" : "||");
9834         // Suggest replacing the logical operator with the bitwise version
9835         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9836             << (Opc == BO_LAnd ? "&" : "|")
9837             << FixItHint::CreateReplacement(SourceRange(
9838                                                  Loc, getLocForEndOfToken(Loc)),
9839                                             Opc == BO_LAnd ? "&" : "|");
9840         if (Opc == BO_LAnd)
9841           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9842           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9843               << FixItHint::CreateRemoval(
9844                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9845                               RHS.get()->getLocEnd()));
9846       }
9847   }
9848 
9849   if (!Context.getLangOpts().CPlusPlus) {
9850     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9851     // not operate on the built-in scalar and vector float types.
9852     if (Context.getLangOpts().OpenCL &&
9853         Context.getLangOpts().OpenCLVersion < 120) {
9854       if (LHS.get()->getType()->isFloatingType() ||
9855           RHS.get()->getType()->isFloatingType())
9856         return InvalidOperands(Loc, LHS, RHS);
9857     }
9858 
9859     LHS = UsualUnaryConversions(LHS.get());
9860     if (LHS.isInvalid())
9861       return QualType();
9862 
9863     RHS = UsualUnaryConversions(RHS.get());
9864     if (RHS.isInvalid())
9865       return QualType();
9866 
9867     if (!LHS.get()->getType()->isScalarType() ||
9868         !RHS.get()->getType()->isScalarType())
9869       return InvalidOperands(Loc, LHS, RHS);
9870 
9871     return Context.IntTy;
9872   }
9873 
9874   // The following is safe because we only use this method for
9875   // non-overloadable operands.
9876 
9877   // C++ [expr.log.and]p1
9878   // C++ [expr.log.or]p1
9879   // The operands are both contextually converted to type bool.
9880   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9881   if (LHSRes.isInvalid())
9882     return InvalidOperands(Loc, LHS, RHS);
9883   LHS = LHSRes;
9884 
9885   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9886   if (RHSRes.isInvalid())
9887     return InvalidOperands(Loc, LHS, RHS);
9888   RHS = RHSRes;
9889 
9890   // C++ [expr.log.and]p2
9891   // C++ [expr.log.or]p2
9892   // The result is a bool.
9893   return Context.BoolTy;
9894 }
9895 
9896 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9897   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9898   if (!ME) return false;
9899   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9900   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9901       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9902   if (!Base) return false;
9903   return Base->getMethodDecl() != nullptr;
9904 }
9905 
9906 /// Is the given expression (which must be 'const') a reference to a
9907 /// variable which was originally non-const, but which has become
9908 /// 'const' due to being captured within a block?
9909 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9910 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9911   assert(E->isLValue() && E->getType().isConstQualified());
9912   E = E->IgnoreParens();
9913 
9914   // Must be a reference to a declaration from an enclosing scope.
9915   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9916   if (!DRE) return NCCK_None;
9917   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9918 
9919   // The declaration must be a variable which is not declared 'const'.
9920   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9921   if (!var) return NCCK_None;
9922   if (var->getType().isConstQualified()) return NCCK_None;
9923   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9924 
9925   // Decide whether the first capture was for a block or a lambda.
9926   DeclContext *DC = S.CurContext, *Prev = nullptr;
9927   // Decide whether the first capture was for a block or a lambda.
9928   while (DC) {
9929     // For init-capture, it is possible that the variable belongs to the
9930     // template pattern of the current context.
9931     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9932       if (var->isInitCapture() &&
9933           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9934         break;
9935     if (DC == var->getDeclContext())
9936       break;
9937     Prev = DC;
9938     DC = DC->getParent();
9939   }
9940   // Unless we have an init-capture, we've gone one step too far.
9941   if (!var->isInitCapture())
9942     DC = Prev;
9943   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9944 }
9945 
9946 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9947   Ty = Ty.getNonReferenceType();
9948   if (IsDereference && Ty->isPointerType())
9949     Ty = Ty->getPointeeType();
9950   return !Ty.isConstQualified();
9951 }
9952 
9953 /// Emit the "read-only variable not assignable" error and print notes to give
9954 /// more information about why the variable is not assignable, such as pointing
9955 /// to the declaration of a const variable, showing that a method is const, or
9956 /// that the function is returning a const reference.
9957 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9958                                     SourceLocation Loc) {
9959   // Update err_typecheck_assign_const and note_typecheck_assign_const
9960   // when this enum is changed.
9961   enum {
9962     ConstFunction,
9963     ConstVariable,
9964     ConstMember,
9965     ConstMethod,
9966     ConstUnknown,  // Keep as last element
9967   };
9968 
9969   SourceRange ExprRange = E->getSourceRange();
9970 
9971   // Only emit one error on the first const found.  All other consts will emit
9972   // a note to the error.
9973   bool DiagnosticEmitted = false;
9974 
9975   // Track if the current expression is the result of a dereference, and if the
9976   // next checked expression is the result of a dereference.
9977   bool IsDereference = false;
9978   bool NextIsDereference = false;
9979 
9980   // Loop to process MemberExpr chains.
9981   while (true) {
9982     IsDereference = NextIsDereference;
9983 
9984     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9985     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9986       NextIsDereference = ME->isArrow();
9987       const ValueDecl *VD = ME->getMemberDecl();
9988       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9989         // Mutable fields can be modified even if the class is const.
9990         if (Field->isMutable()) {
9991           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9992           break;
9993         }
9994 
9995         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9996           if (!DiagnosticEmitted) {
9997             S.Diag(Loc, diag::err_typecheck_assign_const)
9998                 << ExprRange << ConstMember << false /*static*/ << Field
9999                 << Field->getType();
10000             DiagnosticEmitted = true;
10001           }
10002           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10003               << ConstMember << false /*static*/ << Field << Field->getType()
10004               << Field->getSourceRange();
10005         }
10006         E = ME->getBase();
10007         continue;
10008       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10009         if (VDecl->getType().isConstQualified()) {
10010           if (!DiagnosticEmitted) {
10011             S.Diag(Loc, diag::err_typecheck_assign_const)
10012                 << ExprRange << ConstMember << true /*static*/ << VDecl
10013                 << VDecl->getType();
10014             DiagnosticEmitted = true;
10015           }
10016           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10017               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10018               << VDecl->getSourceRange();
10019         }
10020         // Static fields do not inherit constness from parents.
10021         break;
10022       }
10023       break;
10024     } // End MemberExpr
10025     break;
10026   }
10027 
10028   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10029     // Function calls
10030     const FunctionDecl *FD = CE->getDirectCallee();
10031     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10032       if (!DiagnosticEmitted) {
10033         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10034                                                       << ConstFunction << FD;
10035         DiagnosticEmitted = true;
10036       }
10037       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10038              diag::note_typecheck_assign_const)
10039           << ConstFunction << FD << FD->getReturnType()
10040           << FD->getReturnTypeSourceRange();
10041     }
10042   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10043     // Point to variable declaration.
10044     if (const ValueDecl *VD = DRE->getDecl()) {
10045       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10046         if (!DiagnosticEmitted) {
10047           S.Diag(Loc, diag::err_typecheck_assign_const)
10048               << ExprRange << ConstVariable << VD << VD->getType();
10049           DiagnosticEmitted = true;
10050         }
10051         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10052             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10053       }
10054     }
10055   } else if (isa<CXXThisExpr>(E)) {
10056     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10057       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10058         if (MD->isConst()) {
10059           if (!DiagnosticEmitted) {
10060             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10061                                                           << ConstMethod << MD;
10062             DiagnosticEmitted = true;
10063           }
10064           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10065               << ConstMethod << MD << MD->getSourceRange();
10066         }
10067       }
10068     }
10069   }
10070 
10071   if (DiagnosticEmitted)
10072     return;
10073 
10074   // Can't determine a more specific message, so display the generic error.
10075   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10076 }
10077 
10078 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10079 /// emit an error and return true.  If so, return false.
10080 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10081   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10082 
10083   S.CheckShadowingDeclModification(E, Loc);
10084 
10085   SourceLocation OrigLoc = Loc;
10086   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10087                                                               &Loc);
10088   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10089     IsLV = Expr::MLV_InvalidMessageExpression;
10090   if (IsLV == Expr::MLV_Valid)
10091     return false;
10092 
10093   unsigned DiagID = 0;
10094   bool NeedType = false;
10095   switch (IsLV) { // C99 6.5.16p2
10096   case Expr::MLV_ConstQualified:
10097     // Use a specialized diagnostic when we're assigning to an object
10098     // from an enclosing function or block.
10099     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10100       if (NCCK == NCCK_Block)
10101         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10102       else
10103         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10104       break;
10105     }
10106 
10107     // In ARC, use some specialized diagnostics for occasions where we
10108     // infer 'const'.  These are always pseudo-strong variables.
10109     if (S.getLangOpts().ObjCAutoRefCount) {
10110       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10111       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10112         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10113 
10114         // Use the normal diagnostic if it's pseudo-__strong but the
10115         // user actually wrote 'const'.
10116         if (var->isARCPseudoStrong() &&
10117             (!var->getTypeSourceInfo() ||
10118              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10119           // There are two pseudo-strong cases:
10120           //  - self
10121           ObjCMethodDecl *method = S.getCurMethodDecl();
10122           if (method && var == method->getSelfDecl())
10123             DiagID = method->isClassMethod()
10124               ? diag::err_typecheck_arc_assign_self_class_method
10125               : diag::err_typecheck_arc_assign_self;
10126 
10127           //  - fast enumeration variables
10128           else
10129             DiagID = diag::err_typecheck_arr_assign_enumeration;
10130 
10131           SourceRange Assign;
10132           if (Loc != OrigLoc)
10133             Assign = SourceRange(OrigLoc, OrigLoc);
10134           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10135           // We need to preserve the AST regardless, so migration tool
10136           // can do its job.
10137           return false;
10138         }
10139       }
10140     }
10141 
10142     // If none of the special cases above are triggered, then this is a
10143     // simple const assignment.
10144     if (DiagID == 0) {
10145       DiagnoseConstAssignment(S, E, Loc);
10146       return true;
10147     }
10148 
10149     break;
10150   case Expr::MLV_ConstAddrSpace:
10151     DiagnoseConstAssignment(S, E, Loc);
10152     return true;
10153   case Expr::MLV_ArrayType:
10154   case Expr::MLV_ArrayTemporary:
10155     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10156     NeedType = true;
10157     break;
10158   case Expr::MLV_NotObjectType:
10159     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10160     NeedType = true;
10161     break;
10162   case Expr::MLV_LValueCast:
10163     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10164     break;
10165   case Expr::MLV_Valid:
10166     llvm_unreachable("did not take early return for MLV_Valid");
10167   case Expr::MLV_InvalidExpression:
10168   case Expr::MLV_MemberFunction:
10169   case Expr::MLV_ClassTemporary:
10170     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10171     break;
10172   case Expr::MLV_IncompleteType:
10173   case Expr::MLV_IncompleteVoidType:
10174     return S.RequireCompleteType(Loc, E->getType(),
10175              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10176   case Expr::MLV_DuplicateVectorComponents:
10177     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10178     break;
10179   case Expr::MLV_NoSetterProperty:
10180     llvm_unreachable("readonly properties should be processed differently");
10181   case Expr::MLV_InvalidMessageExpression:
10182     DiagID = diag::err_readonly_message_assignment;
10183     break;
10184   case Expr::MLV_SubObjCPropertySetting:
10185     DiagID = diag::err_no_subobject_property_setting;
10186     break;
10187   }
10188 
10189   SourceRange Assign;
10190   if (Loc != OrigLoc)
10191     Assign = SourceRange(OrigLoc, OrigLoc);
10192   if (NeedType)
10193     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10194   else
10195     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10196   return true;
10197 }
10198 
10199 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10200                                          SourceLocation Loc,
10201                                          Sema &Sema) {
10202   // C / C++ fields
10203   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10204   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10205   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10206     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10207       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10208   }
10209 
10210   // Objective-C instance variables
10211   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10212   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10213   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10214     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10215     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10216     if (RL && RR && RL->getDecl() == RR->getDecl())
10217       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10218   }
10219 }
10220 
10221 // C99 6.5.16.1
10222 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10223                                        SourceLocation Loc,
10224                                        QualType CompoundType) {
10225   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10226 
10227   // Verify that LHS is a modifiable lvalue, and emit error if not.
10228   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10229     return QualType();
10230 
10231   QualType LHSType = LHSExpr->getType();
10232   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10233                                              CompoundType;
10234   // OpenCL v1.2 s6.1.1.1 p2:
10235   // The half data type can only be used to declare a pointer to a buffer that
10236   // contains half values
10237   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10238     LHSType->isHalfType()) {
10239     Diag(Loc, diag::err_opencl_half_load_store) << 1
10240         << LHSType.getUnqualifiedType();
10241     return QualType();
10242   }
10243 
10244   AssignConvertType ConvTy;
10245   if (CompoundType.isNull()) {
10246     Expr *RHSCheck = RHS.get();
10247 
10248     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10249 
10250     QualType LHSTy(LHSType);
10251     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10252     if (RHS.isInvalid())
10253       return QualType();
10254     // Special case of NSObject attributes on c-style pointer types.
10255     if (ConvTy == IncompatiblePointer &&
10256         ((Context.isObjCNSObjectType(LHSType) &&
10257           RHSType->isObjCObjectPointerType()) ||
10258          (Context.isObjCNSObjectType(RHSType) &&
10259           LHSType->isObjCObjectPointerType())))
10260       ConvTy = Compatible;
10261 
10262     if (ConvTy == Compatible &&
10263         LHSType->isObjCObjectType())
10264         Diag(Loc, diag::err_objc_object_assignment)
10265           << LHSType;
10266 
10267     // If the RHS is a unary plus or minus, check to see if they = and + are
10268     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10269     // instead of "x += 4".
10270     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10271       RHSCheck = ICE->getSubExpr();
10272     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10273       if ((UO->getOpcode() == UO_Plus ||
10274            UO->getOpcode() == UO_Minus) &&
10275           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10276           // Only if the two operators are exactly adjacent.
10277           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10278           // And there is a space or other character before the subexpr of the
10279           // unary +/-.  We don't want to warn on "x=-1".
10280           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10281           UO->getSubExpr()->getLocStart().isFileID()) {
10282         Diag(Loc, diag::warn_not_compound_assign)
10283           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10284           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10285       }
10286     }
10287 
10288     if (ConvTy == Compatible) {
10289       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10290         // Warn about retain cycles where a block captures the LHS, but
10291         // not if the LHS is a simple variable into which the block is
10292         // being stored...unless that variable can be captured by reference!
10293         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10294         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10295         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10296           checkRetainCycles(LHSExpr, RHS.get());
10297 
10298         // It is safe to assign a weak reference into a strong variable.
10299         // Although this code can still have problems:
10300         //   id x = self.weakProp;
10301         //   id y = self.weakProp;
10302         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10303         // paths through the function. This should be revisited if
10304         // -Wrepeated-use-of-weak is made flow-sensitive.
10305         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10306                              RHS.get()->getLocStart()))
10307           getCurFunction()->markSafeWeakUse(RHS.get());
10308 
10309       } else if (getLangOpts().ObjCAutoRefCount) {
10310         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10311       }
10312     }
10313   } else {
10314     // Compound assignment "x += y"
10315     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10316   }
10317 
10318   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10319                                RHS.get(), AA_Assigning))
10320     return QualType();
10321 
10322   CheckForNullPointerDereference(*this, LHSExpr);
10323 
10324   // C99 6.5.16p3: The type of an assignment expression is the type of the
10325   // left operand unless the left operand has qualified type, in which case
10326   // it is the unqualified version of the type of the left operand.
10327   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10328   // is converted to the type of the assignment expression (above).
10329   // C++ 5.17p1: the type of the assignment expression is that of its left
10330   // operand.
10331   return (getLangOpts().CPlusPlus
10332           ? LHSType : LHSType.getUnqualifiedType());
10333 }
10334 
10335 // Only ignore explicit casts to void.
10336 static bool IgnoreCommaOperand(const Expr *E) {
10337   E = E->IgnoreParens();
10338 
10339   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10340     if (CE->getCastKind() == CK_ToVoid) {
10341       return true;
10342     }
10343   }
10344 
10345   return false;
10346 }
10347 
10348 // Look for instances where it is likely the comma operator is confused with
10349 // another operator.  There is a whitelist of acceptable expressions for the
10350 // left hand side of the comma operator, otherwise emit a warning.
10351 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10352   // No warnings in macros
10353   if (Loc.isMacroID())
10354     return;
10355 
10356   // Don't warn in template instantiations.
10357   if (!ActiveTemplateInstantiations.empty())
10358     return;
10359 
10360   // Scope isn't fine-grained enough to whitelist the specific cases, so
10361   // instead, skip more than needed, then call back into here with the
10362   // CommaVisitor in SemaStmt.cpp.
10363   // The whitelisted locations are the initialization and increment portions
10364   // of a for loop.  The additional checks are on the condition of
10365   // if statements, do/while loops, and for loops.
10366   const unsigned ForIncrementFlags =
10367       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10368   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10369   const unsigned ScopeFlags = getCurScope()->getFlags();
10370   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10371       (ScopeFlags & ForInitFlags) == ForInitFlags)
10372     return;
10373 
10374   // If there are multiple comma operators used together, get the RHS of the
10375   // of the comma operator as the LHS.
10376   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10377     if (BO->getOpcode() != BO_Comma)
10378       break;
10379     LHS = BO->getRHS();
10380   }
10381 
10382   // Only allow some expressions on LHS to not warn.
10383   if (IgnoreCommaOperand(LHS))
10384     return;
10385 
10386   Diag(Loc, diag::warn_comma_operator);
10387   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10388       << LHS->getSourceRange()
10389       << FixItHint::CreateInsertion(LHS->getLocStart(),
10390                                     LangOpts.CPlusPlus ? "static_cast<void>("
10391                                                        : "(void)(")
10392       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10393                                     ")");
10394 }
10395 
10396 // C99 6.5.17
10397 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10398                                    SourceLocation Loc) {
10399   LHS = S.CheckPlaceholderExpr(LHS.get());
10400   RHS = S.CheckPlaceholderExpr(RHS.get());
10401   if (LHS.isInvalid() || RHS.isInvalid())
10402     return QualType();
10403 
10404   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10405   // operands, but not unary promotions.
10406   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10407 
10408   // So we treat the LHS as a ignored value, and in C++ we allow the
10409   // containing site to determine what should be done with the RHS.
10410   LHS = S.IgnoredValueConversions(LHS.get());
10411   if (LHS.isInvalid())
10412     return QualType();
10413 
10414   S.DiagnoseUnusedExprResult(LHS.get());
10415 
10416   if (!S.getLangOpts().CPlusPlus) {
10417     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10418     if (RHS.isInvalid())
10419       return QualType();
10420     if (!RHS.get()->getType()->isVoidType())
10421       S.RequireCompleteType(Loc, RHS.get()->getType(),
10422                             diag::err_incomplete_type);
10423   }
10424 
10425   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10426     S.DiagnoseCommaOperator(LHS.get(), Loc);
10427 
10428   return RHS.get()->getType();
10429 }
10430 
10431 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10432 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10433 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10434                                                ExprValueKind &VK,
10435                                                ExprObjectKind &OK,
10436                                                SourceLocation OpLoc,
10437                                                bool IsInc, bool IsPrefix) {
10438   if (Op->isTypeDependent())
10439     return S.Context.DependentTy;
10440 
10441   QualType ResType = Op->getType();
10442   // Atomic types can be used for increment / decrement where the non-atomic
10443   // versions can, so ignore the _Atomic() specifier for the purpose of
10444   // checking.
10445   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10446     ResType = ResAtomicType->getValueType();
10447 
10448   assert(!ResType.isNull() && "no type for increment/decrement expression");
10449 
10450   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10451     // Decrement of bool is not allowed.
10452     if (!IsInc) {
10453       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10454       return QualType();
10455     }
10456     // Increment of bool sets it to true, but is deprecated.
10457     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10458                                               : diag::warn_increment_bool)
10459       << Op->getSourceRange();
10460   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10461     // Error on enum increments and decrements in C++ mode
10462     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10463     return QualType();
10464   } else if (ResType->isRealType()) {
10465     // OK!
10466   } else if (ResType->isPointerType()) {
10467     // C99 6.5.2.4p2, 6.5.6p2
10468     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10469       return QualType();
10470   } else if (ResType->isObjCObjectPointerType()) {
10471     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10472     // Otherwise, we just need a complete type.
10473     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10474         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10475       return QualType();
10476   } else if (ResType->isAnyComplexType()) {
10477     // C99 does not support ++/-- on complex types, we allow as an extension.
10478     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10479       << ResType << Op->getSourceRange();
10480   } else if (ResType->isPlaceholderType()) {
10481     ExprResult PR = S.CheckPlaceholderExpr(Op);
10482     if (PR.isInvalid()) return QualType();
10483     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10484                                           IsInc, IsPrefix);
10485   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10486     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10487   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10488              (ResType->getAs<VectorType>()->getVectorKind() !=
10489               VectorType::AltiVecBool)) {
10490     // The z vector extensions allow ++ and -- for non-bool vectors.
10491   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10492             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10493     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10494   } else {
10495     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10496       << ResType << int(IsInc) << Op->getSourceRange();
10497     return QualType();
10498   }
10499   // At this point, we know we have a real, complex or pointer type.
10500   // Now make sure the operand is a modifiable lvalue.
10501   if (CheckForModifiableLvalue(Op, OpLoc, S))
10502     return QualType();
10503   // In C++, a prefix increment is the same type as the operand. Otherwise
10504   // (in C or with postfix), the increment is the unqualified type of the
10505   // operand.
10506   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10507     VK = VK_LValue;
10508     OK = Op->getObjectKind();
10509     return ResType;
10510   } else {
10511     VK = VK_RValue;
10512     return ResType.getUnqualifiedType();
10513   }
10514 }
10515 
10516 
10517 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10518 /// This routine allows us to typecheck complex/recursive expressions
10519 /// where the declaration is needed for type checking. We only need to
10520 /// handle cases when the expression references a function designator
10521 /// or is an lvalue. Here are some examples:
10522 ///  - &(x) => x
10523 ///  - &*****f => f for f a function designator.
10524 ///  - &s.xx => s
10525 ///  - &s.zz[1].yy -> s, if zz is an array
10526 ///  - *(x + 1) -> x, if x is an array
10527 ///  - &"123"[2] -> 0
10528 ///  - & __real__ x -> x
10529 static ValueDecl *getPrimaryDecl(Expr *E) {
10530   switch (E->getStmtClass()) {
10531   case Stmt::DeclRefExprClass:
10532     return cast<DeclRefExpr>(E)->getDecl();
10533   case Stmt::MemberExprClass:
10534     // If this is an arrow operator, the address is an offset from
10535     // the base's value, so the object the base refers to is
10536     // irrelevant.
10537     if (cast<MemberExpr>(E)->isArrow())
10538       return nullptr;
10539     // Otherwise, the expression refers to a part of the base
10540     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10541   case Stmt::ArraySubscriptExprClass: {
10542     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10543     // promotion of register arrays earlier.
10544     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10545     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10546       if (ICE->getSubExpr()->getType()->isArrayType())
10547         return getPrimaryDecl(ICE->getSubExpr());
10548     }
10549     return nullptr;
10550   }
10551   case Stmt::UnaryOperatorClass: {
10552     UnaryOperator *UO = cast<UnaryOperator>(E);
10553 
10554     switch(UO->getOpcode()) {
10555     case UO_Real:
10556     case UO_Imag:
10557     case UO_Extension:
10558       return getPrimaryDecl(UO->getSubExpr());
10559     default:
10560       return nullptr;
10561     }
10562   }
10563   case Stmt::ParenExprClass:
10564     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10565   case Stmt::ImplicitCastExprClass:
10566     // If the result of an implicit cast is an l-value, we care about
10567     // the sub-expression; otherwise, the result here doesn't matter.
10568     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10569   default:
10570     return nullptr;
10571   }
10572 }
10573 
10574 namespace {
10575   enum {
10576     AO_Bit_Field = 0,
10577     AO_Vector_Element = 1,
10578     AO_Property_Expansion = 2,
10579     AO_Register_Variable = 3,
10580     AO_No_Error = 4
10581   };
10582 }
10583 /// \brief Diagnose invalid operand for address of operations.
10584 ///
10585 /// \param Type The type of operand which cannot have its address taken.
10586 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10587                                          Expr *E, unsigned Type) {
10588   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10589 }
10590 
10591 /// CheckAddressOfOperand - The operand of & must be either a function
10592 /// designator or an lvalue designating an object. If it is an lvalue, the
10593 /// object cannot be declared with storage class register or be a bit field.
10594 /// Note: The usual conversions are *not* applied to the operand of the &
10595 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10596 /// In C++, the operand might be an overloaded function name, in which case
10597 /// we allow the '&' but retain the overloaded-function type.
10598 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10599   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10600     if (PTy->getKind() == BuiltinType::Overload) {
10601       Expr *E = OrigOp.get()->IgnoreParens();
10602       if (!isa<OverloadExpr>(E)) {
10603         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10604         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10605           << OrigOp.get()->getSourceRange();
10606         return QualType();
10607       }
10608 
10609       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10610       if (isa<UnresolvedMemberExpr>(Ovl))
10611         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10612           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10613             << OrigOp.get()->getSourceRange();
10614           return QualType();
10615         }
10616 
10617       return Context.OverloadTy;
10618     }
10619 
10620     if (PTy->getKind() == BuiltinType::UnknownAny)
10621       return Context.UnknownAnyTy;
10622 
10623     if (PTy->getKind() == BuiltinType::BoundMember) {
10624       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10625         << OrigOp.get()->getSourceRange();
10626       return QualType();
10627     }
10628 
10629     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10630     if (OrigOp.isInvalid()) return QualType();
10631   }
10632 
10633   if (OrigOp.get()->isTypeDependent())
10634     return Context.DependentTy;
10635 
10636   assert(!OrigOp.get()->getType()->isPlaceholderType());
10637 
10638   // Make sure to ignore parentheses in subsequent checks
10639   Expr *op = OrigOp.get()->IgnoreParens();
10640 
10641   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10642   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10643     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10644     return QualType();
10645   }
10646 
10647   if (getLangOpts().C99) {
10648     // Implement C99-only parts of addressof rules.
10649     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10650       if (uOp->getOpcode() == UO_Deref)
10651         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10652         // (assuming the deref expression is valid).
10653         return uOp->getSubExpr()->getType();
10654     }
10655     // Technically, there should be a check for array subscript
10656     // expressions here, but the result of one is always an lvalue anyway.
10657   }
10658   ValueDecl *dcl = getPrimaryDecl(op);
10659 
10660   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10661     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10662                                            op->getLocStart()))
10663       return QualType();
10664 
10665   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10666   unsigned AddressOfError = AO_No_Error;
10667 
10668   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10669     bool sfinae = (bool)isSFINAEContext();
10670     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10671                                   : diag::ext_typecheck_addrof_temporary)
10672       << op->getType() << op->getSourceRange();
10673     if (sfinae)
10674       return QualType();
10675     // Materialize the temporary as an lvalue so that we can take its address.
10676     OrigOp = op =
10677         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10678   } else if (isa<ObjCSelectorExpr>(op)) {
10679     return Context.getPointerType(op->getType());
10680   } else if (lval == Expr::LV_MemberFunction) {
10681     // If it's an instance method, make a member pointer.
10682     // The expression must have exactly the form &A::foo.
10683 
10684     // If the underlying expression isn't a decl ref, give up.
10685     if (!isa<DeclRefExpr>(op)) {
10686       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10687         << OrigOp.get()->getSourceRange();
10688       return QualType();
10689     }
10690     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10691     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10692 
10693     // The id-expression was parenthesized.
10694     if (OrigOp.get() != DRE) {
10695       Diag(OpLoc, diag::err_parens_pointer_member_function)
10696         << OrigOp.get()->getSourceRange();
10697 
10698     // The method was named without a qualifier.
10699     } else if (!DRE->getQualifier()) {
10700       if (MD->getParent()->getName().empty())
10701         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10702           << op->getSourceRange();
10703       else {
10704         SmallString<32> Str;
10705         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10706         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10707           << op->getSourceRange()
10708           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10709       }
10710     }
10711 
10712     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10713     if (isa<CXXDestructorDecl>(MD))
10714       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10715 
10716     QualType MPTy = Context.getMemberPointerType(
10717         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10718     // Under the MS ABI, lock down the inheritance model now.
10719     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10720       (void)isCompleteType(OpLoc, MPTy);
10721     return MPTy;
10722   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10723     // C99 6.5.3.2p1
10724     // The operand must be either an l-value or a function designator
10725     if (!op->getType()->isFunctionType()) {
10726       // Use a special diagnostic for loads from property references.
10727       if (isa<PseudoObjectExpr>(op)) {
10728         AddressOfError = AO_Property_Expansion;
10729       } else {
10730         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10731           << op->getType() << op->getSourceRange();
10732         return QualType();
10733       }
10734     }
10735   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10736     // The operand cannot be a bit-field
10737     AddressOfError = AO_Bit_Field;
10738   } else if (op->getObjectKind() == OK_VectorComponent) {
10739     // The operand cannot be an element of a vector
10740     AddressOfError = AO_Vector_Element;
10741   } else if (dcl) { // C99 6.5.3.2p1
10742     // We have an lvalue with a decl. Make sure the decl is not declared
10743     // with the register storage-class specifier.
10744     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10745       // in C++ it is not error to take address of a register
10746       // variable (c++03 7.1.1P3)
10747       if (vd->getStorageClass() == SC_Register &&
10748           !getLangOpts().CPlusPlus) {
10749         AddressOfError = AO_Register_Variable;
10750       }
10751     } else if (isa<MSPropertyDecl>(dcl)) {
10752       AddressOfError = AO_Property_Expansion;
10753     } else if (isa<FunctionTemplateDecl>(dcl)) {
10754       return Context.OverloadTy;
10755     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10756       // Okay: we can take the address of a field.
10757       // Could be a pointer to member, though, if there is an explicit
10758       // scope qualifier for the class.
10759       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10760         DeclContext *Ctx = dcl->getDeclContext();
10761         if (Ctx && Ctx->isRecord()) {
10762           if (dcl->getType()->isReferenceType()) {
10763             Diag(OpLoc,
10764                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10765               << dcl->getDeclName() << dcl->getType();
10766             return QualType();
10767           }
10768 
10769           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10770             Ctx = Ctx->getParent();
10771 
10772           QualType MPTy = Context.getMemberPointerType(
10773               op->getType(),
10774               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10775           // Under the MS ABI, lock down the inheritance model now.
10776           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10777             (void)isCompleteType(OpLoc, MPTy);
10778           return MPTy;
10779         }
10780       }
10781     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10782                !isa<BindingDecl>(dcl))
10783       llvm_unreachable("Unknown/unexpected decl type");
10784   }
10785 
10786   if (AddressOfError != AO_No_Error) {
10787     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10788     return QualType();
10789   }
10790 
10791   if (lval == Expr::LV_IncompleteVoidType) {
10792     // Taking the address of a void variable is technically illegal, but we
10793     // allow it in cases which are otherwise valid.
10794     // Example: "extern void x; void* y = &x;".
10795     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10796   }
10797 
10798   // If the operand has type "type", the result has type "pointer to type".
10799   if (op->getType()->isObjCObjectType())
10800     return Context.getObjCObjectPointerType(op->getType());
10801 
10802   CheckAddressOfPackedMember(op);
10803 
10804   return Context.getPointerType(op->getType());
10805 }
10806 
10807 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10808   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10809   if (!DRE)
10810     return;
10811   const Decl *D = DRE->getDecl();
10812   if (!D)
10813     return;
10814   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10815   if (!Param)
10816     return;
10817   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10818     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10819       return;
10820   if (FunctionScopeInfo *FD = S.getCurFunction())
10821     if (!FD->ModifiedNonNullParams.count(Param))
10822       FD->ModifiedNonNullParams.insert(Param);
10823 }
10824 
10825 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10826 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10827                                         SourceLocation OpLoc) {
10828   if (Op->isTypeDependent())
10829     return S.Context.DependentTy;
10830 
10831   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10832   if (ConvResult.isInvalid())
10833     return QualType();
10834   Op = ConvResult.get();
10835   QualType OpTy = Op->getType();
10836   QualType Result;
10837 
10838   if (isa<CXXReinterpretCastExpr>(Op)) {
10839     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10840     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10841                                      Op->getSourceRange());
10842   }
10843 
10844   if (const PointerType *PT = OpTy->getAs<PointerType>())
10845   {
10846     Result = PT->getPointeeType();
10847   }
10848   else if (const ObjCObjectPointerType *OPT =
10849              OpTy->getAs<ObjCObjectPointerType>())
10850     Result = OPT->getPointeeType();
10851   else {
10852     ExprResult PR = S.CheckPlaceholderExpr(Op);
10853     if (PR.isInvalid()) return QualType();
10854     if (PR.get() != Op)
10855       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10856   }
10857 
10858   if (Result.isNull()) {
10859     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10860       << OpTy << Op->getSourceRange();
10861     return QualType();
10862   }
10863 
10864   // Note that per both C89 and C99, indirection is always legal, even if Result
10865   // is an incomplete type or void.  It would be possible to warn about
10866   // dereferencing a void pointer, but it's completely well-defined, and such a
10867   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10868   // for pointers to 'void' but is fine for any other pointer type:
10869   //
10870   // C++ [expr.unary.op]p1:
10871   //   [...] the expression to which [the unary * operator] is applied shall
10872   //   be a pointer to an object type, or a pointer to a function type
10873   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10874     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10875       << OpTy << Op->getSourceRange();
10876 
10877   // Dereferences are usually l-values...
10878   VK = VK_LValue;
10879 
10880   // ...except that certain expressions are never l-values in C.
10881   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10882     VK = VK_RValue;
10883 
10884   return Result;
10885 }
10886 
10887 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10888   BinaryOperatorKind Opc;
10889   switch (Kind) {
10890   default: llvm_unreachable("Unknown binop!");
10891   case tok::periodstar:           Opc = BO_PtrMemD; break;
10892   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10893   case tok::star:                 Opc = BO_Mul; break;
10894   case tok::slash:                Opc = BO_Div; break;
10895   case tok::percent:              Opc = BO_Rem; break;
10896   case tok::plus:                 Opc = BO_Add; break;
10897   case tok::minus:                Opc = BO_Sub; break;
10898   case tok::lessless:             Opc = BO_Shl; break;
10899   case tok::greatergreater:       Opc = BO_Shr; break;
10900   case tok::lessequal:            Opc = BO_LE; break;
10901   case tok::less:                 Opc = BO_LT; break;
10902   case tok::greaterequal:         Opc = BO_GE; break;
10903   case tok::greater:              Opc = BO_GT; break;
10904   case tok::exclaimequal:         Opc = BO_NE; break;
10905   case tok::equalequal:           Opc = BO_EQ; break;
10906   case tok::amp:                  Opc = BO_And; break;
10907   case tok::caret:                Opc = BO_Xor; break;
10908   case tok::pipe:                 Opc = BO_Or; break;
10909   case tok::ampamp:               Opc = BO_LAnd; break;
10910   case tok::pipepipe:             Opc = BO_LOr; break;
10911   case tok::equal:                Opc = BO_Assign; break;
10912   case tok::starequal:            Opc = BO_MulAssign; break;
10913   case tok::slashequal:           Opc = BO_DivAssign; break;
10914   case tok::percentequal:         Opc = BO_RemAssign; break;
10915   case tok::plusequal:            Opc = BO_AddAssign; break;
10916   case tok::minusequal:           Opc = BO_SubAssign; break;
10917   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10918   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10919   case tok::ampequal:             Opc = BO_AndAssign; break;
10920   case tok::caretequal:           Opc = BO_XorAssign; break;
10921   case tok::pipeequal:            Opc = BO_OrAssign; break;
10922   case tok::comma:                Opc = BO_Comma; break;
10923   }
10924   return Opc;
10925 }
10926 
10927 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10928   tok::TokenKind Kind) {
10929   UnaryOperatorKind Opc;
10930   switch (Kind) {
10931   default: llvm_unreachable("Unknown unary op!");
10932   case tok::plusplus:     Opc = UO_PreInc; break;
10933   case tok::minusminus:   Opc = UO_PreDec; break;
10934   case tok::amp:          Opc = UO_AddrOf; break;
10935   case tok::star:         Opc = UO_Deref; break;
10936   case tok::plus:         Opc = UO_Plus; break;
10937   case tok::minus:        Opc = UO_Minus; break;
10938   case tok::tilde:        Opc = UO_Not; break;
10939   case tok::exclaim:      Opc = UO_LNot; break;
10940   case tok::kw___real:    Opc = UO_Real; break;
10941   case tok::kw___imag:    Opc = UO_Imag; break;
10942   case tok::kw___extension__: Opc = UO_Extension; break;
10943   }
10944   return Opc;
10945 }
10946 
10947 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10948 /// This warning is only emitted for builtin assignment operations. It is also
10949 /// suppressed in the event of macro expansions.
10950 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10951                                    SourceLocation OpLoc) {
10952   if (!S.ActiveTemplateInstantiations.empty())
10953     return;
10954   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10955     return;
10956   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10957   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10958   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10959   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10960   if (!LHSDeclRef || !RHSDeclRef ||
10961       LHSDeclRef->getLocation().isMacroID() ||
10962       RHSDeclRef->getLocation().isMacroID())
10963     return;
10964   const ValueDecl *LHSDecl =
10965     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10966   const ValueDecl *RHSDecl =
10967     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10968   if (LHSDecl != RHSDecl)
10969     return;
10970   if (LHSDecl->getType().isVolatileQualified())
10971     return;
10972   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10973     if (RefTy->getPointeeType().isVolatileQualified())
10974       return;
10975 
10976   S.Diag(OpLoc, diag::warn_self_assignment)
10977       << LHSDeclRef->getType()
10978       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10979 }
10980 
10981 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10982 /// is usually indicative of introspection within the Objective-C pointer.
10983 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10984                                           SourceLocation OpLoc) {
10985   if (!S.getLangOpts().ObjC1)
10986     return;
10987 
10988   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10989   const Expr *LHS = L.get();
10990   const Expr *RHS = R.get();
10991 
10992   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10993     ObjCPointerExpr = LHS;
10994     OtherExpr = RHS;
10995   }
10996   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10997     ObjCPointerExpr = RHS;
10998     OtherExpr = LHS;
10999   }
11000 
11001   // This warning is deliberately made very specific to reduce false
11002   // positives with logic that uses '&' for hashing.  This logic mainly
11003   // looks for code trying to introspect into tagged pointers, which
11004   // code should generally never do.
11005   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11006     unsigned Diag = diag::warn_objc_pointer_masking;
11007     // Determine if we are introspecting the result of performSelectorXXX.
11008     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11009     // Special case messages to -performSelector and friends, which
11010     // can return non-pointer values boxed in a pointer value.
11011     // Some clients may wish to silence warnings in this subcase.
11012     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11013       Selector S = ME->getSelector();
11014       StringRef SelArg0 = S.getNameForSlot(0);
11015       if (SelArg0.startswith("performSelector"))
11016         Diag = diag::warn_objc_pointer_masking_performSelector;
11017     }
11018 
11019     S.Diag(OpLoc, Diag)
11020       << ObjCPointerExpr->getSourceRange();
11021   }
11022 }
11023 
11024 static NamedDecl *getDeclFromExpr(Expr *E) {
11025   if (!E)
11026     return nullptr;
11027   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11028     return DRE->getDecl();
11029   if (auto *ME = dyn_cast<MemberExpr>(E))
11030     return ME->getMemberDecl();
11031   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11032     return IRE->getDecl();
11033   return nullptr;
11034 }
11035 
11036 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11037 /// operator @p Opc at location @c TokLoc. This routine only supports
11038 /// built-in operations; ActOnBinOp handles overloaded operators.
11039 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11040                                     BinaryOperatorKind Opc,
11041                                     Expr *LHSExpr, Expr *RHSExpr) {
11042   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11043     // The syntax only allows initializer lists on the RHS of assignment,
11044     // so we don't need to worry about accepting invalid code for
11045     // non-assignment operators.
11046     // C++11 5.17p9:
11047     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11048     //   of x = {} is x = T().
11049     InitializationKind Kind =
11050         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11051     InitializedEntity Entity =
11052         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11053     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11054     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11055     if (Init.isInvalid())
11056       return Init;
11057     RHSExpr = Init.get();
11058   }
11059 
11060   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11061   QualType ResultTy;     // Result type of the binary operator.
11062   // The following two variables are used for compound assignment operators
11063   QualType CompLHSTy;    // Type of LHS after promotions for computation
11064   QualType CompResultTy; // Type of computation result
11065   ExprValueKind VK = VK_RValue;
11066   ExprObjectKind OK = OK_Ordinary;
11067 
11068   if (!getLangOpts().CPlusPlus) {
11069     // C cannot handle TypoExpr nodes on either side of a binop because it
11070     // doesn't handle dependent types properly, so make sure any TypoExprs have
11071     // been dealt with before checking the operands.
11072     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11073     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11074       if (Opc != BO_Assign)
11075         return ExprResult(E);
11076       // Avoid correcting the RHS to the same Expr as the LHS.
11077       Decl *D = getDeclFromExpr(E);
11078       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11079     });
11080     if (!LHS.isUsable() || !RHS.isUsable())
11081       return ExprError();
11082   }
11083 
11084   if (getLangOpts().OpenCL) {
11085     QualType LHSTy = LHSExpr->getType();
11086     QualType RHSTy = RHSExpr->getType();
11087     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11088     // the ATOMIC_VAR_INIT macro.
11089     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11090       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11091       if (BO_Assign == Opc)
11092         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11093       else
11094         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11095       return ExprError();
11096     }
11097 
11098     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11099     // only with a builtin functions and therefore should be disallowed here.
11100     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11101         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11102         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11103         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11104       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11105       return ExprError();
11106     }
11107   }
11108 
11109   switch (Opc) {
11110   case BO_Assign:
11111     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11112     if (getLangOpts().CPlusPlus &&
11113         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11114       VK = LHS.get()->getValueKind();
11115       OK = LHS.get()->getObjectKind();
11116     }
11117     if (!ResultTy.isNull()) {
11118       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11119       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11120     }
11121     RecordModifiableNonNullParam(*this, LHS.get());
11122     break;
11123   case BO_PtrMemD:
11124   case BO_PtrMemI:
11125     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11126                                             Opc == BO_PtrMemI);
11127     break;
11128   case BO_Mul:
11129   case BO_Div:
11130     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11131                                            Opc == BO_Div);
11132     break;
11133   case BO_Rem:
11134     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11135     break;
11136   case BO_Add:
11137     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11138     break;
11139   case BO_Sub:
11140     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11141     break;
11142   case BO_Shl:
11143   case BO_Shr:
11144     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11145     break;
11146   case BO_LE:
11147   case BO_LT:
11148   case BO_GE:
11149   case BO_GT:
11150     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11151     break;
11152   case BO_EQ:
11153   case BO_NE:
11154     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11155     break;
11156   case BO_And:
11157     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11158   case BO_Xor:
11159   case BO_Or:
11160     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11161     break;
11162   case BO_LAnd:
11163   case BO_LOr:
11164     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11165     break;
11166   case BO_MulAssign:
11167   case BO_DivAssign:
11168     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11169                                                Opc == BO_DivAssign);
11170     CompLHSTy = CompResultTy;
11171     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11172       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11173     break;
11174   case BO_RemAssign:
11175     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11176     CompLHSTy = CompResultTy;
11177     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11178       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11179     break;
11180   case BO_AddAssign:
11181     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11182     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11183       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11184     break;
11185   case BO_SubAssign:
11186     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11187     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11188       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11189     break;
11190   case BO_ShlAssign:
11191   case BO_ShrAssign:
11192     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11193     CompLHSTy = CompResultTy;
11194     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11195       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11196     break;
11197   case BO_AndAssign:
11198   case BO_OrAssign: // fallthrough
11199     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11200   case BO_XorAssign:
11201     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11202     CompLHSTy = CompResultTy;
11203     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11204       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11205     break;
11206   case BO_Comma:
11207     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11208     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11209       VK = RHS.get()->getValueKind();
11210       OK = RHS.get()->getObjectKind();
11211     }
11212     break;
11213   }
11214   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11215     return ExprError();
11216 
11217   // Check for array bounds violations for both sides of the BinaryOperator
11218   CheckArrayAccess(LHS.get());
11219   CheckArrayAccess(RHS.get());
11220 
11221   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11222     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11223                                                  &Context.Idents.get("object_setClass"),
11224                                                  SourceLocation(), LookupOrdinaryName);
11225     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11226       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11227       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11228       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11229       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11230       FixItHint::CreateInsertion(RHSLocEnd, ")");
11231     }
11232     else
11233       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11234   }
11235   else if (const ObjCIvarRefExpr *OIRE =
11236            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11237     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11238 
11239   if (CompResultTy.isNull())
11240     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11241                                         OK, OpLoc, FPFeatures.fp_contract);
11242   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11243       OK_ObjCProperty) {
11244     VK = VK_LValue;
11245     OK = LHS.get()->getObjectKind();
11246   }
11247   return new (Context) CompoundAssignOperator(
11248       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11249       OpLoc, FPFeatures.fp_contract);
11250 }
11251 
11252 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11253 /// operators are mixed in a way that suggests that the programmer forgot that
11254 /// comparison operators have higher precedence. The most typical example of
11255 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11256 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11257                                       SourceLocation OpLoc, Expr *LHSExpr,
11258                                       Expr *RHSExpr) {
11259   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11260   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11261 
11262   // Check that one of the sides is a comparison operator and the other isn't.
11263   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11264   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11265   if (isLeftComp == isRightComp)
11266     return;
11267 
11268   // Bitwise operations are sometimes used as eager logical ops.
11269   // Don't diagnose this.
11270   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11271   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11272   if (isLeftBitwise || isRightBitwise)
11273     return;
11274 
11275   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11276                                                    OpLoc)
11277                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11278   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11279   SourceRange ParensRange = isLeftComp ?
11280       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11281     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11282 
11283   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11284     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11285   SuggestParentheses(Self, OpLoc,
11286     Self.PDiag(diag::note_precedence_silence) << OpStr,
11287     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11288   SuggestParentheses(Self, OpLoc,
11289     Self.PDiag(diag::note_precedence_bitwise_first)
11290       << BinaryOperator::getOpcodeStr(Opc),
11291     ParensRange);
11292 }
11293 
11294 /// \brief It accepts a '&&' expr that is inside a '||' one.
11295 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11296 /// in parentheses.
11297 static void
11298 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11299                                        BinaryOperator *Bop) {
11300   assert(Bop->getOpcode() == BO_LAnd);
11301   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11302       << Bop->getSourceRange() << OpLoc;
11303   SuggestParentheses(Self, Bop->getOperatorLoc(),
11304     Self.PDiag(diag::note_precedence_silence)
11305       << Bop->getOpcodeStr(),
11306     Bop->getSourceRange());
11307 }
11308 
11309 /// \brief Returns true if the given expression can be evaluated as a constant
11310 /// 'true'.
11311 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11312   bool Res;
11313   return !E->isValueDependent() &&
11314          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11315 }
11316 
11317 /// \brief Returns true if the given expression can be evaluated as a constant
11318 /// 'false'.
11319 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11320   bool Res;
11321   return !E->isValueDependent() &&
11322          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11323 }
11324 
11325 /// \brief Look for '&&' in the left hand of a '||' expr.
11326 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11327                                              Expr *LHSExpr, Expr *RHSExpr) {
11328   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11329     if (Bop->getOpcode() == BO_LAnd) {
11330       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11331       if (EvaluatesAsFalse(S, RHSExpr))
11332         return;
11333       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11334       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11335         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11336     } else if (Bop->getOpcode() == BO_LOr) {
11337       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11338         // If it's "a || b && 1 || c" we didn't warn earlier for
11339         // "a || b && 1", but warn now.
11340         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11341           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11342       }
11343     }
11344   }
11345 }
11346 
11347 /// \brief Look for '&&' in the right hand of a '||' expr.
11348 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11349                                              Expr *LHSExpr, Expr *RHSExpr) {
11350   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11351     if (Bop->getOpcode() == BO_LAnd) {
11352       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11353       if (EvaluatesAsFalse(S, LHSExpr))
11354         return;
11355       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11356       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11357         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11358     }
11359   }
11360 }
11361 
11362 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11363 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11364 /// the '&' expression in parentheses.
11365 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11366                                          SourceLocation OpLoc, Expr *SubExpr) {
11367   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11368     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11369       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11370         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11371         << Bop->getSourceRange() << OpLoc;
11372       SuggestParentheses(S, Bop->getOperatorLoc(),
11373         S.PDiag(diag::note_precedence_silence)
11374           << Bop->getOpcodeStr(),
11375         Bop->getSourceRange());
11376     }
11377   }
11378 }
11379 
11380 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11381                                     Expr *SubExpr, StringRef Shift) {
11382   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11383     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11384       StringRef Op = Bop->getOpcodeStr();
11385       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11386           << Bop->getSourceRange() << OpLoc << Shift << Op;
11387       SuggestParentheses(S, Bop->getOperatorLoc(),
11388           S.PDiag(diag::note_precedence_silence) << Op,
11389           Bop->getSourceRange());
11390     }
11391   }
11392 }
11393 
11394 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11395                                  Expr *LHSExpr, Expr *RHSExpr) {
11396   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11397   if (!OCE)
11398     return;
11399 
11400   FunctionDecl *FD = OCE->getDirectCallee();
11401   if (!FD || !FD->isOverloadedOperator())
11402     return;
11403 
11404   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11405   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11406     return;
11407 
11408   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11409       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11410       << (Kind == OO_LessLess);
11411   SuggestParentheses(S, OCE->getOperatorLoc(),
11412                      S.PDiag(diag::note_precedence_silence)
11413                          << (Kind == OO_LessLess ? "<<" : ">>"),
11414                      OCE->getSourceRange());
11415   SuggestParentheses(S, OpLoc,
11416                      S.PDiag(diag::note_evaluate_comparison_first),
11417                      SourceRange(OCE->getArg(1)->getLocStart(),
11418                                  RHSExpr->getLocEnd()));
11419 }
11420 
11421 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11422 /// precedence.
11423 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11424                                     SourceLocation OpLoc, Expr *LHSExpr,
11425                                     Expr *RHSExpr){
11426   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11427   if (BinaryOperator::isBitwiseOp(Opc))
11428     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11429 
11430   // Diagnose "arg1 & arg2 | arg3"
11431   if ((Opc == BO_Or || Opc == BO_Xor) &&
11432       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11433     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11434     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11435   }
11436 
11437   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11438   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11439   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11440     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11441     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11442   }
11443 
11444   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11445       || Opc == BO_Shr) {
11446     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11447     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11448     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11449   }
11450 
11451   // Warn on overloaded shift operators and comparisons, such as:
11452   // cout << 5 == 4;
11453   if (BinaryOperator::isComparisonOp(Opc))
11454     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11455 }
11456 
11457 // Binary Operators.  'Tok' is the token for the operator.
11458 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11459                             tok::TokenKind Kind,
11460                             Expr *LHSExpr, Expr *RHSExpr) {
11461   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11462   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11463   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11464 
11465   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11466   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11467 
11468   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11469 }
11470 
11471 /// Build an overloaded binary operator expression in the given scope.
11472 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11473                                        BinaryOperatorKind Opc,
11474                                        Expr *LHS, Expr *RHS) {
11475   // Find all of the overloaded operators visible from this
11476   // point. We perform both an operator-name lookup from the local
11477   // scope and an argument-dependent lookup based on the types of
11478   // the arguments.
11479   UnresolvedSet<16> Functions;
11480   OverloadedOperatorKind OverOp
11481     = BinaryOperator::getOverloadedOperator(Opc);
11482   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11483     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11484                                    RHS->getType(), Functions);
11485 
11486   // Build the (potentially-overloaded, potentially-dependent)
11487   // binary operation.
11488   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11489 }
11490 
11491 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11492                             BinaryOperatorKind Opc,
11493                             Expr *LHSExpr, Expr *RHSExpr) {
11494   // We want to end up calling one of checkPseudoObjectAssignment
11495   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11496   // both expressions are overloadable or either is type-dependent),
11497   // or CreateBuiltinBinOp (in any other case).  We also want to get
11498   // any placeholder types out of the way.
11499 
11500   // Handle pseudo-objects in the LHS.
11501   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11502     // Assignments with a pseudo-object l-value need special analysis.
11503     if (pty->getKind() == BuiltinType::PseudoObject &&
11504         BinaryOperator::isAssignmentOp(Opc))
11505       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11506 
11507     // Don't resolve overloads if the other type is overloadable.
11508     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11509       // We can't actually test that if we still have a placeholder,
11510       // though.  Fortunately, none of the exceptions we see in that
11511       // code below are valid when the LHS is an overload set.  Note
11512       // that an overload set can be dependently-typed, but it never
11513       // instantiates to having an overloadable type.
11514       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11515       if (resolvedRHS.isInvalid()) return ExprError();
11516       RHSExpr = resolvedRHS.get();
11517 
11518       if (RHSExpr->isTypeDependent() ||
11519           RHSExpr->getType()->isOverloadableType())
11520         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11521     }
11522 
11523     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11524     if (LHS.isInvalid()) return ExprError();
11525     LHSExpr = LHS.get();
11526   }
11527 
11528   // Handle pseudo-objects in the RHS.
11529   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11530     // An overload in the RHS can potentially be resolved by the type
11531     // being assigned to.
11532     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11533       if (getLangOpts().CPlusPlus &&
11534           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11535            LHSExpr->getType()->isOverloadableType()))
11536         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11537 
11538       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11539     }
11540 
11541     // Don't resolve overloads if the other type is overloadable.
11542     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11543         LHSExpr->getType()->isOverloadableType())
11544       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11545 
11546     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11547     if (!resolvedRHS.isUsable()) return ExprError();
11548     RHSExpr = resolvedRHS.get();
11549   }
11550 
11551   if (getLangOpts().CPlusPlus) {
11552     // If either expression is type-dependent, always build an
11553     // overloaded op.
11554     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11555       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11556 
11557     // Otherwise, build an overloaded op if either expression has an
11558     // overloadable type.
11559     if (LHSExpr->getType()->isOverloadableType() ||
11560         RHSExpr->getType()->isOverloadableType())
11561       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11562   }
11563 
11564   // Build a built-in binary operation.
11565   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11566 }
11567 
11568 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11569                                       UnaryOperatorKind Opc,
11570                                       Expr *InputExpr) {
11571   ExprResult Input = InputExpr;
11572   ExprValueKind VK = VK_RValue;
11573   ExprObjectKind OK = OK_Ordinary;
11574   QualType resultType;
11575   if (getLangOpts().OpenCL) {
11576     QualType Ty = InputExpr->getType();
11577     // The only legal unary operation for atomics is '&'.
11578     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11579     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11580     // only with a builtin functions and therefore should be disallowed here.
11581         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11582         || Ty->isBlockPointerType())) {
11583       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11584                        << InputExpr->getType()
11585                        << Input.get()->getSourceRange());
11586     }
11587   }
11588   switch (Opc) {
11589   case UO_PreInc:
11590   case UO_PreDec:
11591   case UO_PostInc:
11592   case UO_PostDec:
11593     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11594                                                 OpLoc,
11595                                                 Opc == UO_PreInc ||
11596                                                 Opc == UO_PostInc,
11597                                                 Opc == UO_PreInc ||
11598                                                 Opc == UO_PreDec);
11599     break;
11600   case UO_AddrOf:
11601     resultType = CheckAddressOfOperand(Input, OpLoc);
11602     RecordModifiableNonNullParam(*this, InputExpr);
11603     break;
11604   case UO_Deref: {
11605     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11606     if (Input.isInvalid()) return ExprError();
11607     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11608     break;
11609   }
11610   case UO_Plus:
11611   case UO_Minus:
11612     Input = UsualUnaryConversions(Input.get());
11613     if (Input.isInvalid()) return ExprError();
11614     resultType = Input.get()->getType();
11615     if (resultType->isDependentType())
11616       break;
11617     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11618       break;
11619     else if (resultType->isVectorType() &&
11620              // The z vector extensions don't allow + or - with bool vectors.
11621              (!Context.getLangOpts().ZVector ||
11622               resultType->getAs<VectorType>()->getVectorKind() !=
11623               VectorType::AltiVecBool))
11624       break;
11625     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11626              Opc == UO_Plus &&
11627              resultType->isPointerType())
11628       break;
11629 
11630     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11631       << resultType << Input.get()->getSourceRange());
11632 
11633   case UO_Not: // bitwise complement
11634     Input = UsualUnaryConversions(Input.get());
11635     if (Input.isInvalid())
11636       return ExprError();
11637     resultType = Input.get()->getType();
11638     if (resultType->isDependentType())
11639       break;
11640     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11641     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11642       // C99 does not support '~' for complex conjugation.
11643       Diag(OpLoc, diag::ext_integer_complement_complex)
11644           << resultType << Input.get()->getSourceRange();
11645     else if (resultType->hasIntegerRepresentation())
11646       break;
11647     else if (resultType->isExtVectorType()) {
11648       if (Context.getLangOpts().OpenCL) {
11649         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11650         // on vector float types.
11651         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11652         if (!T->isIntegerType())
11653           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11654                            << resultType << Input.get()->getSourceRange());
11655       }
11656       break;
11657     } else {
11658       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11659                        << resultType << Input.get()->getSourceRange());
11660     }
11661     break;
11662 
11663   case UO_LNot: // logical negation
11664     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11665     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11666     if (Input.isInvalid()) return ExprError();
11667     resultType = Input.get()->getType();
11668 
11669     // Though we still have to promote half FP to float...
11670     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11671       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11672       resultType = Context.FloatTy;
11673     }
11674 
11675     if (resultType->isDependentType())
11676       break;
11677     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11678       // C99 6.5.3.3p1: ok, fallthrough;
11679       if (Context.getLangOpts().CPlusPlus) {
11680         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11681         // operand contextually converted to bool.
11682         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11683                                   ScalarTypeToBooleanCastKind(resultType));
11684       } else if (Context.getLangOpts().OpenCL &&
11685                  Context.getLangOpts().OpenCLVersion < 120) {
11686         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11687         // operate on scalar float types.
11688         if (!resultType->isIntegerType())
11689           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11690                            << resultType << Input.get()->getSourceRange());
11691       }
11692     } else if (resultType->isExtVectorType()) {
11693       if (Context.getLangOpts().OpenCL &&
11694           Context.getLangOpts().OpenCLVersion < 120) {
11695         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11696         // operate on vector float types.
11697         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11698         if (!T->isIntegerType())
11699           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11700                            << resultType << Input.get()->getSourceRange());
11701       }
11702       // Vector logical not returns the signed variant of the operand type.
11703       resultType = GetSignedVectorType(resultType);
11704       break;
11705     } else {
11706       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11707         << resultType << Input.get()->getSourceRange());
11708     }
11709 
11710     // LNot always has type int. C99 6.5.3.3p5.
11711     // In C++, it's bool. C++ 5.3.1p8
11712     resultType = Context.getLogicalOperationType();
11713     break;
11714   case UO_Real:
11715   case UO_Imag:
11716     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11717     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11718     // complex l-values to ordinary l-values and all other values to r-values.
11719     if (Input.isInvalid()) return ExprError();
11720     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11721       if (Input.get()->getValueKind() != VK_RValue &&
11722           Input.get()->getObjectKind() == OK_Ordinary)
11723         VK = Input.get()->getValueKind();
11724     } else if (!getLangOpts().CPlusPlus) {
11725       // In C, a volatile scalar is read by __imag. In C++, it is not.
11726       Input = DefaultLvalueConversion(Input.get());
11727     }
11728     break;
11729   case UO_Extension:
11730   case UO_Coawait:
11731     resultType = Input.get()->getType();
11732     VK = Input.get()->getValueKind();
11733     OK = Input.get()->getObjectKind();
11734     break;
11735   }
11736   if (resultType.isNull() || Input.isInvalid())
11737     return ExprError();
11738 
11739   // Check for array bounds violations in the operand of the UnaryOperator,
11740   // except for the '*' and '&' operators that have to be handled specially
11741   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11742   // that are explicitly defined as valid by the standard).
11743   if (Opc != UO_AddrOf && Opc != UO_Deref)
11744     CheckArrayAccess(Input.get());
11745 
11746   return new (Context)
11747       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11748 }
11749 
11750 /// \brief Determine whether the given expression is a qualified member
11751 /// access expression, of a form that could be turned into a pointer to member
11752 /// with the address-of operator.
11753 static bool isQualifiedMemberAccess(Expr *E) {
11754   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11755     if (!DRE->getQualifier())
11756       return false;
11757 
11758     ValueDecl *VD = DRE->getDecl();
11759     if (!VD->isCXXClassMember())
11760       return false;
11761 
11762     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11763       return true;
11764     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11765       return Method->isInstance();
11766 
11767     return false;
11768   }
11769 
11770   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11771     if (!ULE->getQualifier())
11772       return false;
11773 
11774     for (NamedDecl *D : ULE->decls()) {
11775       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11776         if (Method->isInstance())
11777           return true;
11778       } else {
11779         // Overload set does not contain methods.
11780         break;
11781       }
11782     }
11783 
11784     return false;
11785   }
11786 
11787   return false;
11788 }
11789 
11790 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11791                               UnaryOperatorKind Opc, Expr *Input) {
11792   // First things first: handle placeholders so that the
11793   // overloaded-operator check considers the right type.
11794   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11795     // Increment and decrement of pseudo-object references.
11796     if (pty->getKind() == BuiltinType::PseudoObject &&
11797         UnaryOperator::isIncrementDecrementOp(Opc))
11798       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11799 
11800     // extension is always a builtin operator.
11801     if (Opc == UO_Extension)
11802       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11803 
11804     // & gets special logic for several kinds of placeholder.
11805     // The builtin code knows what to do.
11806     if (Opc == UO_AddrOf &&
11807         (pty->getKind() == BuiltinType::Overload ||
11808          pty->getKind() == BuiltinType::UnknownAny ||
11809          pty->getKind() == BuiltinType::BoundMember))
11810       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11811 
11812     // Anything else needs to be handled now.
11813     ExprResult Result = CheckPlaceholderExpr(Input);
11814     if (Result.isInvalid()) return ExprError();
11815     Input = Result.get();
11816   }
11817 
11818   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11819       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11820       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11821     // Find all of the overloaded operators visible from this
11822     // point. We perform both an operator-name lookup from the local
11823     // scope and an argument-dependent lookup based on the types of
11824     // the arguments.
11825     UnresolvedSet<16> Functions;
11826     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11827     if (S && OverOp != OO_None)
11828       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11829                                    Functions);
11830 
11831     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11832   }
11833 
11834   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11835 }
11836 
11837 // Unary Operators.  'Tok' is the token for the operator.
11838 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11839                               tok::TokenKind Op, Expr *Input) {
11840   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11841 }
11842 
11843 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11844 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11845                                 LabelDecl *TheDecl) {
11846   TheDecl->markUsed(Context);
11847   // Create the AST node.  The address of a label always has type 'void*'.
11848   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11849                                      Context.getPointerType(Context.VoidTy));
11850 }
11851 
11852 /// Given the last statement in a statement-expression, check whether
11853 /// the result is a producing expression (like a call to an
11854 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11855 /// release out of the full-expression.  Otherwise, return null.
11856 /// Cannot fail.
11857 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11858   // Should always be wrapped with one of these.
11859   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11860   if (!cleanups) return nullptr;
11861 
11862   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11863   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11864     return nullptr;
11865 
11866   // Splice out the cast.  This shouldn't modify any interesting
11867   // features of the statement.
11868   Expr *producer = cast->getSubExpr();
11869   assert(producer->getType() == cast->getType());
11870   assert(producer->getValueKind() == cast->getValueKind());
11871   cleanups->setSubExpr(producer);
11872   return cleanups;
11873 }
11874 
11875 void Sema::ActOnStartStmtExpr() {
11876   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11877 }
11878 
11879 void Sema::ActOnStmtExprError() {
11880   // Note that function is also called by TreeTransform when leaving a
11881   // StmtExpr scope without rebuilding anything.
11882 
11883   DiscardCleanupsInEvaluationContext();
11884   PopExpressionEvaluationContext();
11885 }
11886 
11887 ExprResult
11888 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11889                     SourceLocation RPLoc) { // "({..})"
11890   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11891   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11892 
11893   if (hasAnyUnrecoverableErrorsInThisFunction())
11894     DiscardCleanupsInEvaluationContext();
11895   assert(!Cleanup.exprNeedsCleanups() &&
11896          "cleanups within StmtExpr not correctly bound!");
11897   PopExpressionEvaluationContext();
11898 
11899   // FIXME: there are a variety of strange constraints to enforce here, for
11900   // example, it is not possible to goto into a stmt expression apparently.
11901   // More semantic analysis is needed.
11902 
11903   // If there are sub-stmts in the compound stmt, take the type of the last one
11904   // as the type of the stmtexpr.
11905   QualType Ty = Context.VoidTy;
11906   bool StmtExprMayBindToTemp = false;
11907   if (!Compound->body_empty()) {
11908     Stmt *LastStmt = Compound->body_back();
11909     LabelStmt *LastLabelStmt = nullptr;
11910     // If LastStmt is a label, skip down through into the body.
11911     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11912       LastLabelStmt = Label;
11913       LastStmt = Label->getSubStmt();
11914     }
11915 
11916     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11917       // Do function/array conversion on the last expression, but not
11918       // lvalue-to-rvalue.  However, initialize an unqualified type.
11919       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11920       if (LastExpr.isInvalid())
11921         return ExprError();
11922       Ty = LastExpr.get()->getType().getUnqualifiedType();
11923 
11924       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11925         // In ARC, if the final expression ends in a consume, splice
11926         // the consume out and bind it later.  In the alternate case
11927         // (when dealing with a retainable type), the result
11928         // initialization will create a produce.  In both cases the
11929         // result will be +1, and we'll need to balance that out with
11930         // a bind.
11931         if (Expr *rebuiltLastStmt
11932               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11933           LastExpr = rebuiltLastStmt;
11934         } else {
11935           LastExpr = PerformCopyInitialization(
11936                             InitializedEntity::InitializeResult(LPLoc,
11937                                                                 Ty,
11938                                                                 false),
11939                                                    SourceLocation(),
11940                                                LastExpr);
11941         }
11942 
11943         if (LastExpr.isInvalid())
11944           return ExprError();
11945         if (LastExpr.get() != nullptr) {
11946           if (!LastLabelStmt)
11947             Compound->setLastStmt(LastExpr.get());
11948           else
11949             LastLabelStmt->setSubStmt(LastExpr.get());
11950           StmtExprMayBindToTemp = true;
11951         }
11952       }
11953     }
11954   }
11955 
11956   // FIXME: Check that expression type is complete/non-abstract; statement
11957   // expressions are not lvalues.
11958   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11959   if (StmtExprMayBindToTemp)
11960     return MaybeBindToTemporary(ResStmtExpr);
11961   return ResStmtExpr;
11962 }
11963 
11964 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11965                                       TypeSourceInfo *TInfo,
11966                                       ArrayRef<OffsetOfComponent> Components,
11967                                       SourceLocation RParenLoc) {
11968   QualType ArgTy = TInfo->getType();
11969   bool Dependent = ArgTy->isDependentType();
11970   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11971 
11972   // We must have at least one component that refers to the type, and the first
11973   // one is known to be a field designator.  Verify that the ArgTy represents
11974   // a struct/union/class.
11975   if (!Dependent && !ArgTy->isRecordType())
11976     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11977                        << ArgTy << TypeRange);
11978 
11979   // Type must be complete per C99 7.17p3 because a declaring a variable
11980   // with an incomplete type would be ill-formed.
11981   if (!Dependent
11982       && RequireCompleteType(BuiltinLoc, ArgTy,
11983                              diag::err_offsetof_incomplete_type, TypeRange))
11984     return ExprError();
11985 
11986   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11987   // GCC extension, diagnose them.
11988   // FIXME: This diagnostic isn't actually visible because the location is in
11989   // a system header!
11990   if (Components.size() != 1)
11991     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11992       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11993 
11994   bool DidWarnAboutNonPOD = false;
11995   QualType CurrentType = ArgTy;
11996   SmallVector<OffsetOfNode, 4> Comps;
11997   SmallVector<Expr*, 4> Exprs;
11998   for (const OffsetOfComponent &OC : Components) {
11999     if (OC.isBrackets) {
12000       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12001       if (!CurrentType->isDependentType()) {
12002         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12003         if(!AT)
12004           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12005                            << CurrentType);
12006         CurrentType = AT->getElementType();
12007       } else
12008         CurrentType = Context.DependentTy;
12009 
12010       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12011       if (IdxRval.isInvalid())
12012         return ExprError();
12013       Expr *Idx = IdxRval.get();
12014 
12015       // The expression must be an integral expression.
12016       // FIXME: An integral constant expression?
12017       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12018           !Idx->getType()->isIntegerType())
12019         return ExprError(Diag(Idx->getLocStart(),
12020                               diag::err_typecheck_subscript_not_integer)
12021                          << Idx->getSourceRange());
12022 
12023       // Record this array index.
12024       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12025       Exprs.push_back(Idx);
12026       continue;
12027     }
12028 
12029     // Offset of a field.
12030     if (CurrentType->isDependentType()) {
12031       // We have the offset of a field, but we can't look into the dependent
12032       // type. Just record the identifier of the field.
12033       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12034       CurrentType = Context.DependentTy;
12035       continue;
12036     }
12037 
12038     // We need to have a complete type to look into.
12039     if (RequireCompleteType(OC.LocStart, CurrentType,
12040                             diag::err_offsetof_incomplete_type))
12041       return ExprError();
12042 
12043     // Look for the designated field.
12044     const RecordType *RC = CurrentType->getAs<RecordType>();
12045     if (!RC)
12046       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12047                        << CurrentType);
12048     RecordDecl *RD = RC->getDecl();
12049 
12050     // C++ [lib.support.types]p5:
12051     //   The macro offsetof accepts a restricted set of type arguments in this
12052     //   International Standard. type shall be a POD structure or a POD union
12053     //   (clause 9).
12054     // C++11 [support.types]p4:
12055     //   If type is not a standard-layout class (Clause 9), the results are
12056     //   undefined.
12057     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12058       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12059       unsigned DiagID =
12060         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12061                             : diag::ext_offsetof_non_pod_type;
12062 
12063       if (!IsSafe && !DidWarnAboutNonPOD &&
12064           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12065                               PDiag(DiagID)
12066                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12067                               << CurrentType))
12068         DidWarnAboutNonPOD = true;
12069     }
12070 
12071     // Look for the field.
12072     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12073     LookupQualifiedName(R, RD);
12074     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12075     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12076     if (!MemberDecl) {
12077       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12078         MemberDecl = IndirectMemberDecl->getAnonField();
12079     }
12080 
12081     if (!MemberDecl)
12082       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12083                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12084                                                               OC.LocEnd));
12085 
12086     // C99 7.17p3:
12087     //   (If the specified member is a bit-field, the behavior is undefined.)
12088     //
12089     // We diagnose this as an error.
12090     if (MemberDecl->isBitField()) {
12091       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12092         << MemberDecl->getDeclName()
12093         << SourceRange(BuiltinLoc, RParenLoc);
12094       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12095       return ExprError();
12096     }
12097 
12098     RecordDecl *Parent = MemberDecl->getParent();
12099     if (IndirectMemberDecl)
12100       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12101 
12102     // If the member was found in a base class, introduce OffsetOfNodes for
12103     // the base class indirections.
12104     CXXBasePaths Paths;
12105     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12106                       Paths)) {
12107       if (Paths.getDetectedVirtual()) {
12108         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12109           << MemberDecl->getDeclName()
12110           << SourceRange(BuiltinLoc, RParenLoc);
12111         return ExprError();
12112       }
12113 
12114       CXXBasePath &Path = Paths.front();
12115       for (const CXXBasePathElement &B : Path)
12116         Comps.push_back(OffsetOfNode(B.Base));
12117     }
12118 
12119     if (IndirectMemberDecl) {
12120       for (auto *FI : IndirectMemberDecl->chain()) {
12121         assert(isa<FieldDecl>(FI));
12122         Comps.push_back(OffsetOfNode(OC.LocStart,
12123                                      cast<FieldDecl>(FI), OC.LocEnd));
12124       }
12125     } else
12126       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12127 
12128     CurrentType = MemberDecl->getType().getNonReferenceType();
12129   }
12130 
12131   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12132                               Comps, Exprs, RParenLoc);
12133 }
12134 
12135 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12136                                       SourceLocation BuiltinLoc,
12137                                       SourceLocation TypeLoc,
12138                                       ParsedType ParsedArgTy,
12139                                       ArrayRef<OffsetOfComponent> Components,
12140                                       SourceLocation RParenLoc) {
12141 
12142   TypeSourceInfo *ArgTInfo;
12143   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12144   if (ArgTy.isNull())
12145     return ExprError();
12146 
12147   if (!ArgTInfo)
12148     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12149 
12150   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12151 }
12152 
12153 
12154 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12155                                  Expr *CondExpr,
12156                                  Expr *LHSExpr, Expr *RHSExpr,
12157                                  SourceLocation RPLoc) {
12158   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12159 
12160   ExprValueKind VK = VK_RValue;
12161   ExprObjectKind OK = OK_Ordinary;
12162   QualType resType;
12163   bool ValueDependent = false;
12164   bool CondIsTrue = false;
12165   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12166     resType = Context.DependentTy;
12167     ValueDependent = true;
12168   } else {
12169     // The conditional expression is required to be a constant expression.
12170     llvm::APSInt condEval(32);
12171     ExprResult CondICE
12172       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12173           diag::err_typecheck_choose_expr_requires_constant, false);
12174     if (CondICE.isInvalid())
12175       return ExprError();
12176     CondExpr = CondICE.get();
12177     CondIsTrue = condEval.getZExtValue();
12178 
12179     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12180     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12181 
12182     resType = ActiveExpr->getType();
12183     ValueDependent = ActiveExpr->isValueDependent();
12184     VK = ActiveExpr->getValueKind();
12185     OK = ActiveExpr->getObjectKind();
12186   }
12187 
12188   return new (Context)
12189       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12190                  CondIsTrue, resType->isDependentType(), ValueDependent);
12191 }
12192 
12193 //===----------------------------------------------------------------------===//
12194 // Clang Extensions.
12195 //===----------------------------------------------------------------------===//
12196 
12197 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12198 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12199   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12200 
12201   if (LangOpts.CPlusPlus) {
12202     Decl *ManglingContextDecl;
12203     if (MangleNumberingContext *MCtx =
12204             getCurrentMangleNumberContext(Block->getDeclContext(),
12205                                           ManglingContextDecl)) {
12206       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12207       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12208     }
12209   }
12210 
12211   PushBlockScope(CurScope, Block);
12212   CurContext->addDecl(Block);
12213   if (CurScope)
12214     PushDeclContext(CurScope, Block);
12215   else
12216     CurContext = Block;
12217 
12218   getCurBlock()->HasImplicitReturnType = true;
12219 
12220   // Enter a new evaluation context to insulate the block from any
12221   // cleanups from the enclosing full-expression.
12222   PushExpressionEvaluationContext(PotentiallyEvaluated);
12223 }
12224 
12225 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12226                                Scope *CurScope) {
12227   assert(ParamInfo.getIdentifier() == nullptr &&
12228          "block-id should have no identifier!");
12229   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12230   BlockScopeInfo *CurBlock = getCurBlock();
12231 
12232   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12233   QualType T = Sig->getType();
12234 
12235   // FIXME: We should allow unexpanded parameter packs here, but that would,
12236   // in turn, make the block expression contain unexpanded parameter packs.
12237   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12238     // Drop the parameters.
12239     FunctionProtoType::ExtProtoInfo EPI;
12240     EPI.HasTrailingReturn = false;
12241     EPI.TypeQuals |= DeclSpec::TQ_const;
12242     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12243     Sig = Context.getTrivialTypeSourceInfo(T);
12244   }
12245 
12246   // GetTypeForDeclarator always produces a function type for a block
12247   // literal signature.  Furthermore, it is always a FunctionProtoType
12248   // unless the function was written with a typedef.
12249   assert(T->isFunctionType() &&
12250          "GetTypeForDeclarator made a non-function block signature");
12251 
12252   // Look for an explicit signature in that function type.
12253   FunctionProtoTypeLoc ExplicitSignature;
12254 
12255   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12256   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12257 
12258     // Check whether that explicit signature was synthesized by
12259     // GetTypeForDeclarator.  If so, don't save that as part of the
12260     // written signature.
12261     if (ExplicitSignature.getLocalRangeBegin() ==
12262         ExplicitSignature.getLocalRangeEnd()) {
12263       // This would be much cheaper if we stored TypeLocs instead of
12264       // TypeSourceInfos.
12265       TypeLoc Result = ExplicitSignature.getReturnLoc();
12266       unsigned Size = Result.getFullDataSize();
12267       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12268       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12269 
12270       ExplicitSignature = FunctionProtoTypeLoc();
12271     }
12272   }
12273 
12274   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12275   CurBlock->FunctionType = T;
12276 
12277   const FunctionType *Fn = T->getAs<FunctionType>();
12278   QualType RetTy = Fn->getReturnType();
12279   bool isVariadic =
12280     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12281 
12282   CurBlock->TheDecl->setIsVariadic(isVariadic);
12283 
12284   // Context.DependentTy is used as a placeholder for a missing block
12285   // return type.  TODO:  what should we do with declarators like:
12286   //   ^ * { ... }
12287   // If the answer is "apply template argument deduction"....
12288   if (RetTy != Context.DependentTy) {
12289     CurBlock->ReturnType = RetTy;
12290     CurBlock->TheDecl->setBlockMissingReturnType(false);
12291     CurBlock->HasImplicitReturnType = false;
12292   }
12293 
12294   // Push block parameters from the declarator if we had them.
12295   SmallVector<ParmVarDecl*, 8> Params;
12296   if (ExplicitSignature) {
12297     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12298       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12299       if (Param->getIdentifier() == nullptr &&
12300           !Param->isImplicit() &&
12301           !Param->isInvalidDecl() &&
12302           !getLangOpts().CPlusPlus)
12303         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12304       Params.push_back(Param);
12305     }
12306 
12307   // Fake up parameter variables if we have a typedef, like
12308   //   ^ fntype { ... }
12309   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12310     for (const auto &I : Fn->param_types()) {
12311       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12312           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12313       Params.push_back(Param);
12314     }
12315   }
12316 
12317   // Set the parameters on the block decl.
12318   if (!Params.empty()) {
12319     CurBlock->TheDecl->setParams(Params);
12320     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12321                              /*CheckParameterNames=*/false);
12322   }
12323 
12324   // Finally we can process decl attributes.
12325   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12326 
12327   // Put the parameter variables in scope.
12328   for (auto AI : CurBlock->TheDecl->parameters()) {
12329     AI->setOwningFunction(CurBlock->TheDecl);
12330 
12331     // If this has an identifier, add it to the scope stack.
12332     if (AI->getIdentifier()) {
12333       CheckShadow(CurBlock->TheScope, AI);
12334 
12335       PushOnScopeChains(AI, CurBlock->TheScope);
12336     }
12337   }
12338 }
12339 
12340 /// ActOnBlockError - If there is an error parsing a block, this callback
12341 /// is invoked to pop the information about the block from the action impl.
12342 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12343   // Leave the expression-evaluation context.
12344   DiscardCleanupsInEvaluationContext();
12345   PopExpressionEvaluationContext();
12346 
12347   // Pop off CurBlock, handle nested blocks.
12348   PopDeclContext();
12349   PopFunctionScopeInfo();
12350 }
12351 
12352 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12353 /// literal was successfully completed.  ^(int x){...}
12354 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12355                                     Stmt *Body, Scope *CurScope) {
12356   // If blocks are disabled, emit an error.
12357   if (!LangOpts.Blocks)
12358     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12359 
12360   // Leave the expression-evaluation context.
12361   if (hasAnyUnrecoverableErrorsInThisFunction())
12362     DiscardCleanupsInEvaluationContext();
12363   assert(!Cleanup.exprNeedsCleanups() &&
12364          "cleanups within block not correctly bound!");
12365   PopExpressionEvaluationContext();
12366 
12367   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12368 
12369   if (BSI->HasImplicitReturnType)
12370     deduceClosureReturnType(*BSI);
12371 
12372   PopDeclContext();
12373 
12374   QualType RetTy = Context.VoidTy;
12375   if (!BSI->ReturnType.isNull())
12376     RetTy = BSI->ReturnType;
12377 
12378   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12379   QualType BlockTy;
12380 
12381   // Set the captured variables on the block.
12382   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12383   SmallVector<BlockDecl::Capture, 4> Captures;
12384   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12385     if (Cap.isThisCapture())
12386       continue;
12387     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12388                               Cap.isNested(), Cap.getInitExpr());
12389     Captures.push_back(NewCap);
12390   }
12391   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12392 
12393   // If the user wrote a function type in some form, try to use that.
12394   if (!BSI->FunctionType.isNull()) {
12395     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12396 
12397     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12398     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12399 
12400     // Turn protoless block types into nullary block types.
12401     if (isa<FunctionNoProtoType>(FTy)) {
12402       FunctionProtoType::ExtProtoInfo EPI;
12403       EPI.ExtInfo = Ext;
12404       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12405 
12406     // Otherwise, if we don't need to change anything about the function type,
12407     // preserve its sugar structure.
12408     } else if (FTy->getReturnType() == RetTy &&
12409                (!NoReturn || FTy->getNoReturnAttr())) {
12410       BlockTy = BSI->FunctionType;
12411 
12412     // Otherwise, make the minimal modifications to the function type.
12413     } else {
12414       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12415       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12416       EPI.TypeQuals = 0; // FIXME: silently?
12417       EPI.ExtInfo = Ext;
12418       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12419     }
12420 
12421   // If we don't have a function type, just build one from nothing.
12422   } else {
12423     FunctionProtoType::ExtProtoInfo EPI;
12424     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12425     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12426   }
12427 
12428   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12429   BlockTy = Context.getBlockPointerType(BlockTy);
12430 
12431   // If needed, diagnose invalid gotos and switches in the block.
12432   if (getCurFunction()->NeedsScopeChecking() &&
12433       !PP.isCodeCompletionEnabled())
12434     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12435 
12436   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12437 
12438   // Try to apply the named return value optimization. We have to check again
12439   // if we can do this, though, because blocks keep return statements around
12440   // to deduce an implicit return type.
12441   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12442       !BSI->TheDecl->isDependentContext())
12443     computeNRVO(Body, BSI);
12444 
12445   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12446   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12447   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12448 
12449   // If the block isn't obviously global, i.e. it captures anything at
12450   // all, then we need to do a few things in the surrounding context:
12451   if (Result->getBlockDecl()->hasCaptures()) {
12452     // First, this expression has a new cleanup object.
12453     ExprCleanupObjects.push_back(Result->getBlockDecl());
12454     Cleanup.setExprNeedsCleanups(true);
12455 
12456     // It also gets a branch-protected scope if any of the captured
12457     // variables needs destruction.
12458     for (const auto &CI : Result->getBlockDecl()->captures()) {
12459       const VarDecl *var = CI.getVariable();
12460       if (var->getType().isDestructedType() != QualType::DK_none) {
12461         getCurFunction()->setHasBranchProtectedScope();
12462         break;
12463       }
12464     }
12465   }
12466 
12467   return Result;
12468 }
12469 
12470 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12471                             SourceLocation RPLoc) {
12472   TypeSourceInfo *TInfo;
12473   GetTypeFromParser(Ty, &TInfo);
12474   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12475 }
12476 
12477 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12478                                 Expr *E, TypeSourceInfo *TInfo,
12479                                 SourceLocation RPLoc) {
12480   Expr *OrigExpr = E;
12481   bool IsMS = false;
12482 
12483   // CUDA device code does not support varargs.
12484   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12485     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12486       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12487       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12488         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12489     }
12490   }
12491 
12492   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12493   // as Microsoft ABI on an actual Microsoft platform, where
12494   // __builtin_ms_va_list and __builtin_va_list are the same.)
12495   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12496       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12497     QualType MSVaListType = Context.getBuiltinMSVaListType();
12498     if (Context.hasSameType(MSVaListType, E->getType())) {
12499       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12500         return ExprError();
12501       IsMS = true;
12502     }
12503   }
12504 
12505   // Get the va_list type
12506   QualType VaListType = Context.getBuiltinVaListType();
12507   if (!IsMS) {
12508     if (VaListType->isArrayType()) {
12509       // Deal with implicit array decay; for example, on x86-64,
12510       // va_list is an array, but it's supposed to decay to
12511       // a pointer for va_arg.
12512       VaListType = Context.getArrayDecayedType(VaListType);
12513       // Make sure the input expression also decays appropriately.
12514       ExprResult Result = UsualUnaryConversions(E);
12515       if (Result.isInvalid())
12516         return ExprError();
12517       E = Result.get();
12518     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12519       // If va_list is a record type and we are compiling in C++ mode,
12520       // check the argument using reference binding.
12521       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12522           Context, Context.getLValueReferenceType(VaListType), false);
12523       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12524       if (Init.isInvalid())
12525         return ExprError();
12526       E = Init.getAs<Expr>();
12527     } else {
12528       // Otherwise, the va_list argument must be an l-value because
12529       // it is modified by va_arg.
12530       if (!E->isTypeDependent() &&
12531           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12532         return ExprError();
12533     }
12534   }
12535 
12536   if (!IsMS && !E->isTypeDependent() &&
12537       !Context.hasSameType(VaListType, E->getType()))
12538     return ExprError(Diag(E->getLocStart(),
12539                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12540       << OrigExpr->getType() << E->getSourceRange());
12541 
12542   if (!TInfo->getType()->isDependentType()) {
12543     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12544                             diag::err_second_parameter_to_va_arg_incomplete,
12545                             TInfo->getTypeLoc()))
12546       return ExprError();
12547 
12548     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12549                                TInfo->getType(),
12550                                diag::err_second_parameter_to_va_arg_abstract,
12551                                TInfo->getTypeLoc()))
12552       return ExprError();
12553 
12554     if (!TInfo->getType().isPODType(Context)) {
12555       Diag(TInfo->getTypeLoc().getBeginLoc(),
12556            TInfo->getType()->isObjCLifetimeType()
12557              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12558              : diag::warn_second_parameter_to_va_arg_not_pod)
12559         << TInfo->getType()
12560         << TInfo->getTypeLoc().getSourceRange();
12561     }
12562 
12563     // Check for va_arg where arguments of the given type will be promoted
12564     // (i.e. this va_arg is guaranteed to have undefined behavior).
12565     QualType PromoteType;
12566     if (TInfo->getType()->isPromotableIntegerType()) {
12567       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12568       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12569         PromoteType = QualType();
12570     }
12571     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12572       PromoteType = Context.DoubleTy;
12573     if (!PromoteType.isNull())
12574       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12575                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12576                           << TInfo->getType()
12577                           << PromoteType
12578                           << TInfo->getTypeLoc().getSourceRange());
12579   }
12580 
12581   QualType T = TInfo->getType().getNonLValueExprType(Context);
12582   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12583 }
12584 
12585 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12586   // The type of __null will be int or long, depending on the size of
12587   // pointers on the target.
12588   QualType Ty;
12589   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12590   if (pw == Context.getTargetInfo().getIntWidth())
12591     Ty = Context.IntTy;
12592   else if (pw == Context.getTargetInfo().getLongWidth())
12593     Ty = Context.LongTy;
12594   else if (pw == Context.getTargetInfo().getLongLongWidth())
12595     Ty = Context.LongLongTy;
12596   else {
12597     llvm_unreachable("I don't know size of pointer!");
12598   }
12599 
12600   return new (Context) GNUNullExpr(Ty, TokenLoc);
12601 }
12602 
12603 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12604                                               bool Diagnose) {
12605   if (!getLangOpts().ObjC1)
12606     return false;
12607 
12608   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12609   if (!PT)
12610     return false;
12611 
12612   if (!PT->isObjCIdType()) {
12613     // Check if the destination is the 'NSString' interface.
12614     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12615     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12616       return false;
12617   }
12618 
12619   // Ignore any parens, implicit casts (should only be
12620   // array-to-pointer decays), and not-so-opaque values.  The last is
12621   // important for making this trigger for property assignments.
12622   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12623   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12624     if (OV->getSourceExpr())
12625       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12626 
12627   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12628   if (!SL || !SL->isAscii())
12629     return false;
12630   if (Diagnose) {
12631     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12632       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12633     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12634   }
12635   return true;
12636 }
12637 
12638 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12639                                               const Expr *SrcExpr) {
12640   if (!DstType->isFunctionPointerType() ||
12641       !SrcExpr->getType()->isFunctionType())
12642     return false;
12643 
12644   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12645   if (!DRE)
12646     return false;
12647 
12648   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12649   if (!FD)
12650     return false;
12651 
12652   return !S.checkAddressOfFunctionIsAvailable(FD,
12653                                               /*Complain=*/true,
12654                                               SrcExpr->getLocStart());
12655 }
12656 
12657 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12658                                     SourceLocation Loc,
12659                                     QualType DstType, QualType SrcType,
12660                                     Expr *SrcExpr, AssignmentAction Action,
12661                                     bool *Complained) {
12662   if (Complained)
12663     *Complained = false;
12664 
12665   // Decode the result (notice that AST's are still created for extensions).
12666   bool CheckInferredResultType = false;
12667   bool isInvalid = false;
12668   unsigned DiagKind = 0;
12669   FixItHint Hint;
12670   ConversionFixItGenerator ConvHints;
12671   bool MayHaveConvFixit = false;
12672   bool MayHaveFunctionDiff = false;
12673   const ObjCInterfaceDecl *IFace = nullptr;
12674   const ObjCProtocolDecl *PDecl = nullptr;
12675 
12676   switch (ConvTy) {
12677   case Compatible:
12678       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12679       return false;
12680 
12681   case PointerToInt:
12682     DiagKind = diag::ext_typecheck_convert_pointer_int;
12683     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12684     MayHaveConvFixit = true;
12685     break;
12686   case IntToPointer:
12687     DiagKind = diag::ext_typecheck_convert_int_pointer;
12688     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12689     MayHaveConvFixit = true;
12690     break;
12691   case IncompatiblePointer:
12692     if (Action == AA_Passing_CFAudited)
12693       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12694     else if (SrcType->isFunctionPointerType() &&
12695              DstType->isFunctionPointerType())
12696       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12697     else
12698       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12699 
12700     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12701       SrcType->isObjCObjectPointerType();
12702     if (Hint.isNull() && !CheckInferredResultType) {
12703       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12704     }
12705     else if (CheckInferredResultType) {
12706       SrcType = SrcType.getUnqualifiedType();
12707       DstType = DstType.getUnqualifiedType();
12708     }
12709     MayHaveConvFixit = true;
12710     break;
12711   case IncompatiblePointerSign:
12712     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12713     break;
12714   case FunctionVoidPointer:
12715     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12716     break;
12717   case IncompatiblePointerDiscardsQualifiers: {
12718     // Perform array-to-pointer decay if necessary.
12719     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12720 
12721     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12722     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12723     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12724       DiagKind = diag::err_typecheck_incompatible_address_space;
12725       break;
12726 
12727 
12728     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12729       DiagKind = diag::err_typecheck_incompatible_ownership;
12730       break;
12731     }
12732 
12733     llvm_unreachable("unknown error case for discarding qualifiers!");
12734     // fallthrough
12735   }
12736   case CompatiblePointerDiscardsQualifiers:
12737     // If the qualifiers lost were because we were applying the
12738     // (deprecated) C++ conversion from a string literal to a char*
12739     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12740     // Ideally, this check would be performed in
12741     // checkPointerTypesForAssignment. However, that would require a
12742     // bit of refactoring (so that the second argument is an
12743     // expression, rather than a type), which should be done as part
12744     // of a larger effort to fix checkPointerTypesForAssignment for
12745     // C++ semantics.
12746     if (getLangOpts().CPlusPlus &&
12747         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12748       return false;
12749     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12750     break;
12751   case IncompatibleNestedPointerQualifiers:
12752     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12753     break;
12754   case IntToBlockPointer:
12755     DiagKind = diag::err_int_to_block_pointer;
12756     break;
12757   case IncompatibleBlockPointer:
12758     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12759     break;
12760   case IncompatibleObjCQualifiedId: {
12761     if (SrcType->isObjCQualifiedIdType()) {
12762       const ObjCObjectPointerType *srcOPT =
12763                 SrcType->getAs<ObjCObjectPointerType>();
12764       for (auto *srcProto : srcOPT->quals()) {
12765         PDecl = srcProto;
12766         break;
12767       }
12768       if (const ObjCInterfaceType *IFaceT =
12769             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12770         IFace = IFaceT->getDecl();
12771     }
12772     else if (DstType->isObjCQualifiedIdType()) {
12773       const ObjCObjectPointerType *dstOPT =
12774         DstType->getAs<ObjCObjectPointerType>();
12775       for (auto *dstProto : dstOPT->quals()) {
12776         PDecl = dstProto;
12777         break;
12778       }
12779       if (const ObjCInterfaceType *IFaceT =
12780             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12781         IFace = IFaceT->getDecl();
12782     }
12783     DiagKind = diag::warn_incompatible_qualified_id;
12784     break;
12785   }
12786   case IncompatibleVectors:
12787     DiagKind = diag::warn_incompatible_vectors;
12788     break;
12789   case IncompatibleObjCWeakRef:
12790     DiagKind = diag::err_arc_weak_unavailable_assign;
12791     break;
12792   case Incompatible:
12793     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12794       if (Complained)
12795         *Complained = true;
12796       return true;
12797     }
12798 
12799     DiagKind = diag::err_typecheck_convert_incompatible;
12800     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12801     MayHaveConvFixit = true;
12802     isInvalid = true;
12803     MayHaveFunctionDiff = true;
12804     break;
12805   }
12806 
12807   QualType FirstType, SecondType;
12808   switch (Action) {
12809   case AA_Assigning:
12810   case AA_Initializing:
12811     // The destination type comes first.
12812     FirstType = DstType;
12813     SecondType = SrcType;
12814     break;
12815 
12816   case AA_Returning:
12817   case AA_Passing:
12818   case AA_Passing_CFAudited:
12819   case AA_Converting:
12820   case AA_Sending:
12821   case AA_Casting:
12822     // The source type comes first.
12823     FirstType = SrcType;
12824     SecondType = DstType;
12825     break;
12826   }
12827 
12828   PartialDiagnostic FDiag = PDiag(DiagKind);
12829   if (Action == AA_Passing_CFAudited)
12830     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12831   else
12832     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12833 
12834   // If we can fix the conversion, suggest the FixIts.
12835   assert(ConvHints.isNull() || Hint.isNull());
12836   if (!ConvHints.isNull()) {
12837     for (FixItHint &H : ConvHints.Hints)
12838       FDiag << H;
12839   } else {
12840     FDiag << Hint;
12841   }
12842   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12843 
12844   if (MayHaveFunctionDiff)
12845     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12846 
12847   Diag(Loc, FDiag);
12848   if (DiagKind == diag::warn_incompatible_qualified_id &&
12849       PDecl && IFace && !IFace->hasDefinition())
12850       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12851         << IFace->getName() << PDecl->getName();
12852 
12853   if (SecondType == Context.OverloadTy)
12854     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12855                               FirstType, /*TakingAddress=*/true);
12856 
12857   if (CheckInferredResultType)
12858     EmitRelatedResultTypeNote(SrcExpr);
12859 
12860   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12861     EmitRelatedResultTypeNoteForReturn(DstType);
12862 
12863   if (Complained)
12864     *Complained = true;
12865   return isInvalid;
12866 }
12867 
12868 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12869                                                  llvm::APSInt *Result) {
12870   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12871   public:
12872     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12873       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12874     }
12875   } Diagnoser;
12876 
12877   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12878 }
12879 
12880 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12881                                                  llvm::APSInt *Result,
12882                                                  unsigned DiagID,
12883                                                  bool AllowFold) {
12884   class IDDiagnoser : public VerifyICEDiagnoser {
12885     unsigned DiagID;
12886 
12887   public:
12888     IDDiagnoser(unsigned DiagID)
12889       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12890 
12891     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12892       S.Diag(Loc, DiagID) << SR;
12893     }
12894   } Diagnoser(DiagID);
12895 
12896   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12897 }
12898 
12899 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12900                                             SourceRange SR) {
12901   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12902 }
12903 
12904 ExprResult
12905 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12906                                       VerifyICEDiagnoser &Diagnoser,
12907                                       bool AllowFold) {
12908   SourceLocation DiagLoc = E->getLocStart();
12909 
12910   if (getLangOpts().CPlusPlus11) {
12911     // C++11 [expr.const]p5:
12912     //   If an expression of literal class type is used in a context where an
12913     //   integral constant expression is required, then that class type shall
12914     //   have a single non-explicit conversion function to an integral or
12915     //   unscoped enumeration type
12916     ExprResult Converted;
12917     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12918     public:
12919       CXX11ConvertDiagnoser(bool Silent)
12920           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12921                                 Silent, true) {}
12922 
12923       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12924                                            QualType T) override {
12925         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12926       }
12927 
12928       SemaDiagnosticBuilder diagnoseIncomplete(
12929           Sema &S, SourceLocation Loc, QualType T) override {
12930         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12931       }
12932 
12933       SemaDiagnosticBuilder diagnoseExplicitConv(
12934           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12935         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12936       }
12937 
12938       SemaDiagnosticBuilder noteExplicitConv(
12939           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12940         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12941                  << ConvTy->isEnumeralType() << ConvTy;
12942       }
12943 
12944       SemaDiagnosticBuilder diagnoseAmbiguous(
12945           Sema &S, SourceLocation Loc, QualType T) override {
12946         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12947       }
12948 
12949       SemaDiagnosticBuilder noteAmbiguous(
12950           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12951         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12952                  << ConvTy->isEnumeralType() << ConvTy;
12953       }
12954 
12955       SemaDiagnosticBuilder diagnoseConversion(
12956           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12957         llvm_unreachable("conversion functions are permitted");
12958       }
12959     } ConvertDiagnoser(Diagnoser.Suppress);
12960 
12961     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12962                                                     ConvertDiagnoser);
12963     if (Converted.isInvalid())
12964       return Converted;
12965     E = Converted.get();
12966     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12967       return ExprError();
12968   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12969     // An ICE must be of integral or unscoped enumeration type.
12970     if (!Diagnoser.Suppress)
12971       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12972     return ExprError();
12973   }
12974 
12975   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12976   // in the non-ICE case.
12977   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12978     if (Result)
12979       *Result = E->EvaluateKnownConstInt(Context);
12980     return E;
12981   }
12982 
12983   Expr::EvalResult EvalResult;
12984   SmallVector<PartialDiagnosticAt, 8> Notes;
12985   EvalResult.Diag = &Notes;
12986 
12987   // Try to evaluate the expression, and produce diagnostics explaining why it's
12988   // not a constant expression as a side-effect.
12989   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12990                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12991 
12992   // In C++11, we can rely on diagnostics being produced for any expression
12993   // which is not a constant expression. If no diagnostics were produced, then
12994   // this is a constant expression.
12995   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12996     if (Result)
12997       *Result = EvalResult.Val.getInt();
12998     return E;
12999   }
13000 
13001   // If our only note is the usual "invalid subexpression" note, just point
13002   // the caret at its location rather than producing an essentially
13003   // redundant note.
13004   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13005         diag::note_invalid_subexpr_in_const_expr) {
13006     DiagLoc = Notes[0].first;
13007     Notes.clear();
13008   }
13009 
13010   if (!Folded || !AllowFold) {
13011     if (!Diagnoser.Suppress) {
13012       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13013       for (const PartialDiagnosticAt &Note : Notes)
13014         Diag(Note.first, Note.second);
13015     }
13016 
13017     return ExprError();
13018   }
13019 
13020   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13021   for (const PartialDiagnosticAt &Note : Notes)
13022     Diag(Note.first, Note.second);
13023 
13024   if (Result)
13025     *Result = EvalResult.Val.getInt();
13026   return E;
13027 }
13028 
13029 namespace {
13030   // Handle the case where we conclude a expression which we speculatively
13031   // considered to be unevaluated is actually evaluated.
13032   class TransformToPE : public TreeTransform<TransformToPE> {
13033     typedef TreeTransform<TransformToPE> BaseTransform;
13034 
13035   public:
13036     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13037 
13038     // Make sure we redo semantic analysis
13039     bool AlwaysRebuild() { return true; }
13040 
13041     // Make sure we handle LabelStmts correctly.
13042     // FIXME: This does the right thing, but maybe we need a more general
13043     // fix to TreeTransform?
13044     StmtResult TransformLabelStmt(LabelStmt *S) {
13045       S->getDecl()->setStmt(nullptr);
13046       return BaseTransform::TransformLabelStmt(S);
13047     }
13048 
13049     // We need to special-case DeclRefExprs referring to FieldDecls which
13050     // are not part of a member pointer formation; normal TreeTransforming
13051     // doesn't catch this case because of the way we represent them in the AST.
13052     // FIXME: This is a bit ugly; is it really the best way to handle this
13053     // case?
13054     //
13055     // Error on DeclRefExprs referring to FieldDecls.
13056     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13057       if (isa<FieldDecl>(E->getDecl()) &&
13058           !SemaRef.isUnevaluatedContext())
13059         return SemaRef.Diag(E->getLocation(),
13060                             diag::err_invalid_non_static_member_use)
13061             << E->getDecl() << E->getSourceRange();
13062 
13063       return BaseTransform::TransformDeclRefExpr(E);
13064     }
13065 
13066     // Exception: filter out member pointer formation
13067     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13068       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13069         return E;
13070 
13071       return BaseTransform::TransformUnaryOperator(E);
13072     }
13073 
13074     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13075       // Lambdas never need to be transformed.
13076       return E;
13077     }
13078   };
13079 }
13080 
13081 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13082   assert(isUnevaluatedContext() &&
13083          "Should only transform unevaluated expressions");
13084   ExprEvalContexts.back().Context =
13085       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13086   if (isUnevaluatedContext())
13087     return E;
13088   return TransformToPE(*this).TransformExpr(E);
13089 }
13090 
13091 void
13092 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13093                                       Decl *LambdaContextDecl,
13094                                       bool IsDecltype) {
13095   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13096                                 LambdaContextDecl, IsDecltype);
13097   Cleanup.reset();
13098   if (!MaybeODRUseExprs.empty())
13099     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13100 }
13101 
13102 void
13103 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13104                                       ReuseLambdaContextDecl_t,
13105                                       bool IsDecltype) {
13106   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13107   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13108 }
13109 
13110 void Sema::PopExpressionEvaluationContext() {
13111   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13112   unsigned NumTypos = Rec.NumTypos;
13113 
13114   if (!Rec.Lambdas.empty()) {
13115     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13116       unsigned D;
13117       if (Rec.isUnevaluated()) {
13118         // C++11 [expr.prim.lambda]p2:
13119         //   A lambda-expression shall not appear in an unevaluated operand
13120         //   (Clause 5).
13121         D = diag::err_lambda_unevaluated_operand;
13122       } else {
13123         // C++1y [expr.const]p2:
13124         //   A conditional-expression e is a core constant expression unless the
13125         //   evaluation of e, following the rules of the abstract machine, would
13126         //   evaluate [...] a lambda-expression.
13127         D = diag::err_lambda_in_constant_expression;
13128       }
13129 
13130       // C++1z allows lambda expressions as core constant expressions.
13131       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13132       // 1607) from appearing within template-arguments and array-bounds that
13133       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13134       // unevaluated contexts) might lift some of these restrictions in a
13135       // future version.
13136       if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z)
13137         for (const auto *L : Rec.Lambdas)
13138           Diag(L->getLocStart(), D);
13139     } else {
13140       // Mark the capture expressions odr-used. This was deferred
13141       // during lambda expression creation.
13142       for (auto *Lambda : Rec.Lambdas) {
13143         for (auto *C : Lambda->capture_inits())
13144           MarkDeclarationsReferencedInExpr(C);
13145       }
13146     }
13147   }
13148 
13149   // When are coming out of an unevaluated context, clear out any
13150   // temporaries that we may have created as part of the evaluation of
13151   // the expression in that context: they aren't relevant because they
13152   // will never be constructed.
13153   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13154     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13155                              ExprCleanupObjects.end());
13156     Cleanup = Rec.ParentCleanup;
13157     CleanupVarDeclMarking();
13158     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13159   // Otherwise, merge the contexts together.
13160   } else {
13161     Cleanup.mergeFrom(Rec.ParentCleanup);
13162     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13163                             Rec.SavedMaybeODRUseExprs.end());
13164   }
13165 
13166   // Pop the current expression evaluation context off the stack.
13167   ExprEvalContexts.pop_back();
13168 
13169   if (!ExprEvalContexts.empty())
13170     ExprEvalContexts.back().NumTypos += NumTypos;
13171   else
13172     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13173                             "last ExpressionEvaluationContextRecord");
13174 }
13175 
13176 void Sema::DiscardCleanupsInEvaluationContext() {
13177   ExprCleanupObjects.erase(
13178          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13179          ExprCleanupObjects.end());
13180   Cleanup.reset();
13181   MaybeODRUseExprs.clear();
13182 }
13183 
13184 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13185   if (!E->getType()->isVariablyModifiedType())
13186     return E;
13187   return TransformToPotentiallyEvaluated(E);
13188 }
13189 
13190 /// Are we within a context in which some evaluation could be performed (be it
13191 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13192 /// captured by C++'s idea of an "unevaluated context".
13193 static bool isEvaluatableContext(Sema &SemaRef) {
13194   switch (SemaRef.ExprEvalContexts.back().Context) {
13195     case Sema::Unevaluated:
13196     case Sema::UnevaluatedAbstract:
13197     case Sema::DiscardedStatement:
13198       // Expressions in this context are never evaluated.
13199       return false;
13200 
13201     case Sema::UnevaluatedList:
13202     case Sema::ConstantEvaluated:
13203     case Sema::PotentiallyEvaluated:
13204       // Expressions in this context could be evaluated.
13205       return true;
13206 
13207     case Sema::PotentiallyEvaluatedIfUsed:
13208       // Referenced declarations will only be used if the construct in the
13209       // containing expression is used, at which point we'll be given another
13210       // turn to mark them.
13211       return false;
13212   }
13213   llvm_unreachable("Invalid context");
13214 }
13215 
13216 /// Are we within a context in which references to resolved functions or to
13217 /// variables result in odr-use?
13218 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13219   // An expression in a template is not really an expression until it's been
13220   // instantiated, so it doesn't trigger odr-use.
13221   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13222     return false;
13223 
13224   switch (SemaRef.ExprEvalContexts.back().Context) {
13225     case Sema::Unevaluated:
13226     case Sema::UnevaluatedList:
13227     case Sema::UnevaluatedAbstract:
13228     case Sema::DiscardedStatement:
13229       return false;
13230 
13231     case Sema::ConstantEvaluated:
13232     case Sema::PotentiallyEvaluated:
13233       return true;
13234 
13235     case Sema::PotentiallyEvaluatedIfUsed:
13236       return false;
13237   }
13238   llvm_unreachable("Invalid context");
13239 }
13240 
13241 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13242   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13243   return Func->isConstexpr() &&
13244          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13245 }
13246 
13247 /// \brief Mark a function referenced, and check whether it is odr-used
13248 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13249 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13250                                   bool MightBeOdrUse) {
13251   assert(Func && "No function?");
13252 
13253   Func->setReferenced();
13254 
13255   // C++11 [basic.def.odr]p3:
13256   //   A function whose name appears as a potentially-evaluated expression is
13257   //   odr-used if it is the unique lookup result or the selected member of a
13258   //   set of overloaded functions [...].
13259   //
13260   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13261   // can just check that here.
13262   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13263 
13264   // Determine whether we require a function definition to exist, per
13265   // C++11 [temp.inst]p3:
13266   //   Unless a function template specialization has been explicitly
13267   //   instantiated or explicitly specialized, the function template
13268   //   specialization is implicitly instantiated when the specialization is
13269   //   referenced in a context that requires a function definition to exist.
13270   //
13271   // That is either when this is an odr-use, or when a usage of a constexpr
13272   // function occurs within an evaluatable context.
13273   bool NeedDefinition =
13274       OdrUse || (isEvaluatableContext(*this) &&
13275                  isImplicitlyDefinableConstexprFunction(Func));
13276 
13277   // C++14 [temp.expl.spec]p6:
13278   //   If a template [...] is explicitly specialized then that specialization
13279   //   shall be declared before the first use of that specialization that would
13280   //   cause an implicit instantiation to take place, in every translation unit
13281   //   in which such a use occurs
13282   if (NeedDefinition &&
13283       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13284        Func->getMemberSpecializationInfo()))
13285     checkSpecializationVisibility(Loc, Func);
13286 
13287   // C++14 [except.spec]p17:
13288   //   An exception-specification is considered to be needed when:
13289   //   - the function is odr-used or, if it appears in an unevaluated operand,
13290   //     would be odr-used if the expression were potentially-evaluated;
13291   //
13292   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13293   // function is a pure virtual function we're calling, and in that case the
13294   // function was selected by overload resolution and we need to resolve its
13295   // exception specification for a different reason.
13296   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13297   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13298     ResolveExceptionSpec(Loc, FPT);
13299 
13300   // If we don't need to mark the function as used, and we don't need to
13301   // try to provide a definition, there's nothing more to do.
13302   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13303       (!NeedDefinition || Func->getBody()))
13304     return;
13305 
13306   // Note that this declaration has been used.
13307   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13308     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13309     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13310       if (Constructor->isDefaultConstructor()) {
13311         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13312           return;
13313         DefineImplicitDefaultConstructor(Loc, Constructor);
13314       } else if (Constructor->isCopyConstructor()) {
13315         DefineImplicitCopyConstructor(Loc, Constructor);
13316       } else if (Constructor->isMoveConstructor()) {
13317         DefineImplicitMoveConstructor(Loc, Constructor);
13318       }
13319     } else if (Constructor->getInheritedConstructor()) {
13320       DefineInheritingConstructor(Loc, Constructor);
13321     }
13322   } else if (CXXDestructorDecl *Destructor =
13323                  dyn_cast<CXXDestructorDecl>(Func)) {
13324     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13325     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13326       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13327         return;
13328       DefineImplicitDestructor(Loc, Destructor);
13329     }
13330     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13331       MarkVTableUsed(Loc, Destructor->getParent());
13332   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13333     if (MethodDecl->isOverloadedOperator() &&
13334         MethodDecl->getOverloadedOperator() == OO_Equal) {
13335       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13336       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13337         if (MethodDecl->isCopyAssignmentOperator())
13338           DefineImplicitCopyAssignment(Loc, MethodDecl);
13339         else if (MethodDecl->isMoveAssignmentOperator())
13340           DefineImplicitMoveAssignment(Loc, MethodDecl);
13341       }
13342     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13343                MethodDecl->getParent()->isLambda()) {
13344       CXXConversionDecl *Conversion =
13345           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13346       if (Conversion->isLambdaToBlockPointerConversion())
13347         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13348       else
13349         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13350     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13351       MarkVTableUsed(Loc, MethodDecl->getParent());
13352   }
13353 
13354   // Recursive functions should be marked when used from another function.
13355   // FIXME: Is this really right?
13356   if (CurContext == Func) return;
13357 
13358   // Implicit instantiation of function templates and member functions of
13359   // class templates.
13360   if (Func->isImplicitlyInstantiable()) {
13361     bool AlreadyInstantiated = false;
13362     SourceLocation PointOfInstantiation = Loc;
13363     if (FunctionTemplateSpecializationInfo *SpecInfo
13364                               = Func->getTemplateSpecializationInfo()) {
13365       if (SpecInfo->getPointOfInstantiation().isInvalid())
13366         SpecInfo->setPointOfInstantiation(Loc);
13367       else if (SpecInfo->getTemplateSpecializationKind()
13368                  == TSK_ImplicitInstantiation) {
13369         AlreadyInstantiated = true;
13370         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13371       }
13372     } else if (MemberSpecializationInfo *MSInfo
13373                                 = Func->getMemberSpecializationInfo()) {
13374       if (MSInfo->getPointOfInstantiation().isInvalid())
13375         MSInfo->setPointOfInstantiation(Loc);
13376       else if (MSInfo->getTemplateSpecializationKind()
13377                  == TSK_ImplicitInstantiation) {
13378         AlreadyInstantiated = true;
13379         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13380       }
13381     }
13382 
13383     if (!AlreadyInstantiated || Func->isConstexpr()) {
13384       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13385           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13386           ActiveTemplateInstantiations.size())
13387         PendingLocalImplicitInstantiations.push_back(
13388             std::make_pair(Func, PointOfInstantiation));
13389       else if (Func->isConstexpr())
13390         // Do not defer instantiations of constexpr functions, to avoid the
13391         // expression evaluator needing to call back into Sema if it sees a
13392         // call to such a function.
13393         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13394       else {
13395         PendingInstantiations.push_back(std::make_pair(Func,
13396                                                        PointOfInstantiation));
13397         // Notify the consumer that a function was implicitly instantiated.
13398         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13399       }
13400     }
13401   } else {
13402     // Walk redefinitions, as some of them may be instantiable.
13403     for (auto i : Func->redecls()) {
13404       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13405         MarkFunctionReferenced(Loc, i, OdrUse);
13406     }
13407   }
13408 
13409   if (!OdrUse) return;
13410 
13411   // Keep track of used but undefined functions.
13412   if (!Func->isDefined()) {
13413     if (mightHaveNonExternalLinkage(Func))
13414       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13415     else if (Func->getMostRecentDecl()->isInlined() &&
13416              !LangOpts.GNUInline &&
13417              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13418       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13419   }
13420 
13421   Func->markUsed(Context);
13422 }
13423 
13424 static void
13425 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13426                                    ValueDecl *var, DeclContext *DC) {
13427   DeclContext *VarDC = var->getDeclContext();
13428 
13429   //  If the parameter still belongs to the translation unit, then
13430   //  we're actually just using one parameter in the declaration of
13431   //  the next.
13432   if (isa<ParmVarDecl>(var) &&
13433       isa<TranslationUnitDecl>(VarDC))
13434     return;
13435 
13436   // For C code, don't diagnose about capture if we're not actually in code
13437   // right now; it's impossible to write a non-constant expression outside of
13438   // function context, so we'll get other (more useful) diagnostics later.
13439   //
13440   // For C++, things get a bit more nasty... it would be nice to suppress this
13441   // diagnostic for certain cases like using a local variable in an array bound
13442   // for a member of a local class, but the correct predicate is not obvious.
13443   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13444     return;
13445 
13446   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13447   unsigned ContextKind = 3; // unknown
13448   if (isa<CXXMethodDecl>(VarDC) &&
13449       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13450     ContextKind = 2;
13451   } else if (isa<FunctionDecl>(VarDC)) {
13452     ContextKind = 0;
13453   } else if (isa<BlockDecl>(VarDC)) {
13454     ContextKind = 1;
13455   }
13456 
13457   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13458     << var << ValueKind << ContextKind << VarDC;
13459   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13460       << var;
13461 
13462   // FIXME: Add additional diagnostic info about class etc. which prevents
13463   // capture.
13464 }
13465 
13466 
13467 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13468                                       bool &SubCapturesAreNested,
13469                                       QualType &CaptureType,
13470                                       QualType &DeclRefType) {
13471    // Check whether we've already captured it.
13472   if (CSI->CaptureMap.count(Var)) {
13473     // If we found a capture, any subcaptures are nested.
13474     SubCapturesAreNested = true;
13475 
13476     // Retrieve the capture type for this variable.
13477     CaptureType = CSI->getCapture(Var).getCaptureType();
13478 
13479     // Compute the type of an expression that refers to this variable.
13480     DeclRefType = CaptureType.getNonReferenceType();
13481 
13482     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13483     // are mutable in the sense that user can change their value - they are
13484     // private instances of the captured declarations.
13485     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13486     if (Cap.isCopyCapture() &&
13487         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13488         !(isa<CapturedRegionScopeInfo>(CSI) &&
13489           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13490       DeclRefType.addConst();
13491     return true;
13492   }
13493   return false;
13494 }
13495 
13496 // Only block literals, captured statements, and lambda expressions can
13497 // capture; other scopes don't work.
13498 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13499                                  SourceLocation Loc,
13500                                  const bool Diagnose, Sema &S) {
13501   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13502     return getLambdaAwareParentOfDeclContext(DC);
13503   else if (Var->hasLocalStorage()) {
13504     if (Diagnose)
13505        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13506   }
13507   return nullptr;
13508 }
13509 
13510 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13511 // certain types of variables (unnamed, variably modified types etc.)
13512 // so check for eligibility.
13513 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13514                                  SourceLocation Loc,
13515                                  const bool Diagnose, Sema &S) {
13516 
13517   bool IsBlock = isa<BlockScopeInfo>(CSI);
13518   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13519 
13520   // Lambdas are not allowed to capture unnamed variables
13521   // (e.g. anonymous unions).
13522   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13523   // assuming that's the intent.
13524   if (IsLambda && !Var->getDeclName()) {
13525     if (Diagnose) {
13526       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13527       S.Diag(Var->getLocation(), diag::note_declared_at);
13528     }
13529     return false;
13530   }
13531 
13532   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13533   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13534     if (Diagnose) {
13535       S.Diag(Loc, diag::err_ref_vm_type);
13536       S.Diag(Var->getLocation(), diag::note_previous_decl)
13537         << Var->getDeclName();
13538     }
13539     return false;
13540   }
13541   // Prohibit structs with flexible array members too.
13542   // We cannot capture what is in the tail end of the struct.
13543   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13544     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13545       if (Diagnose) {
13546         if (IsBlock)
13547           S.Diag(Loc, diag::err_ref_flexarray_type);
13548         else
13549           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13550             << Var->getDeclName();
13551         S.Diag(Var->getLocation(), diag::note_previous_decl)
13552           << Var->getDeclName();
13553       }
13554       return false;
13555     }
13556   }
13557   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13558   // Lambdas and captured statements are not allowed to capture __block
13559   // variables; they don't support the expected semantics.
13560   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13561     if (Diagnose) {
13562       S.Diag(Loc, diag::err_capture_block_variable)
13563         << Var->getDeclName() << !IsLambda;
13564       S.Diag(Var->getLocation(), diag::note_previous_decl)
13565         << Var->getDeclName();
13566     }
13567     return false;
13568   }
13569 
13570   return true;
13571 }
13572 
13573 // Returns true if the capture by block was successful.
13574 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13575                                  SourceLocation Loc,
13576                                  const bool BuildAndDiagnose,
13577                                  QualType &CaptureType,
13578                                  QualType &DeclRefType,
13579                                  const bool Nested,
13580                                  Sema &S) {
13581   Expr *CopyExpr = nullptr;
13582   bool ByRef = false;
13583 
13584   // Blocks are not allowed to capture arrays.
13585   if (CaptureType->isArrayType()) {
13586     if (BuildAndDiagnose) {
13587       S.Diag(Loc, diag::err_ref_array_type);
13588       S.Diag(Var->getLocation(), diag::note_previous_decl)
13589       << Var->getDeclName();
13590     }
13591     return false;
13592   }
13593 
13594   // Forbid the block-capture of autoreleasing variables.
13595   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13596     if (BuildAndDiagnose) {
13597       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13598         << /*block*/ 0;
13599       S.Diag(Var->getLocation(), diag::note_previous_decl)
13600         << Var->getDeclName();
13601     }
13602     return false;
13603   }
13604 
13605   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13606   if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13607     QualType PointeeTy = PT->getPointeeType();
13608     if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13609         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13610         !isa<AttributedType>(PointeeTy)) {
13611       if (BuildAndDiagnose) {
13612         SourceLocation VarLoc = Var->getLocation();
13613         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13614         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13615             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13616         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13617       }
13618     }
13619   }
13620 
13621   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13622   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13623       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13624     // Block capture by reference does not change the capture or
13625     // declaration reference types.
13626     ByRef = true;
13627   } else {
13628     // Block capture by copy introduces 'const'.
13629     CaptureType = CaptureType.getNonReferenceType().withConst();
13630     DeclRefType = CaptureType;
13631 
13632     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13633       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13634         // The capture logic needs the destructor, so make sure we mark it.
13635         // Usually this is unnecessary because most local variables have
13636         // their destructors marked at declaration time, but parameters are
13637         // an exception because it's technically only the call site that
13638         // actually requires the destructor.
13639         if (isa<ParmVarDecl>(Var))
13640           S.FinalizeVarWithDestructor(Var, Record);
13641 
13642         // Enter a new evaluation context to insulate the copy
13643         // full-expression.
13644         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13645 
13646         // According to the blocks spec, the capture of a variable from
13647         // the stack requires a const copy constructor.  This is not true
13648         // of the copy/move done to move a __block variable to the heap.
13649         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13650                                                   DeclRefType.withConst(),
13651                                                   VK_LValue, Loc);
13652 
13653         ExprResult Result
13654           = S.PerformCopyInitialization(
13655               InitializedEntity::InitializeBlock(Var->getLocation(),
13656                                                   CaptureType, false),
13657               Loc, DeclRef);
13658 
13659         // Build a full-expression copy expression if initialization
13660         // succeeded and used a non-trivial constructor.  Recover from
13661         // errors by pretending that the copy isn't necessary.
13662         if (!Result.isInvalid() &&
13663             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13664                 ->isTrivial()) {
13665           Result = S.MaybeCreateExprWithCleanups(Result);
13666           CopyExpr = Result.get();
13667         }
13668       }
13669     }
13670   }
13671 
13672   // Actually capture the variable.
13673   if (BuildAndDiagnose)
13674     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13675                     SourceLocation(), CaptureType, CopyExpr);
13676 
13677   return true;
13678 
13679 }
13680 
13681 
13682 /// \brief Capture the given variable in the captured region.
13683 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13684                                     VarDecl *Var,
13685                                     SourceLocation Loc,
13686                                     const bool BuildAndDiagnose,
13687                                     QualType &CaptureType,
13688                                     QualType &DeclRefType,
13689                                     const bool RefersToCapturedVariable,
13690                                     Sema &S) {
13691   // By default, capture variables by reference.
13692   bool ByRef = true;
13693   // Using an LValue reference type is consistent with Lambdas (see below).
13694   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13695     if (S.IsOpenMPCapturedDecl(Var))
13696       DeclRefType = DeclRefType.getUnqualifiedType();
13697     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13698   }
13699 
13700   if (ByRef)
13701     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13702   else
13703     CaptureType = DeclRefType;
13704 
13705   Expr *CopyExpr = nullptr;
13706   if (BuildAndDiagnose) {
13707     // The current implementation assumes that all variables are captured
13708     // by references. Since there is no capture by copy, no expression
13709     // evaluation will be needed.
13710     RecordDecl *RD = RSI->TheRecordDecl;
13711 
13712     FieldDecl *Field
13713       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13714                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13715                           nullptr, false, ICIS_NoInit);
13716     Field->setImplicit(true);
13717     Field->setAccess(AS_private);
13718     RD->addDecl(Field);
13719 
13720     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13721                                             DeclRefType, VK_LValue, Loc);
13722     Var->setReferenced(true);
13723     Var->markUsed(S.Context);
13724   }
13725 
13726   // Actually capture the variable.
13727   if (BuildAndDiagnose)
13728     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13729                     SourceLocation(), CaptureType, CopyExpr);
13730 
13731 
13732   return true;
13733 }
13734 
13735 /// \brief Create a field within the lambda class for the variable
13736 /// being captured.
13737 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13738                                     QualType FieldType, QualType DeclRefType,
13739                                     SourceLocation Loc,
13740                                     bool RefersToCapturedVariable) {
13741   CXXRecordDecl *Lambda = LSI->Lambda;
13742 
13743   // Build the non-static data member.
13744   FieldDecl *Field
13745     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13746                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13747                         nullptr, false, ICIS_NoInit);
13748   Field->setImplicit(true);
13749   Field->setAccess(AS_private);
13750   Lambda->addDecl(Field);
13751 }
13752 
13753 /// \brief Capture the given variable in the lambda.
13754 static bool captureInLambda(LambdaScopeInfo *LSI,
13755                             VarDecl *Var,
13756                             SourceLocation Loc,
13757                             const bool BuildAndDiagnose,
13758                             QualType &CaptureType,
13759                             QualType &DeclRefType,
13760                             const bool RefersToCapturedVariable,
13761                             const Sema::TryCaptureKind Kind,
13762                             SourceLocation EllipsisLoc,
13763                             const bool IsTopScope,
13764                             Sema &S) {
13765 
13766   // Determine whether we are capturing by reference or by value.
13767   bool ByRef = false;
13768   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13769     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13770   } else {
13771     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13772   }
13773 
13774   // Compute the type of the field that will capture this variable.
13775   if (ByRef) {
13776     // C++11 [expr.prim.lambda]p15:
13777     //   An entity is captured by reference if it is implicitly or
13778     //   explicitly captured but not captured by copy. It is
13779     //   unspecified whether additional unnamed non-static data
13780     //   members are declared in the closure type for entities
13781     //   captured by reference.
13782     //
13783     // FIXME: It is not clear whether we want to build an lvalue reference
13784     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13785     // to do the former, while EDG does the latter. Core issue 1249 will
13786     // clarify, but for now we follow GCC because it's a more permissive and
13787     // easily defensible position.
13788     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13789   } else {
13790     // C++11 [expr.prim.lambda]p14:
13791     //   For each entity captured by copy, an unnamed non-static
13792     //   data member is declared in the closure type. The
13793     //   declaration order of these members is unspecified. The type
13794     //   of such a data member is the type of the corresponding
13795     //   captured entity if the entity is not a reference to an
13796     //   object, or the referenced type otherwise. [Note: If the
13797     //   captured entity is a reference to a function, the
13798     //   corresponding data member is also a reference to a
13799     //   function. - end note ]
13800     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13801       if (!RefType->getPointeeType()->isFunctionType())
13802         CaptureType = RefType->getPointeeType();
13803     }
13804 
13805     // Forbid the lambda copy-capture of autoreleasing variables.
13806     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13807       if (BuildAndDiagnose) {
13808         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13809         S.Diag(Var->getLocation(), diag::note_previous_decl)
13810           << Var->getDeclName();
13811       }
13812       return false;
13813     }
13814 
13815     // Make sure that by-copy captures are of a complete and non-abstract type.
13816     if (BuildAndDiagnose) {
13817       if (!CaptureType->isDependentType() &&
13818           S.RequireCompleteType(Loc, CaptureType,
13819                                 diag::err_capture_of_incomplete_type,
13820                                 Var->getDeclName()))
13821         return false;
13822 
13823       if (S.RequireNonAbstractType(Loc, CaptureType,
13824                                    diag::err_capture_of_abstract_type))
13825         return false;
13826     }
13827   }
13828 
13829   // Capture this variable in the lambda.
13830   if (BuildAndDiagnose)
13831     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13832                             RefersToCapturedVariable);
13833 
13834   // Compute the type of a reference to this captured variable.
13835   if (ByRef)
13836     DeclRefType = CaptureType.getNonReferenceType();
13837   else {
13838     // C++ [expr.prim.lambda]p5:
13839     //   The closure type for a lambda-expression has a public inline
13840     //   function call operator [...]. This function call operator is
13841     //   declared const (9.3.1) if and only if the lambda-expression's
13842     //   parameter-declaration-clause is not followed by mutable.
13843     DeclRefType = CaptureType.getNonReferenceType();
13844     if (!LSI->Mutable && !CaptureType->isReferenceType())
13845       DeclRefType.addConst();
13846   }
13847 
13848   // Add the capture.
13849   if (BuildAndDiagnose)
13850     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13851                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13852 
13853   return true;
13854 }
13855 
13856 bool Sema::tryCaptureVariable(
13857     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13858     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13859     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13860   // An init-capture is notionally from the context surrounding its
13861   // declaration, but its parent DC is the lambda class.
13862   DeclContext *VarDC = Var->getDeclContext();
13863   if (Var->isInitCapture())
13864     VarDC = VarDC->getParent();
13865 
13866   DeclContext *DC = CurContext;
13867   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13868       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13869   // We need to sync up the Declaration Context with the
13870   // FunctionScopeIndexToStopAt
13871   if (FunctionScopeIndexToStopAt) {
13872     unsigned FSIndex = FunctionScopes.size() - 1;
13873     while (FSIndex != MaxFunctionScopesIndex) {
13874       DC = getLambdaAwareParentOfDeclContext(DC);
13875       --FSIndex;
13876     }
13877   }
13878 
13879 
13880   // If the variable is declared in the current context, there is no need to
13881   // capture it.
13882   if (VarDC == DC) return true;
13883 
13884   // Capture global variables if it is required to use private copy of this
13885   // variable.
13886   bool IsGlobal = !Var->hasLocalStorage();
13887   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13888     return true;
13889 
13890   // Walk up the stack to determine whether we can capture the variable,
13891   // performing the "simple" checks that don't depend on type. We stop when
13892   // we've either hit the declared scope of the variable or find an existing
13893   // capture of that variable.  We start from the innermost capturing-entity
13894   // (the DC) and ensure that all intervening capturing-entities
13895   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13896   // declcontext can either capture the variable or have already captured
13897   // the variable.
13898   CaptureType = Var->getType();
13899   DeclRefType = CaptureType.getNonReferenceType();
13900   bool Nested = false;
13901   bool Explicit = (Kind != TryCapture_Implicit);
13902   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13903   do {
13904     // Only block literals, captured statements, and lambda expressions can
13905     // capture; other scopes don't work.
13906     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13907                                                               ExprLoc,
13908                                                               BuildAndDiagnose,
13909                                                               *this);
13910     // We need to check for the parent *first* because, if we *have*
13911     // private-captured a global variable, we need to recursively capture it in
13912     // intermediate blocks, lambdas, etc.
13913     if (!ParentDC) {
13914       if (IsGlobal) {
13915         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13916         break;
13917       }
13918       return true;
13919     }
13920 
13921     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13922     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13923 
13924 
13925     // Check whether we've already captured it.
13926     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13927                                              DeclRefType)) {
13928       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
13929       break;
13930     }
13931     // If we are instantiating a generic lambda call operator body,
13932     // we do not want to capture new variables.  What was captured
13933     // during either a lambdas transformation or initial parsing
13934     // should be used.
13935     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13936       if (BuildAndDiagnose) {
13937         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13938         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13939           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13940           Diag(Var->getLocation(), diag::note_previous_decl)
13941              << Var->getDeclName();
13942           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13943         } else
13944           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13945       }
13946       return true;
13947     }
13948     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13949     // certain types of variables (unnamed, variably modified types etc.)
13950     // so check for eligibility.
13951     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13952        return true;
13953 
13954     // Try to capture variable-length arrays types.
13955     if (Var->getType()->isVariablyModifiedType()) {
13956       // We're going to walk down into the type and look for VLA
13957       // expressions.
13958       QualType QTy = Var->getType();
13959       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13960         QTy = PVD->getOriginalType();
13961       captureVariablyModifiedType(Context, QTy, CSI);
13962     }
13963 
13964     if (getLangOpts().OpenMP) {
13965       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13966         // OpenMP private variables should not be captured in outer scope, so
13967         // just break here. Similarly, global variables that are captured in a
13968         // target region should not be captured outside the scope of the region.
13969         if (RSI->CapRegionKind == CR_OpenMP) {
13970           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13971           // When we detect target captures we are looking from inside the
13972           // target region, therefore we need to propagate the capture from the
13973           // enclosing region. Therefore, the capture is not initially nested.
13974           if (IsTargetCap)
13975             FunctionScopesIndex--;
13976 
13977           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13978             Nested = !IsTargetCap;
13979             DeclRefType = DeclRefType.getUnqualifiedType();
13980             CaptureType = Context.getLValueReferenceType(DeclRefType);
13981             break;
13982           }
13983         }
13984       }
13985     }
13986     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13987       // No capture-default, and this is not an explicit capture
13988       // so cannot capture this variable.
13989       if (BuildAndDiagnose) {
13990         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13991         Diag(Var->getLocation(), diag::note_previous_decl)
13992           << Var->getDeclName();
13993         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13994           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13995                diag::note_lambda_decl);
13996         // FIXME: If we error out because an outer lambda can not implicitly
13997         // capture a variable that an inner lambda explicitly captures, we
13998         // should have the inner lambda do the explicit capture - because
13999         // it makes for cleaner diagnostics later.  This would purely be done
14000         // so that the diagnostic does not misleadingly claim that a variable
14001         // can not be captured by a lambda implicitly even though it is captured
14002         // explicitly.  Suggestion:
14003         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14004         //    at the function head
14005         //  - cache the StartingDeclContext - this must be a lambda
14006         //  - captureInLambda in the innermost lambda the variable.
14007       }
14008       return true;
14009     }
14010 
14011     FunctionScopesIndex--;
14012     DC = ParentDC;
14013     Explicit = false;
14014   } while (!VarDC->Equals(DC));
14015 
14016   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14017   // computing the type of the capture at each step, checking type-specific
14018   // requirements, and adding captures if requested.
14019   // If the variable had already been captured previously, we start capturing
14020   // at the lambda nested within that one.
14021   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14022        ++I) {
14023     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14024 
14025     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14026       if (!captureInBlock(BSI, Var, ExprLoc,
14027                           BuildAndDiagnose, CaptureType,
14028                           DeclRefType, Nested, *this))
14029         return true;
14030       Nested = true;
14031     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14032       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14033                                    BuildAndDiagnose, CaptureType,
14034                                    DeclRefType, Nested, *this))
14035         return true;
14036       Nested = true;
14037     } else {
14038       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14039       if (!captureInLambda(LSI, Var, ExprLoc,
14040                            BuildAndDiagnose, CaptureType,
14041                            DeclRefType, Nested, Kind, EllipsisLoc,
14042                             /*IsTopScope*/I == N - 1, *this))
14043         return true;
14044       Nested = true;
14045     }
14046   }
14047   return false;
14048 }
14049 
14050 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14051                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14052   QualType CaptureType;
14053   QualType DeclRefType;
14054   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14055                             /*BuildAndDiagnose=*/true, CaptureType,
14056                             DeclRefType, nullptr);
14057 }
14058 
14059 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14060   QualType CaptureType;
14061   QualType DeclRefType;
14062   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14063                              /*BuildAndDiagnose=*/false, CaptureType,
14064                              DeclRefType, nullptr);
14065 }
14066 
14067 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14068   QualType CaptureType;
14069   QualType DeclRefType;
14070 
14071   // Determine whether we can capture this variable.
14072   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14073                          /*BuildAndDiagnose=*/false, CaptureType,
14074                          DeclRefType, nullptr))
14075     return QualType();
14076 
14077   return DeclRefType;
14078 }
14079 
14080 
14081 
14082 // If either the type of the variable or the initializer is dependent,
14083 // return false. Otherwise, determine whether the variable is a constant
14084 // expression. Use this if you need to know if a variable that might or
14085 // might not be dependent is truly a constant expression.
14086 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14087     ASTContext &Context) {
14088 
14089   if (Var->getType()->isDependentType())
14090     return false;
14091   const VarDecl *DefVD = nullptr;
14092   Var->getAnyInitializer(DefVD);
14093   if (!DefVD)
14094     return false;
14095   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14096   Expr *Init = cast<Expr>(Eval->Value);
14097   if (Init->isValueDependent())
14098     return false;
14099   return IsVariableAConstantExpression(Var, Context);
14100 }
14101 
14102 
14103 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14104   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14105   // an object that satisfies the requirements for appearing in a
14106   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14107   // is immediately applied."  This function handles the lvalue-to-rvalue
14108   // conversion part.
14109   MaybeODRUseExprs.erase(E->IgnoreParens());
14110 
14111   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14112   // to a variable that is a constant expression, and if so, identify it as
14113   // a reference to a variable that does not involve an odr-use of that
14114   // variable.
14115   if (LambdaScopeInfo *LSI = getCurLambda()) {
14116     Expr *SansParensExpr = E->IgnoreParens();
14117     VarDecl *Var = nullptr;
14118     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14119       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14120     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14121       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14122 
14123     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14124       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14125   }
14126 }
14127 
14128 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14129   Res = CorrectDelayedTyposInExpr(Res);
14130 
14131   if (!Res.isUsable())
14132     return Res;
14133 
14134   // If a constant-expression is a reference to a variable where we delay
14135   // deciding whether it is an odr-use, just assume we will apply the
14136   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14137   // (a non-type template argument), we have special handling anyway.
14138   UpdateMarkingForLValueToRValue(Res.get());
14139   return Res;
14140 }
14141 
14142 void Sema::CleanupVarDeclMarking() {
14143   for (Expr *E : MaybeODRUseExprs) {
14144     VarDecl *Var;
14145     SourceLocation Loc;
14146     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14147       Var = cast<VarDecl>(DRE->getDecl());
14148       Loc = DRE->getLocation();
14149     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14150       Var = cast<VarDecl>(ME->getMemberDecl());
14151       Loc = ME->getMemberLoc();
14152     } else {
14153       llvm_unreachable("Unexpected expression");
14154     }
14155 
14156     MarkVarDeclODRUsed(Var, Loc, *this,
14157                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14158   }
14159 
14160   MaybeODRUseExprs.clear();
14161 }
14162 
14163 
14164 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14165                                     VarDecl *Var, Expr *E) {
14166   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14167          "Invalid Expr argument to DoMarkVarDeclReferenced");
14168   Var->setReferenced();
14169 
14170   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14171 
14172   bool OdrUseContext = isOdrUseContext(SemaRef);
14173   bool NeedDefinition =
14174       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14175                         Var->isUsableInConstantExpressions(SemaRef.Context));
14176 
14177   VarTemplateSpecializationDecl *VarSpec =
14178       dyn_cast<VarTemplateSpecializationDecl>(Var);
14179   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14180          "Can't instantiate a partial template specialization.");
14181 
14182   // If this might be a member specialization of a static data member, check
14183   // the specialization is visible. We already did the checks for variable
14184   // template specializations when we created them.
14185   if (NeedDefinition && TSK != TSK_Undeclared &&
14186       !isa<VarTemplateSpecializationDecl>(Var))
14187     SemaRef.checkSpecializationVisibility(Loc, Var);
14188 
14189   // Perform implicit instantiation of static data members, static data member
14190   // templates of class templates, and variable template specializations. Delay
14191   // instantiations of variable templates, except for those that could be used
14192   // in a constant expression.
14193   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14194     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14195 
14196     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14197       if (Var->getPointOfInstantiation().isInvalid()) {
14198         // This is a modification of an existing AST node. Notify listeners.
14199         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14200           L->StaticDataMemberInstantiated(Var);
14201       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14202         // Don't bother trying to instantiate it again, unless we might need
14203         // its initializer before we get to the end of the TU.
14204         TryInstantiating = false;
14205     }
14206 
14207     if (Var->getPointOfInstantiation().isInvalid())
14208       Var->setTemplateSpecializationKind(TSK, Loc);
14209 
14210     if (TryInstantiating) {
14211       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14212       bool InstantiationDependent = false;
14213       bool IsNonDependent =
14214           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14215                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14216                   : true;
14217 
14218       // Do not instantiate specializations that are still type-dependent.
14219       if (IsNonDependent) {
14220         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14221           // Do not defer instantiations of variables which could be used in a
14222           // constant expression.
14223           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14224         } else {
14225           SemaRef.PendingInstantiations
14226               .push_back(std::make_pair(Var, PointOfInstantiation));
14227         }
14228       }
14229     }
14230   }
14231 
14232   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14233   // the requirements for appearing in a constant expression (5.19) and, if
14234   // it is an object, the lvalue-to-rvalue conversion (4.1)
14235   // is immediately applied."  We check the first part here, and
14236   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14237   // Note that we use the C++11 definition everywhere because nothing in
14238   // C++03 depends on whether we get the C++03 version correct. The second
14239   // part does not apply to references, since they are not objects.
14240   if (OdrUseContext && E &&
14241       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14242     // A reference initialized by a constant expression can never be
14243     // odr-used, so simply ignore it.
14244     if (!Var->getType()->isReferenceType())
14245       SemaRef.MaybeODRUseExprs.insert(E);
14246   } else if (OdrUseContext) {
14247     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14248                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14249   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14250     // If this is a dependent context, we don't need to mark variables as
14251     // odr-used, but we may still need to track them for lambda capture.
14252     // FIXME: Do we also need to do this inside dependent typeid expressions
14253     // (which are modeled as unevaluated at this point)?
14254     const bool RefersToEnclosingScope =
14255         (SemaRef.CurContext != Var->getDeclContext() &&
14256          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14257     if (RefersToEnclosingScope) {
14258       if (LambdaScopeInfo *const LSI =
14259               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14260         // If a variable could potentially be odr-used, defer marking it so
14261         // until we finish analyzing the full expression for any
14262         // lvalue-to-rvalue
14263         // or discarded value conversions that would obviate odr-use.
14264         // Add it to the list of potential captures that will be analyzed
14265         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14266         // unless the variable is a reference that was initialized by a constant
14267         // expression (this will never need to be captured or odr-used).
14268         assert(E && "Capture variable should be used in an expression.");
14269         if (!Var->getType()->isReferenceType() ||
14270             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14271           LSI->addPotentialCapture(E->IgnoreParens());
14272       }
14273     }
14274   }
14275 }
14276 
14277 /// \brief Mark a variable referenced, and check whether it is odr-used
14278 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14279 /// used directly for normal expressions referring to VarDecl.
14280 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14281   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14282 }
14283 
14284 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14285                                Decl *D, Expr *E, bool MightBeOdrUse) {
14286   if (SemaRef.isInOpenMPDeclareTargetContext())
14287     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14288 
14289   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14290     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14291     return;
14292   }
14293 
14294   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14295 
14296   // If this is a call to a method via a cast, also mark the method in the
14297   // derived class used in case codegen can devirtualize the call.
14298   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14299   if (!ME)
14300     return;
14301   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14302   if (!MD)
14303     return;
14304   // Only attempt to devirtualize if this is truly a virtual call.
14305   bool IsVirtualCall = MD->isVirtual() &&
14306                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14307   if (!IsVirtualCall)
14308     return;
14309   const Expr *Base = ME->getBase();
14310   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14311   if (!MostDerivedClassDecl)
14312     return;
14313   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14314   if (!DM || DM->isPure())
14315     return;
14316   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14317 }
14318 
14319 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14320 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14321   // TODO: update this with DR# once a defect report is filed.
14322   // C++11 defect. The address of a pure member should not be an ODR use, even
14323   // if it's a qualified reference.
14324   bool OdrUse = true;
14325   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14326     if (Method->isVirtual())
14327       OdrUse = false;
14328   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14329 }
14330 
14331 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14332 void Sema::MarkMemberReferenced(MemberExpr *E) {
14333   // C++11 [basic.def.odr]p2:
14334   //   A non-overloaded function whose name appears as a potentially-evaluated
14335   //   expression or a member of a set of candidate functions, if selected by
14336   //   overload resolution when referred to from a potentially-evaluated
14337   //   expression, is odr-used, unless it is a pure virtual function and its
14338   //   name is not explicitly qualified.
14339   bool MightBeOdrUse = true;
14340   if (E->performsVirtualDispatch(getLangOpts())) {
14341     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14342       if (Method->isPure())
14343         MightBeOdrUse = false;
14344   }
14345   SourceLocation Loc = E->getMemberLoc().isValid() ?
14346                             E->getMemberLoc() : E->getLocStart();
14347   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14348 }
14349 
14350 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14351 /// marks the declaration referenced, and performs odr-use checking for
14352 /// functions and variables. This method should not be used when building a
14353 /// normal expression which refers to a variable.
14354 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14355                                  bool MightBeOdrUse) {
14356   if (MightBeOdrUse) {
14357     if (auto *VD = dyn_cast<VarDecl>(D)) {
14358       MarkVariableReferenced(Loc, VD);
14359       return;
14360     }
14361   }
14362   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14363     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14364     return;
14365   }
14366   D->setReferenced();
14367 }
14368 
14369 namespace {
14370   // Mark all of the declarations used by a type as referenced.
14371   // FIXME: Not fully implemented yet! We need to have a better understanding
14372   // of when we're entering a context we should not recurse into.
14373   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14374   // TreeTransforms rebuilding the type in a new context. Rather than
14375   // duplicating the TreeTransform logic, we should consider reusing it here.
14376   // Currently that causes problems when rebuilding LambdaExprs.
14377   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14378     Sema &S;
14379     SourceLocation Loc;
14380 
14381   public:
14382     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14383 
14384     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14385 
14386     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14387   };
14388 }
14389 
14390 bool MarkReferencedDecls::TraverseTemplateArgument(
14391     const TemplateArgument &Arg) {
14392   {
14393     // A non-type template argument is a constant-evaluated context.
14394     EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated);
14395     if (Arg.getKind() == TemplateArgument::Declaration) {
14396       if (Decl *D = Arg.getAsDecl())
14397         S.MarkAnyDeclReferenced(Loc, D, true);
14398     } else if (Arg.getKind() == TemplateArgument::Expression) {
14399       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14400     }
14401   }
14402 
14403   return Inherited::TraverseTemplateArgument(Arg);
14404 }
14405 
14406 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14407   MarkReferencedDecls Marker(*this, Loc);
14408   Marker.TraverseType(T);
14409 }
14410 
14411 namespace {
14412   /// \brief Helper class that marks all of the declarations referenced by
14413   /// potentially-evaluated subexpressions as "referenced".
14414   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14415     Sema &S;
14416     bool SkipLocalVariables;
14417 
14418   public:
14419     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14420 
14421     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14422       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14423 
14424     void VisitDeclRefExpr(DeclRefExpr *E) {
14425       // If we were asked not to visit local variables, don't.
14426       if (SkipLocalVariables) {
14427         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14428           if (VD->hasLocalStorage())
14429             return;
14430       }
14431 
14432       S.MarkDeclRefReferenced(E);
14433     }
14434 
14435     void VisitMemberExpr(MemberExpr *E) {
14436       S.MarkMemberReferenced(E);
14437       Inherited::VisitMemberExpr(E);
14438     }
14439 
14440     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14441       S.MarkFunctionReferenced(E->getLocStart(),
14442             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14443       Visit(E->getSubExpr());
14444     }
14445 
14446     void VisitCXXNewExpr(CXXNewExpr *E) {
14447       if (E->getOperatorNew())
14448         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14449       if (E->getOperatorDelete())
14450         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14451       Inherited::VisitCXXNewExpr(E);
14452     }
14453 
14454     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14455       if (E->getOperatorDelete())
14456         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14457       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14458       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14459         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14460         S.MarkFunctionReferenced(E->getLocStart(),
14461                                     S.LookupDestructor(Record));
14462       }
14463 
14464       Inherited::VisitCXXDeleteExpr(E);
14465     }
14466 
14467     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14468       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14469       Inherited::VisitCXXConstructExpr(E);
14470     }
14471 
14472     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14473       Visit(E->getExpr());
14474     }
14475 
14476     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14477       Inherited::VisitImplicitCastExpr(E);
14478 
14479       if (E->getCastKind() == CK_LValueToRValue)
14480         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14481     }
14482   };
14483 }
14484 
14485 /// \brief Mark any declarations that appear within this expression or any
14486 /// potentially-evaluated subexpressions as "referenced".
14487 ///
14488 /// \param SkipLocalVariables If true, don't mark local variables as
14489 /// 'referenced'.
14490 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14491                                             bool SkipLocalVariables) {
14492   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14493 }
14494 
14495 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14496 /// of the program being compiled.
14497 ///
14498 /// This routine emits the given diagnostic when the code currently being
14499 /// type-checked is "potentially evaluated", meaning that there is a
14500 /// possibility that the code will actually be executable. Code in sizeof()
14501 /// expressions, code used only during overload resolution, etc., are not
14502 /// potentially evaluated. This routine will suppress such diagnostics or,
14503 /// in the absolutely nutty case of potentially potentially evaluated
14504 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14505 /// later.
14506 ///
14507 /// This routine should be used for all diagnostics that describe the run-time
14508 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14509 /// Failure to do so will likely result in spurious diagnostics or failures
14510 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14511 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14512                                const PartialDiagnostic &PD) {
14513   switch (ExprEvalContexts.back().Context) {
14514   case Unevaluated:
14515   case UnevaluatedList:
14516   case UnevaluatedAbstract:
14517   case DiscardedStatement:
14518     // The argument will never be evaluated, so don't complain.
14519     break;
14520 
14521   case ConstantEvaluated:
14522     // Relevant diagnostics should be produced by constant evaluation.
14523     break;
14524 
14525   case PotentiallyEvaluated:
14526   case PotentiallyEvaluatedIfUsed:
14527     if (Statement && getCurFunctionOrMethodDecl()) {
14528       FunctionScopes.back()->PossiblyUnreachableDiags.
14529         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14530     }
14531     else
14532       Diag(Loc, PD);
14533 
14534     return true;
14535   }
14536 
14537   return false;
14538 }
14539 
14540 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14541                                CallExpr *CE, FunctionDecl *FD) {
14542   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14543     return false;
14544 
14545   // If we're inside a decltype's expression, don't check for a valid return
14546   // type or construct temporaries until we know whether this is the last call.
14547   if (ExprEvalContexts.back().IsDecltype) {
14548     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14549     return false;
14550   }
14551 
14552   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14553     FunctionDecl *FD;
14554     CallExpr *CE;
14555 
14556   public:
14557     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14558       : FD(FD), CE(CE) { }
14559 
14560     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14561       if (!FD) {
14562         S.Diag(Loc, diag::err_call_incomplete_return)
14563           << T << CE->getSourceRange();
14564         return;
14565       }
14566 
14567       S.Diag(Loc, diag::err_call_function_incomplete_return)
14568         << CE->getSourceRange() << FD->getDeclName() << T;
14569       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14570           << FD->getDeclName();
14571     }
14572   } Diagnoser(FD, CE);
14573 
14574   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14575     return true;
14576 
14577   return false;
14578 }
14579 
14580 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14581 // will prevent this condition from triggering, which is what we want.
14582 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14583   SourceLocation Loc;
14584 
14585   unsigned diagnostic = diag::warn_condition_is_assignment;
14586   bool IsOrAssign = false;
14587 
14588   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14589     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14590       return;
14591 
14592     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14593 
14594     // Greylist some idioms by putting them into a warning subcategory.
14595     if (ObjCMessageExpr *ME
14596           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14597       Selector Sel = ME->getSelector();
14598 
14599       // self = [<foo> init...]
14600       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14601         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14602 
14603       // <foo> = [<bar> nextObject]
14604       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14605         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14606     }
14607 
14608     Loc = Op->getOperatorLoc();
14609   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14610     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14611       return;
14612 
14613     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14614     Loc = Op->getOperatorLoc();
14615   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14616     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14617   else {
14618     // Not an assignment.
14619     return;
14620   }
14621 
14622   Diag(Loc, diagnostic) << E->getSourceRange();
14623 
14624   SourceLocation Open = E->getLocStart();
14625   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14626   Diag(Loc, diag::note_condition_assign_silence)
14627         << FixItHint::CreateInsertion(Open, "(")
14628         << FixItHint::CreateInsertion(Close, ")");
14629 
14630   if (IsOrAssign)
14631     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14632       << FixItHint::CreateReplacement(Loc, "!=");
14633   else
14634     Diag(Loc, diag::note_condition_assign_to_comparison)
14635       << FixItHint::CreateReplacement(Loc, "==");
14636 }
14637 
14638 /// \brief Redundant parentheses over an equality comparison can indicate
14639 /// that the user intended an assignment used as condition.
14640 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14641   // Don't warn if the parens came from a macro.
14642   SourceLocation parenLoc = ParenE->getLocStart();
14643   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14644     return;
14645   // Don't warn for dependent expressions.
14646   if (ParenE->isTypeDependent())
14647     return;
14648 
14649   Expr *E = ParenE->IgnoreParens();
14650 
14651   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14652     if (opE->getOpcode() == BO_EQ &&
14653         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14654                                                            == Expr::MLV_Valid) {
14655       SourceLocation Loc = opE->getOperatorLoc();
14656 
14657       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14658       SourceRange ParenERange = ParenE->getSourceRange();
14659       Diag(Loc, diag::note_equality_comparison_silence)
14660         << FixItHint::CreateRemoval(ParenERange.getBegin())
14661         << FixItHint::CreateRemoval(ParenERange.getEnd());
14662       Diag(Loc, diag::note_equality_comparison_to_assign)
14663         << FixItHint::CreateReplacement(Loc, "=");
14664     }
14665 }
14666 
14667 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14668                                        bool IsConstexpr) {
14669   DiagnoseAssignmentAsCondition(E);
14670   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14671     DiagnoseEqualityWithExtraParens(parenE);
14672 
14673   ExprResult result = CheckPlaceholderExpr(E);
14674   if (result.isInvalid()) return ExprError();
14675   E = result.get();
14676 
14677   if (!E->isTypeDependent()) {
14678     if (getLangOpts().CPlusPlus)
14679       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14680 
14681     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14682     if (ERes.isInvalid())
14683       return ExprError();
14684     E = ERes.get();
14685 
14686     QualType T = E->getType();
14687     if (!T->isScalarType()) { // C99 6.8.4.1p1
14688       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14689         << T << E->getSourceRange();
14690       return ExprError();
14691     }
14692     CheckBoolLikeConversion(E, Loc);
14693   }
14694 
14695   return E;
14696 }
14697 
14698 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14699                                            Expr *SubExpr, ConditionKind CK) {
14700   // Empty conditions are valid in for-statements.
14701   if (!SubExpr)
14702     return ConditionResult();
14703 
14704   ExprResult Cond;
14705   switch (CK) {
14706   case ConditionKind::Boolean:
14707     Cond = CheckBooleanCondition(Loc, SubExpr);
14708     break;
14709 
14710   case ConditionKind::ConstexprIf:
14711     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14712     break;
14713 
14714   case ConditionKind::Switch:
14715     Cond = CheckSwitchCondition(Loc, SubExpr);
14716     break;
14717   }
14718   if (Cond.isInvalid())
14719     return ConditionError();
14720 
14721   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14722   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14723   if (!FullExpr.get())
14724     return ConditionError();
14725 
14726   return ConditionResult(*this, nullptr, FullExpr,
14727                          CK == ConditionKind::ConstexprIf);
14728 }
14729 
14730 namespace {
14731   /// A visitor for rebuilding a call to an __unknown_any expression
14732   /// to have an appropriate type.
14733   struct RebuildUnknownAnyFunction
14734     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14735 
14736     Sema &S;
14737 
14738     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14739 
14740     ExprResult VisitStmt(Stmt *S) {
14741       llvm_unreachable("unexpected statement!");
14742     }
14743 
14744     ExprResult VisitExpr(Expr *E) {
14745       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14746         << E->getSourceRange();
14747       return ExprError();
14748     }
14749 
14750     /// Rebuild an expression which simply semantically wraps another
14751     /// expression which it shares the type and value kind of.
14752     template <class T> ExprResult rebuildSugarExpr(T *E) {
14753       ExprResult SubResult = Visit(E->getSubExpr());
14754       if (SubResult.isInvalid()) return ExprError();
14755 
14756       Expr *SubExpr = SubResult.get();
14757       E->setSubExpr(SubExpr);
14758       E->setType(SubExpr->getType());
14759       E->setValueKind(SubExpr->getValueKind());
14760       assert(E->getObjectKind() == OK_Ordinary);
14761       return E;
14762     }
14763 
14764     ExprResult VisitParenExpr(ParenExpr *E) {
14765       return rebuildSugarExpr(E);
14766     }
14767 
14768     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14769       return rebuildSugarExpr(E);
14770     }
14771 
14772     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14773       ExprResult SubResult = Visit(E->getSubExpr());
14774       if (SubResult.isInvalid()) return ExprError();
14775 
14776       Expr *SubExpr = SubResult.get();
14777       E->setSubExpr(SubExpr);
14778       E->setType(S.Context.getPointerType(SubExpr->getType()));
14779       assert(E->getValueKind() == VK_RValue);
14780       assert(E->getObjectKind() == OK_Ordinary);
14781       return E;
14782     }
14783 
14784     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14785       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14786 
14787       E->setType(VD->getType());
14788 
14789       assert(E->getValueKind() == VK_RValue);
14790       if (S.getLangOpts().CPlusPlus &&
14791           !(isa<CXXMethodDecl>(VD) &&
14792             cast<CXXMethodDecl>(VD)->isInstance()))
14793         E->setValueKind(VK_LValue);
14794 
14795       return E;
14796     }
14797 
14798     ExprResult VisitMemberExpr(MemberExpr *E) {
14799       return resolveDecl(E, E->getMemberDecl());
14800     }
14801 
14802     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14803       return resolveDecl(E, E->getDecl());
14804     }
14805   };
14806 }
14807 
14808 /// Given a function expression of unknown-any type, try to rebuild it
14809 /// to have a function type.
14810 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14811   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14812   if (Result.isInvalid()) return ExprError();
14813   return S.DefaultFunctionArrayConversion(Result.get());
14814 }
14815 
14816 namespace {
14817   /// A visitor for rebuilding an expression of type __unknown_anytype
14818   /// into one which resolves the type directly on the referring
14819   /// expression.  Strict preservation of the original source
14820   /// structure is not a goal.
14821   struct RebuildUnknownAnyExpr
14822     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14823 
14824     Sema &S;
14825 
14826     /// The current destination type.
14827     QualType DestType;
14828 
14829     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14830       : S(S), DestType(CastType) {}
14831 
14832     ExprResult VisitStmt(Stmt *S) {
14833       llvm_unreachable("unexpected statement!");
14834     }
14835 
14836     ExprResult VisitExpr(Expr *E) {
14837       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14838         << E->getSourceRange();
14839       return ExprError();
14840     }
14841 
14842     ExprResult VisitCallExpr(CallExpr *E);
14843     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14844 
14845     /// Rebuild an expression which simply semantically wraps another
14846     /// expression which it shares the type and value kind of.
14847     template <class T> ExprResult rebuildSugarExpr(T *E) {
14848       ExprResult SubResult = Visit(E->getSubExpr());
14849       if (SubResult.isInvalid()) return ExprError();
14850       Expr *SubExpr = SubResult.get();
14851       E->setSubExpr(SubExpr);
14852       E->setType(SubExpr->getType());
14853       E->setValueKind(SubExpr->getValueKind());
14854       assert(E->getObjectKind() == OK_Ordinary);
14855       return E;
14856     }
14857 
14858     ExprResult VisitParenExpr(ParenExpr *E) {
14859       return rebuildSugarExpr(E);
14860     }
14861 
14862     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14863       return rebuildSugarExpr(E);
14864     }
14865 
14866     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14867       const PointerType *Ptr = DestType->getAs<PointerType>();
14868       if (!Ptr) {
14869         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14870           << E->getSourceRange();
14871         return ExprError();
14872       }
14873 
14874       if (isa<CallExpr>(E->getSubExpr())) {
14875         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14876           << E->getSourceRange();
14877         return ExprError();
14878       }
14879 
14880       assert(E->getValueKind() == VK_RValue);
14881       assert(E->getObjectKind() == OK_Ordinary);
14882       E->setType(DestType);
14883 
14884       // Build the sub-expression as if it were an object of the pointee type.
14885       DestType = Ptr->getPointeeType();
14886       ExprResult SubResult = Visit(E->getSubExpr());
14887       if (SubResult.isInvalid()) return ExprError();
14888       E->setSubExpr(SubResult.get());
14889       return E;
14890     }
14891 
14892     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14893 
14894     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14895 
14896     ExprResult VisitMemberExpr(MemberExpr *E) {
14897       return resolveDecl(E, E->getMemberDecl());
14898     }
14899 
14900     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14901       return resolveDecl(E, E->getDecl());
14902     }
14903   };
14904 }
14905 
14906 /// Rebuilds a call expression which yielded __unknown_anytype.
14907 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14908   Expr *CalleeExpr = E->getCallee();
14909 
14910   enum FnKind {
14911     FK_MemberFunction,
14912     FK_FunctionPointer,
14913     FK_BlockPointer
14914   };
14915 
14916   FnKind Kind;
14917   QualType CalleeType = CalleeExpr->getType();
14918   if (CalleeType == S.Context.BoundMemberTy) {
14919     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14920     Kind = FK_MemberFunction;
14921     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14922   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14923     CalleeType = Ptr->getPointeeType();
14924     Kind = FK_FunctionPointer;
14925   } else {
14926     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14927     Kind = FK_BlockPointer;
14928   }
14929   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14930 
14931   // Verify that this is a legal result type of a function.
14932   if (DestType->isArrayType() || DestType->isFunctionType()) {
14933     unsigned diagID = diag::err_func_returning_array_function;
14934     if (Kind == FK_BlockPointer)
14935       diagID = diag::err_block_returning_array_function;
14936 
14937     S.Diag(E->getExprLoc(), diagID)
14938       << DestType->isFunctionType() << DestType;
14939     return ExprError();
14940   }
14941 
14942   // Otherwise, go ahead and set DestType as the call's result.
14943   E->setType(DestType.getNonLValueExprType(S.Context));
14944   E->setValueKind(Expr::getValueKindForType(DestType));
14945   assert(E->getObjectKind() == OK_Ordinary);
14946 
14947   // Rebuild the function type, replacing the result type with DestType.
14948   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14949   if (Proto) {
14950     // __unknown_anytype(...) is a special case used by the debugger when
14951     // it has no idea what a function's signature is.
14952     //
14953     // We want to build this call essentially under the K&R
14954     // unprototyped rules, but making a FunctionNoProtoType in C++
14955     // would foul up all sorts of assumptions.  However, we cannot
14956     // simply pass all arguments as variadic arguments, nor can we
14957     // portably just call the function under a non-variadic type; see
14958     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14959     // However, it turns out that in practice it is generally safe to
14960     // call a function declared as "A foo(B,C,D);" under the prototype
14961     // "A foo(B,C,D,...);".  The only known exception is with the
14962     // Windows ABI, where any variadic function is implicitly cdecl
14963     // regardless of its normal CC.  Therefore we change the parameter
14964     // types to match the types of the arguments.
14965     //
14966     // This is a hack, but it is far superior to moving the
14967     // corresponding target-specific code from IR-gen to Sema/AST.
14968 
14969     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14970     SmallVector<QualType, 8> ArgTypes;
14971     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14972       ArgTypes.reserve(E->getNumArgs());
14973       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14974         Expr *Arg = E->getArg(i);
14975         QualType ArgType = Arg->getType();
14976         if (E->isLValue()) {
14977           ArgType = S.Context.getLValueReferenceType(ArgType);
14978         } else if (E->isXValue()) {
14979           ArgType = S.Context.getRValueReferenceType(ArgType);
14980         }
14981         ArgTypes.push_back(ArgType);
14982       }
14983       ParamTypes = ArgTypes;
14984     }
14985     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14986                                          Proto->getExtProtoInfo());
14987   } else {
14988     DestType = S.Context.getFunctionNoProtoType(DestType,
14989                                                 FnType->getExtInfo());
14990   }
14991 
14992   // Rebuild the appropriate pointer-to-function type.
14993   switch (Kind) {
14994   case FK_MemberFunction:
14995     // Nothing to do.
14996     break;
14997 
14998   case FK_FunctionPointer:
14999     DestType = S.Context.getPointerType(DestType);
15000     break;
15001 
15002   case FK_BlockPointer:
15003     DestType = S.Context.getBlockPointerType(DestType);
15004     break;
15005   }
15006 
15007   // Finally, we can recurse.
15008   ExprResult CalleeResult = Visit(CalleeExpr);
15009   if (!CalleeResult.isUsable()) return ExprError();
15010   E->setCallee(CalleeResult.get());
15011 
15012   // Bind a temporary if necessary.
15013   return S.MaybeBindToTemporary(E);
15014 }
15015 
15016 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15017   // Verify that this is a legal result type of a call.
15018   if (DestType->isArrayType() || DestType->isFunctionType()) {
15019     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15020       << DestType->isFunctionType() << DestType;
15021     return ExprError();
15022   }
15023 
15024   // Rewrite the method result type if available.
15025   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15026     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15027     Method->setReturnType(DestType);
15028   }
15029 
15030   // Change the type of the message.
15031   E->setType(DestType.getNonReferenceType());
15032   E->setValueKind(Expr::getValueKindForType(DestType));
15033 
15034   return S.MaybeBindToTemporary(E);
15035 }
15036 
15037 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15038   // The only case we should ever see here is a function-to-pointer decay.
15039   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15040     assert(E->getValueKind() == VK_RValue);
15041     assert(E->getObjectKind() == OK_Ordinary);
15042 
15043     E->setType(DestType);
15044 
15045     // Rebuild the sub-expression as the pointee (function) type.
15046     DestType = DestType->castAs<PointerType>()->getPointeeType();
15047 
15048     ExprResult Result = Visit(E->getSubExpr());
15049     if (!Result.isUsable()) return ExprError();
15050 
15051     E->setSubExpr(Result.get());
15052     return E;
15053   } else if (E->getCastKind() == CK_LValueToRValue) {
15054     assert(E->getValueKind() == VK_RValue);
15055     assert(E->getObjectKind() == OK_Ordinary);
15056 
15057     assert(isa<BlockPointerType>(E->getType()));
15058 
15059     E->setType(DestType);
15060 
15061     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15062     DestType = S.Context.getLValueReferenceType(DestType);
15063 
15064     ExprResult Result = Visit(E->getSubExpr());
15065     if (!Result.isUsable()) return ExprError();
15066 
15067     E->setSubExpr(Result.get());
15068     return E;
15069   } else {
15070     llvm_unreachable("Unhandled cast type!");
15071   }
15072 }
15073 
15074 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15075   ExprValueKind ValueKind = VK_LValue;
15076   QualType Type = DestType;
15077 
15078   // We know how to make this work for certain kinds of decls:
15079 
15080   //  - functions
15081   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15082     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15083       DestType = Ptr->getPointeeType();
15084       ExprResult Result = resolveDecl(E, VD);
15085       if (Result.isInvalid()) return ExprError();
15086       return S.ImpCastExprToType(Result.get(), Type,
15087                                  CK_FunctionToPointerDecay, VK_RValue);
15088     }
15089 
15090     if (!Type->isFunctionType()) {
15091       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15092         << VD << E->getSourceRange();
15093       return ExprError();
15094     }
15095     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15096       // We must match the FunctionDecl's type to the hack introduced in
15097       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15098       // type. See the lengthy commentary in that routine.
15099       QualType FDT = FD->getType();
15100       const FunctionType *FnType = FDT->castAs<FunctionType>();
15101       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15102       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15103       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15104         SourceLocation Loc = FD->getLocation();
15105         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15106                                       FD->getDeclContext(),
15107                                       Loc, Loc, FD->getNameInfo().getName(),
15108                                       DestType, FD->getTypeSourceInfo(),
15109                                       SC_None, false/*isInlineSpecified*/,
15110                                       FD->hasPrototype(),
15111                                       false/*isConstexprSpecified*/);
15112 
15113         if (FD->getQualifier())
15114           NewFD->setQualifierInfo(FD->getQualifierLoc());
15115 
15116         SmallVector<ParmVarDecl*, 16> Params;
15117         for (const auto &AI : FT->param_types()) {
15118           ParmVarDecl *Param =
15119             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15120           Param->setScopeInfo(0, Params.size());
15121           Params.push_back(Param);
15122         }
15123         NewFD->setParams(Params);
15124         DRE->setDecl(NewFD);
15125         VD = DRE->getDecl();
15126       }
15127     }
15128 
15129     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15130       if (MD->isInstance()) {
15131         ValueKind = VK_RValue;
15132         Type = S.Context.BoundMemberTy;
15133       }
15134 
15135     // Function references aren't l-values in C.
15136     if (!S.getLangOpts().CPlusPlus)
15137       ValueKind = VK_RValue;
15138 
15139   //  - variables
15140   } else if (isa<VarDecl>(VD)) {
15141     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15142       Type = RefTy->getPointeeType();
15143     } else if (Type->isFunctionType()) {
15144       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15145         << VD << E->getSourceRange();
15146       return ExprError();
15147     }
15148 
15149   //  - nothing else
15150   } else {
15151     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15152       << VD << E->getSourceRange();
15153     return ExprError();
15154   }
15155 
15156   // Modifying the declaration like this is friendly to IR-gen but
15157   // also really dangerous.
15158   VD->setType(DestType);
15159   E->setType(Type);
15160   E->setValueKind(ValueKind);
15161   return E;
15162 }
15163 
15164 /// Check a cast of an unknown-any type.  We intentionally only
15165 /// trigger this for C-style casts.
15166 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15167                                      Expr *CastExpr, CastKind &CastKind,
15168                                      ExprValueKind &VK, CXXCastPath &Path) {
15169   // The type we're casting to must be either void or complete.
15170   if (!CastType->isVoidType() &&
15171       RequireCompleteType(TypeRange.getBegin(), CastType,
15172                           diag::err_typecheck_cast_to_incomplete))
15173     return ExprError();
15174 
15175   // Rewrite the casted expression from scratch.
15176   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15177   if (!result.isUsable()) return ExprError();
15178 
15179   CastExpr = result.get();
15180   VK = CastExpr->getValueKind();
15181   CastKind = CK_NoOp;
15182 
15183   return CastExpr;
15184 }
15185 
15186 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15187   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15188 }
15189 
15190 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15191                                     Expr *arg, QualType &paramType) {
15192   // If the syntactic form of the argument is not an explicit cast of
15193   // any sort, just do default argument promotion.
15194   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15195   if (!castArg) {
15196     ExprResult result = DefaultArgumentPromotion(arg);
15197     if (result.isInvalid()) return ExprError();
15198     paramType = result.get()->getType();
15199     return result;
15200   }
15201 
15202   // Otherwise, use the type that was written in the explicit cast.
15203   assert(!arg->hasPlaceholderType());
15204   paramType = castArg->getTypeAsWritten();
15205 
15206   // Copy-initialize a parameter of that type.
15207   InitializedEntity entity =
15208     InitializedEntity::InitializeParameter(Context, paramType,
15209                                            /*consumed*/ false);
15210   return PerformCopyInitialization(entity, callLoc, arg);
15211 }
15212 
15213 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15214   Expr *orig = E;
15215   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15216   while (true) {
15217     E = E->IgnoreParenImpCasts();
15218     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15219       E = call->getCallee();
15220       diagID = diag::err_uncasted_call_of_unknown_any;
15221     } else {
15222       break;
15223     }
15224   }
15225 
15226   SourceLocation loc;
15227   NamedDecl *d;
15228   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15229     loc = ref->getLocation();
15230     d = ref->getDecl();
15231   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15232     loc = mem->getMemberLoc();
15233     d = mem->getMemberDecl();
15234   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15235     diagID = diag::err_uncasted_call_of_unknown_any;
15236     loc = msg->getSelectorStartLoc();
15237     d = msg->getMethodDecl();
15238     if (!d) {
15239       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15240         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15241         << orig->getSourceRange();
15242       return ExprError();
15243     }
15244   } else {
15245     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15246       << E->getSourceRange();
15247     return ExprError();
15248   }
15249 
15250   S.Diag(loc, diagID) << d << orig->getSourceRange();
15251 
15252   // Never recoverable.
15253   return ExprError();
15254 }
15255 
15256 /// Check for operands with placeholder types and complain if found.
15257 /// Returns true if there was an error and no recovery was possible.
15258 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15259   if (!getLangOpts().CPlusPlus) {
15260     // C cannot handle TypoExpr nodes on either side of a binop because it
15261     // doesn't handle dependent types properly, so make sure any TypoExprs have
15262     // been dealt with before checking the operands.
15263     ExprResult Result = CorrectDelayedTyposInExpr(E);
15264     if (!Result.isUsable()) return ExprError();
15265     E = Result.get();
15266   }
15267 
15268   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15269   if (!placeholderType) return E;
15270 
15271   switch (placeholderType->getKind()) {
15272 
15273   // Overloaded expressions.
15274   case BuiltinType::Overload: {
15275     // Try to resolve a single function template specialization.
15276     // This is obligatory.
15277     ExprResult Result = E;
15278     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15279       return Result;
15280 
15281     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15282     // leaves Result unchanged on failure.
15283     Result = E;
15284     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15285       return Result;
15286 
15287     // If that failed, try to recover with a call.
15288     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15289                          /*complain*/ true);
15290     return Result;
15291   }
15292 
15293   // Bound member functions.
15294   case BuiltinType::BoundMember: {
15295     ExprResult result = E;
15296     const Expr *BME = E->IgnoreParens();
15297     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15298     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15299     if (isa<CXXPseudoDestructorExpr>(BME)) {
15300       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15301     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15302       if (ME->getMemberNameInfo().getName().getNameKind() ==
15303           DeclarationName::CXXDestructorName)
15304         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15305     }
15306     tryToRecoverWithCall(result, PD,
15307                          /*complain*/ true);
15308     return result;
15309   }
15310 
15311   // ARC unbridged casts.
15312   case BuiltinType::ARCUnbridgedCast: {
15313     Expr *realCast = stripARCUnbridgedCast(E);
15314     diagnoseARCUnbridgedCast(realCast);
15315     return realCast;
15316   }
15317 
15318   // Expressions of unknown type.
15319   case BuiltinType::UnknownAny:
15320     return diagnoseUnknownAnyExpr(*this, E);
15321 
15322   // Pseudo-objects.
15323   case BuiltinType::PseudoObject:
15324     return checkPseudoObjectRValue(E);
15325 
15326   case BuiltinType::BuiltinFn: {
15327     // Accept __noop without parens by implicitly converting it to a call expr.
15328     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15329     if (DRE) {
15330       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15331       if (FD->getBuiltinID() == Builtin::BI__noop) {
15332         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15333                               CK_BuiltinFnToFnPtr).get();
15334         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15335                                       VK_RValue, SourceLocation());
15336       }
15337     }
15338 
15339     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15340     return ExprError();
15341   }
15342 
15343   // Expressions of unknown type.
15344   case BuiltinType::OMPArraySection:
15345     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15346     return ExprError();
15347 
15348   // Everything else should be impossible.
15349 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15350   case BuiltinType::Id:
15351 #include "clang/Basic/OpenCLImageTypes.def"
15352 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15353 #define PLACEHOLDER_TYPE(Id, SingletonId)
15354 #include "clang/AST/BuiltinTypes.def"
15355     break;
15356   }
15357 
15358   llvm_unreachable("invalid placeholder type!");
15359 }
15360 
15361 bool Sema::CheckCaseExpression(Expr *E) {
15362   if (E->isTypeDependent())
15363     return true;
15364   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15365     return E->getType()->isIntegralOrEnumerationType();
15366   return false;
15367 }
15368 
15369 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15370 ExprResult
15371 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15372   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15373          "Unknown Objective-C Boolean value!");
15374   QualType BoolT = Context.ObjCBuiltinBoolTy;
15375   if (!Context.getBOOLDecl()) {
15376     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15377                         Sema::LookupOrdinaryName);
15378     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15379       NamedDecl *ND = Result.getFoundDecl();
15380       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15381         Context.setBOOLDecl(TD);
15382     }
15383   }
15384   if (Context.getBOOLDecl())
15385     BoolT = Context.getBOOLType();
15386   return new (Context)
15387       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15388 }
15389 
15390 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15391     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15392     SourceLocation RParen) {
15393 
15394   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15395 
15396   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15397                            [&](const AvailabilitySpec &Spec) {
15398                              return Spec.getPlatform() == Platform;
15399                            });
15400 
15401   VersionTuple Version;
15402   if (Spec != AvailSpecs.end())
15403     Version = Spec->getVersion();
15404 
15405   return new (Context)
15406       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15407 }
15408