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 Sema::ShouldDiagnoseAvailabilityOfDecl(
107     NamedDecl *&D, VersionTuple ContextVersion, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message, ContextVersion);
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, ContextVersion);
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, ContextVersion);
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, ContextVersion);
136     }
137 
138   switch (Result) {
139   case AR_Available:
140     return Result;
141 
142   case AR_Unavailable:
143   case AR_Deprecated:
144     return getCurContextAvailability() != Result ? Result : AR_Available;
145 
146   case AR_NotYetIntroduced: {
147     // Don't do this for enums, they can't be redeclared.
148     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
149       return AR_Available;
150 
151     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
152     // Objective-C method declarations in categories are not modelled as
153     // redeclarations, so manually look for a redeclaration in a category
154     // if necessary.
155     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
156       Warn = false;
157     // In general, D will point to the most recent redeclaration. However,
158     // for `@class A;` decls, this isn't true -- manually go through the
159     // redecl chain in that case.
160     if (Warn && isa<ObjCInterfaceDecl>(D))
161       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
162            Redecl = Redecl->getPreviousDecl())
163         if (!Redecl->hasAttr<AvailabilityAttr>() ||
164             Redecl->getAttr<AvailabilityAttr>()->isInherited())
165           Warn = false;
166 
167     return Warn ? AR_NotYetIntroduced : AR_Available;
168   }
169   }
170   llvm_unreachable("Unknown availability result!");
171 }
172 
173 static void
174 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
175                            const ObjCInterfaceDecl *UnknownObjCClass,
176                            bool ObjCPropertyAccess) {
177   VersionTuple ContextVersion;
178   if (const DeclContext *DC = S.getCurObjCLexicalContext())
179     ContextVersion = S.getVersionForDecl(cast<Decl>(DC));
180 
181   std::string Message;
182   // See if this declaration is unavailable, deprecated, or partial in the
183   // current context.
184   if (AvailabilityResult Result =
185           S.ShouldDiagnoseAvailabilityOfDecl(D, ContextVersion, &Message)) {
186 
187     const ObjCPropertyDecl *ObjCPDecl = nullptr;
188     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
189       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
190         AvailabilityResult PDeclResult =
191             PD->getAvailability(nullptr, ContextVersion);
192         if (PDeclResult == Result)
193           ObjCPDecl = PD;
194       }
195     }
196 
197     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
198                               ObjCPDecl, ObjCPropertyAccess);
199   }
200 }
201 
202 /// \brief Emit a note explaining that this function is deleted.
203 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
204   assert(Decl->isDeleted());
205 
206   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
207 
208   if (Method && Method->isDeleted() && Method->isDefaulted()) {
209     // If the method was explicitly defaulted, point at that declaration.
210     if (!Method->isImplicit())
211       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
212 
213     // Try to diagnose why this special member function was implicitly
214     // deleted. This might fail, if that reason no longer applies.
215     CXXSpecialMember CSM = getSpecialMember(Method);
216     if (CSM != CXXInvalid)
217       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
218 
219     return;
220   }
221 
222   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
223   if (Ctor && Ctor->isInheritingConstructor())
224     return NoteDeletedInheritingConstructor(Ctor);
225 
226   Diag(Decl->getLocation(), diag::note_availability_specified_here)
227     << Decl << true;
228 }
229 
230 /// \brief Determine whether a FunctionDecl was ever declared with an
231 /// explicit storage class.
232 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
233   for (auto I : D->redecls()) {
234     if (I->getStorageClass() != SC_None)
235       return true;
236   }
237   return false;
238 }
239 
240 /// \brief Check whether we're in an extern inline function and referring to a
241 /// variable or function with internal linkage (C11 6.7.4p3).
242 ///
243 /// This is only a warning because we used to silently accept this code, but
244 /// in many cases it will not behave correctly. This is not enabled in C++ mode
245 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
246 /// and so while there may still be user mistakes, most of the time we can't
247 /// prove that there are errors.
248 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
249                                                       const NamedDecl *D,
250                                                       SourceLocation Loc) {
251   // This is disabled under C++; there are too many ways for this to fire in
252   // contexts where the warning is a false positive, or where it is technically
253   // correct but benign.
254   if (S.getLangOpts().CPlusPlus)
255     return;
256 
257   // Check if this is an inlined function or method.
258   FunctionDecl *Current = S.getCurFunctionDecl();
259   if (!Current)
260     return;
261   if (!Current->isInlined())
262     return;
263   if (!Current->isExternallyVisible())
264     return;
265 
266   // Check if the decl has internal linkage.
267   if (D->getFormalLinkage() != InternalLinkage)
268     return;
269 
270   // Downgrade from ExtWarn to Extension if
271   //  (1) the supposedly external inline function is in the main file,
272   //      and probably won't be included anywhere else.
273   //  (2) the thing we're referencing is a pure function.
274   //  (3) the thing we're referencing is another inline function.
275   // This last can give us false negatives, but it's better than warning on
276   // wrappers for simple C library functions.
277   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
278   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
279   if (!DowngradeWarning && UsedFn)
280     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
281 
282   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
283                                : diag::ext_internal_in_extern_inline)
284     << /*IsVar=*/!UsedFn << D;
285 
286   S.MaybeSuggestAddingStaticToDecl(Current);
287 
288   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
289       << D;
290 }
291 
292 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
293   const FunctionDecl *First = Cur->getFirstDecl();
294 
295   // Suggest "static" on the function, if possible.
296   if (!hasAnyExplicitStorageClass(First)) {
297     SourceLocation DeclBegin = First->getSourceRange().getBegin();
298     Diag(DeclBegin, diag::note_convert_inline_to_static)
299       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
300   }
301 }
302 
303 /// \brief Determine whether the use of this declaration is valid, and
304 /// emit any corresponding diagnostics.
305 ///
306 /// This routine diagnoses various problems with referencing
307 /// declarations that can occur when using a declaration. For example,
308 /// it might warn if a deprecated or unavailable declaration is being
309 /// used, or produce an error (and return true) if a C++0x deleted
310 /// function is being used.
311 ///
312 /// \returns true if there was an error (this declaration cannot be
313 /// referenced), false otherwise.
314 ///
315 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
316                              const ObjCInterfaceDecl *UnknownObjCClass,
317                              bool ObjCPropertyAccess) {
318   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
319     // If there were any diagnostics suppressed by template argument deduction,
320     // emit them now.
321     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
322     if (Pos != SuppressedDiagnostics.end()) {
323       for (const PartialDiagnosticAt &Suppressed : Pos->second)
324         Diag(Suppressed.first, Suppressed.second);
325 
326       // Clear out the list of suppressed diagnostics, so that we don't emit
327       // them again for this specialization. However, we don't obsolete this
328       // entry from the table, because we want to avoid ever emitting these
329       // diagnostics again.
330       Pos->second.clear();
331     }
332 
333     // C++ [basic.start.main]p3:
334     //   The function 'main' shall not be used within a program.
335     if (cast<FunctionDecl>(D)->isMain())
336       Diag(Loc, diag::ext_main_used);
337   }
338 
339   // See if this is an auto-typed variable whose initializer we are parsing.
340   if (ParsingInitForAutoVars.count(D)) {
341     if (isa<BindingDecl>(D)) {
342       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
343         << D->getDeclName();
344     } else {
345       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
346 
347       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
348         << D->getDeclName() << (unsigned)AT->getKeyword();
349     }
350     return true;
351   }
352 
353   // See if this is a deleted function.
354   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
355     if (FD->isDeleted()) {
356       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
357       if (Ctor && Ctor->isInheritingConstructor())
358         Diag(Loc, diag::err_deleted_inherited_ctor_use)
359             << Ctor->getParent()
360             << Ctor->getInheritedConstructor().getConstructor()->getParent();
361       else
362         Diag(Loc, diag::err_deleted_function_use);
363       NoteDeletedFunction(FD);
364       return true;
365     }
366 
367     // If the function has a deduced return type, and we can't deduce it,
368     // then we can't use it either.
369     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
370         DeduceReturnType(FD, Loc))
371       return true;
372   }
373 
374   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
375   // Only the variables omp_in and omp_out are allowed in the combiner.
376   // Only the variables omp_priv and omp_orig are allowed in the
377   // initializer-clause.
378   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
379   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
380       isa<VarDecl>(D)) {
381     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
382         << getCurFunction()->HasOMPDeclareReductionCombiner;
383     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
384     return true;
385   }
386   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
387                              ObjCPropertyAccess);
388 
389   DiagnoseUnusedOfDecl(*this, D, Loc);
390 
391   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
392 
393   return false;
394 }
395 
396 /// \brief Retrieve the message suffix that should be added to a
397 /// diagnostic complaining about the given function being deleted or
398 /// unavailable.
399 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
400   std::string Message;
401   if (FD->getAvailability(&Message))
402     return ": " + Message;
403 
404   return std::string();
405 }
406 
407 /// DiagnoseSentinelCalls - This routine checks whether a call or
408 /// message-send is to a declaration with the sentinel attribute, and
409 /// if so, it checks that the requirements of the sentinel are
410 /// satisfied.
411 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
412                                  ArrayRef<Expr *> Args) {
413   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
414   if (!attr)
415     return;
416 
417   // The number of formal parameters of the declaration.
418   unsigned numFormalParams;
419 
420   // The kind of declaration.  This is also an index into a %select in
421   // the diagnostic.
422   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
423 
424   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
425     numFormalParams = MD->param_size();
426     calleeType = CT_Method;
427   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
428     numFormalParams = FD->param_size();
429     calleeType = CT_Function;
430   } else if (isa<VarDecl>(D)) {
431     QualType type = cast<ValueDecl>(D)->getType();
432     const FunctionType *fn = nullptr;
433     if (const PointerType *ptr = type->getAs<PointerType>()) {
434       fn = ptr->getPointeeType()->getAs<FunctionType>();
435       if (!fn) return;
436       calleeType = CT_Function;
437     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
438       fn = ptr->getPointeeType()->castAs<FunctionType>();
439       calleeType = CT_Block;
440     } else {
441       return;
442     }
443 
444     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
445       numFormalParams = proto->getNumParams();
446     } else {
447       numFormalParams = 0;
448     }
449   } else {
450     return;
451   }
452 
453   // "nullPos" is the number of formal parameters at the end which
454   // effectively count as part of the variadic arguments.  This is
455   // useful if you would prefer to not have *any* formal parameters,
456   // but the language forces you to have at least one.
457   unsigned nullPos = attr->getNullPos();
458   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
459   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
460 
461   // The number of arguments which should follow the sentinel.
462   unsigned numArgsAfterSentinel = attr->getSentinel();
463 
464   // If there aren't enough arguments for all the formal parameters,
465   // the sentinel, and the args after the sentinel, complain.
466   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
467     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
468     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
469     return;
470   }
471 
472   // Otherwise, find the sentinel expression.
473   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
474   if (!sentinelExpr) return;
475   if (sentinelExpr->isValueDependent()) return;
476   if (Context.isSentinelNullExpr(sentinelExpr)) return;
477 
478   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
479   // or 'NULL' if those are actually defined in the context.  Only use
480   // 'nil' for ObjC methods, where it's much more likely that the
481   // variadic arguments form a list of object pointers.
482   SourceLocation MissingNilLoc
483     = getLocForEndOfToken(sentinelExpr->getLocEnd());
484   std::string NullValue;
485   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
486     NullValue = "nil";
487   else if (getLangOpts().CPlusPlus11)
488     NullValue = "nullptr";
489   else if (PP.isMacroDefined("NULL"))
490     NullValue = "NULL";
491   else
492     NullValue = "(void*) 0";
493 
494   if (MissingNilLoc.isInvalid())
495     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
496   else
497     Diag(MissingNilLoc, diag::warn_missing_sentinel)
498       << int(calleeType)
499       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
500   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
501 }
502 
503 SourceRange Sema::getExprRange(Expr *E) const {
504   return E ? E->getSourceRange() : SourceRange();
505 }
506 
507 //===----------------------------------------------------------------------===//
508 //  Standard Promotions and Conversions
509 //===----------------------------------------------------------------------===//
510 
511 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
512 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
513   // Handle any placeholder expressions which made it here.
514   if (E->getType()->isPlaceholderType()) {
515     ExprResult result = CheckPlaceholderExpr(E);
516     if (result.isInvalid()) return ExprError();
517     E = result.get();
518   }
519 
520   QualType Ty = E->getType();
521   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
522 
523   if (Ty->isFunctionType()) {
524     // If we are here, we are not calling a function but taking
525     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
526     if (getLangOpts().OpenCL) {
527       if (Diagnose)
528         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
529       return ExprError();
530     }
531 
532     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
533       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
534         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
535           return ExprError();
536 
537     E = ImpCastExprToType(E, Context.getPointerType(Ty),
538                           CK_FunctionToPointerDecay).get();
539   } else if (Ty->isArrayType()) {
540     // In C90 mode, arrays only promote to pointers if the array expression is
541     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
542     // type 'array of type' is converted to an expression that has type 'pointer
543     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
544     // that has type 'array of type' ...".  The relevant change is "an lvalue"
545     // (C90) to "an expression" (C99).
546     //
547     // C++ 4.2p1:
548     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
549     // T" can be converted to an rvalue of type "pointer to T".
550     //
551     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
552       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
553                             CK_ArrayToPointerDecay).get();
554   }
555   return E;
556 }
557 
558 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
559   // Check to see if we are dereferencing a null pointer.  If so,
560   // and if not volatile-qualified, this is undefined behavior that the
561   // optimizer will delete, so warn about it.  People sometimes try to use this
562   // to get a deterministic trap and are surprised by clang's behavior.  This
563   // only handles the pattern "*null", which is a very syntactic check.
564   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
565     if (UO->getOpcode() == UO_Deref &&
566         UO->getSubExpr()->IgnoreParenCasts()->
567           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
568         !UO->getType().isVolatileQualified()) {
569     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
570                           S.PDiag(diag::warn_indirection_through_null)
571                             << UO->getSubExpr()->getSourceRange());
572     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
573                         S.PDiag(diag::note_indirection_through_null));
574   }
575 }
576 
577 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
578                                     SourceLocation AssignLoc,
579                                     const Expr* RHS) {
580   const ObjCIvarDecl *IV = OIRE->getDecl();
581   if (!IV)
582     return;
583 
584   DeclarationName MemberName = IV->getDeclName();
585   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
586   if (!Member || !Member->isStr("isa"))
587     return;
588 
589   const Expr *Base = OIRE->getBase();
590   QualType BaseType = Base->getType();
591   if (OIRE->isArrow())
592     BaseType = BaseType->getPointeeType();
593   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
594     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
595       ObjCInterfaceDecl *ClassDeclared = nullptr;
596       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
597       if (!ClassDeclared->getSuperClass()
598           && (*ClassDeclared->ivar_begin()) == IV) {
599         if (RHS) {
600           NamedDecl *ObjectSetClass =
601             S.LookupSingleName(S.TUScope,
602                                &S.Context.Idents.get("object_setClass"),
603                                SourceLocation(), S.LookupOrdinaryName);
604           if (ObjectSetClass) {
605             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
606             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
607             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
608             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
609                                                      AssignLoc), ",") <<
610             FixItHint::CreateInsertion(RHSLocEnd, ")");
611           }
612           else
613             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
614         } else {
615           NamedDecl *ObjectGetClass =
616             S.LookupSingleName(S.TUScope,
617                                &S.Context.Idents.get("object_getClass"),
618                                SourceLocation(), S.LookupOrdinaryName);
619           if (ObjectGetClass)
620             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
621             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
622             FixItHint::CreateReplacement(
623                                          SourceRange(OIRE->getOpLoc(),
624                                                      OIRE->getLocEnd()), ")");
625           else
626             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
627         }
628         S.Diag(IV->getLocation(), diag::note_ivar_decl);
629       }
630     }
631 }
632 
633 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
634   // Handle any placeholder expressions which made it here.
635   if (E->getType()->isPlaceholderType()) {
636     ExprResult result = CheckPlaceholderExpr(E);
637     if (result.isInvalid()) return ExprError();
638     E = result.get();
639   }
640 
641   // C++ [conv.lval]p1:
642   //   A glvalue of a non-function, non-array type T can be
643   //   converted to a prvalue.
644   if (!E->isGLValue()) return E;
645 
646   QualType T = E->getType();
647   assert(!T.isNull() && "r-value conversion on typeless expression?");
648 
649   // We don't want to throw lvalue-to-rvalue casts on top of
650   // expressions of certain types in C++.
651   if (getLangOpts().CPlusPlus &&
652       (E->getType() == Context.OverloadTy ||
653        T->isDependentType() ||
654        T->isRecordType()))
655     return E;
656 
657   // The C standard is actually really unclear on this point, and
658   // DR106 tells us what the result should be but not why.  It's
659   // generally best to say that void types just doesn't undergo
660   // lvalue-to-rvalue at all.  Note that expressions of unqualified
661   // 'void' type are never l-values, but qualified void can be.
662   if (T->isVoidType())
663     return E;
664 
665   // OpenCL usually rejects direct accesses to values of 'half' type.
666   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
667       T->isHalfType()) {
668     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
669       << 0 << T;
670     return ExprError();
671   }
672 
673   CheckForNullPointerDereference(*this, E);
674   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
675     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
676                                      &Context.Idents.get("object_getClass"),
677                                      SourceLocation(), LookupOrdinaryName);
678     if (ObjectGetClass)
679       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
680         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
681         FixItHint::CreateReplacement(
682                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
683     else
684       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
685   }
686   else if (const ObjCIvarRefExpr *OIRE =
687             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
688     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
689 
690   // C++ [conv.lval]p1:
691   //   [...] If T is a non-class type, the type of the prvalue is the
692   //   cv-unqualified version of T. Otherwise, the type of the
693   //   rvalue is T.
694   //
695   // C99 6.3.2.1p2:
696   //   If the lvalue has qualified type, the value has the unqualified
697   //   version of the type of the lvalue; otherwise, the value has the
698   //   type of the lvalue.
699   if (T.hasQualifiers())
700     T = T.getUnqualifiedType();
701 
702   // Under the MS ABI, lock down the inheritance model now.
703   if (T->isMemberPointerType() &&
704       Context.getTargetInfo().getCXXABI().isMicrosoft())
705     (void)isCompleteType(E->getExprLoc(), T);
706 
707   UpdateMarkingForLValueToRValue(E);
708 
709   // Loading a __weak object implicitly retains the value, so we need a cleanup to
710   // balance that.
711   if (getLangOpts().ObjCAutoRefCount &&
712       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713     Cleanup.setExprNeedsCleanups(true);
714 
715   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
716                                             nullptr, VK_RValue);
717 
718   // C11 6.3.2.1p2:
719   //   ... if the lvalue has atomic type, the value has the non-atomic version
720   //   of the type of the lvalue ...
721   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
722     T = Atomic->getValueType().getUnqualifiedType();
723     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
724                                    nullptr, VK_RValue);
725   }
726 
727   return Res;
728 }
729 
730 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
731   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
732   if (Res.isInvalid())
733     return ExprError();
734   Res = DefaultLvalueConversion(Res.get());
735   if (Res.isInvalid())
736     return ExprError();
737   return Res;
738 }
739 
740 /// CallExprUnaryConversions - a special case of an unary conversion
741 /// performed on a function designator of a call expression.
742 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
743   QualType Ty = E->getType();
744   ExprResult Res = E;
745   // Only do implicit cast for a function type, but not for a pointer
746   // to function type.
747   if (Ty->isFunctionType()) {
748     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
749                             CK_FunctionToPointerDecay).get();
750     if (Res.isInvalid())
751       return ExprError();
752   }
753   Res = DefaultLvalueConversion(Res.get());
754   if (Res.isInvalid())
755     return ExprError();
756   return Res.get();
757 }
758 
759 /// UsualUnaryConversions - Performs various conversions that are common to most
760 /// operators (C99 6.3). The conversions of array and function types are
761 /// sometimes suppressed. For example, the array->pointer conversion doesn't
762 /// apply if the array is an argument to the sizeof or address (&) operators.
763 /// In these instances, this routine should *not* be called.
764 ExprResult Sema::UsualUnaryConversions(Expr *E) {
765   // First, convert to an r-value.
766   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
767   if (Res.isInvalid())
768     return ExprError();
769   E = Res.get();
770 
771   QualType Ty = E->getType();
772   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
773 
774   // Half FP have to be promoted to float unless it is natively supported
775   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
776     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
777 
778   // Try to perform integral promotions if the object has a theoretically
779   // promotable type.
780   if (Ty->isIntegralOrUnscopedEnumerationType()) {
781     // C99 6.3.1.1p2:
782     //
783     //   The following may be used in an expression wherever an int or
784     //   unsigned int may be used:
785     //     - an object or expression with an integer type whose integer
786     //       conversion rank is less than or equal to the rank of int
787     //       and unsigned int.
788     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
789     //
790     //   If an int can represent all values of the original type, the
791     //   value is converted to an int; otherwise, it is converted to an
792     //   unsigned int. These are called the integer promotions. All
793     //   other types are unchanged by the integer promotions.
794 
795     QualType PTy = Context.isPromotableBitField(E);
796     if (!PTy.isNull()) {
797       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
798       return E;
799     }
800     if (Ty->isPromotableIntegerType()) {
801       QualType PT = Context.getPromotedIntegerType(Ty);
802       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
803       return E;
804     }
805   }
806   return E;
807 }
808 
809 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
810 /// do not have a prototype. Arguments that have type float or __fp16
811 /// are promoted to double. All other argument types are converted by
812 /// UsualUnaryConversions().
813 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
814   QualType Ty = E->getType();
815   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
816 
817   ExprResult Res = UsualUnaryConversions(E);
818   if (Res.isInvalid())
819     return ExprError();
820   E = Res.get();
821 
822   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
823   // double.
824   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
825   if (BTy && (BTy->getKind() == BuiltinType::Half ||
826               BTy->getKind() == BuiltinType::Float))
827     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
828 
829   // C++ performs lvalue-to-rvalue conversion as a default argument
830   // promotion, even on class types, but note:
831   //   C++11 [conv.lval]p2:
832   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
833   //     operand or a subexpression thereof the value contained in the
834   //     referenced object is not accessed. Otherwise, if the glvalue
835   //     has a class type, the conversion copy-initializes a temporary
836   //     of type T from the glvalue and the result of the conversion
837   //     is a prvalue for the temporary.
838   // FIXME: add some way to gate this entire thing for correctness in
839   // potentially potentially evaluated contexts.
840   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
841     ExprResult Temp = PerformCopyInitialization(
842                        InitializedEntity::InitializeTemporary(E->getType()),
843                                                 E->getExprLoc(), E);
844     if (Temp.isInvalid())
845       return ExprError();
846     E = Temp.get();
847   }
848 
849   return E;
850 }
851 
852 /// Determine the degree of POD-ness for an expression.
853 /// Incomplete types are considered POD, since this check can be performed
854 /// when we're in an unevaluated context.
855 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
856   if (Ty->isIncompleteType()) {
857     // C++11 [expr.call]p7:
858     //   After these conversions, if the argument does not have arithmetic,
859     //   enumeration, pointer, pointer to member, or class type, the program
860     //   is ill-formed.
861     //
862     // Since we've already performed array-to-pointer and function-to-pointer
863     // decay, the only such type in C++ is cv void. This also handles
864     // initializer lists as variadic arguments.
865     if (Ty->isVoidType())
866       return VAK_Invalid;
867 
868     if (Ty->isObjCObjectType())
869       return VAK_Invalid;
870     return VAK_Valid;
871   }
872 
873   if (Ty.isCXX98PODType(Context))
874     return VAK_Valid;
875 
876   // C++11 [expr.call]p7:
877   //   Passing a potentially-evaluated argument of class type (Clause 9)
878   //   having a non-trivial copy constructor, a non-trivial move constructor,
879   //   or a non-trivial destructor, with no corresponding parameter,
880   //   is conditionally-supported with implementation-defined semantics.
881   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
882     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
883       if (!Record->hasNonTrivialCopyConstructor() &&
884           !Record->hasNonTrivialMoveConstructor() &&
885           !Record->hasNonTrivialDestructor())
886         return VAK_ValidInCXX11;
887 
888   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
889     return VAK_Valid;
890 
891   if (Ty->isObjCObjectType())
892     return VAK_Invalid;
893 
894   if (getLangOpts().MSVCCompat)
895     return VAK_MSVCUndefined;
896 
897   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
898   // permitted to reject them. We should consider doing so.
899   return VAK_Undefined;
900 }
901 
902 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
903   // Don't allow one to pass an Objective-C interface to a vararg.
904   const QualType &Ty = E->getType();
905   VarArgKind VAK = isValidVarArgType(Ty);
906 
907   // Complain about passing non-POD types through varargs.
908   switch (VAK) {
909   case VAK_ValidInCXX11:
910     DiagRuntimeBehavior(
911         E->getLocStart(), nullptr,
912         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
913           << Ty << CT);
914     // Fall through.
915   case VAK_Valid:
916     if (Ty->isRecordType()) {
917       // This is unlikely to be what the user intended. If the class has a
918       // 'c_str' member function, the user probably meant to call that.
919       DiagRuntimeBehavior(E->getLocStart(), nullptr,
920                           PDiag(diag::warn_pass_class_arg_to_vararg)
921                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
922     }
923     break;
924 
925   case VAK_Undefined:
926   case VAK_MSVCUndefined:
927     DiagRuntimeBehavior(
928         E->getLocStart(), nullptr,
929         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
930           << getLangOpts().CPlusPlus11 << Ty << CT);
931     break;
932 
933   case VAK_Invalid:
934     if (Ty->isObjCObjectType())
935       DiagRuntimeBehavior(
936           E->getLocStart(), nullptr,
937           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
938             << Ty << CT);
939     else
940       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
941         << isa<InitListExpr>(E) << Ty << CT;
942     break;
943   }
944 }
945 
946 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
947 /// will create a trap if the resulting type is not a POD type.
948 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
949                                                   FunctionDecl *FDecl) {
950   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
951     // Strip the unbridged-cast placeholder expression off, if applicable.
952     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
953         (CT == VariadicMethod ||
954          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
955       E = stripARCUnbridgedCast(E);
956 
957     // Otherwise, do normal placeholder checking.
958     } else {
959       ExprResult ExprRes = CheckPlaceholderExpr(E);
960       if (ExprRes.isInvalid())
961         return ExprError();
962       E = ExprRes.get();
963     }
964   }
965 
966   ExprResult ExprRes = DefaultArgumentPromotion(E);
967   if (ExprRes.isInvalid())
968     return ExprError();
969   E = ExprRes.get();
970 
971   // Diagnostics regarding non-POD argument types are
972   // emitted along with format string checking in Sema::CheckFunctionCall().
973   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
974     // Turn this into a trap.
975     CXXScopeSpec SS;
976     SourceLocation TemplateKWLoc;
977     UnqualifiedId Name;
978     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
979                        E->getLocStart());
980     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
981                                           Name, true, false);
982     if (TrapFn.isInvalid())
983       return ExprError();
984 
985     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
986                                     E->getLocStart(), None,
987                                     E->getLocEnd());
988     if (Call.isInvalid())
989       return ExprError();
990 
991     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
992                                   Call.get(), E);
993     if (Comma.isInvalid())
994       return ExprError();
995     return Comma.get();
996   }
997 
998   if (!getLangOpts().CPlusPlus &&
999       RequireCompleteType(E->getExprLoc(), E->getType(),
1000                           diag::err_call_incomplete_argument))
1001     return ExprError();
1002 
1003   return E;
1004 }
1005 
1006 /// \brief Converts an integer to complex float type.  Helper function of
1007 /// UsualArithmeticConversions()
1008 ///
1009 /// \return false if the integer expression is an integer type and is
1010 /// successfully converted to the complex type.
1011 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1012                                                   ExprResult &ComplexExpr,
1013                                                   QualType IntTy,
1014                                                   QualType ComplexTy,
1015                                                   bool SkipCast) {
1016   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1017   if (SkipCast) return false;
1018   if (IntTy->isIntegerType()) {
1019     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1020     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1021     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1022                                   CK_FloatingRealToComplex);
1023   } else {
1024     assert(IntTy->isComplexIntegerType());
1025     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1026                                   CK_IntegralComplexToFloatingComplex);
1027   }
1028   return false;
1029 }
1030 
1031 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1032 /// UsualArithmeticConversions()
1033 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1034                                              ExprResult &RHS, QualType LHSType,
1035                                              QualType RHSType,
1036                                              bool IsCompAssign) {
1037   // if we have an integer operand, the result is the complex type.
1038   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1039                                              /*skipCast*/false))
1040     return LHSType;
1041   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1042                                              /*skipCast*/IsCompAssign))
1043     return RHSType;
1044 
1045   // This handles complex/complex, complex/float, or float/complex.
1046   // When both operands are complex, the shorter operand is converted to the
1047   // type of the longer, and that is the type of the result. This corresponds
1048   // to what is done when combining two real floating-point operands.
1049   // The fun begins when size promotion occur across type domains.
1050   // From H&S 6.3.4: When one operand is complex and the other is a real
1051   // floating-point type, the less precise type is converted, within it's
1052   // real or complex domain, to the precision of the other type. For example,
1053   // when combining a "long double" with a "double _Complex", the
1054   // "double _Complex" is promoted to "long double _Complex".
1055 
1056   // Compute the rank of the two types, regardless of whether they are complex.
1057   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1058 
1059   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1060   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1061   QualType LHSElementType =
1062       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1063   QualType RHSElementType =
1064       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1065 
1066   QualType ResultType = S.Context.getComplexType(LHSElementType);
1067   if (Order < 0) {
1068     // Promote the precision of the LHS if not an assignment.
1069     ResultType = S.Context.getComplexType(RHSElementType);
1070     if (!IsCompAssign) {
1071       if (LHSComplexType)
1072         LHS =
1073             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1074       else
1075         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1076     }
1077   } else if (Order > 0) {
1078     // Promote the precision of the RHS.
1079     if (RHSComplexType)
1080       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1081     else
1082       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1083   }
1084   return ResultType;
1085 }
1086 
1087 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1088 /// of UsualArithmeticConversions()
1089 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1090                                            ExprResult &IntExpr,
1091                                            QualType FloatTy, QualType IntTy,
1092                                            bool ConvertFloat, bool ConvertInt) {
1093   if (IntTy->isIntegerType()) {
1094     if (ConvertInt)
1095       // Convert intExpr to the lhs floating point type.
1096       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1097                                     CK_IntegralToFloating);
1098     return FloatTy;
1099   }
1100 
1101   // Convert both sides to the appropriate complex float.
1102   assert(IntTy->isComplexIntegerType());
1103   QualType result = S.Context.getComplexType(FloatTy);
1104 
1105   // _Complex int -> _Complex float
1106   if (ConvertInt)
1107     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1108                                   CK_IntegralComplexToFloatingComplex);
1109 
1110   // float -> _Complex float
1111   if (ConvertFloat)
1112     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1113                                     CK_FloatingRealToComplex);
1114 
1115   return result;
1116 }
1117 
1118 /// \brief Handle arithmethic conversion with floating point types.  Helper
1119 /// function of UsualArithmeticConversions()
1120 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1121                                       ExprResult &RHS, QualType LHSType,
1122                                       QualType RHSType, bool IsCompAssign) {
1123   bool LHSFloat = LHSType->isRealFloatingType();
1124   bool RHSFloat = RHSType->isRealFloatingType();
1125 
1126   // If we have two real floating types, convert the smaller operand
1127   // to the bigger result.
1128   if (LHSFloat && RHSFloat) {
1129     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1130     if (order > 0) {
1131       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1132       return LHSType;
1133     }
1134 
1135     assert(order < 0 && "illegal float comparison");
1136     if (!IsCompAssign)
1137       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1138     return RHSType;
1139   }
1140 
1141   if (LHSFloat) {
1142     // Half FP has to be promoted to float unless it is natively supported
1143     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1144       LHSType = S.Context.FloatTy;
1145 
1146     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1147                                       /*convertFloat=*/!IsCompAssign,
1148                                       /*convertInt=*/ true);
1149   }
1150   assert(RHSFloat);
1151   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1152                                     /*convertInt=*/ true,
1153                                     /*convertFloat=*/!IsCompAssign);
1154 }
1155 
1156 /// \brief Diagnose attempts to convert between __float128 and long double if
1157 /// there is no support for such conversion. Helper function of
1158 /// UsualArithmeticConversions().
1159 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1160                                       QualType RHSType) {
1161   /*  No issue converting if at least one of the types is not a floating point
1162       type or the two types have the same rank.
1163   */
1164   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1165       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1166     return false;
1167 
1168   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1169          "The remaining types must be floating point types.");
1170 
1171   auto *LHSComplex = LHSType->getAs<ComplexType>();
1172   auto *RHSComplex = RHSType->getAs<ComplexType>();
1173 
1174   QualType LHSElemType = LHSComplex ?
1175     LHSComplex->getElementType() : LHSType;
1176   QualType RHSElemType = RHSComplex ?
1177     RHSComplex->getElementType() : RHSType;
1178 
1179   // No issue if the two types have the same representation
1180   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1181       &S.Context.getFloatTypeSemantics(RHSElemType))
1182     return false;
1183 
1184   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1185                                 RHSElemType == S.Context.LongDoubleTy);
1186   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1187                             RHSElemType == S.Context.Float128Ty);
1188 
1189   /* We've handled the situation where __float128 and long double have the same
1190      representation. The only other allowable conversion is if long double is
1191      really just double.
1192   */
1193   return Float128AndLongDouble &&
1194     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1195      &llvm::APFloat::IEEEdouble);
1196 }
1197 
1198 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1199 
1200 namespace {
1201 /// These helper callbacks are placed in an anonymous namespace to
1202 /// permit their use as function template parameters.
1203 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1204   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1205 }
1206 
1207 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1208   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1209                              CK_IntegralComplexCast);
1210 }
1211 }
1212 
1213 /// \brief Handle integer arithmetic conversions.  Helper function of
1214 /// UsualArithmeticConversions()
1215 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1216 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1217                                         ExprResult &RHS, QualType LHSType,
1218                                         QualType RHSType, bool IsCompAssign) {
1219   // The rules for this case are in C99 6.3.1.8
1220   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1221   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1222   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1223   if (LHSSigned == RHSSigned) {
1224     // Same signedness; use the higher-ranked type
1225     if (order >= 0) {
1226       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1227       return LHSType;
1228     } else if (!IsCompAssign)
1229       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1230     return RHSType;
1231   } else if (order != (LHSSigned ? 1 : -1)) {
1232     // The unsigned type has greater than or equal rank to the
1233     // signed type, so use the unsigned type
1234     if (RHSSigned) {
1235       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1236       return LHSType;
1237     } else if (!IsCompAssign)
1238       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1239     return RHSType;
1240   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1241     // The two types are different widths; if we are here, that
1242     // means the signed type is larger than the unsigned type, so
1243     // use the signed type.
1244     if (LHSSigned) {
1245       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1246       return LHSType;
1247     } else if (!IsCompAssign)
1248       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1249     return RHSType;
1250   } else {
1251     // The signed type is higher-ranked than the unsigned type,
1252     // but isn't actually any bigger (like unsigned int and long
1253     // on most 32-bit systems).  Use the unsigned type corresponding
1254     // to the signed type.
1255     QualType result =
1256       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1257     RHS = (*doRHSCast)(S, RHS.get(), result);
1258     if (!IsCompAssign)
1259       LHS = (*doLHSCast)(S, LHS.get(), result);
1260     return result;
1261   }
1262 }
1263 
1264 /// \brief Handle conversions with GCC complex int extension.  Helper function
1265 /// of UsualArithmeticConversions()
1266 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1267                                            ExprResult &RHS, QualType LHSType,
1268                                            QualType RHSType,
1269                                            bool IsCompAssign) {
1270   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1271   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1272 
1273   if (LHSComplexInt && RHSComplexInt) {
1274     QualType LHSEltType = LHSComplexInt->getElementType();
1275     QualType RHSEltType = RHSComplexInt->getElementType();
1276     QualType ScalarType =
1277       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1278         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1279 
1280     return S.Context.getComplexType(ScalarType);
1281   }
1282 
1283   if (LHSComplexInt) {
1284     QualType LHSEltType = LHSComplexInt->getElementType();
1285     QualType ScalarType =
1286       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1287         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1288     QualType ComplexType = S.Context.getComplexType(ScalarType);
1289     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1290                               CK_IntegralRealToComplex);
1291 
1292     return ComplexType;
1293   }
1294 
1295   assert(RHSComplexInt);
1296 
1297   QualType RHSEltType = RHSComplexInt->getElementType();
1298   QualType ScalarType =
1299     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1300       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1301   QualType ComplexType = S.Context.getComplexType(ScalarType);
1302 
1303   if (!IsCompAssign)
1304     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1305                               CK_IntegralRealToComplex);
1306   return ComplexType;
1307 }
1308 
1309 /// UsualArithmeticConversions - Performs various conversions that are common to
1310 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1311 /// routine returns the first non-arithmetic type found. The client is
1312 /// responsible for emitting appropriate error diagnostics.
1313 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1314                                           bool IsCompAssign) {
1315   if (!IsCompAssign) {
1316     LHS = UsualUnaryConversions(LHS.get());
1317     if (LHS.isInvalid())
1318       return QualType();
1319   }
1320 
1321   RHS = UsualUnaryConversions(RHS.get());
1322   if (RHS.isInvalid())
1323     return QualType();
1324 
1325   // For conversion purposes, we ignore any qualifiers.
1326   // For example, "const float" and "float" are equivalent.
1327   QualType LHSType =
1328     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1329   QualType RHSType =
1330     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1331 
1332   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1333   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1334     LHSType = AtomicLHS->getValueType();
1335 
1336   // If both types are identical, no conversion is needed.
1337   if (LHSType == RHSType)
1338     return LHSType;
1339 
1340   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1341   // The caller can deal with this (e.g. pointer + int).
1342   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1343     return QualType();
1344 
1345   // Apply unary and bitfield promotions to the LHS's type.
1346   QualType LHSUnpromotedType = LHSType;
1347   if (LHSType->isPromotableIntegerType())
1348     LHSType = Context.getPromotedIntegerType(LHSType);
1349   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1350   if (!LHSBitfieldPromoteTy.isNull())
1351     LHSType = LHSBitfieldPromoteTy;
1352   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1353     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1354 
1355   // If both types are identical, no conversion is needed.
1356   if (LHSType == RHSType)
1357     return LHSType;
1358 
1359   // At this point, we have two different arithmetic types.
1360 
1361   // Diagnose attempts to convert between __float128 and long double where
1362   // such conversions currently can't be handled.
1363   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1364     return QualType();
1365 
1366   // Handle complex types first (C99 6.3.1.8p1).
1367   if (LHSType->isComplexType() || RHSType->isComplexType())
1368     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1369                                         IsCompAssign);
1370 
1371   // Now handle "real" floating types (i.e. float, double, long double).
1372   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1373     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1374                                  IsCompAssign);
1375 
1376   // Handle GCC complex int extension.
1377   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1378     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1379                                       IsCompAssign);
1380 
1381   // Finally, we have two differing integer types.
1382   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1383            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1384 }
1385 
1386 
1387 //===----------------------------------------------------------------------===//
1388 //  Semantic Analysis for various Expression Types
1389 //===----------------------------------------------------------------------===//
1390 
1391 
1392 ExprResult
1393 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1394                                 SourceLocation DefaultLoc,
1395                                 SourceLocation RParenLoc,
1396                                 Expr *ControllingExpr,
1397                                 ArrayRef<ParsedType> ArgTypes,
1398                                 ArrayRef<Expr *> ArgExprs) {
1399   unsigned NumAssocs = ArgTypes.size();
1400   assert(NumAssocs == ArgExprs.size());
1401 
1402   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1403   for (unsigned i = 0; i < NumAssocs; ++i) {
1404     if (ArgTypes[i])
1405       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1406     else
1407       Types[i] = nullptr;
1408   }
1409 
1410   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1411                                              ControllingExpr,
1412                                              llvm::makeArrayRef(Types, NumAssocs),
1413                                              ArgExprs);
1414   delete [] Types;
1415   return ER;
1416 }
1417 
1418 ExprResult
1419 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1420                                  SourceLocation DefaultLoc,
1421                                  SourceLocation RParenLoc,
1422                                  Expr *ControllingExpr,
1423                                  ArrayRef<TypeSourceInfo *> Types,
1424                                  ArrayRef<Expr *> Exprs) {
1425   unsigned NumAssocs = Types.size();
1426   assert(NumAssocs == Exprs.size());
1427 
1428   // Decay and strip qualifiers for the controlling expression type, and handle
1429   // placeholder type replacement. See committee discussion from WG14 DR423.
1430   {
1431     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1432     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1433     if (R.isInvalid())
1434       return ExprError();
1435     ControllingExpr = R.get();
1436   }
1437 
1438   // The controlling expression is an unevaluated operand, so side effects are
1439   // likely unintended.
1440   if (ActiveTemplateInstantiations.empty() &&
1441       ControllingExpr->HasSideEffects(Context, false))
1442     Diag(ControllingExpr->getExprLoc(),
1443          diag::warn_side_effects_unevaluated_context);
1444 
1445   bool TypeErrorFound = false,
1446        IsResultDependent = ControllingExpr->isTypeDependent(),
1447        ContainsUnexpandedParameterPack
1448          = ControllingExpr->containsUnexpandedParameterPack();
1449 
1450   for (unsigned i = 0; i < NumAssocs; ++i) {
1451     if (Exprs[i]->containsUnexpandedParameterPack())
1452       ContainsUnexpandedParameterPack = true;
1453 
1454     if (Types[i]) {
1455       if (Types[i]->getType()->containsUnexpandedParameterPack())
1456         ContainsUnexpandedParameterPack = true;
1457 
1458       if (Types[i]->getType()->isDependentType()) {
1459         IsResultDependent = true;
1460       } else {
1461         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1462         // complete object type other than a variably modified type."
1463         unsigned D = 0;
1464         if (Types[i]->getType()->isIncompleteType())
1465           D = diag::err_assoc_type_incomplete;
1466         else if (!Types[i]->getType()->isObjectType())
1467           D = diag::err_assoc_type_nonobject;
1468         else if (Types[i]->getType()->isVariablyModifiedType())
1469           D = diag::err_assoc_type_variably_modified;
1470 
1471         if (D != 0) {
1472           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1473             << Types[i]->getTypeLoc().getSourceRange()
1474             << Types[i]->getType();
1475           TypeErrorFound = true;
1476         }
1477 
1478         // C11 6.5.1.1p2 "No two generic associations in the same generic
1479         // selection shall specify compatible types."
1480         for (unsigned j = i+1; j < NumAssocs; ++j)
1481           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1482               Context.typesAreCompatible(Types[i]->getType(),
1483                                          Types[j]->getType())) {
1484             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1485                  diag::err_assoc_compatible_types)
1486               << Types[j]->getTypeLoc().getSourceRange()
1487               << Types[j]->getType()
1488               << Types[i]->getType();
1489             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1490                  diag::note_compat_assoc)
1491               << Types[i]->getTypeLoc().getSourceRange()
1492               << Types[i]->getType();
1493             TypeErrorFound = true;
1494           }
1495       }
1496     }
1497   }
1498   if (TypeErrorFound)
1499     return ExprError();
1500 
1501   // If we determined that the generic selection is result-dependent, don't
1502   // try to compute the result expression.
1503   if (IsResultDependent)
1504     return new (Context) GenericSelectionExpr(
1505         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1506         ContainsUnexpandedParameterPack);
1507 
1508   SmallVector<unsigned, 1> CompatIndices;
1509   unsigned DefaultIndex = -1U;
1510   for (unsigned i = 0; i < NumAssocs; ++i) {
1511     if (!Types[i])
1512       DefaultIndex = i;
1513     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1514                                         Types[i]->getType()))
1515       CompatIndices.push_back(i);
1516   }
1517 
1518   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1519   // type compatible with at most one of the types named in its generic
1520   // association list."
1521   if (CompatIndices.size() > 1) {
1522     // We strip parens here because the controlling expression is typically
1523     // parenthesized in macro definitions.
1524     ControllingExpr = ControllingExpr->IgnoreParens();
1525     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1526       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1527       << (unsigned) CompatIndices.size();
1528     for (unsigned I : CompatIndices) {
1529       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1530            diag::note_compat_assoc)
1531         << Types[I]->getTypeLoc().getSourceRange()
1532         << Types[I]->getType();
1533     }
1534     return ExprError();
1535   }
1536 
1537   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1538   // its controlling expression shall have type compatible with exactly one of
1539   // the types named in its generic association list."
1540   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1541     // We strip parens here because the controlling expression is typically
1542     // parenthesized in macro definitions.
1543     ControllingExpr = ControllingExpr->IgnoreParens();
1544     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1545       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1546     return ExprError();
1547   }
1548 
1549   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1550   // type name that is compatible with the type of the controlling expression,
1551   // then the result expression of the generic selection is the expression
1552   // in that generic association. Otherwise, the result expression of the
1553   // generic selection is the expression in the default generic association."
1554   unsigned ResultIndex =
1555     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1556 
1557   return new (Context) GenericSelectionExpr(
1558       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1559       ContainsUnexpandedParameterPack, ResultIndex);
1560 }
1561 
1562 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1563 /// location of the token and the offset of the ud-suffix within it.
1564 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1565                                      unsigned Offset) {
1566   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1567                                         S.getLangOpts());
1568 }
1569 
1570 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1571 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1572 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1573                                                  IdentifierInfo *UDSuffix,
1574                                                  SourceLocation UDSuffixLoc,
1575                                                  ArrayRef<Expr*> Args,
1576                                                  SourceLocation LitEndLoc) {
1577   assert(Args.size() <= 2 && "too many arguments for literal operator");
1578 
1579   QualType ArgTy[2];
1580   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1581     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1582     if (ArgTy[ArgIdx]->isArrayType())
1583       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1584   }
1585 
1586   DeclarationName OpName =
1587     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1588   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1589   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1590 
1591   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1592   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1593                               /*AllowRaw*/false, /*AllowTemplate*/false,
1594                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1595     return ExprError();
1596 
1597   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1598 }
1599 
1600 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1601 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1602 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1603 /// multiple tokens.  However, the common case is that StringToks points to one
1604 /// string.
1605 ///
1606 ExprResult
1607 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1608   assert(!StringToks.empty() && "Must have at least one string!");
1609 
1610   StringLiteralParser Literal(StringToks, PP);
1611   if (Literal.hadError)
1612     return ExprError();
1613 
1614   SmallVector<SourceLocation, 4> StringTokLocs;
1615   for (const Token &Tok : StringToks)
1616     StringTokLocs.push_back(Tok.getLocation());
1617 
1618   QualType CharTy = Context.CharTy;
1619   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1620   if (Literal.isWide()) {
1621     CharTy = Context.getWideCharType();
1622     Kind = StringLiteral::Wide;
1623   } else if (Literal.isUTF8()) {
1624     Kind = StringLiteral::UTF8;
1625   } else if (Literal.isUTF16()) {
1626     CharTy = Context.Char16Ty;
1627     Kind = StringLiteral::UTF16;
1628   } else if (Literal.isUTF32()) {
1629     CharTy = Context.Char32Ty;
1630     Kind = StringLiteral::UTF32;
1631   } else if (Literal.isPascal()) {
1632     CharTy = Context.UnsignedCharTy;
1633   }
1634 
1635   QualType CharTyConst = CharTy;
1636   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1637   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1638     CharTyConst.addConst();
1639 
1640   // Get an array type for the string, according to C99 6.4.5.  This includes
1641   // the nul terminator character as well as the string length for pascal
1642   // strings.
1643   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1644                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1645                                  ArrayType::Normal, 0);
1646 
1647   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1648   if (getLangOpts().OpenCL) {
1649     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1650   }
1651 
1652   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1653   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1654                                              Kind, Literal.Pascal, StrTy,
1655                                              &StringTokLocs[0],
1656                                              StringTokLocs.size());
1657   if (Literal.getUDSuffix().empty())
1658     return Lit;
1659 
1660   // We're building a user-defined literal.
1661   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1662   SourceLocation UDSuffixLoc =
1663     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1664                    Literal.getUDSuffixOffset());
1665 
1666   // Make sure we're allowed user-defined literals here.
1667   if (!UDLScope)
1668     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1669 
1670   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1671   //   operator "" X (str, len)
1672   QualType SizeType = Context.getSizeType();
1673 
1674   DeclarationName OpName =
1675     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1676   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1677   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1678 
1679   QualType ArgTy[] = {
1680     Context.getArrayDecayedType(StrTy), SizeType
1681   };
1682 
1683   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1684   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1685                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1686                                 /*AllowStringTemplate*/true)) {
1687 
1688   case LOLR_Cooked: {
1689     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1690     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1691                                                     StringTokLocs[0]);
1692     Expr *Args[] = { Lit, LenArg };
1693 
1694     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1695   }
1696 
1697   case LOLR_StringTemplate: {
1698     TemplateArgumentListInfo ExplicitArgs;
1699 
1700     unsigned CharBits = Context.getIntWidth(CharTy);
1701     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1702     llvm::APSInt Value(CharBits, CharIsUnsigned);
1703 
1704     TemplateArgument TypeArg(CharTy);
1705     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1706     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1707 
1708     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1709       Value = Lit->getCodeUnit(I);
1710       TemplateArgument Arg(Context, Value, CharTy);
1711       TemplateArgumentLocInfo ArgInfo;
1712       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1713     }
1714     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1715                                     &ExplicitArgs);
1716   }
1717   case LOLR_Raw:
1718   case LOLR_Template:
1719     llvm_unreachable("unexpected literal operator lookup result");
1720   case LOLR_Error:
1721     return ExprError();
1722   }
1723   llvm_unreachable("unexpected literal operator lookup result");
1724 }
1725 
1726 ExprResult
1727 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1728                        SourceLocation Loc,
1729                        const CXXScopeSpec *SS) {
1730   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1731   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1732 }
1733 
1734 /// BuildDeclRefExpr - Build an expression that references a
1735 /// declaration that does not require a closure capture.
1736 ExprResult
1737 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1738                        const DeclarationNameInfo &NameInfo,
1739                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1740                        const TemplateArgumentListInfo *TemplateArgs) {
1741   if (getLangOpts().CUDA)
1742     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1743       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1744         if (!IsAllowedCUDACall(Caller, Callee)) {
1745           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1746             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1747             << IdentifyCUDATarget(Caller);
1748           Diag(D->getLocation(), diag::note_previous_decl)
1749             << D->getIdentifier();
1750           return ExprError();
1751         }
1752       }
1753 
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::error_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::error_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::error_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 (isa<TypedefNameDecl>(D)) {
2792     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2793     return true;
2794   }
2795 
2796   if (isa<ObjCInterfaceDecl>(D)) {
2797     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2798     return true;
2799   }
2800 
2801   if (isa<NamespaceDecl>(D)) {
2802     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2803     return true;
2804   }
2805 
2806   return false;
2807 }
2808 
2809 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2810                                           LookupResult &R, bool NeedsADL,
2811                                           bool AcceptInvalidDecl) {
2812   // If this is a single, fully-resolved result and we don't need ADL,
2813   // just build an ordinary singleton decl ref.
2814   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2815     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2816                                     R.getRepresentativeDecl(), nullptr,
2817                                     AcceptInvalidDecl);
2818 
2819   // We only need to check the declaration if there's exactly one
2820   // result, because in the overloaded case the results can only be
2821   // functions and function templates.
2822   if (R.isSingleResult() &&
2823       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2824     return ExprError();
2825 
2826   // Otherwise, just build an unresolved lookup expression.  Suppress
2827   // any lookup-related diagnostics; we'll hash these out later, when
2828   // we've picked a target.
2829   R.suppressDiagnostics();
2830 
2831   UnresolvedLookupExpr *ULE
2832     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2833                                    SS.getWithLocInContext(Context),
2834                                    R.getLookupNameInfo(),
2835                                    NeedsADL, R.isOverloadedResult(),
2836                                    R.begin(), R.end());
2837 
2838   return ULE;
2839 }
2840 
2841 /// \brief Complete semantic analysis for a reference to the given declaration.
2842 ExprResult Sema::BuildDeclarationNameExpr(
2843     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2844     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2845     bool AcceptInvalidDecl) {
2846   assert(D && "Cannot refer to a NULL declaration");
2847   assert(!isa<FunctionTemplateDecl>(D) &&
2848          "Cannot refer unambiguously to a function template");
2849 
2850   SourceLocation Loc = NameInfo.getLoc();
2851   if (CheckDeclInExpr(*this, Loc, D))
2852     return ExprError();
2853 
2854   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2855     // Specifically diagnose references to class templates that are missing
2856     // a template argument list.
2857     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2858                                            << Template << SS.getRange();
2859     Diag(Template->getLocation(), diag::note_template_decl_here);
2860     return ExprError();
2861   }
2862 
2863   // Make sure that we're referring to a value.
2864   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2865   if (!VD) {
2866     Diag(Loc, diag::err_ref_non_value)
2867       << D << SS.getRange();
2868     Diag(D->getLocation(), diag::note_declared_at);
2869     return ExprError();
2870   }
2871 
2872   // Check whether this declaration can be used. Note that we suppress
2873   // this check when we're going to perform argument-dependent lookup
2874   // on this function name, because this might not be the function
2875   // that overload resolution actually selects.
2876   if (DiagnoseUseOfDecl(VD, Loc))
2877     return ExprError();
2878 
2879   // Only create DeclRefExpr's for valid Decl's.
2880   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2881     return ExprError();
2882 
2883   // Handle members of anonymous structs and unions.  If we got here,
2884   // and the reference is to a class member indirect field, then this
2885   // must be the subject of a pointer-to-member expression.
2886   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2887     if (!indirectField->isCXXClassMember())
2888       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2889                                                       indirectField);
2890 
2891   {
2892     QualType type = VD->getType();
2893     ExprValueKind valueKind = VK_RValue;
2894 
2895     switch (D->getKind()) {
2896     // Ignore all the non-ValueDecl kinds.
2897 #define ABSTRACT_DECL(kind)
2898 #define VALUE(type, base)
2899 #define DECL(type, base) \
2900     case Decl::type:
2901 #include "clang/AST/DeclNodes.inc"
2902       llvm_unreachable("invalid value decl kind");
2903 
2904     // These shouldn't make it here.
2905     case Decl::ObjCAtDefsField:
2906     case Decl::ObjCIvar:
2907       llvm_unreachable("forming non-member reference to ivar?");
2908 
2909     // Enum constants are always r-values and never references.
2910     // Unresolved using declarations are dependent.
2911     case Decl::EnumConstant:
2912     case Decl::UnresolvedUsingValue:
2913     case Decl::OMPDeclareReduction:
2914       valueKind = VK_RValue;
2915       break;
2916 
2917     // Fields and indirect fields that got here must be for
2918     // pointer-to-member expressions; we just call them l-values for
2919     // internal consistency, because this subexpression doesn't really
2920     // exist in the high-level semantics.
2921     case Decl::Field:
2922     case Decl::IndirectField:
2923       assert(getLangOpts().CPlusPlus &&
2924              "building reference to field in C?");
2925 
2926       // These can't have reference type in well-formed programs, but
2927       // for internal consistency we do this anyway.
2928       type = type.getNonReferenceType();
2929       valueKind = VK_LValue;
2930       break;
2931 
2932     // Non-type template parameters are either l-values or r-values
2933     // depending on the type.
2934     case Decl::NonTypeTemplateParm: {
2935       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2936         type = reftype->getPointeeType();
2937         valueKind = VK_LValue; // even if the parameter is an r-value reference
2938         break;
2939       }
2940 
2941       // For non-references, we need to strip qualifiers just in case
2942       // the template parameter was declared as 'const int' or whatever.
2943       valueKind = VK_RValue;
2944       type = type.getUnqualifiedType();
2945       break;
2946     }
2947 
2948     case Decl::Var:
2949     case Decl::VarTemplateSpecialization:
2950     case Decl::VarTemplatePartialSpecialization:
2951     case Decl::Decomposition:
2952     case Decl::OMPCapturedExpr:
2953       // In C, "extern void blah;" is valid and is an r-value.
2954       if (!getLangOpts().CPlusPlus &&
2955           !type.hasQualifiers() &&
2956           type->isVoidType()) {
2957         valueKind = VK_RValue;
2958         break;
2959       }
2960       // fallthrough
2961 
2962     case Decl::ImplicitParam:
2963     case Decl::ParmVar: {
2964       // These are always l-values.
2965       valueKind = VK_LValue;
2966       type = type.getNonReferenceType();
2967 
2968       // FIXME: Does the addition of const really only apply in
2969       // potentially-evaluated contexts? Since the variable isn't actually
2970       // captured in an unevaluated context, it seems that the answer is no.
2971       if (!isUnevaluatedContext()) {
2972         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2973         if (!CapturedType.isNull())
2974           type = CapturedType;
2975       }
2976 
2977       break;
2978     }
2979 
2980     case Decl::Binding: {
2981       // These are always lvalues.
2982       valueKind = VK_LValue;
2983       type = type.getNonReferenceType();
2984       // FIXME: Adjust cv-qualifiers for capture.
2985       break;
2986     }
2987 
2988     case Decl::Function: {
2989       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2990         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2991           type = Context.BuiltinFnTy;
2992           valueKind = VK_RValue;
2993           break;
2994         }
2995       }
2996 
2997       const FunctionType *fty = type->castAs<FunctionType>();
2998 
2999       // If we're referring to a function with an __unknown_anytype
3000       // result type, make the entire expression __unknown_anytype.
3001       if (fty->getReturnType() == Context.UnknownAnyTy) {
3002         type = Context.UnknownAnyTy;
3003         valueKind = VK_RValue;
3004         break;
3005       }
3006 
3007       // Functions are l-values in C++.
3008       if (getLangOpts().CPlusPlus) {
3009         valueKind = VK_LValue;
3010         break;
3011       }
3012 
3013       // C99 DR 316 says that, if a function type comes from a
3014       // function definition (without a prototype), that type is only
3015       // used for checking compatibility. Therefore, when referencing
3016       // the function, we pretend that we don't have the full function
3017       // type.
3018       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3019           isa<FunctionProtoType>(fty))
3020         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3021                                               fty->getExtInfo());
3022 
3023       // Functions are r-values in C.
3024       valueKind = VK_RValue;
3025       break;
3026     }
3027 
3028     case Decl::MSProperty:
3029       valueKind = VK_LValue;
3030       break;
3031 
3032     case Decl::CXXMethod:
3033       // If we're referring to a method with an __unknown_anytype
3034       // result type, make the entire expression __unknown_anytype.
3035       // This should only be possible with a type written directly.
3036       if (const FunctionProtoType *proto
3037             = dyn_cast<FunctionProtoType>(VD->getType()))
3038         if (proto->getReturnType() == Context.UnknownAnyTy) {
3039           type = Context.UnknownAnyTy;
3040           valueKind = VK_RValue;
3041           break;
3042         }
3043 
3044       // C++ methods are l-values if static, r-values if non-static.
3045       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3046         valueKind = VK_LValue;
3047         break;
3048       }
3049       // fallthrough
3050 
3051     case Decl::CXXConversion:
3052     case Decl::CXXDestructor:
3053     case Decl::CXXConstructor:
3054       valueKind = VK_RValue;
3055       break;
3056     }
3057 
3058     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3059                             TemplateArgs);
3060   }
3061 }
3062 
3063 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3064                                     SmallString<32> &Target) {
3065   Target.resize(CharByteWidth * (Source.size() + 1));
3066   char *ResultPtr = &Target[0];
3067   const UTF8 *ErrorPtr;
3068   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3069   (void)success;
3070   assert(success);
3071   Target.resize(ResultPtr - &Target[0]);
3072 }
3073 
3074 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3075                                      PredefinedExpr::IdentType IT) {
3076   // Pick the current block, lambda, captured statement or function.
3077   Decl *currentDecl = nullptr;
3078   if (const BlockScopeInfo *BSI = getCurBlock())
3079     currentDecl = BSI->TheDecl;
3080   else if (const LambdaScopeInfo *LSI = getCurLambda())
3081     currentDecl = LSI->CallOperator;
3082   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3083     currentDecl = CSI->TheCapturedDecl;
3084   else
3085     currentDecl = getCurFunctionOrMethodDecl();
3086 
3087   if (!currentDecl) {
3088     Diag(Loc, diag::ext_predef_outside_function);
3089     currentDecl = Context.getTranslationUnitDecl();
3090   }
3091 
3092   QualType ResTy;
3093   StringLiteral *SL = nullptr;
3094   if (cast<DeclContext>(currentDecl)->isDependentContext())
3095     ResTy = Context.DependentTy;
3096   else {
3097     // Pre-defined identifiers are of type char[x], where x is the length of
3098     // the string.
3099     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3100     unsigned Length = Str.length();
3101 
3102     llvm::APInt LengthI(32, Length + 1);
3103     if (IT == PredefinedExpr::LFunction) {
3104       ResTy = Context.WideCharTy.withConst();
3105       SmallString<32> RawChars;
3106       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3107                               Str, RawChars);
3108       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3109                                            /*IndexTypeQuals*/ 0);
3110       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3111                                  /*Pascal*/ false, ResTy, Loc);
3112     } else {
3113       ResTy = Context.CharTy.withConst();
3114       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3115                                            /*IndexTypeQuals*/ 0);
3116       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3117                                  /*Pascal*/ false, ResTy, Loc);
3118     }
3119   }
3120 
3121   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3122 }
3123 
3124 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3125   PredefinedExpr::IdentType IT;
3126 
3127   switch (Kind) {
3128   default: llvm_unreachable("Unknown simple primary expr!");
3129   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3130   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3131   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3132   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3133   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3134   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3135   }
3136 
3137   return BuildPredefinedExpr(Loc, IT);
3138 }
3139 
3140 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3141   SmallString<16> CharBuffer;
3142   bool Invalid = false;
3143   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3144   if (Invalid)
3145     return ExprError();
3146 
3147   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3148                             PP, Tok.getKind());
3149   if (Literal.hadError())
3150     return ExprError();
3151 
3152   QualType Ty;
3153   if (Literal.isWide())
3154     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3155   else if (Literal.isUTF16())
3156     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3157   else if (Literal.isUTF32())
3158     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3159   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3160     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3161   else
3162     Ty = Context.CharTy;  // 'x' -> char in C++
3163 
3164   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3165   if (Literal.isWide())
3166     Kind = CharacterLiteral::Wide;
3167   else if (Literal.isUTF16())
3168     Kind = CharacterLiteral::UTF16;
3169   else if (Literal.isUTF32())
3170     Kind = CharacterLiteral::UTF32;
3171   else if (Literal.isUTF8())
3172     Kind = CharacterLiteral::UTF8;
3173 
3174   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3175                                              Tok.getLocation());
3176 
3177   if (Literal.getUDSuffix().empty())
3178     return Lit;
3179 
3180   // We're building a user-defined literal.
3181   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3182   SourceLocation UDSuffixLoc =
3183     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3184 
3185   // Make sure we're allowed user-defined literals here.
3186   if (!UDLScope)
3187     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3188 
3189   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3190   //   operator "" X (ch)
3191   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3192                                         Lit, Tok.getLocation());
3193 }
3194 
3195 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3196   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3197   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3198                                 Context.IntTy, Loc);
3199 }
3200 
3201 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3202                                   QualType Ty, SourceLocation Loc) {
3203   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3204 
3205   using llvm::APFloat;
3206   APFloat Val(Format);
3207 
3208   APFloat::opStatus result = Literal.GetFloatValue(Val);
3209 
3210   // Overflow is always an error, but underflow is only an error if
3211   // we underflowed to zero (APFloat reports denormals as underflow).
3212   if ((result & APFloat::opOverflow) ||
3213       ((result & APFloat::opUnderflow) && Val.isZero())) {
3214     unsigned diagnostic;
3215     SmallString<20> buffer;
3216     if (result & APFloat::opOverflow) {
3217       diagnostic = diag::warn_float_overflow;
3218       APFloat::getLargest(Format).toString(buffer);
3219     } else {
3220       diagnostic = diag::warn_float_underflow;
3221       APFloat::getSmallest(Format).toString(buffer);
3222     }
3223 
3224     S.Diag(Loc, diagnostic)
3225       << Ty
3226       << StringRef(buffer.data(), buffer.size());
3227   }
3228 
3229   bool isExact = (result == APFloat::opOK);
3230   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3231 }
3232 
3233 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3234   assert(E && "Invalid expression");
3235 
3236   if (E->isValueDependent())
3237     return false;
3238 
3239   QualType QT = E->getType();
3240   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3241     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3242     return true;
3243   }
3244 
3245   llvm::APSInt ValueAPS;
3246   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3247 
3248   if (R.isInvalid())
3249     return true;
3250 
3251   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3252   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3253     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3254         << ValueAPS.toString(10) << ValueIsPositive;
3255     return true;
3256   }
3257 
3258   return false;
3259 }
3260 
3261 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3262   // Fast path for a single digit (which is quite common).  A single digit
3263   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3264   if (Tok.getLength() == 1) {
3265     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3266     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3267   }
3268 
3269   SmallString<128> SpellingBuffer;
3270   // NumericLiteralParser wants to overread by one character.  Add padding to
3271   // the buffer in case the token is copied to the buffer.  If getSpelling()
3272   // returns a StringRef to the memory buffer, it should have a null char at
3273   // the EOF, so it is also safe.
3274   SpellingBuffer.resize(Tok.getLength() + 1);
3275 
3276   // Get the spelling of the token, which eliminates trigraphs, etc.
3277   bool Invalid = false;
3278   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3279   if (Invalid)
3280     return ExprError();
3281 
3282   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3283   if (Literal.hadError)
3284     return ExprError();
3285 
3286   if (Literal.hasUDSuffix()) {
3287     // We're building a user-defined literal.
3288     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3289     SourceLocation UDSuffixLoc =
3290       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3291 
3292     // Make sure we're allowed user-defined literals here.
3293     if (!UDLScope)
3294       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3295 
3296     QualType CookedTy;
3297     if (Literal.isFloatingLiteral()) {
3298       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3299       // long double, the literal is treated as a call of the form
3300       //   operator "" X (f L)
3301       CookedTy = Context.LongDoubleTy;
3302     } else {
3303       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3304       // unsigned long long, the literal is treated as a call of the form
3305       //   operator "" X (n ULL)
3306       CookedTy = Context.UnsignedLongLongTy;
3307     }
3308 
3309     DeclarationName OpName =
3310       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3311     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3312     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3313 
3314     SourceLocation TokLoc = Tok.getLocation();
3315 
3316     // Perform literal operator lookup to determine if we're building a raw
3317     // literal or a cooked one.
3318     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3319     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3320                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3321                                   /*AllowStringTemplate*/false)) {
3322     case LOLR_Error:
3323       return ExprError();
3324 
3325     case LOLR_Cooked: {
3326       Expr *Lit;
3327       if (Literal.isFloatingLiteral()) {
3328         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3329       } else {
3330         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3331         if (Literal.GetIntegerValue(ResultVal))
3332           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3333               << /* Unsigned */ 1;
3334         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3335                                      Tok.getLocation());
3336       }
3337       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3338     }
3339 
3340     case LOLR_Raw: {
3341       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3342       // literal is treated as a call of the form
3343       //   operator "" X ("n")
3344       unsigned Length = Literal.getUDSuffixOffset();
3345       QualType StrTy = Context.getConstantArrayType(
3346           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3347           ArrayType::Normal, 0);
3348       Expr *Lit = StringLiteral::Create(
3349           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3350           /*Pascal*/false, StrTy, &TokLoc, 1);
3351       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3352     }
3353 
3354     case LOLR_Template: {
3355       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3356       // template), L is treated as a call fo the form
3357       //   operator "" X <'c1', 'c2', ... 'ck'>()
3358       // where n is the source character sequence c1 c2 ... ck.
3359       TemplateArgumentListInfo ExplicitArgs;
3360       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3361       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3362       llvm::APSInt Value(CharBits, CharIsUnsigned);
3363       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3364         Value = TokSpelling[I];
3365         TemplateArgument Arg(Context, Value, Context.CharTy);
3366         TemplateArgumentLocInfo ArgInfo;
3367         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3368       }
3369       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3370                                       &ExplicitArgs);
3371     }
3372     case LOLR_StringTemplate:
3373       llvm_unreachable("unexpected literal operator lookup result");
3374     }
3375   }
3376 
3377   Expr *Res;
3378 
3379   if (Literal.isFloatingLiteral()) {
3380     QualType Ty;
3381     if (Literal.isHalf){
3382       if (getOpenCLOptions().cl_khr_fp16)
3383         Ty = Context.HalfTy;
3384       else {
3385         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3386         return ExprError();
3387       }
3388     } else if (Literal.isFloat)
3389       Ty = Context.FloatTy;
3390     else if (Literal.isLong)
3391       Ty = Context.LongDoubleTy;
3392     else if (Literal.isFloat128)
3393       Ty = Context.Float128Ty;
3394     else
3395       Ty = Context.DoubleTy;
3396 
3397     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3398 
3399     if (Ty == Context.DoubleTy) {
3400       if (getLangOpts().SinglePrecisionConstants) {
3401         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3402       } else if (getLangOpts().OpenCL &&
3403                  !((getLangOpts().OpenCLVersion >= 120) ||
3404                    getOpenCLOptions().cl_khr_fp64)) {
3405         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3406         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3407       }
3408     }
3409   } else if (!Literal.isIntegerLiteral()) {
3410     return ExprError();
3411   } else {
3412     QualType Ty;
3413 
3414     // 'long long' is a C99 or C++11 feature.
3415     if (!getLangOpts().C99 && Literal.isLongLong) {
3416       if (getLangOpts().CPlusPlus)
3417         Diag(Tok.getLocation(),
3418              getLangOpts().CPlusPlus11 ?
3419              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3420       else
3421         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3422     }
3423 
3424     // Get the value in the widest-possible width.
3425     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3426     llvm::APInt ResultVal(MaxWidth, 0);
3427 
3428     if (Literal.GetIntegerValue(ResultVal)) {
3429       // If this value didn't fit into uintmax_t, error and force to ull.
3430       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3431           << /* Unsigned */ 1;
3432       Ty = Context.UnsignedLongLongTy;
3433       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3434              "long long is not intmax_t?");
3435     } else {
3436       // If this value fits into a ULL, try to figure out what else it fits into
3437       // according to the rules of C99 6.4.4.1p5.
3438 
3439       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3440       // be an unsigned int.
3441       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3442 
3443       // Check from smallest to largest, picking the smallest type we can.
3444       unsigned Width = 0;
3445 
3446       // Microsoft specific integer suffixes are explicitly sized.
3447       if (Literal.MicrosoftInteger) {
3448         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3449           Width = 8;
3450           Ty = Context.CharTy;
3451         } else {
3452           Width = Literal.MicrosoftInteger;
3453           Ty = Context.getIntTypeForBitwidth(Width,
3454                                              /*Signed=*/!Literal.isUnsigned);
3455         }
3456       }
3457 
3458       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3459         // Are int/unsigned possibilities?
3460         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3461 
3462         // Does it fit in a unsigned int?
3463         if (ResultVal.isIntN(IntSize)) {
3464           // Does it fit in a signed int?
3465           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3466             Ty = Context.IntTy;
3467           else if (AllowUnsigned)
3468             Ty = Context.UnsignedIntTy;
3469           Width = IntSize;
3470         }
3471       }
3472 
3473       // Are long/unsigned long possibilities?
3474       if (Ty.isNull() && !Literal.isLongLong) {
3475         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3476 
3477         // Does it fit in a unsigned long?
3478         if (ResultVal.isIntN(LongSize)) {
3479           // Does it fit in a signed long?
3480           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3481             Ty = Context.LongTy;
3482           else if (AllowUnsigned)
3483             Ty = Context.UnsignedLongTy;
3484           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3485           // is compatible.
3486           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3487             const unsigned LongLongSize =
3488                 Context.getTargetInfo().getLongLongWidth();
3489             Diag(Tok.getLocation(),
3490                  getLangOpts().CPlusPlus
3491                      ? Literal.isLong
3492                            ? diag::warn_old_implicitly_unsigned_long_cxx
3493                            : /*C++98 UB*/ diag::
3494                                  ext_old_implicitly_unsigned_long_cxx
3495                      : diag::warn_old_implicitly_unsigned_long)
3496                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3497                                             : /*will be ill-formed*/ 1);
3498             Ty = Context.UnsignedLongTy;
3499           }
3500           Width = LongSize;
3501         }
3502       }
3503 
3504       // Check long long if needed.
3505       if (Ty.isNull()) {
3506         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3507 
3508         // Does it fit in a unsigned long long?
3509         if (ResultVal.isIntN(LongLongSize)) {
3510           // Does it fit in a signed long long?
3511           // To be compatible with MSVC, hex integer literals ending with the
3512           // LL or i64 suffix are always signed in Microsoft mode.
3513           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3514               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3515             Ty = Context.LongLongTy;
3516           else if (AllowUnsigned)
3517             Ty = Context.UnsignedLongLongTy;
3518           Width = LongLongSize;
3519         }
3520       }
3521 
3522       // If we still couldn't decide a type, we probably have something that
3523       // does not fit in a signed long long, but has no U suffix.
3524       if (Ty.isNull()) {
3525         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3526         Ty = Context.UnsignedLongLongTy;
3527         Width = Context.getTargetInfo().getLongLongWidth();
3528       }
3529 
3530       if (ResultVal.getBitWidth() != Width)
3531         ResultVal = ResultVal.trunc(Width);
3532     }
3533     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3534   }
3535 
3536   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3537   if (Literal.isImaginary)
3538     Res = new (Context) ImaginaryLiteral(Res,
3539                                         Context.getComplexType(Res->getType()));
3540 
3541   return Res;
3542 }
3543 
3544 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3545   assert(E && "ActOnParenExpr() missing expr");
3546   return new (Context) ParenExpr(L, R, E);
3547 }
3548 
3549 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3550                                          SourceLocation Loc,
3551                                          SourceRange ArgRange) {
3552   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3553   // scalar or vector data type argument..."
3554   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3555   // type (C99 6.2.5p18) or void.
3556   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3557     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3558       << T << ArgRange;
3559     return true;
3560   }
3561 
3562   assert((T->isVoidType() || !T->isIncompleteType()) &&
3563          "Scalar types should always be complete");
3564   return false;
3565 }
3566 
3567 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3568                                            SourceLocation Loc,
3569                                            SourceRange ArgRange,
3570                                            UnaryExprOrTypeTrait TraitKind) {
3571   // Invalid types must be hard errors for SFINAE in C++.
3572   if (S.LangOpts.CPlusPlus)
3573     return true;
3574 
3575   // C99 6.5.3.4p1:
3576   if (T->isFunctionType() &&
3577       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3578     // sizeof(function)/alignof(function) is allowed as an extension.
3579     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3580       << TraitKind << ArgRange;
3581     return false;
3582   }
3583 
3584   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3585   // this is an error (OpenCL v1.1 s6.3.k)
3586   if (T->isVoidType()) {
3587     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3588                                         : diag::ext_sizeof_alignof_void_type;
3589     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3590     return false;
3591   }
3592 
3593   return true;
3594 }
3595 
3596 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3597                                              SourceLocation Loc,
3598                                              SourceRange ArgRange,
3599                                              UnaryExprOrTypeTrait TraitKind) {
3600   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3601   // runtime doesn't allow it.
3602   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3603     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3604       << T << (TraitKind == UETT_SizeOf)
3605       << ArgRange;
3606     return true;
3607   }
3608 
3609   return false;
3610 }
3611 
3612 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3613 /// pointer type is equal to T) and emit a warning if it is.
3614 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3615                                      Expr *E) {
3616   // Don't warn if the operation changed the type.
3617   if (T != E->getType())
3618     return;
3619 
3620   // Now look for array decays.
3621   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3622   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3623     return;
3624 
3625   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3626                                              << ICE->getType()
3627                                              << ICE->getSubExpr()->getType();
3628 }
3629 
3630 /// \brief Check the constraints on expression operands to unary type expression
3631 /// and type traits.
3632 ///
3633 /// Completes any types necessary and validates the constraints on the operand
3634 /// expression. The logic mostly mirrors the type-based overload, but may modify
3635 /// the expression as it completes the type for that expression through template
3636 /// instantiation, etc.
3637 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3638                                             UnaryExprOrTypeTrait ExprKind) {
3639   QualType ExprTy = E->getType();
3640   assert(!ExprTy->isReferenceType());
3641 
3642   if (ExprKind == UETT_VecStep)
3643     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3644                                         E->getSourceRange());
3645 
3646   // Whitelist some types as extensions
3647   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3648                                       E->getSourceRange(), ExprKind))
3649     return false;
3650 
3651   // 'alignof' applied to an expression only requires the base element type of
3652   // the expression to be complete. 'sizeof' requires the expression's type to
3653   // be complete (and will attempt to complete it if it's an array of unknown
3654   // bound).
3655   if (ExprKind == UETT_AlignOf) {
3656     if (RequireCompleteType(E->getExprLoc(),
3657                             Context.getBaseElementType(E->getType()),
3658                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3659                             E->getSourceRange()))
3660       return true;
3661   } else {
3662     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3663                                 ExprKind, E->getSourceRange()))
3664       return true;
3665   }
3666 
3667   // Completing the expression's type may have changed it.
3668   ExprTy = E->getType();
3669   assert(!ExprTy->isReferenceType());
3670 
3671   if (ExprTy->isFunctionType()) {
3672     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3673       << ExprKind << E->getSourceRange();
3674     return true;
3675   }
3676 
3677   // The operand for sizeof and alignof is in an unevaluated expression context,
3678   // so side effects could result in unintended consequences.
3679   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3680       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3681     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3682 
3683   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3684                                        E->getSourceRange(), ExprKind))
3685     return true;
3686 
3687   if (ExprKind == UETT_SizeOf) {
3688     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3689       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3690         QualType OType = PVD->getOriginalType();
3691         QualType Type = PVD->getType();
3692         if (Type->isPointerType() && OType->isArrayType()) {
3693           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3694             << Type << OType;
3695           Diag(PVD->getLocation(), diag::note_declared_at);
3696         }
3697       }
3698     }
3699 
3700     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3701     // decays into a pointer and returns an unintended result. This is most
3702     // likely a typo for "sizeof(array) op x".
3703     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3704       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3705                                BO->getLHS());
3706       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3707                                BO->getRHS());
3708     }
3709   }
3710 
3711   return false;
3712 }
3713 
3714 /// \brief Check the constraints on operands to unary expression and type
3715 /// traits.
3716 ///
3717 /// This will complete any types necessary, and validate the various constraints
3718 /// on those operands.
3719 ///
3720 /// The UsualUnaryConversions() function is *not* called by this routine.
3721 /// C99 6.3.2.1p[2-4] all state:
3722 ///   Except when it is the operand of the sizeof operator ...
3723 ///
3724 /// C++ [expr.sizeof]p4
3725 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3726 ///   standard conversions are not applied to the operand of sizeof.
3727 ///
3728 /// This policy is followed for all of the unary trait expressions.
3729 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3730                                             SourceLocation OpLoc,
3731                                             SourceRange ExprRange,
3732                                             UnaryExprOrTypeTrait ExprKind) {
3733   if (ExprType->isDependentType())
3734     return false;
3735 
3736   // C++ [expr.sizeof]p2:
3737   //     When applied to a reference or a reference type, the result
3738   //     is the size of the referenced type.
3739   // C++11 [expr.alignof]p3:
3740   //     When alignof is applied to a reference type, the result
3741   //     shall be the alignment of the referenced type.
3742   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3743     ExprType = Ref->getPointeeType();
3744 
3745   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3746   //   When alignof or _Alignof is applied to an array type, the result
3747   //   is the alignment of the element type.
3748   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3749     ExprType = Context.getBaseElementType(ExprType);
3750 
3751   if (ExprKind == UETT_VecStep)
3752     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3753 
3754   // Whitelist some types as extensions
3755   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3756                                       ExprKind))
3757     return false;
3758 
3759   if (RequireCompleteType(OpLoc, ExprType,
3760                           diag::err_sizeof_alignof_incomplete_type,
3761                           ExprKind, ExprRange))
3762     return true;
3763 
3764   if (ExprType->isFunctionType()) {
3765     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3766       << ExprKind << ExprRange;
3767     return true;
3768   }
3769 
3770   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3771                                        ExprKind))
3772     return true;
3773 
3774   return false;
3775 }
3776 
3777 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3778   E = E->IgnoreParens();
3779 
3780   // Cannot know anything else if the expression is dependent.
3781   if (E->isTypeDependent())
3782     return false;
3783 
3784   if (E->getObjectKind() == OK_BitField) {
3785     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3786        << 1 << E->getSourceRange();
3787     return true;
3788   }
3789 
3790   ValueDecl *D = nullptr;
3791   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3792     D = DRE->getDecl();
3793   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3794     D = ME->getMemberDecl();
3795   }
3796 
3797   // If it's a field, require the containing struct to have a
3798   // complete definition so that we can compute the layout.
3799   //
3800   // This can happen in C++11 onwards, either by naming the member
3801   // in a way that is not transformed into a member access expression
3802   // (in an unevaluated operand, for instance), or by naming the member
3803   // in a trailing-return-type.
3804   //
3805   // For the record, since __alignof__ on expressions is a GCC
3806   // extension, GCC seems to permit this but always gives the
3807   // nonsensical answer 0.
3808   //
3809   // We don't really need the layout here --- we could instead just
3810   // directly check for all the appropriate alignment-lowing
3811   // attributes --- but that would require duplicating a lot of
3812   // logic that just isn't worth duplicating for such a marginal
3813   // use-case.
3814   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3815     // Fast path this check, since we at least know the record has a
3816     // definition if we can find a member of it.
3817     if (!FD->getParent()->isCompleteDefinition()) {
3818       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3819         << E->getSourceRange();
3820       return true;
3821     }
3822 
3823     // Otherwise, if it's a field, and the field doesn't have
3824     // reference type, then it must have a complete type (or be a
3825     // flexible array member, which we explicitly want to
3826     // white-list anyway), which makes the following checks trivial.
3827     if (!FD->getType()->isReferenceType())
3828       return false;
3829   }
3830 
3831   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3832 }
3833 
3834 bool Sema::CheckVecStepExpr(Expr *E) {
3835   E = E->IgnoreParens();
3836 
3837   // Cannot know anything else if the expression is dependent.
3838   if (E->isTypeDependent())
3839     return false;
3840 
3841   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3842 }
3843 
3844 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3845                                         CapturingScopeInfo *CSI) {
3846   assert(T->isVariablyModifiedType());
3847   assert(CSI != nullptr);
3848 
3849   // We're going to walk down into the type and look for VLA expressions.
3850   do {
3851     const Type *Ty = T.getTypePtr();
3852     switch (Ty->getTypeClass()) {
3853 #define TYPE(Class, Base)
3854 #define ABSTRACT_TYPE(Class, Base)
3855 #define NON_CANONICAL_TYPE(Class, Base)
3856 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3857 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3858 #include "clang/AST/TypeNodes.def"
3859       T = QualType();
3860       break;
3861     // These types are never variably-modified.
3862     case Type::Builtin:
3863     case Type::Complex:
3864     case Type::Vector:
3865     case Type::ExtVector:
3866     case Type::Record:
3867     case Type::Enum:
3868     case Type::Elaborated:
3869     case Type::TemplateSpecialization:
3870     case Type::ObjCObject:
3871     case Type::ObjCInterface:
3872     case Type::ObjCObjectPointer:
3873     case Type::Pipe:
3874       llvm_unreachable("type class is never variably-modified!");
3875     case Type::Adjusted:
3876       T = cast<AdjustedType>(Ty)->getOriginalType();
3877       break;
3878     case Type::Decayed:
3879       T = cast<DecayedType>(Ty)->getPointeeType();
3880       break;
3881     case Type::Pointer:
3882       T = cast<PointerType>(Ty)->getPointeeType();
3883       break;
3884     case Type::BlockPointer:
3885       T = cast<BlockPointerType>(Ty)->getPointeeType();
3886       break;
3887     case Type::LValueReference:
3888     case Type::RValueReference:
3889       T = cast<ReferenceType>(Ty)->getPointeeType();
3890       break;
3891     case Type::MemberPointer:
3892       T = cast<MemberPointerType>(Ty)->getPointeeType();
3893       break;
3894     case Type::ConstantArray:
3895     case Type::IncompleteArray:
3896       // Losing element qualification here is fine.
3897       T = cast<ArrayType>(Ty)->getElementType();
3898       break;
3899     case Type::VariableArray: {
3900       // Losing element qualification here is fine.
3901       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3902 
3903       // Unknown size indication requires no size computation.
3904       // Otherwise, evaluate and record it.
3905       if (auto Size = VAT->getSizeExpr()) {
3906         if (!CSI->isVLATypeCaptured(VAT)) {
3907           RecordDecl *CapRecord = nullptr;
3908           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3909             CapRecord = LSI->Lambda;
3910           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3911             CapRecord = CRSI->TheRecordDecl;
3912           }
3913           if (CapRecord) {
3914             auto ExprLoc = Size->getExprLoc();
3915             auto SizeType = Context.getSizeType();
3916             // Build the non-static data member.
3917             auto Field =
3918                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3919                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3920                                   /*BW*/ nullptr, /*Mutable*/ false,
3921                                   /*InitStyle*/ ICIS_NoInit);
3922             Field->setImplicit(true);
3923             Field->setAccess(AS_private);
3924             Field->setCapturedVLAType(VAT);
3925             CapRecord->addDecl(Field);
3926 
3927             CSI->addVLATypeCapture(ExprLoc, SizeType);
3928           }
3929         }
3930       }
3931       T = VAT->getElementType();
3932       break;
3933     }
3934     case Type::FunctionProto:
3935     case Type::FunctionNoProto:
3936       T = cast<FunctionType>(Ty)->getReturnType();
3937       break;
3938     case Type::Paren:
3939     case Type::TypeOf:
3940     case Type::UnaryTransform:
3941     case Type::Attributed:
3942     case Type::SubstTemplateTypeParm:
3943     case Type::PackExpansion:
3944       // Keep walking after single level desugaring.
3945       T = T.getSingleStepDesugaredType(Context);
3946       break;
3947     case Type::Typedef:
3948       T = cast<TypedefType>(Ty)->desugar();
3949       break;
3950     case Type::Decltype:
3951       T = cast<DecltypeType>(Ty)->desugar();
3952       break;
3953     case Type::Auto:
3954       T = cast<AutoType>(Ty)->getDeducedType();
3955       break;
3956     case Type::TypeOfExpr:
3957       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3958       break;
3959     case Type::Atomic:
3960       T = cast<AtomicType>(Ty)->getValueType();
3961       break;
3962     }
3963   } while (!T.isNull() && T->isVariablyModifiedType());
3964 }
3965 
3966 /// \brief Build a sizeof or alignof expression given a type operand.
3967 ExprResult
3968 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3969                                      SourceLocation OpLoc,
3970                                      UnaryExprOrTypeTrait ExprKind,
3971                                      SourceRange R) {
3972   if (!TInfo)
3973     return ExprError();
3974 
3975   QualType T = TInfo->getType();
3976 
3977   if (!T->isDependentType() &&
3978       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3979     return ExprError();
3980 
3981   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3982     if (auto *TT = T->getAs<TypedefType>()) {
3983       for (auto I = FunctionScopes.rbegin(),
3984                 E = std::prev(FunctionScopes.rend());
3985            I != E; ++I) {
3986         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3987         if (CSI == nullptr)
3988           break;
3989         DeclContext *DC = nullptr;
3990         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3991           DC = LSI->CallOperator;
3992         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3993           DC = CRSI->TheCapturedDecl;
3994         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3995           DC = BSI->TheDecl;
3996         if (DC) {
3997           if (DC->containsDecl(TT->getDecl()))
3998             break;
3999           captureVariablyModifiedType(Context, T, CSI);
4000         }
4001       }
4002     }
4003   }
4004 
4005   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4006   return new (Context) UnaryExprOrTypeTraitExpr(
4007       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4008 }
4009 
4010 /// \brief Build a sizeof or alignof expression given an expression
4011 /// operand.
4012 ExprResult
4013 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4014                                      UnaryExprOrTypeTrait ExprKind) {
4015   ExprResult PE = CheckPlaceholderExpr(E);
4016   if (PE.isInvalid())
4017     return ExprError();
4018 
4019   E = PE.get();
4020 
4021   // Verify that the operand is valid.
4022   bool isInvalid = false;
4023   if (E->isTypeDependent()) {
4024     // Delay type-checking for type-dependent expressions.
4025   } else if (ExprKind == UETT_AlignOf) {
4026     isInvalid = CheckAlignOfExpr(*this, E);
4027   } else if (ExprKind == UETT_VecStep) {
4028     isInvalid = CheckVecStepExpr(E);
4029   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4030       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4031       isInvalid = true;
4032   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4033     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4034     isInvalid = true;
4035   } else {
4036     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4037   }
4038 
4039   if (isInvalid)
4040     return ExprError();
4041 
4042   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4043     PE = TransformToPotentiallyEvaluated(E);
4044     if (PE.isInvalid()) return ExprError();
4045     E = PE.get();
4046   }
4047 
4048   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4049   return new (Context) UnaryExprOrTypeTraitExpr(
4050       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4051 }
4052 
4053 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4054 /// expr and the same for @c alignof and @c __alignof
4055 /// Note that the ArgRange is invalid if isType is false.
4056 ExprResult
4057 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4058                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4059                                     void *TyOrEx, SourceRange ArgRange) {
4060   // If error parsing type, ignore.
4061   if (!TyOrEx) return ExprError();
4062 
4063   if (IsType) {
4064     TypeSourceInfo *TInfo;
4065     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4066     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4067   }
4068 
4069   Expr *ArgEx = (Expr *)TyOrEx;
4070   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4071   return Result;
4072 }
4073 
4074 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4075                                      bool IsReal) {
4076   if (V.get()->isTypeDependent())
4077     return S.Context.DependentTy;
4078 
4079   // _Real and _Imag are only l-values for normal l-values.
4080   if (V.get()->getObjectKind() != OK_Ordinary) {
4081     V = S.DefaultLvalueConversion(V.get());
4082     if (V.isInvalid())
4083       return QualType();
4084   }
4085 
4086   // These operators return the element type of a complex type.
4087   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4088     return CT->getElementType();
4089 
4090   // Otherwise they pass through real integer and floating point types here.
4091   if (V.get()->getType()->isArithmeticType())
4092     return V.get()->getType();
4093 
4094   // Test for placeholders.
4095   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4096   if (PR.isInvalid()) return QualType();
4097   if (PR.get() != V.get()) {
4098     V = PR;
4099     return CheckRealImagOperand(S, V, Loc, IsReal);
4100   }
4101 
4102   // Reject anything else.
4103   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4104     << (IsReal ? "__real" : "__imag");
4105   return QualType();
4106 }
4107 
4108 
4109 
4110 ExprResult
4111 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4112                           tok::TokenKind Kind, Expr *Input) {
4113   UnaryOperatorKind Opc;
4114   switch (Kind) {
4115   default: llvm_unreachable("Unknown unary op!");
4116   case tok::plusplus:   Opc = UO_PostInc; break;
4117   case tok::minusminus: Opc = UO_PostDec; break;
4118   }
4119 
4120   // Since this might is a postfix expression, get rid of ParenListExprs.
4121   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4122   if (Result.isInvalid()) return ExprError();
4123   Input = Result.get();
4124 
4125   return BuildUnaryOp(S, OpLoc, Opc, Input);
4126 }
4127 
4128 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4129 ///
4130 /// \return true on error
4131 static bool checkArithmeticOnObjCPointer(Sema &S,
4132                                          SourceLocation opLoc,
4133                                          Expr *op) {
4134   assert(op->getType()->isObjCObjectPointerType());
4135   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4136       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4137     return false;
4138 
4139   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4140     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4141     << op->getSourceRange();
4142   return true;
4143 }
4144 
4145 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4146   auto *BaseNoParens = Base->IgnoreParens();
4147   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4148     return MSProp->getPropertyDecl()->getType()->isArrayType();
4149   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4150 }
4151 
4152 ExprResult
4153 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4154                               Expr *idx, SourceLocation rbLoc) {
4155   if (base && !base->getType().isNull() &&
4156       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4157     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4158                                     /*Length=*/nullptr, rbLoc);
4159 
4160   // Since this might be a postfix expression, get rid of ParenListExprs.
4161   if (isa<ParenListExpr>(base)) {
4162     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4163     if (result.isInvalid()) return ExprError();
4164     base = result.get();
4165   }
4166 
4167   // Handle any non-overload placeholder types in the base and index
4168   // expressions.  We can't handle overloads here because the other
4169   // operand might be an overloadable type, in which case the overload
4170   // resolution for the operator overload should get the first crack
4171   // at the overload.
4172   bool IsMSPropertySubscript = false;
4173   if (base->getType()->isNonOverloadPlaceholderType()) {
4174     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4175     if (!IsMSPropertySubscript) {
4176       ExprResult result = CheckPlaceholderExpr(base);
4177       if (result.isInvalid())
4178         return ExprError();
4179       base = result.get();
4180     }
4181   }
4182   if (idx->getType()->isNonOverloadPlaceholderType()) {
4183     ExprResult result = CheckPlaceholderExpr(idx);
4184     if (result.isInvalid()) return ExprError();
4185     idx = result.get();
4186   }
4187 
4188   // Build an unanalyzed expression if either operand is type-dependent.
4189   if (getLangOpts().CPlusPlus &&
4190       (base->isTypeDependent() || idx->isTypeDependent())) {
4191     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4192                                             VK_LValue, OK_Ordinary, rbLoc);
4193   }
4194 
4195   // MSDN, property (C++)
4196   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4197   // This attribute can also be used in the declaration of an empty array in a
4198   // class or structure definition. For example:
4199   // __declspec(property(get=GetX, put=PutX)) int x[];
4200   // The above statement indicates that x[] can be used with one or more array
4201   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4202   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4203   if (IsMSPropertySubscript) {
4204     // Build MS property subscript expression if base is MS property reference
4205     // or MS property subscript.
4206     return new (Context) MSPropertySubscriptExpr(
4207         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4208   }
4209 
4210   // Use C++ overloaded-operator rules if either operand has record
4211   // type.  The spec says to do this if either type is *overloadable*,
4212   // but enum types can't declare subscript operators or conversion
4213   // operators, so there's nothing interesting for overload resolution
4214   // to do if there aren't any record types involved.
4215   //
4216   // ObjC pointers have their own subscripting logic that is not tied
4217   // to overload resolution and so should not take this path.
4218   if (getLangOpts().CPlusPlus &&
4219       (base->getType()->isRecordType() ||
4220        (!base->getType()->isObjCObjectPointerType() &&
4221         idx->getType()->isRecordType()))) {
4222     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4223   }
4224 
4225   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4226 }
4227 
4228 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4229                                           Expr *LowerBound,
4230                                           SourceLocation ColonLoc, Expr *Length,
4231                                           SourceLocation RBLoc) {
4232   if (Base->getType()->isPlaceholderType() &&
4233       !Base->getType()->isSpecificPlaceholderType(
4234           BuiltinType::OMPArraySection)) {
4235     ExprResult Result = CheckPlaceholderExpr(Base);
4236     if (Result.isInvalid())
4237       return ExprError();
4238     Base = Result.get();
4239   }
4240   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4241     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4242     if (Result.isInvalid())
4243       return ExprError();
4244     Result = DefaultLvalueConversion(Result.get());
4245     if (Result.isInvalid())
4246       return ExprError();
4247     LowerBound = Result.get();
4248   }
4249   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4250     ExprResult Result = CheckPlaceholderExpr(Length);
4251     if (Result.isInvalid())
4252       return ExprError();
4253     Result = DefaultLvalueConversion(Result.get());
4254     if (Result.isInvalid())
4255       return ExprError();
4256     Length = Result.get();
4257   }
4258 
4259   // Build an unanalyzed expression if either operand is type-dependent.
4260   if (Base->isTypeDependent() ||
4261       (LowerBound &&
4262        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4263       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4264     return new (Context)
4265         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4266                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4267   }
4268 
4269   // Perform default conversions.
4270   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4271   QualType ResultTy;
4272   if (OriginalTy->isAnyPointerType()) {
4273     ResultTy = OriginalTy->getPointeeType();
4274   } else if (OriginalTy->isArrayType()) {
4275     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4276   } else {
4277     return ExprError(
4278         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4279         << Base->getSourceRange());
4280   }
4281   // C99 6.5.2.1p1
4282   if (LowerBound) {
4283     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4284                                                       LowerBound);
4285     if (Res.isInvalid())
4286       return ExprError(Diag(LowerBound->getExprLoc(),
4287                             diag::err_omp_typecheck_section_not_integer)
4288                        << 0 << LowerBound->getSourceRange());
4289     LowerBound = Res.get();
4290 
4291     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4292         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4293       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4294           << 0 << LowerBound->getSourceRange();
4295   }
4296   if (Length) {
4297     auto Res =
4298         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4299     if (Res.isInvalid())
4300       return ExprError(Diag(Length->getExprLoc(),
4301                             diag::err_omp_typecheck_section_not_integer)
4302                        << 1 << Length->getSourceRange());
4303     Length = Res.get();
4304 
4305     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4306         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4307       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4308           << 1 << Length->getSourceRange();
4309   }
4310 
4311   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4312   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4313   // type. Note that functions are not objects, and that (in C99 parlance)
4314   // incomplete types are not object types.
4315   if (ResultTy->isFunctionType()) {
4316     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4317         << ResultTy << Base->getSourceRange();
4318     return ExprError();
4319   }
4320 
4321   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4322                           diag::err_omp_section_incomplete_type, Base))
4323     return ExprError();
4324 
4325   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4326     llvm::APSInt LowerBoundValue;
4327     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4328       // OpenMP 4.5, [2.4 Array Sections]
4329       // The array section must be a subset of the original array.
4330       if (LowerBoundValue.isNegative()) {
4331         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4332             << LowerBound->getSourceRange();
4333         return ExprError();
4334       }
4335     }
4336   }
4337 
4338   if (Length) {
4339     llvm::APSInt LengthValue;
4340     if (Length->EvaluateAsInt(LengthValue, Context)) {
4341       // OpenMP 4.5, [2.4 Array Sections]
4342       // The length must evaluate to non-negative integers.
4343       if (LengthValue.isNegative()) {
4344         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4345             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4346             << Length->getSourceRange();
4347         return ExprError();
4348       }
4349     }
4350   } else if (ColonLoc.isValid() &&
4351              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4352                                       !OriginalTy->isVariableArrayType()))) {
4353     // OpenMP 4.5, [2.4 Array Sections]
4354     // When the size of the array dimension is not known, the length must be
4355     // specified explicitly.
4356     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4357         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4358     return ExprError();
4359   }
4360 
4361   if (!Base->getType()->isSpecificPlaceholderType(
4362           BuiltinType::OMPArraySection)) {
4363     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4364     if (Result.isInvalid())
4365       return ExprError();
4366     Base = Result.get();
4367   }
4368   return new (Context)
4369       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4370                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4371 }
4372 
4373 ExprResult
4374 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4375                                       Expr *Idx, SourceLocation RLoc) {
4376   Expr *LHSExp = Base;
4377   Expr *RHSExp = Idx;
4378 
4379   // Perform default conversions.
4380   if (!LHSExp->getType()->getAs<VectorType>()) {
4381     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4382     if (Result.isInvalid())
4383       return ExprError();
4384     LHSExp = Result.get();
4385   }
4386   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4387   if (Result.isInvalid())
4388     return ExprError();
4389   RHSExp = Result.get();
4390 
4391   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4392   ExprValueKind VK = VK_LValue;
4393   ExprObjectKind OK = OK_Ordinary;
4394 
4395   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4396   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4397   // in the subscript position. As a result, we need to derive the array base
4398   // and index from the expression types.
4399   Expr *BaseExpr, *IndexExpr;
4400   QualType ResultType;
4401   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4402     BaseExpr = LHSExp;
4403     IndexExpr = RHSExp;
4404     ResultType = Context.DependentTy;
4405   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4406     BaseExpr = LHSExp;
4407     IndexExpr = RHSExp;
4408     ResultType = PTy->getPointeeType();
4409   } else if (const ObjCObjectPointerType *PTy =
4410                LHSTy->getAs<ObjCObjectPointerType>()) {
4411     BaseExpr = LHSExp;
4412     IndexExpr = RHSExp;
4413 
4414     // Use custom logic if this should be the pseudo-object subscript
4415     // expression.
4416     if (!LangOpts.isSubscriptPointerArithmetic())
4417       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4418                                           nullptr);
4419 
4420     ResultType = PTy->getPointeeType();
4421   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4422      // Handle the uncommon case of "123[Ptr]".
4423     BaseExpr = RHSExp;
4424     IndexExpr = LHSExp;
4425     ResultType = PTy->getPointeeType();
4426   } else if (const ObjCObjectPointerType *PTy =
4427                RHSTy->getAs<ObjCObjectPointerType>()) {
4428      // Handle the uncommon case of "123[Ptr]".
4429     BaseExpr = RHSExp;
4430     IndexExpr = LHSExp;
4431     ResultType = PTy->getPointeeType();
4432     if (!LangOpts.isSubscriptPointerArithmetic()) {
4433       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4434         << ResultType << BaseExpr->getSourceRange();
4435       return ExprError();
4436     }
4437   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4438     BaseExpr = LHSExp;    // vectors: V[123]
4439     IndexExpr = RHSExp;
4440     VK = LHSExp->getValueKind();
4441     if (VK != VK_RValue)
4442       OK = OK_VectorComponent;
4443 
4444     // FIXME: need to deal with const...
4445     ResultType = VTy->getElementType();
4446   } else if (LHSTy->isArrayType()) {
4447     // If we see an array that wasn't promoted by
4448     // DefaultFunctionArrayLvalueConversion, it must be an array that
4449     // wasn't promoted because of the C90 rule that doesn't
4450     // allow promoting non-lvalue arrays.  Warn, then
4451     // force the promotion here.
4452     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4453         LHSExp->getSourceRange();
4454     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4455                                CK_ArrayToPointerDecay).get();
4456     LHSTy = LHSExp->getType();
4457 
4458     BaseExpr = LHSExp;
4459     IndexExpr = RHSExp;
4460     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4461   } else if (RHSTy->isArrayType()) {
4462     // Same as previous, except for 123[f().a] case
4463     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4464         RHSExp->getSourceRange();
4465     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4466                                CK_ArrayToPointerDecay).get();
4467     RHSTy = RHSExp->getType();
4468 
4469     BaseExpr = RHSExp;
4470     IndexExpr = LHSExp;
4471     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4472   } else {
4473     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4474        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4475   }
4476   // C99 6.5.2.1p1
4477   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4478     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4479                      << IndexExpr->getSourceRange());
4480 
4481   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4482        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4483          && !IndexExpr->isTypeDependent())
4484     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4485 
4486   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4487   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4488   // type. Note that Functions are not objects, and that (in C99 parlance)
4489   // incomplete types are not object types.
4490   if (ResultType->isFunctionType()) {
4491     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4492       << ResultType << BaseExpr->getSourceRange();
4493     return ExprError();
4494   }
4495 
4496   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4497     // GNU extension: subscripting on pointer to void
4498     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4499       << BaseExpr->getSourceRange();
4500 
4501     // C forbids expressions of unqualified void type from being l-values.
4502     // See IsCForbiddenLValueType.
4503     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4504   } else if (!ResultType->isDependentType() &&
4505       RequireCompleteType(LLoc, ResultType,
4506                           diag::err_subscript_incomplete_type, BaseExpr))
4507     return ExprError();
4508 
4509   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4510          !ResultType.isCForbiddenLValueType());
4511 
4512   return new (Context)
4513       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4514 }
4515 
4516 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4517                                         FunctionDecl *FD,
4518                                         ParmVarDecl *Param) {
4519   if (Param->hasUnparsedDefaultArg()) {
4520     Diag(CallLoc,
4521          diag::err_use_of_default_argument_to_function_declared_later) <<
4522       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4523     Diag(UnparsedDefaultArgLocs[Param],
4524          diag::note_default_argument_declared_here);
4525     return ExprError();
4526   }
4527 
4528   if (Param->hasUninstantiatedDefaultArg()) {
4529     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4530 
4531     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4532                                                  Param);
4533 
4534     // Instantiate the expression.
4535     MultiLevelTemplateArgumentList MutiLevelArgList
4536       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4537 
4538     InstantiatingTemplate Inst(*this, CallLoc, Param,
4539                                MutiLevelArgList.getInnermost());
4540     if (Inst.isInvalid())
4541       return ExprError();
4542 
4543     ExprResult Result;
4544     {
4545       // C++ [dcl.fct.default]p5:
4546       //   The names in the [default argument] expression are bound, and
4547       //   the semantic constraints are checked, at the point where the
4548       //   default argument expression appears.
4549       ContextRAII SavedContext(*this, FD);
4550       LocalInstantiationScope Local(*this);
4551       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4552     }
4553     if (Result.isInvalid())
4554       return ExprError();
4555 
4556     // Check the expression as an initializer for the parameter.
4557     InitializedEntity Entity
4558       = InitializedEntity::InitializeParameter(Context, Param);
4559     InitializationKind Kind
4560       = InitializationKind::CreateCopy(Param->getLocation(),
4561              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4562     Expr *ResultE = Result.getAs<Expr>();
4563 
4564     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4565     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4566     if (Result.isInvalid())
4567       return ExprError();
4568 
4569     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4570                                  Param->getOuterLocStart());
4571     if (Result.isInvalid())
4572       return ExprError();
4573 
4574     // Remember the instantiated default argument.
4575     Param->setDefaultArg(Result.getAs<Expr>());
4576     if (ASTMutationListener *L = getASTMutationListener()) {
4577       L->DefaultArgumentInstantiated(Param);
4578     }
4579   }
4580 
4581   // If the default argument expression is not set yet, we are building it now.
4582   if (!Param->hasInit()) {
4583     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4584     Param->setInvalidDecl();
4585     return ExprError();
4586   }
4587 
4588   // If the default expression creates temporaries, we need to
4589   // push them to the current stack of expression temporaries so they'll
4590   // be properly destroyed.
4591   // FIXME: We should really be rebuilding the default argument with new
4592   // bound temporaries; see the comment in PR5810.
4593   // We don't need to do that with block decls, though, because
4594   // blocks in default argument expression can never capture anything.
4595   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4596     // Set the "needs cleanups" bit regardless of whether there are
4597     // any explicit objects.
4598     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4599 
4600     // Append all the objects to the cleanup list.  Right now, this
4601     // should always be a no-op, because blocks in default argument
4602     // expressions should never be able to capture anything.
4603     assert(!Init->getNumObjects() &&
4604            "default argument expression has capturing blocks?");
4605   }
4606 
4607   // We already type-checked the argument, so we know it works.
4608   // Just mark all of the declarations in this potentially-evaluated expression
4609   // as being "referenced".
4610   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4611                                    /*SkipLocalVariables=*/true);
4612   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4613 }
4614 
4615 
4616 Sema::VariadicCallType
4617 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4618                           Expr *Fn) {
4619   if (Proto && Proto->isVariadic()) {
4620     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4621       return VariadicConstructor;
4622     else if (Fn && Fn->getType()->isBlockPointerType())
4623       return VariadicBlock;
4624     else if (FDecl) {
4625       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4626         if (Method->isInstance())
4627           return VariadicMethod;
4628     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4629       return VariadicMethod;
4630     return VariadicFunction;
4631   }
4632   return VariadicDoesNotApply;
4633 }
4634 
4635 namespace {
4636 class FunctionCallCCC : public FunctionCallFilterCCC {
4637 public:
4638   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4639                   unsigned NumArgs, MemberExpr *ME)
4640       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4641         FunctionName(FuncName) {}
4642 
4643   bool ValidateCandidate(const TypoCorrection &candidate) override {
4644     if (!candidate.getCorrectionSpecifier() ||
4645         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4646       return false;
4647     }
4648 
4649     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4650   }
4651 
4652 private:
4653   const IdentifierInfo *const FunctionName;
4654 };
4655 }
4656 
4657 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4658                                                FunctionDecl *FDecl,
4659                                                ArrayRef<Expr *> Args) {
4660   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4661   DeclarationName FuncName = FDecl->getDeclName();
4662   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4663 
4664   if (TypoCorrection Corrected = S.CorrectTypo(
4665           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4666           S.getScopeForContext(S.CurContext), nullptr,
4667           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4668                                              Args.size(), ME),
4669           Sema::CTK_ErrorRecovery)) {
4670     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4671       if (Corrected.isOverloaded()) {
4672         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4673         OverloadCandidateSet::iterator Best;
4674         for (NamedDecl *CD : Corrected) {
4675           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4676             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4677                                    OCS);
4678         }
4679         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4680         case OR_Success:
4681           ND = Best->FoundDecl;
4682           Corrected.setCorrectionDecl(ND);
4683           break;
4684         default:
4685           break;
4686         }
4687       }
4688       ND = ND->getUnderlyingDecl();
4689       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4690         return Corrected;
4691     }
4692   }
4693   return TypoCorrection();
4694 }
4695 
4696 /// ConvertArgumentsForCall - Converts the arguments specified in
4697 /// Args/NumArgs to the parameter types of the function FDecl with
4698 /// function prototype Proto. Call is the call expression itself, and
4699 /// Fn is the function expression. For a C++ member function, this
4700 /// routine does not attempt to convert the object argument. Returns
4701 /// true if the call is ill-formed.
4702 bool
4703 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4704                               FunctionDecl *FDecl,
4705                               const FunctionProtoType *Proto,
4706                               ArrayRef<Expr *> Args,
4707                               SourceLocation RParenLoc,
4708                               bool IsExecConfig) {
4709   // Bail out early if calling a builtin with custom typechecking.
4710   if (FDecl)
4711     if (unsigned ID = FDecl->getBuiltinID())
4712       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4713         return false;
4714 
4715   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4716   // assignment, to the types of the corresponding parameter, ...
4717   unsigned NumParams = Proto->getNumParams();
4718   bool Invalid = false;
4719   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4720   unsigned FnKind = Fn->getType()->isBlockPointerType()
4721                        ? 1 /* block */
4722                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4723                                        : 0 /* function */);
4724 
4725   // If too few arguments are available (and we don't have default
4726   // arguments for the remaining parameters), don't make the call.
4727   if (Args.size() < NumParams) {
4728     if (Args.size() < MinArgs) {
4729       TypoCorrection TC;
4730       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4731         unsigned diag_id =
4732             MinArgs == NumParams && !Proto->isVariadic()
4733                 ? diag::err_typecheck_call_too_few_args_suggest
4734                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4735         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4736                                         << static_cast<unsigned>(Args.size())
4737                                         << TC.getCorrectionRange());
4738       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4739         Diag(RParenLoc,
4740              MinArgs == NumParams && !Proto->isVariadic()
4741                  ? diag::err_typecheck_call_too_few_args_one
4742                  : diag::err_typecheck_call_too_few_args_at_least_one)
4743             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4744       else
4745         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4746                             ? diag::err_typecheck_call_too_few_args
4747                             : diag::err_typecheck_call_too_few_args_at_least)
4748             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4749             << Fn->getSourceRange();
4750 
4751       // Emit the location of the prototype.
4752       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4753         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4754           << FDecl;
4755 
4756       return true;
4757     }
4758     Call->setNumArgs(Context, NumParams);
4759   }
4760 
4761   // If too many are passed and not variadic, error on the extras and drop
4762   // them.
4763   if (Args.size() > NumParams) {
4764     if (!Proto->isVariadic()) {
4765       TypoCorrection TC;
4766       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4767         unsigned diag_id =
4768             MinArgs == NumParams && !Proto->isVariadic()
4769                 ? diag::err_typecheck_call_too_many_args_suggest
4770                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4771         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4772                                         << static_cast<unsigned>(Args.size())
4773                                         << TC.getCorrectionRange());
4774       } else if (NumParams == 1 && FDecl &&
4775                  FDecl->getParamDecl(0)->getDeclName())
4776         Diag(Args[NumParams]->getLocStart(),
4777              MinArgs == NumParams
4778                  ? diag::err_typecheck_call_too_many_args_one
4779                  : diag::err_typecheck_call_too_many_args_at_most_one)
4780             << FnKind << FDecl->getParamDecl(0)
4781             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4782             << SourceRange(Args[NumParams]->getLocStart(),
4783                            Args.back()->getLocEnd());
4784       else
4785         Diag(Args[NumParams]->getLocStart(),
4786              MinArgs == NumParams
4787                  ? diag::err_typecheck_call_too_many_args
4788                  : diag::err_typecheck_call_too_many_args_at_most)
4789             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4790             << Fn->getSourceRange()
4791             << SourceRange(Args[NumParams]->getLocStart(),
4792                            Args.back()->getLocEnd());
4793 
4794       // Emit the location of the prototype.
4795       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4796         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4797           << FDecl;
4798 
4799       // This deletes the extra arguments.
4800       Call->setNumArgs(Context, NumParams);
4801       return true;
4802     }
4803   }
4804   SmallVector<Expr *, 8> AllArgs;
4805   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4806 
4807   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4808                                    Proto, 0, Args, AllArgs, CallType);
4809   if (Invalid)
4810     return true;
4811   unsigned TotalNumArgs = AllArgs.size();
4812   for (unsigned i = 0; i < TotalNumArgs; ++i)
4813     Call->setArg(i, AllArgs[i]);
4814 
4815   return false;
4816 }
4817 
4818 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4819                                   const FunctionProtoType *Proto,
4820                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4821                                   SmallVectorImpl<Expr *> &AllArgs,
4822                                   VariadicCallType CallType, bool AllowExplicit,
4823                                   bool IsListInitialization) {
4824   unsigned NumParams = Proto->getNumParams();
4825   bool Invalid = false;
4826   size_t ArgIx = 0;
4827   // Continue to check argument types (even if we have too few/many args).
4828   for (unsigned i = FirstParam; i < NumParams; i++) {
4829     QualType ProtoArgType = Proto->getParamType(i);
4830 
4831     Expr *Arg;
4832     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4833     if (ArgIx < Args.size()) {
4834       Arg = Args[ArgIx++];
4835 
4836       if (RequireCompleteType(Arg->getLocStart(),
4837                               ProtoArgType,
4838                               diag::err_call_incomplete_argument, Arg))
4839         return true;
4840 
4841       // Strip the unbridged-cast placeholder expression off, if applicable.
4842       bool CFAudited = false;
4843       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4844           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4845           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4846         Arg = stripARCUnbridgedCast(Arg);
4847       else if (getLangOpts().ObjCAutoRefCount &&
4848                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4849                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4850         CFAudited = true;
4851 
4852       InitializedEntity Entity =
4853           Param ? InitializedEntity::InitializeParameter(Context, Param,
4854                                                          ProtoArgType)
4855                 : InitializedEntity::InitializeParameter(
4856                       Context, ProtoArgType, Proto->isParamConsumed(i));
4857 
4858       // Remember that parameter belongs to a CF audited API.
4859       if (CFAudited)
4860         Entity.setParameterCFAudited();
4861 
4862       ExprResult ArgE = PerformCopyInitialization(
4863           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4864       if (ArgE.isInvalid())
4865         return true;
4866 
4867       Arg = ArgE.getAs<Expr>();
4868     } else {
4869       assert(Param && "can't use default arguments without a known callee");
4870 
4871       ExprResult ArgExpr =
4872         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4873       if (ArgExpr.isInvalid())
4874         return true;
4875 
4876       Arg = ArgExpr.getAs<Expr>();
4877     }
4878 
4879     // Check for array bounds violations for each argument to the call. This
4880     // check only triggers warnings when the argument isn't a more complex Expr
4881     // with its own checking, such as a BinaryOperator.
4882     CheckArrayAccess(Arg);
4883 
4884     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4885     CheckStaticArrayArgument(CallLoc, Param, Arg);
4886 
4887     AllArgs.push_back(Arg);
4888   }
4889 
4890   // If this is a variadic call, handle args passed through "...".
4891   if (CallType != VariadicDoesNotApply) {
4892     // Assume that extern "C" functions with variadic arguments that
4893     // return __unknown_anytype aren't *really* variadic.
4894     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4895         FDecl->isExternC()) {
4896       for (Expr *A : Args.slice(ArgIx)) {
4897         QualType paramType; // ignored
4898         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4899         Invalid |= arg.isInvalid();
4900         AllArgs.push_back(arg.get());
4901       }
4902 
4903     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4904     } else {
4905       for (Expr *A : Args.slice(ArgIx)) {
4906         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4907         Invalid |= Arg.isInvalid();
4908         AllArgs.push_back(Arg.get());
4909       }
4910     }
4911 
4912     // Check for array bounds violations.
4913     for (Expr *A : Args.slice(ArgIx))
4914       CheckArrayAccess(A);
4915   }
4916   return Invalid;
4917 }
4918 
4919 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4920   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4921   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4922     TL = DTL.getOriginalLoc();
4923   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4924     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4925       << ATL.getLocalSourceRange();
4926 }
4927 
4928 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4929 /// array parameter, check that it is non-null, and that if it is formed by
4930 /// array-to-pointer decay, the underlying array is sufficiently large.
4931 ///
4932 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4933 /// array type derivation, then for each call to the function, the value of the
4934 /// corresponding actual argument shall provide access to the first element of
4935 /// an array with at least as many elements as specified by the size expression.
4936 void
4937 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4938                                ParmVarDecl *Param,
4939                                const Expr *ArgExpr) {
4940   // Static array parameters are not supported in C++.
4941   if (!Param || getLangOpts().CPlusPlus)
4942     return;
4943 
4944   QualType OrigTy = Param->getOriginalType();
4945 
4946   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4947   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4948     return;
4949 
4950   if (ArgExpr->isNullPointerConstant(Context,
4951                                      Expr::NPC_NeverValueDependent)) {
4952     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4953     DiagnoseCalleeStaticArrayParam(*this, Param);
4954     return;
4955   }
4956 
4957   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4958   if (!CAT)
4959     return;
4960 
4961   const ConstantArrayType *ArgCAT =
4962     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4963   if (!ArgCAT)
4964     return;
4965 
4966   if (ArgCAT->getSize().ult(CAT->getSize())) {
4967     Diag(CallLoc, diag::warn_static_array_too_small)
4968       << ArgExpr->getSourceRange()
4969       << (unsigned) ArgCAT->getSize().getZExtValue()
4970       << (unsigned) CAT->getSize().getZExtValue();
4971     DiagnoseCalleeStaticArrayParam(*this, Param);
4972   }
4973 }
4974 
4975 /// Given a function expression of unknown-any type, try to rebuild it
4976 /// to have a function type.
4977 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4978 
4979 /// Is the given type a placeholder that we need to lower out
4980 /// immediately during argument processing?
4981 static bool isPlaceholderToRemoveAsArg(QualType type) {
4982   // Placeholders are never sugared.
4983   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4984   if (!placeholder) return false;
4985 
4986   switch (placeholder->getKind()) {
4987   // Ignore all the non-placeholder types.
4988 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4989   case BuiltinType::Id:
4990 #include "clang/Basic/OpenCLImageTypes.def"
4991 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4992 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4993 #include "clang/AST/BuiltinTypes.def"
4994     return false;
4995 
4996   // We cannot lower out overload sets; they might validly be resolved
4997   // by the call machinery.
4998   case BuiltinType::Overload:
4999     return false;
5000 
5001   // Unbridged casts in ARC can be handled in some call positions and
5002   // should be left in place.
5003   case BuiltinType::ARCUnbridgedCast:
5004     return false;
5005 
5006   // Pseudo-objects should be converted as soon as possible.
5007   case BuiltinType::PseudoObject:
5008     return true;
5009 
5010   // The debugger mode could theoretically but currently does not try
5011   // to resolve unknown-typed arguments based on known parameter types.
5012   case BuiltinType::UnknownAny:
5013     return true;
5014 
5015   // These are always invalid as call arguments and should be reported.
5016   case BuiltinType::BoundMember:
5017   case BuiltinType::BuiltinFn:
5018   case BuiltinType::OMPArraySection:
5019     return true;
5020 
5021   }
5022   llvm_unreachable("bad builtin type kind");
5023 }
5024 
5025 /// Check an argument list for placeholders that we won't try to
5026 /// handle later.
5027 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5028   // Apply this processing to all the arguments at once instead of
5029   // dying at the first failure.
5030   bool hasInvalid = false;
5031   for (size_t i = 0, e = args.size(); i != e; i++) {
5032     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5033       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5034       if (result.isInvalid()) hasInvalid = true;
5035       else args[i] = result.get();
5036     } else if (hasInvalid) {
5037       (void)S.CorrectDelayedTyposInExpr(args[i]);
5038     }
5039   }
5040   return hasInvalid;
5041 }
5042 
5043 /// If a builtin function has a pointer argument with no explicit address
5044 /// space, then it should be able to accept a pointer to any address
5045 /// space as input.  In order to do this, we need to replace the
5046 /// standard builtin declaration with one that uses the same address space
5047 /// as the call.
5048 ///
5049 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5050 ///                  it does not contain any pointer arguments without
5051 ///                  an address space qualifer.  Otherwise the rewritten
5052 ///                  FunctionDecl is returned.
5053 /// TODO: Handle pointer return types.
5054 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5055                                                 const FunctionDecl *FDecl,
5056                                                 MultiExprArg ArgExprs) {
5057 
5058   QualType DeclType = FDecl->getType();
5059   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5060 
5061   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5062       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5063     return nullptr;
5064 
5065   bool NeedsNewDecl = false;
5066   unsigned i = 0;
5067   SmallVector<QualType, 8> OverloadParams;
5068 
5069   for (QualType ParamType : FT->param_types()) {
5070 
5071     // Convert array arguments to pointer to simplify type lookup.
5072     ExprResult ArgRes =
5073         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5074     if (ArgRes.isInvalid())
5075       return nullptr;
5076     Expr *Arg = ArgRes.get();
5077     QualType ArgType = Arg->getType();
5078     if (!ParamType->isPointerType() ||
5079         ParamType.getQualifiers().hasAddressSpace() ||
5080         !ArgType->isPointerType() ||
5081         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5082       OverloadParams.push_back(ParamType);
5083       continue;
5084     }
5085 
5086     NeedsNewDecl = true;
5087     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5088 
5089     QualType PointeeType = ParamType->getPointeeType();
5090     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5091     OverloadParams.push_back(Context.getPointerType(PointeeType));
5092   }
5093 
5094   if (!NeedsNewDecl)
5095     return nullptr;
5096 
5097   FunctionProtoType::ExtProtoInfo EPI;
5098   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5099                                                 OverloadParams, EPI);
5100   DeclContext *Parent = Context.getTranslationUnitDecl();
5101   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5102                                                     FDecl->getLocation(),
5103                                                     FDecl->getLocation(),
5104                                                     FDecl->getIdentifier(),
5105                                                     OverloadTy,
5106                                                     /*TInfo=*/nullptr,
5107                                                     SC_Extern, false,
5108                                                     /*hasPrototype=*/true);
5109   SmallVector<ParmVarDecl*, 16> Params;
5110   FT = cast<FunctionProtoType>(OverloadTy);
5111   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5112     QualType ParamType = FT->getParamType(i);
5113     ParmVarDecl *Parm =
5114         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5115                                 SourceLocation(), nullptr, ParamType,
5116                                 /*TInfo=*/nullptr, SC_None, nullptr);
5117     Parm->setScopeInfo(0, i);
5118     Params.push_back(Parm);
5119   }
5120   OverloadDecl->setParams(Params);
5121   return OverloadDecl;
5122 }
5123 
5124 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5125                                        std::size_t NumArgs) {
5126   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5127                          /*PartialOverloading=*/false))
5128     return Callee->isVariadic();
5129   return Callee->getMinRequiredArguments() <= NumArgs;
5130 }
5131 
5132 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5133 /// This provides the location of the left/right parens and a list of comma
5134 /// locations.
5135 ExprResult
5136 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5137                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
5138                     Expr *ExecConfig, bool IsExecConfig) {
5139   // Since this might be a postfix expression, get rid of ParenListExprs.
5140   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
5141   if (Result.isInvalid()) return ExprError();
5142   Fn = Result.get();
5143 
5144   if (checkArgsForPlaceholders(*this, ArgExprs))
5145     return ExprError();
5146 
5147   if (getLangOpts().CPlusPlus) {
5148     // If this is a pseudo-destructor expression, build the call immediately.
5149     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5150       if (!ArgExprs.empty()) {
5151         // Pseudo-destructor calls should not have any arguments.
5152         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5153           << FixItHint::CreateRemoval(
5154                                     SourceRange(ArgExprs.front()->getLocStart(),
5155                                                 ArgExprs.back()->getLocEnd()));
5156       }
5157 
5158       return new (Context)
5159           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5160     }
5161     if (Fn->getType() == Context.PseudoObjectTy) {
5162       ExprResult result = CheckPlaceholderExpr(Fn);
5163       if (result.isInvalid()) return ExprError();
5164       Fn = result.get();
5165     }
5166 
5167     // Determine whether this is a dependent call inside a C++ template,
5168     // in which case we won't do any semantic analysis now.
5169     bool Dependent = false;
5170     if (Fn->isTypeDependent())
5171       Dependent = true;
5172     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5173       Dependent = true;
5174 
5175     if (Dependent) {
5176       if (ExecConfig) {
5177         return new (Context) CUDAKernelCallExpr(
5178             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5179             Context.DependentTy, VK_RValue, RParenLoc);
5180       } else {
5181         return new (Context) CallExpr(
5182             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5183       }
5184     }
5185 
5186     // Determine whether this is a call to an object (C++ [over.call.object]).
5187     if (Fn->getType()->isRecordType())
5188       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5189                                           RParenLoc);
5190 
5191     if (Fn->getType() == Context.UnknownAnyTy) {
5192       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5193       if (result.isInvalid()) return ExprError();
5194       Fn = result.get();
5195     }
5196 
5197     if (Fn->getType() == Context.BoundMemberTy) {
5198       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5199     }
5200   }
5201 
5202   // Check for overloaded calls.  This can happen even in C due to extensions.
5203   if (Fn->getType() == Context.OverloadTy) {
5204     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5205 
5206     // We aren't supposed to apply this logic for if there's an '&' involved.
5207     if (!find.HasFormOfMemberPointer) {
5208       OverloadExpr *ovl = find.Expression;
5209       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5210         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
5211                                        RParenLoc, ExecConfig,
5212                                        /*AllowTypoCorrection=*/true,
5213                                        find.IsAddressOfOperand);
5214       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5215     }
5216   }
5217 
5218   // If we're directly calling a function, get the appropriate declaration.
5219   if (Fn->getType() == Context.UnknownAnyTy) {
5220     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5221     if (result.isInvalid()) return ExprError();
5222     Fn = result.get();
5223   }
5224 
5225   Expr *NakedFn = Fn->IgnoreParens();
5226 
5227   bool CallingNDeclIndirectly = false;
5228   NamedDecl *NDecl = nullptr;
5229   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5230     if (UnOp->getOpcode() == UO_AddrOf) {
5231       CallingNDeclIndirectly = true;
5232       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5233     }
5234   }
5235 
5236   if (isa<DeclRefExpr>(NakedFn)) {
5237     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5238 
5239     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5240     if (FDecl && FDecl->getBuiltinID()) {
5241       // Rewrite the function decl for this builtin by replacing parameters
5242       // with no explicit address space with the address space of the arguments
5243       // in ArgExprs.
5244       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5245         NDecl = FDecl;
5246         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5247                            SourceLocation(), FDecl, false,
5248                            SourceLocation(), FDecl->getType(),
5249                            Fn->getValueKind(), FDecl);
5250       }
5251     }
5252   } else if (isa<MemberExpr>(NakedFn))
5253     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5254 
5255   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5256     if (CallingNDeclIndirectly &&
5257         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5258                                            Fn->getLocStart()))
5259       return ExprError();
5260 
5261     // CheckEnableIf assumes that the we're passing in a sane number of args for
5262     // FD, but that doesn't always hold true here. This is because, in some
5263     // cases, we'll emit a diag about an ill-formed function call, but then
5264     // we'll continue on as if the function call wasn't ill-formed. So, if the
5265     // number of args looks incorrect, don't do enable_if checks; we should've
5266     // already emitted an error about the bad call.
5267     if (FD->hasAttr<EnableIfAttr>() &&
5268         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5269       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5270         Diag(Fn->getLocStart(),
5271              isa<CXXMethodDecl>(FD) ?
5272                  diag::err_ovl_no_viable_member_function_in_call :
5273                  diag::err_ovl_no_viable_function_in_call)
5274           << FD << FD->getSourceRange();
5275         Diag(FD->getLocation(),
5276              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5277             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5278       }
5279     }
5280   }
5281 
5282   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5283                                ExecConfig, IsExecConfig);
5284 }
5285 
5286 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5287 ///
5288 /// __builtin_astype( value, dst type )
5289 ///
5290 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5291                                  SourceLocation BuiltinLoc,
5292                                  SourceLocation RParenLoc) {
5293   ExprValueKind VK = VK_RValue;
5294   ExprObjectKind OK = OK_Ordinary;
5295   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5296   QualType SrcTy = E->getType();
5297   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5298     return ExprError(Diag(BuiltinLoc,
5299                           diag::err_invalid_astype_of_different_size)
5300                      << DstTy
5301                      << SrcTy
5302                      << E->getSourceRange());
5303   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5304 }
5305 
5306 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5307 /// provided arguments.
5308 ///
5309 /// __builtin_convertvector( value, dst type )
5310 ///
5311 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5312                                         SourceLocation BuiltinLoc,
5313                                         SourceLocation RParenLoc) {
5314   TypeSourceInfo *TInfo;
5315   GetTypeFromParser(ParsedDestTy, &TInfo);
5316   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5317 }
5318 
5319 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5320 /// i.e. an expression not of \p OverloadTy.  The expression should
5321 /// unary-convert to an expression of function-pointer or
5322 /// block-pointer type.
5323 ///
5324 /// \param NDecl the declaration being called, if available
5325 ExprResult
5326 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5327                             SourceLocation LParenLoc,
5328                             ArrayRef<Expr *> Args,
5329                             SourceLocation RParenLoc,
5330                             Expr *Config, bool IsExecConfig) {
5331   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5332   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5333 
5334   // Functions with 'interrupt' attribute cannot be called directly.
5335   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5336     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5337     return ExprError();
5338   }
5339 
5340   // Promote the function operand.
5341   // We special-case function promotion here because we only allow promoting
5342   // builtin functions to function pointers in the callee of a call.
5343   ExprResult Result;
5344   if (BuiltinID &&
5345       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5346     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5347                                CK_BuiltinFnToFnPtr).get();
5348   } else {
5349     Result = CallExprUnaryConversions(Fn);
5350   }
5351   if (Result.isInvalid())
5352     return ExprError();
5353   Fn = Result.get();
5354 
5355   // Make the call expr early, before semantic checks.  This guarantees cleanup
5356   // of arguments and function on error.
5357   CallExpr *TheCall;
5358   if (Config)
5359     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5360                                                cast<CallExpr>(Config), Args,
5361                                                Context.BoolTy, VK_RValue,
5362                                                RParenLoc);
5363   else
5364     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5365                                      VK_RValue, RParenLoc);
5366 
5367   if (!getLangOpts().CPlusPlus) {
5368     // C cannot always handle TypoExpr nodes in builtin calls and direct
5369     // function calls as their argument checking don't necessarily handle
5370     // dependent types properly, so make sure any TypoExprs have been
5371     // dealt with.
5372     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5373     if (!Result.isUsable()) return ExprError();
5374     TheCall = dyn_cast<CallExpr>(Result.get());
5375     if (!TheCall) return Result;
5376     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5377   }
5378 
5379   // Bail out early if calling a builtin with custom typechecking.
5380   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5381     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5382 
5383  retry:
5384   const FunctionType *FuncT;
5385   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5386     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5387     // have type pointer to function".
5388     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5389     if (!FuncT)
5390       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5391                          << Fn->getType() << Fn->getSourceRange());
5392   } else if (const BlockPointerType *BPT =
5393                Fn->getType()->getAs<BlockPointerType>()) {
5394     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5395   } else {
5396     // Handle calls to expressions of unknown-any type.
5397     if (Fn->getType() == Context.UnknownAnyTy) {
5398       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5399       if (rewrite.isInvalid()) return ExprError();
5400       Fn = rewrite.get();
5401       TheCall->setCallee(Fn);
5402       goto retry;
5403     }
5404 
5405     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5406       << Fn->getType() << Fn->getSourceRange());
5407   }
5408 
5409   if (getLangOpts().CUDA) {
5410     if (Config) {
5411       // CUDA: Kernel calls must be to global functions
5412       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5413         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5414             << FDecl->getName() << Fn->getSourceRange());
5415 
5416       // CUDA: Kernel function must have 'void' return type
5417       if (!FuncT->getReturnType()->isVoidType())
5418         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5419             << Fn->getType() << Fn->getSourceRange());
5420     } else {
5421       // CUDA: Calls to global functions must be configured
5422       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5423         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5424             << FDecl->getName() << Fn->getSourceRange());
5425     }
5426   }
5427 
5428   // Check for a valid return type
5429   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5430                           FDecl))
5431     return ExprError();
5432 
5433   // We know the result type of the call, set it.
5434   TheCall->setType(FuncT->getCallResultType(Context));
5435   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5436 
5437   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5438   if (Proto) {
5439     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5440                                 IsExecConfig))
5441       return ExprError();
5442   } else {
5443     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5444 
5445     if (FDecl) {
5446       // Check if we have too few/too many template arguments, based
5447       // on our knowledge of the function definition.
5448       const FunctionDecl *Def = nullptr;
5449       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5450         Proto = Def->getType()->getAs<FunctionProtoType>();
5451        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5452           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5453           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5454       }
5455 
5456       // If the function we're calling isn't a function prototype, but we have
5457       // a function prototype from a prior declaratiom, use that prototype.
5458       if (!FDecl->hasPrototype())
5459         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5460     }
5461 
5462     // Promote the arguments (C99 6.5.2.2p6).
5463     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5464       Expr *Arg = Args[i];
5465 
5466       if (Proto && i < Proto->getNumParams()) {
5467         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5468             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5469         ExprResult ArgE =
5470             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5471         if (ArgE.isInvalid())
5472           return true;
5473 
5474         Arg = ArgE.getAs<Expr>();
5475 
5476       } else {
5477         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5478 
5479         if (ArgE.isInvalid())
5480           return true;
5481 
5482         Arg = ArgE.getAs<Expr>();
5483       }
5484 
5485       if (RequireCompleteType(Arg->getLocStart(),
5486                               Arg->getType(),
5487                               diag::err_call_incomplete_argument, Arg))
5488         return ExprError();
5489 
5490       TheCall->setArg(i, Arg);
5491     }
5492   }
5493 
5494   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5495     if (!Method->isStatic())
5496       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5497         << Fn->getSourceRange());
5498 
5499   // Check for sentinels
5500   if (NDecl)
5501     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5502 
5503   // Do special checking on direct calls to functions.
5504   if (FDecl) {
5505     if (CheckFunctionCall(FDecl, TheCall, Proto))
5506       return ExprError();
5507 
5508     if (BuiltinID)
5509       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5510   } else if (NDecl) {
5511     if (CheckPointerCall(NDecl, TheCall, Proto))
5512       return ExprError();
5513   } else {
5514     if (CheckOtherCall(TheCall, Proto))
5515       return ExprError();
5516   }
5517 
5518   return MaybeBindToTemporary(TheCall);
5519 }
5520 
5521 ExprResult
5522 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5523                            SourceLocation RParenLoc, Expr *InitExpr) {
5524   assert(Ty && "ActOnCompoundLiteral(): missing type");
5525   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5526 
5527   TypeSourceInfo *TInfo;
5528   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5529   if (!TInfo)
5530     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5531 
5532   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5533 }
5534 
5535 ExprResult
5536 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5537                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5538   QualType literalType = TInfo->getType();
5539 
5540   if (literalType->isArrayType()) {
5541     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5542           diag::err_illegal_decl_array_incomplete_type,
5543           SourceRange(LParenLoc,
5544                       LiteralExpr->getSourceRange().getEnd())))
5545       return ExprError();
5546     if (literalType->isVariableArrayType())
5547       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5548         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5549   } else if (!literalType->isDependentType() &&
5550              RequireCompleteType(LParenLoc, literalType,
5551                diag::err_typecheck_decl_incomplete_type,
5552                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5553     return ExprError();
5554 
5555   InitializedEntity Entity
5556     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5557   InitializationKind Kind
5558     = InitializationKind::CreateCStyleCast(LParenLoc,
5559                                            SourceRange(LParenLoc, RParenLoc),
5560                                            /*InitList=*/true);
5561   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5562   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5563                                       &literalType);
5564   if (Result.isInvalid())
5565     return ExprError();
5566   LiteralExpr = Result.get();
5567 
5568   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5569   if (isFileScope &&
5570       !LiteralExpr->isTypeDependent() &&
5571       !LiteralExpr->isValueDependent() &&
5572       !literalType->isDependentType()) { // 6.5.2.5p3
5573     if (CheckForConstantInitializer(LiteralExpr, literalType))
5574       return ExprError();
5575   }
5576 
5577   // In C, compound literals are l-values for some reason.
5578   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5579 
5580   return MaybeBindToTemporary(
5581            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5582                                              VK, LiteralExpr, isFileScope));
5583 }
5584 
5585 ExprResult
5586 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5587                     SourceLocation RBraceLoc) {
5588   // Immediately handle non-overload placeholders.  Overloads can be
5589   // resolved contextually, but everything else here can't.
5590   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5591     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5592       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5593 
5594       // Ignore failures; dropping the entire initializer list because
5595       // of one failure would be terrible for indexing/etc.
5596       if (result.isInvalid()) continue;
5597 
5598       InitArgList[I] = result.get();
5599     }
5600   }
5601 
5602   // Semantic analysis for initializers is done by ActOnDeclarator() and
5603   // CheckInitializer() - it requires knowledge of the object being intialized.
5604 
5605   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5606                                                RBraceLoc);
5607   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5608   return E;
5609 }
5610 
5611 /// Do an explicit extend of the given block pointer if we're in ARC.
5612 void Sema::maybeExtendBlockObject(ExprResult &E) {
5613   assert(E.get()->getType()->isBlockPointerType());
5614   assert(E.get()->isRValue());
5615 
5616   // Only do this in an r-value context.
5617   if (!getLangOpts().ObjCAutoRefCount) return;
5618 
5619   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5620                                CK_ARCExtendBlockObject, E.get(),
5621                                /*base path*/ nullptr, VK_RValue);
5622   Cleanup.setExprNeedsCleanups(true);
5623 }
5624 
5625 /// Prepare a conversion of the given expression to an ObjC object
5626 /// pointer type.
5627 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5628   QualType type = E.get()->getType();
5629   if (type->isObjCObjectPointerType()) {
5630     return CK_BitCast;
5631   } else if (type->isBlockPointerType()) {
5632     maybeExtendBlockObject(E);
5633     return CK_BlockPointerToObjCPointerCast;
5634   } else {
5635     assert(type->isPointerType());
5636     return CK_CPointerToObjCPointerCast;
5637   }
5638 }
5639 
5640 /// Prepares for a scalar cast, performing all the necessary stages
5641 /// except the final cast and returning the kind required.
5642 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5643   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5644   // Also, callers should have filtered out the invalid cases with
5645   // pointers.  Everything else should be possible.
5646 
5647   QualType SrcTy = Src.get()->getType();
5648   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5649     return CK_NoOp;
5650 
5651   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5652   case Type::STK_MemberPointer:
5653     llvm_unreachable("member pointer type in C");
5654 
5655   case Type::STK_CPointer:
5656   case Type::STK_BlockPointer:
5657   case Type::STK_ObjCObjectPointer:
5658     switch (DestTy->getScalarTypeKind()) {
5659     case Type::STK_CPointer: {
5660       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5661       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5662       if (SrcAS != DestAS)
5663         return CK_AddressSpaceConversion;
5664       return CK_BitCast;
5665     }
5666     case Type::STK_BlockPointer:
5667       return (SrcKind == Type::STK_BlockPointer
5668                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5669     case Type::STK_ObjCObjectPointer:
5670       if (SrcKind == Type::STK_ObjCObjectPointer)
5671         return CK_BitCast;
5672       if (SrcKind == Type::STK_CPointer)
5673         return CK_CPointerToObjCPointerCast;
5674       maybeExtendBlockObject(Src);
5675       return CK_BlockPointerToObjCPointerCast;
5676     case Type::STK_Bool:
5677       return CK_PointerToBoolean;
5678     case Type::STK_Integral:
5679       return CK_PointerToIntegral;
5680     case Type::STK_Floating:
5681     case Type::STK_FloatingComplex:
5682     case Type::STK_IntegralComplex:
5683     case Type::STK_MemberPointer:
5684       llvm_unreachable("illegal cast from pointer");
5685     }
5686     llvm_unreachable("Should have returned before this");
5687 
5688   case Type::STK_Bool: // casting from bool is like casting from an integer
5689   case Type::STK_Integral:
5690     switch (DestTy->getScalarTypeKind()) {
5691     case Type::STK_CPointer:
5692     case Type::STK_ObjCObjectPointer:
5693     case Type::STK_BlockPointer:
5694       if (Src.get()->isNullPointerConstant(Context,
5695                                            Expr::NPC_ValueDependentIsNull))
5696         return CK_NullToPointer;
5697       return CK_IntegralToPointer;
5698     case Type::STK_Bool:
5699       return CK_IntegralToBoolean;
5700     case Type::STK_Integral:
5701       return CK_IntegralCast;
5702     case Type::STK_Floating:
5703       return CK_IntegralToFloating;
5704     case Type::STK_IntegralComplex:
5705       Src = ImpCastExprToType(Src.get(),
5706                       DestTy->castAs<ComplexType>()->getElementType(),
5707                       CK_IntegralCast);
5708       return CK_IntegralRealToComplex;
5709     case Type::STK_FloatingComplex:
5710       Src = ImpCastExprToType(Src.get(),
5711                       DestTy->castAs<ComplexType>()->getElementType(),
5712                       CK_IntegralToFloating);
5713       return CK_FloatingRealToComplex;
5714     case Type::STK_MemberPointer:
5715       llvm_unreachable("member pointer type in C");
5716     }
5717     llvm_unreachable("Should have returned before this");
5718 
5719   case Type::STK_Floating:
5720     switch (DestTy->getScalarTypeKind()) {
5721     case Type::STK_Floating:
5722       return CK_FloatingCast;
5723     case Type::STK_Bool:
5724       return CK_FloatingToBoolean;
5725     case Type::STK_Integral:
5726       return CK_FloatingToIntegral;
5727     case Type::STK_FloatingComplex:
5728       Src = ImpCastExprToType(Src.get(),
5729                               DestTy->castAs<ComplexType>()->getElementType(),
5730                               CK_FloatingCast);
5731       return CK_FloatingRealToComplex;
5732     case Type::STK_IntegralComplex:
5733       Src = ImpCastExprToType(Src.get(),
5734                               DestTy->castAs<ComplexType>()->getElementType(),
5735                               CK_FloatingToIntegral);
5736       return CK_IntegralRealToComplex;
5737     case Type::STK_CPointer:
5738     case Type::STK_ObjCObjectPointer:
5739     case Type::STK_BlockPointer:
5740       llvm_unreachable("valid float->pointer cast?");
5741     case Type::STK_MemberPointer:
5742       llvm_unreachable("member pointer type in C");
5743     }
5744     llvm_unreachable("Should have returned before this");
5745 
5746   case Type::STK_FloatingComplex:
5747     switch (DestTy->getScalarTypeKind()) {
5748     case Type::STK_FloatingComplex:
5749       return CK_FloatingComplexCast;
5750     case Type::STK_IntegralComplex:
5751       return CK_FloatingComplexToIntegralComplex;
5752     case Type::STK_Floating: {
5753       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5754       if (Context.hasSameType(ET, DestTy))
5755         return CK_FloatingComplexToReal;
5756       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5757       return CK_FloatingCast;
5758     }
5759     case Type::STK_Bool:
5760       return CK_FloatingComplexToBoolean;
5761     case Type::STK_Integral:
5762       Src = ImpCastExprToType(Src.get(),
5763                               SrcTy->castAs<ComplexType>()->getElementType(),
5764                               CK_FloatingComplexToReal);
5765       return CK_FloatingToIntegral;
5766     case Type::STK_CPointer:
5767     case Type::STK_ObjCObjectPointer:
5768     case Type::STK_BlockPointer:
5769       llvm_unreachable("valid complex float->pointer cast?");
5770     case Type::STK_MemberPointer:
5771       llvm_unreachable("member pointer type in C");
5772     }
5773     llvm_unreachable("Should have returned before this");
5774 
5775   case Type::STK_IntegralComplex:
5776     switch (DestTy->getScalarTypeKind()) {
5777     case Type::STK_FloatingComplex:
5778       return CK_IntegralComplexToFloatingComplex;
5779     case Type::STK_IntegralComplex:
5780       return CK_IntegralComplexCast;
5781     case Type::STK_Integral: {
5782       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5783       if (Context.hasSameType(ET, DestTy))
5784         return CK_IntegralComplexToReal;
5785       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5786       return CK_IntegralCast;
5787     }
5788     case Type::STK_Bool:
5789       return CK_IntegralComplexToBoolean;
5790     case Type::STK_Floating:
5791       Src = ImpCastExprToType(Src.get(),
5792                               SrcTy->castAs<ComplexType>()->getElementType(),
5793                               CK_IntegralComplexToReal);
5794       return CK_IntegralToFloating;
5795     case Type::STK_CPointer:
5796     case Type::STK_ObjCObjectPointer:
5797     case Type::STK_BlockPointer:
5798       llvm_unreachable("valid complex int->pointer cast?");
5799     case Type::STK_MemberPointer:
5800       llvm_unreachable("member pointer type in C");
5801     }
5802     llvm_unreachable("Should have returned before this");
5803   }
5804 
5805   llvm_unreachable("Unhandled scalar cast");
5806 }
5807 
5808 static bool breakDownVectorType(QualType type, uint64_t &len,
5809                                 QualType &eltType) {
5810   // Vectors are simple.
5811   if (const VectorType *vecType = type->getAs<VectorType>()) {
5812     len = vecType->getNumElements();
5813     eltType = vecType->getElementType();
5814     assert(eltType->isScalarType());
5815     return true;
5816   }
5817 
5818   // We allow lax conversion to and from non-vector types, but only if
5819   // they're real types (i.e. non-complex, non-pointer scalar types).
5820   if (!type->isRealType()) return false;
5821 
5822   len = 1;
5823   eltType = type;
5824   return true;
5825 }
5826 
5827 /// Are the two types lax-compatible vector types?  That is, given
5828 /// that one of them is a vector, do they have equal storage sizes,
5829 /// where the storage size is the number of elements times the element
5830 /// size?
5831 ///
5832 /// This will also return false if either of the types is neither a
5833 /// vector nor a real type.
5834 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5835   assert(destTy->isVectorType() || srcTy->isVectorType());
5836 
5837   // Disallow lax conversions between scalars and ExtVectors (these
5838   // conversions are allowed for other vector types because common headers
5839   // depend on them).  Most scalar OP ExtVector cases are handled by the
5840   // splat path anyway, which does what we want (convert, not bitcast).
5841   // What this rules out for ExtVectors is crazy things like char4*float.
5842   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5843   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5844 
5845   uint64_t srcLen, destLen;
5846   QualType srcEltTy, destEltTy;
5847   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5848   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5849 
5850   // ASTContext::getTypeSize will return the size rounded up to a
5851   // power of 2, so instead of using that, we need to use the raw
5852   // element size multiplied by the element count.
5853   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5854   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5855 
5856   return (srcLen * srcEltSize == destLen * destEltSize);
5857 }
5858 
5859 /// Is this a legal conversion between two types, one of which is
5860 /// known to be a vector type?
5861 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5862   assert(destTy->isVectorType() || srcTy->isVectorType());
5863 
5864   if (!Context.getLangOpts().LaxVectorConversions)
5865     return false;
5866   return areLaxCompatibleVectorTypes(srcTy, destTy);
5867 }
5868 
5869 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5870                            CastKind &Kind) {
5871   assert(VectorTy->isVectorType() && "Not a vector type!");
5872 
5873   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5874     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5875       return Diag(R.getBegin(),
5876                   Ty->isVectorType() ?
5877                   diag::err_invalid_conversion_between_vectors :
5878                   diag::err_invalid_conversion_between_vector_and_integer)
5879         << VectorTy << Ty << R;
5880   } else
5881     return Diag(R.getBegin(),
5882                 diag::err_invalid_conversion_between_vector_and_scalar)
5883       << VectorTy << Ty << R;
5884 
5885   Kind = CK_BitCast;
5886   return false;
5887 }
5888 
5889 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5890   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5891 
5892   if (DestElemTy == SplattedExpr->getType())
5893     return SplattedExpr;
5894 
5895   assert(DestElemTy->isFloatingType() ||
5896          DestElemTy->isIntegralOrEnumerationType());
5897 
5898   CastKind CK;
5899   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5900     // OpenCL requires that we convert `true` boolean expressions to -1, but
5901     // only when splatting vectors.
5902     if (DestElemTy->isFloatingType()) {
5903       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5904       // in two steps: boolean to signed integral, then to floating.
5905       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5906                                                  CK_BooleanToSignedIntegral);
5907       SplattedExpr = CastExprRes.get();
5908       CK = CK_IntegralToFloating;
5909     } else {
5910       CK = CK_BooleanToSignedIntegral;
5911     }
5912   } else {
5913     ExprResult CastExprRes = SplattedExpr;
5914     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5915     if (CastExprRes.isInvalid())
5916       return ExprError();
5917     SplattedExpr = CastExprRes.get();
5918   }
5919   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5920 }
5921 
5922 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5923                                     Expr *CastExpr, CastKind &Kind) {
5924   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5925 
5926   QualType SrcTy = CastExpr->getType();
5927 
5928   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5929   // an ExtVectorType.
5930   // In OpenCL, casts between vectors of different types are not allowed.
5931   // (See OpenCL 6.2).
5932   if (SrcTy->isVectorType()) {
5933     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5934         || (getLangOpts().OpenCL &&
5935             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5936       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5937         << DestTy << SrcTy << R;
5938       return ExprError();
5939     }
5940     Kind = CK_BitCast;
5941     return CastExpr;
5942   }
5943 
5944   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5945   // conversion will take place first from scalar to elt type, and then
5946   // splat from elt type to vector.
5947   if (SrcTy->isPointerType())
5948     return Diag(R.getBegin(),
5949                 diag::err_invalid_conversion_between_vector_and_scalar)
5950       << DestTy << SrcTy << R;
5951 
5952   Kind = CK_VectorSplat;
5953   return prepareVectorSplat(DestTy, CastExpr);
5954 }
5955 
5956 ExprResult
5957 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5958                     Declarator &D, ParsedType &Ty,
5959                     SourceLocation RParenLoc, Expr *CastExpr) {
5960   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5961          "ActOnCastExpr(): missing type or expr");
5962 
5963   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5964   if (D.isInvalidType())
5965     return ExprError();
5966 
5967   if (getLangOpts().CPlusPlus) {
5968     // Check that there are no default arguments (C++ only).
5969     CheckExtraCXXDefaultArguments(D);
5970   } else {
5971     // Make sure any TypoExprs have been dealt with.
5972     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5973     if (!Res.isUsable())
5974       return ExprError();
5975     CastExpr = Res.get();
5976   }
5977 
5978   checkUnusedDeclAttributes(D);
5979 
5980   QualType castType = castTInfo->getType();
5981   Ty = CreateParsedType(castType, castTInfo);
5982 
5983   bool isVectorLiteral = false;
5984 
5985   // Check for an altivec or OpenCL literal,
5986   // i.e. all the elements are integer constants.
5987   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5988   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5989   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5990        && castType->isVectorType() && (PE || PLE)) {
5991     if (PLE && PLE->getNumExprs() == 0) {
5992       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5993       return ExprError();
5994     }
5995     if (PE || PLE->getNumExprs() == 1) {
5996       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5997       if (!E->getType()->isVectorType())
5998         isVectorLiteral = true;
5999     }
6000     else
6001       isVectorLiteral = true;
6002   }
6003 
6004   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6005   // then handle it as such.
6006   if (isVectorLiteral)
6007     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6008 
6009   // If the Expr being casted is a ParenListExpr, handle it specially.
6010   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6011   // sequence of BinOp comma operators.
6012   if (isa<ParenListExpr>(CastExpr)) {
6013     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6014     if (Result.isInvalid()) return ExprError();
6015     CastExpr = Result.get();
6016   }
6017 
6018   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6019       !getSourceManager().isInSystemMacro(LParenLoc))
6020     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6021 
6022   CheckTollFreeBridgeCast(castType, CastExpr);
6023 
6024   CheckObjCBridgeRelatedCast(castType, CastExpr);
6025 
6026   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6027 }
6028 
6029 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6030                                     SourceLocation RParenLoc, Expr *E,
6031                                     TypeSourceInfo *TInfo) {
6032   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6033          "Expected paren or paren list expression");
6034 
6035   Expr **exprs;
6036   unsigned numExprs;
6037   Expr *subExpr;
6038   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6039   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6040     LiteralLParenLoc = PE->getLParenLoc();
6041     LiteralRParenLoc = PE->getRParenLoc();
6042     exprs = PE->getExprs();
6043     numExprs = PE->getNumExprs();
6044   } else { // isa<ParenExpr> by assertion at function entrance
6045     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6046     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6047     subExpr = cast<ParenExpr>(E)->getSubExpr();
6048     exprs = &subExpr;
6049     numExprs = 1;
6050   }
6051 
6052   QualType Ty = TInfo->getType();
6053   assert(Ty->isVectorType() && "Expected vector type");
6054 
6055   SmallVector<Expr *, 8> initExprs;
6056   const VectorType *VTy = Ty->getAs<VectorType>();
6057   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6058 
6059   // '(...)' form of vector initialization in AltiVec: the number of
6060   // initializers must be one or must match the size of the vector.
6061   // If a single value is specified in the initializer then it will be
6062   // replicated to all the components of the vector
6063   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6064     // The number of initializers must be one or must match the size of the
6065     // vector. If a single value is specified in the initializer then it will
6066     // be replicated to all the components of the vector
6067     if (numExprs == 1) {
6068       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6069       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6070       if (Literal.isInvalid())
6071         return ExprError();
6072       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6073                                   PrepareScalarCast(Literal, ElemTy));
6074       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6075     }
6076     else if (numExprs < numElems) {
6077       Diag(E->getExprLoc(),
6078            diag::err_incorrect_number_of_vector_initializers);
6079       return ExprError();
6080     }
6081     else
6082       initExprs.append(exprs, exprs + numExprs);
6083   }
6084   else {
6085     // For OpenCL, when the number of initializers is a single value,
6086     // it will be replicated to all components of the vector.
6087     if (getLangOpts().OpenCL &&
6088         VTy->getVectorKind() == VectorType::GenericVector &&
6089         numExprs == 1) {
6090         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6091         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6092         if (Literal.isInvalid())
6093           return ExprError();
6094         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6095                                     PrepareScalarCast(Literal, ElemTy));
6096         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6097     }
6098 
6099     initExprs.append(exprs, exprs + numExprs);
6100   }
6101   // FIXME: This means that pretty-printing the final AST will produce curly
6102   // braces instead of the original commas.
6103   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6104                                                    initExprs, LiteralRParenLoc);
6105   initE->setType(Ty);
6106   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6107 }
6108 
6109 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6110 /// the ParenListExpr into a sequence of comma binary operators.
6111 ExprResult
6112 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6113   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6114   if (!E)
6115     return OrigExpr;
6116 
6117   ExprResult Result(E->getExpr(0));
6118 
6119   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6120     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6121                         E->getExpr(i));
6122 
6123   if (Result.isInvalid()) return ExprError();
6124 
6125   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6126 }
6127 
6128 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6129                                     SourceLocation R,
6130                                     MultiExprArg Val) {
6131   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6132   return expr;
6133 }
6134 
6135 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6136 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6137 /// emitted.
6138 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6139                                       SourceLocation QuestionLoc) {
6140   Expr *NullExpr = LHSExpr;
6141   Expr *NonPointerExpr = RHSExpr;
6142   Expr::NullPointerConstantKind NullKind =
6143       NullExpr->isNullPointerConstant(Context,
6144                                       Expr::NPC_ValueDependentIsNotNull);
6145 
6146   if (NullKind == Expr::NPCK_NotNull) {
6147     NullExpr = RHSExpr;
6148     NonPointerExpr = LHSExpr;
6149     NullKind =
6150         NullExpr->isNullPointerConstant(Context,
6151                                         Expr::NPC_ValueDependentIsNotNull);
6152   }
6153 
6154   if (NullKind == Expr::NPCK_NotNull)
6155     return false;
6156 
6157   if (NullKind == Expr::NPCK_ZeroExpression)
6158     return false;
6159 
6160   if (NullKind == Expr::NPCK_ZeroLiteral) {
6161     // In this case, check to make sure that we got here from a "NULL"
6162     // string in the source code.
6163     NullExpr = NullExpr->IgnoreParenImpCasts();
6164     SourceLocation loc = NullExpr->getExprLoc();
6165     if (!findMacroSpelling(loc, "NULL"))
6166       return false;
6167   }
6168 
6169   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6170   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6171       << NonPointerExpr->getType() << DiagType
6172       << NonPointerExpr->getSourceRange();
6173   return true;
6174 }
6175 
6176 /// \brief Return false if the condition expression is valid, true otherwise.
6177 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6178   QualType CondTy = Cond->getType();
6179 
6180   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6181   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6182     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6183       << CondTy << Cond->getSourceRange();
6184     return true;
6185   }
6186 
6187   // C99 6.5.15p2
6188   if (CondTy->isScalarType()) return false;
6189 
6190   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6191     << CondTy << Cond->getSourceRange();
6192   return true;
6193 }
6194 
6195 /// \brief Handle when one or both operands are void type.
6196 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6197                                          ExprResult &RHS) {
6198     Expr *LHSExpr = LHS.get();
6199     Expr *RHSExpr = RHS.get();
6200 
6201     if (!LHSExpr->getType()->isVoidType())
6202       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6203         << RHSExpr->getSourceRange();
6204     if (!RHSExpr->getType()->isVoidType())
6205       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6206         << LHSExpr->getSourceRange();
6207     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6208     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6209     return S.Context.VoidTy;
6210 }
6211 
6212 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6213 /// true otherwise.
6214 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6215                                         QualType PointerTy) {
6216   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6217       !NullExpr.get()->isNullPointerConstant(S.Context,
6218                                             Expr::NPC_ValueDependentIsNull))
6219     return true;
6220 
6221   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6222   return false;
6223 }
6224 
6225 /// \brief Checks compatibility between two pointers and return the resulting
6226 /// type.
6227 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6228                                                      ExprResult &RHS,
6229                                                      SourceLocation Loc) {
6230   QualType LHSTy = LHS.get()->getType();
6231   QualType RHSTy = RHS.get()->getType();
6232 
6233   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6234     // Two identical pointers types are always compatible.
6235     return LHSTy;
6236   }
6237 
6238   QualType lhptee, rhptee;
6239 
6240   // Get the pointee types.
6241   bool IsBlockPointer = false;
6242   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6243     lhptee = LHSBTy->getPointeeType();
6244     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6245     IsBlockPointer = true;
6246   } else {
6247     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6248     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6249   }
6250 
6251   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6252   // differently qualified versions of compatible types, the result type is
6253   // a pointer to an appropriately qualified version of the composite
6254   // type.
6255 
6256   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6257   // clause doesn't make sense for our extensions. E.g. address space 2 should
6258   // be incompatible with address space 3: they may live on different devices or
6259   // anything.
6260   Qualifiers lhQual = lhptee.getQualifiers();
6261   Qualifiers rhQual = rhptee.getQualifiers();
6262 
6263   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6264   lhQual.removeCVRQualifiers();
6265   rhQual.removeCVRQualifiers();
6266 
6267   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6268   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6269 
6270   // For OpenCL:
6271   // 1. If LHS and RHS types match exactly and:
6272   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6273   //  (b) AS overlap => generate addrspacecast
6274   //  (c) AS don't overlap => give an error
6275   // 2. if LHS and RHS types don't match:
6276   //  (a) AS match => use standard C rules, generate bitcast
6277   //  (b) AS overlap => generate addrspacecast instead of bitcast
6278   //  (c) AS don't overlap => give an error
6279 
6280   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6281   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6282 
6283   // OpenCL cases 1c, 2a, 2b, and 2c.
6284   if (CompositeTy.isNull()) {
6285     // In this situation, we assume void* type. No especially good
6286     // reason, but this is what gcc does, and we do have to pick
6287     // to get a consistent AST.
6288     QualType incompatTy;
6289     if (S.getLangOpts().OpenCL) {
6290       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6291       // spaces is disallowed.
6292       unsigned ResultAddrSpace;
6293       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6294         // Cases 2a and 2b.
6295         ResultAddrSpace = lhQual.getAddressSpace();
6296       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6297         // Cases 2a and 2b.
6298         ResultAddrSpace = rhQual.getAddressSpace();
6299       } else {
6300         // Cases 1c and 2c.
6301         S.Diag(Loc,
6302                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6303             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6304             << RHS.get()->getSourceRange();
6305         return QualType();
6306       }
6307 
6308       // Continue handling cases 2a and 2b.
6309       incompatTy = S.Context.getPointerType(
6310           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6311       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6312                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6313                                     ? CK_AddressSpaceConversion /* 2b */
6314                                     : CK_BitCast /* 2a */);
6315       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6316                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6317                                     ? CK_AddressSpaceConversion /* 2b */
6318                                     : CK_BitCast /* 2a */);
6319     } else {
6320       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6321           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6322           << RHS.get()->getSourceRange();
6323       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6324       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6325       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6326     }
6327     return incompatTy;
6328   }
6329 
6330   // The pointer types are compatible.
6331   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6332   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6333   if (IsBlockPointer)
6334     ResultTy = S.Context.getBlockPointerType(ResultTy);
6335   else {
6336     // Cases 1a and 1b for OpenCL.
6337     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6338     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6339                       ? CK_BitCast /* 1a */
6340                       : CK_AddressSpaceConversion /* 1b */;
6341     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6342                       ? CK_BitCast /* 1a */
6343                       : CK_AddressSpaceConversion /* 1b */;
6344     ResultTy = S.Context.getPointerType(ResultTy);
6345   }
6346 
6347   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6348   // if the target type does not change.
6349   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6350   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6351   return ResultTy;
6352 }
6353 
6354 /// \brief Return the resulting type when the operands are both block pointers.
6355 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6356                                                           ExprResult &LHS,
6357                                                           ExprResult &RHS,
6358                                                           SourceLocation Loc) {
6359   QualType LHSTy = LHS.get()->getType();
6360   QualType RHSTy = RHS.get()->getType();
6361 
6362   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6363     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6364       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6365       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6366       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6367       return destType;
6368     }
6369     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6370       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6371       << RHS.get()->getSourceRange();
6372     return QualType();
6373   }
6374 
6375   // We have 2 block pointer types.
6376   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6377 }
6378 
6379 /// \brief Return the resulting type when the operands are both pointers.
6380 static QualType
6381 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6382                                             ExprResult &RHS,
6383                                             SourceLocation Loc) {
6384   // get the pointer types
6385   QualType LHSTy = LHS.get()->getType();
6386   QualType RHSTy = RHS.get()->getType();
6387 
6388   // get the "pointed to" types
6389   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6390   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6391 
6392   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6393   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6394     // Figure out necessary qualifiers (C99 6.5.15p6)
6395     QualType destPointee
6396       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6397     QualType destType = S.Context.getPointerType(destPointee);
6398     // Add qualifiers if necessary.
6399     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6400     // Promote to void*.
6401     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6402     return destType;
6403   }
6404   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6405     QualType destPointee
6406       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6407     QualType destType = S.Context.getPointerType(destPointee);
6408     // Add qualifiers if necessary.
6409     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6410     // Promote to void*.
6411     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6412     return destType;
6413   }
6414 
6415   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6416 }
6417 
6418 /// \brief Return false if the first expression is not an integer and the second
6419 /// expression is not a pointer, true otherwise.
6420 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6421                                         Expr* PointerExpr, SourceLocation Loc,
6422                                         bool IsIntFirstExpr) {
6423   if (!PointerExpr->getType()->isPointerType() ||
6424       !Int.get()->getType()->isIntegerType())
6425     return false;
6426 
6427   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6428   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6429 
6430   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6431     << Expr1->getType() << Expr2->getType()
6432     << Expr1->getSourceRange() << Expr2->getSourceRange();
6433   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6434                             CK_IntegralToPointer);
6435   return true;
6436 }
6437 
6438 /// \brief Simple conversion between integer and floating point types.
6439 ///
6440 /// Used when handling the OpenCL conditional operator where the
6441 /// condition is a vector while the other operands are scalar.
6442 ///
6443 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6444 /// types are either integer or floating type. Between the two
6445 /// operands, the type with the higher rank is defined as the "result
6446 /// type". The other operand needs to be promoted to the same type. No
6447 /// other type promotion is allowed. We cannot use
6448 /// UsualArithmeticConversions() for this purpose, since it always
6449 /// promotes promotable types.
6450 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6451                                             ExprResult &RHS,
6452                                             SourceLocation QuestionLoc) {
6453   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6454   if (LHS.isInvalid())
6455     return QualType();
6456   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6457   if (RHS.isInvalid())
6458     return QualType();
6459 
6460   // For conversion purposes, we ignore any qualifiers.
6461   // For example, "const float" and "float" are equivalent.
6462   QualType LHSType =
6463     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6464   QualType RHSType =
6465     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6466 
6467   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6468     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6469       << LHSType << LHS.get()->getSourceRange();
6470     return QualType();
6471   }
6472 
6473   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6474     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6475       << RHSType << RHS.get()->getSourceRange();
6476     return QualType();
6477   }
6478 
6479   // If both types are identical, no conversion is needed.
6480   if (LHSType == RHSType)
6481     return LHSType;
6482 
6483   // Now handle "real" floating types (i.e. float, double, long double).
6484   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6485     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6486                                  /*IsCompAssign = */ false);
6487 
6488   // Finally, we have two differing integer types.
6489   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6490   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6491 }
6492 
6493 /// \brief Convert scalar operands to a vector that matches the
6494 ///        condition in length.
6495 ///
6496 /// Used when handling the OpenCL conditional operator where the
6497 /// condition is a vector while the other operands are scalar.
6498 ///
6499 /// We first compute the "result type" for the scalar operands
6500 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6501 /// into a vector of that type where the length matches the condition
6502 /// vector type. s6.11.6 requires that the element types of the result
6503 /// and the condition must have the same number of bits.
6504 static QualType
6505 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6506                               QualType CondTy, SourceLocation QuestionLoc) {
6507   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6508   if (ResTy.isNull()) return QualType();
6509 
6510   const VectorType *CV = CondTy->getAs<VectorType>();
6511   assert(CV);
6512 
6513   // Determine the vector result type
6514   unsigned NumElements = CV->getNumElements();
6515   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6516 
6517   // Ensure that all types have the same number of bits
6518   if (S.Context.getTypeSize(CV->getElementType())
6519       != S.Context.getTypeSize(ResTy)) {
6520     // Since VectorTy is created internally, it does not pretty print
6521     // with an OpenCL name. Instead, we just print a description.
6522     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6523     SmallString<64> Str;
6524     llvm::raw_svector_ostream OS(Str);
6525     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6526     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6527       << CondTy << OS.str();
6528     return QualType();
6529   }
6530 
6531   // Convert operands to the vector result type
6532   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6533   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6534 
6535   return VectorTy;
6536 }
6537 
6538 /// \brief Return false if this is a valid OpenCL condition vector
6539 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6540                                        SourceLocation QuestionLoc) {
6541   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6542   // integral type.
6543   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6544   assert(CondTy);
6545   QualType EleTy = CondTy->getElementType();
6546   if (EleTy->isIntegerType()) return false;
6547 
6548   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6549     << Cond->getType() << Cond->getSourceRange();
6550   return true;
6551 }
6552 
6553 /// \brief Return false if the vector condition type and the vector
6554 ///        result type are compatible.
6555 ///
6556 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6557 /// number of elements, and their element types have the same number
6558 /// of bits.
6559 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6560                               SourceLocation QuestionLoc) {
6561   const VectorType *CV = CondTy->getAs<VectorType>();
6562   const VectorType *RV = VecResTy->getAs<VectorType>();
6563   assert(CV && RV);
6564 
6565   if (CV->getNumElements() != RV->getNumElements()) {
6566     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6567       << CondTy << VecResTy;
6568     return true;
6569   }
6570 
6571   QualType CVE = CV->getElementType();
6572   QualType RVE = RV->getElementType();
6573 
6574   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6575     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6576       << CondTy << VecResTy;
6577     return true;
6578   }
6579 
6580   return false;
6581 }
6582 
6583 /// \brief Return the resulting type for the conditional operator in
6584 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6585 ///        s6.3.i) when the condition is a vector type.
6586 static QualType
6587 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6588                              ExprResult &LHS, ExprResult &RHS,
6589                              SourceLocation QuestionLoc) {
6590   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6591   if (Cond.isInvalid())
6592     return QualType();
6593   QualType CondTy = Cond.get()->getType();
6594 
6595   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6596     return QualType();
6597 
6598   // If either operand is a vector then find the vector type of the
6599   // result as specified in OpenCL v1.1 s6.3.i.
6600   if (LHS.get()->getType()->isVectorType() ||
6601       RHS.get()->getType()->isVectorType()) {
6602     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6603                                               /*isCompAssign*/false,
6604                                               /*AllowBothBool*/true,
6605                                               /*AllowBoolConversions*/false);
6606     if (VecResTy.isNull()) return QualType();
6607     // The result type must match the condition type as specified in
6608     // OpenCL v1.1 s6.11.6.
6609     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6610       return QualType();
6611     return VecResTy;
6612   }
6613 
6614   // Both operands are scalar.
6615   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6616 }
6617 
6618 /// \brief Return true if the Expr is block type
6619 static bool checkBlockType(Sema &S, const Expr *E) {
6620   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6621     QualType Ty = CE->getCallee()->getType();
6622     if (Ty->isBlockPointerType()) {
6623       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6624       return true;
6625     }
6626   }
6627   return false;
6628 }
6629 
6630 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6631 /// In that case, LHS = cond.
6632 /// C99 6.5.15
6633 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6634                                         ExprResult &RHS, ExprValueKind &VK,
6635                                         ExprObjectKind &OK,
6636                                         SourceLocation QuestionLoc) {
6637 
6638   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6639   if (!LHSResult.isUsable()) return QualType();
6640   LHS = LHSResult;
6641 
6642   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6643   if (!RHSResult.isUsable()) return QualType();
6644   RHS = RHSResult;
6645 
6646   // C++ is sufficiently different to merit its own checker.
6647   if (getLangOpts().CPlusPlus)
6648     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6649 
6650   VK = VK_RValue;
6651   OK = OK_Ordinary;
6652 
6653   // The OpenCL operator with a vector condition is sufficiently
6654   // different to merit its own checker.
6655   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6656     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6657 
6658   // First, check the condition.
6659   Cond = UsualUnaryConversions(Cond.get());
6660   if (Cond.isInvalid())
6661     return QualType();
6662   if (checkCondition(*this, Cond.get(), QuestionLoc))
6663     return QualType();
6664 
6665   // Now check the two expressions.
6666   if (LHS.get()->getType()->isVectorType() ||
6667       RHS.get()->getType()->isVectorType())
6668     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6669                                /*AllowBothBool*/true,
6670                                /*AllowBoolConversions*/false);
6671 
6672   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6673   if (LHS.isInvalid() || RHS.isInvalid())
6674     return QualType();
6675 
6676   QualType LHSTy = LHS.get()->getType();
6677   QualType RHSTy = RHS.get()->getType();
6678 
6679   // Diagnose attempts to convert between __float128 and long double where
6680   // such conversions currently can't be handled.
6681   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6682     Diag(QuestionLoc,
6683          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6684       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6685     return QualType();
6686   }
6687 
6688   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6689   // selection operator (?:).
6690   if (getLangOpts().OpenCL &&
6691       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6692     return QualType();
6693   }
6694 
6695   // If both operands have arithmetic type, do the usual arithmetic conversions
6696   // to find a common type: C99 6.5.15p3,5.
6697   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6698     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6699     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6700 
6701     return ResTy;
6702   }
6703 
6704   // If both operands are the same structure or union type, the result is that
6705   // type.
6706   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6707     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6708       if (LHSRT->getDecl() == RHSRT->getDecl())
6709         // "If both the operands have structure or union type, the result has
6710         // that type."  This implies that CV qualifiers are dropped.
6711         return LHSTy.getUnqualifiedType();
6712     // FIXME: Type of conditional expression must be complete in C mode.
6713   }
6714 
6715   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6716   // The following || allows only one side to be void (a GCC-ism).
6717   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6718     return checkConditionalVoidType(*this, LHS, RHS);
6719   }
6720 
6721   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6722   // the type of the other operand."
6723   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6724   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6725 
6726   // All objective-c pointer type analysis is done here.
6727   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6728                                                         QuestionLoc);
6729   if (LHS.isInvalid() || RHS.isInvalid())
6730     return QualType();
6731   if (!compositeType.isNull())
6732     return compositeType;
6733 
6734 
6735   // Handle block pointer types.
6736   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6737     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6738                                                      QuestionLoc);
6739 
6740   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6741   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6742     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6743                                                        QuestionLoc);
6744 
6745   // GCC compatibility: soften pointer/integer mismatch.  Note that
6746   // null pointers have been filtered out by this point.
6747   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6748       /*isIntFirstExpr=*/true))
6749     return RHSTy;
6750   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6751       /*isIntFirstExpr=*/false))
6752     return LHSTy;
6753 
6754   // Emit a better diagnostic if one of the expressions is a null pointer
6755   // constant and the other is not a pointer type. In this case, the user most
6756   // likely forgot to take the address of the other expression.
6757   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6758     return QualType();
6759 
6760   // Otherwise, the operands are not compatible.
6761   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6762     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6763     << RHS.get()->getSourceRange();
6764   return QualType();
6765 }
6766 
6767 /// FindCompositeObjCPointerType - Helper method to find composite type of
6768 /// two objective-c pointer types of the two input expressions.
6769 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6770                                             SourceLocation QuestionLoc) {
6771   QualType LHSTy = LHS.get()->getType();
6772   QualType RHSTy = RHS.get()->getType();
6773 
6774   // Handle things like Class and struct objc_class*.  Here we case the result
6775   // to the pseudo-builtin, because that will be implicitly cast back to the
6776   // redefinition type if an attempt is made to access its fields.
6777   if (LHSTy->isObjCClassType() &&
6778       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6779     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6780     return LHSTy;
6781   }
6782   if (RHSTy->isObjCClassType() &&
6783       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6784     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6785     return RHSTy;
6786   }
6787   // And the same for struct objc_object* / id
6788   if (LHSTy->isObjCIdType() &&
6789       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6790     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6791     return LHSTy;
6792   }
6793   if (RHSTy->isObjCIdType() &&
6794       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6795     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6796     return RHSTy;
6797   }
6798   // And the same for struct objc_selector* / SEL
6799   if (Context.isObjCSelType(LHSTy) &&
6800       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6801     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6802     return LHSTy;
6803   }
6804   if (Context.isObjCSelType(RHSTy) &&
6805       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6806     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6807     return RHSTy;
6808   }
6809   // Check constraints for Objective-C object pointers types.
6810   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6811 
6812     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6813       // Two identical object pointer types are always compatible.
6814       return LHSTy;
6815     }
6816     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6817     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6818     QualType compositeType = LHSTy;
6819 
6820     // If both operands are interfaces and either operand can be
6821     // assigned to the other, use that type as the composite
6822     // type. This allows
6823     //   xxx ? (A*) a : (B*) b
6824     // where B is a subclass of A.
6825     //
6826     // Additionally, as for assignment, if either type is 'id'
6827     // allow silent coercion. Finally, if the types are
6828     // incompatible then make sure to use 'id' as the composite
6829     // type so the result is acceptable for sending messages to.
6830 
6831     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6832     // It could return the composite type.
6833     if (!(compositeType =
6834           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6835       // Nothing more to do.
6836     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6837       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6838     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6839       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6840     } else if ((LHSTy->isObjCQualifiedIdType() ||
6841                 RHSTy->isObjCQualifiedIdType()) &&
6842                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6843       // Need to handle "id<xx>" explicitly.
6844       // GCC allows qualified id and any Objective-C type to devolve to
6845       // id. Currently localizing to here until clear this should be
6846       // part of ObjCQualifiedIdTypesAreCompatible.
6847       compositeType = Context.getObjCIdType();
6848     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6849       compositeType = Context.getObjCIdType();
6850     } else {
6851       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6852       << LHSTy << RHSTy
6853       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6854       QualType incompatTy = Context.getObjCIdType();
6855       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6856       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6857       return incompatTy;
6858     }
6859     // The object pointer types are compatible.
6860     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6861     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6862     return compositeType;
6863   }
6864   // Check Objective-C object pointer types and 'void *'
6865   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6866     if (getLangOpts().ObjCAutoRefCount) {
6867       // ARC forbids the implicit conversion of object pointers to 'void *',
6868       // so these types are not compatible.
6869       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6870           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6871       LHS = RHS = true;
6872       return QualType();
6873     }
6874     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6875     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6876     QualType destPointee
6877     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6878     QualType destType = Context.getPointerType(destPointee);
6879     // Add qualifiers if necessary.
6880     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6881     // Promote to void*.
6882     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6883     return destType;
6884   }
6885   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6886     if (getLangOpts().ObjCAutoRefCount) {
6887       // ARC forbids the implicit conversion of object pointers to 'void *',
6888       // so these types are not compatible.
6889       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6890           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6891       LHS = RHS = true;
6892       return QualType();
6893     }
6894     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6895     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6896     QualType destPointee
6897     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6898     QualType destType = Context.getPointerType(destPointee);
6899     // Add qualifiers if necessary.
6900     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6901     // Promote to void*.
6902     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6903     return destType;
6904   }
6905   return QualType();
6906 }
6907 
6908 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6909 /// ParenRange in parentheses.
6910 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6911                                const PartialDiagnostic &Note,
6912                                SourceRange ParenRange) {
6913   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6914   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6915       EndLoc.isValid()) {
6916     Self.Diag(Loc, Note)
6917       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6918       << FixItHint::CreateInsertion(EndLoc, ")");
6919   } else {
6920     // We can't display the parentheses, so just show the bare note.
6921     Self.Diag(Loc, Note) << ParenRange;
6922   }
6923 }
6924 
6925 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6926   return BinaryOperator::isAdditiveOp(Opc) ||
6927          BinaryOperator::isMultiplicativeOp(Opc) ||
6928          BinaryOperator::isShiftOp(Opc);
6929 }
6930 
6931 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6932 /// expression, either using a built-in or overloaded operator,
6933 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6934 /// expression.
6935 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6936                                    Expr **RHSExprs) {
6937   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6938   E = E->IgnoreImpCasts();
6939   E = E->IgnoreConversionOperator();
6940   E = E->IgnoreImpCasts();
6941 
6942   // Built-in binary operator.
6943   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6944     if (IsArithmeticOp(OP->getOpcode())) {
6945       *Opcode = OP->getOpcode();
6946       *RHSExprs = OP->getRHS();
6947       return true;
6948     }
6949   }
6950 
6951   // Overloaded operator.
6952   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6953     if (Call->getNumArgs() != 2)
6954       return false;
6955 
6956     // Make sure this is really a binary operator that is safe to pass into
6957     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6958     OverloadedOperatorKind OO = Call->getOperator();
6959     if (OO < OO_Plus || OO > OO_Arrow ||
6960         OO == OO_PlusPlus || OO == OO_MinusMinus)
6961       return false;
6962 
6963     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6964     if (IsArithmeticOp(OpKind)) {
6965       *Opcode = OpKind;
6966       *RHSExprs = Call->getArg(1);
6967       return true;
6968     }
6969   }
6970 
6971   return false;
6972 }
6973 
6974 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6975 /// or is a logical expression such as (x==y) which has int type, but is
6976 /// commonly interpreted as boolean.
6977 static bool ExprLooksBoolean(Expr *E) {
6978   E = E->IgnoreParenImpCasts();
6979 
6980   if (E->getType()->isBooleanType())
6981     return true;
6982   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6983     return OP->isComparisonOp() || OP->isLogicalOp();
6984   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6985     return OP->getOpcode() == UO_LNot;
6986   if (E->getType()->isPointerType())
6987     return true;
6988 
6989   return false;
6990 }
6991 
6992 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6993 /// and binary operator are mixed in a way that suggests the programmer assumed
6994 /// the conditional operator has higher precedence, for example:
6995 /// "int x = a + someBinaryCondition ? 1 : 2".
6996 static void DiagnoseConditionalPrecedence(Sema &Self,
6997                                           SourceLocation OpLoc,
6998                                           Expr *Condition,
6999                                           Expr *LHSExpr,
7000                                           Expr *RHSExpr) {
7001   BinaryOperatorKind CondOpcode;
7002   Expr *CondRHS;
7003 
7004   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7005     return;
7006   if (!ExprLooksBoolean(CondRHS))
7007     return;
7008 
7009   // The condition is an arithmetic binary expression, with a right-
7010   // hand side that looks boolean, so warn.
7011 
7012   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7013       << Condition->getSourceRange()
7014       << BinaryOperator::getOpcodeStr(CondOpcode);
7015 
7016   SuggestParentheses(Self, OpLoc,
7017     Self.PDiag(diag::note_precedence_silence)
7018       << BinaryOperator::getOpcodeStr(CondOpcode),
7019     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7020 
7021   SuggestParentheses(Self, OpLoc,
7022     Self.PDiag(diag::note_precedence_conditional_first),
7023     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7024 }
7025 
7026 /// Compute the nullability of a conditional expression.
7027 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7028                                               QualType LHSTy, QualType RHSTy,
7029                                               ASTContext &Ctx) {
7030   if (!ResTy->isAnyPointerType())
7031     return ResTy;
7032 
7033   auto GetNullability = [&Ctx](QualType Ty) {
7034     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7035     if (Kind)
7036       return *Kind;
7037     return NullabilityKind::Unspecified;
7038   };
7039 
7040   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7041   NullabilityKind MergedKind;
7042 
7043   // Compute nullability of a binary conditional expression.
7044   if (IsBin) {
7045     if (LHSKind == NullabilityKind::NonNull)
7046       MergedKind = NullabilityKind::NonNull;
7047     else
7048       MergedKind = RHSKind;
7049   // Compute nullability of a normal conditional expression.
7050   } else {
7051     if (LHSKind == NullabilityKind::Nullable ||
7052         RHSKind == NullabilityKind::Nullable)
7053       MergedKind = NullabilityKind::Nullable;
7054     else if (LHSKind == NullabilityKind::NonNull)
7055       MergedKind = RHSKind;
7056     else if (RHSKind == NullabilityKind::NonNull)
7057       MergedKind = LHSKind;
7058     else
7059       MergedKind = NullabilityKind::Unspecified;
7060   }
7061 
7062   // Return if ResTy already has the correct nullability.
7063   if (GetNullability(ResTy) == MergedKind)
7064     return ResTy;
7065 
7066   // Strip all nullability from ResTy.
7067   while (ResTy->getNullability(Ctx))
7068     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7069 
7070   // Create a new AttributedType with the new nullability kind.
7071   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7072   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7073 }
7074 
7075 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7076 /// in the case of a the GNU conditional expr extension.
7077 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7078                                     SourceLocation ColonLoc,
7079                                     Expr *CondExpr, Expr *LHSExpr,
7080                                     Expr *RHSExpr) {
7081   if (!getLangOpts().CPlusPlus) {
7082     // C cannot handle TypoExpr nodes in the condition because it
7083     // doesn't handle dependent types properly, so make sure any TypoExprs have
7084     // been dealt with before checking the operands.
7085     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7086     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7087     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7088 
7089     if (!CondResult.isUsable())
7090       return ExprError();
7091 
7092     if (LHSExpr) {
7093       if (!LHSResult.isUsable())
7094         return ExprError();
7095     }
7096 
7097     if (!RHSResult.isUsable())
7098       return ExprError();
7099 
7100     CondExpr = CondResult.get();
7101     LHSExpr = LHSResult.get();
7102     RHSExpr = RHSResult.get();
7103   }
7104 
7105   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7106   // was the condition.
7107   OpaqueValueExpr *opaqueValue = nullptr;
7108   Expr *commonExpr = nullptr;
7109   if (!LHSExpr) {
7110     commonExpr = CondExpr;
7111     // Lower out placeholder types first.  This is important so that we don't
7112     // try to capture a placeholder. This happens in few cases in C++; such
7113     // as Objective-C++'s dictionary subscripting syntax.
7114     if (commonExpr->hasPlaceholderType()) {
7115       ExprResult result = CheckPlaceholderExpr(commonExpr);
7116       if (!result.isUsable()) return ExprError();
7117       commonExpr = result.get();
7118     }
7119     // We usually want to apply unary conversions *before* saving, except
7120     // in the special case of a C++ l-value conditional.
7121     if (!(getLangOpts().CPlusPlus
7122           && !commonExpr->isTypeDependent()
7123           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7124           && commonExpr->isGLValue()
7125           && commonExpr->isOrdinaryOrBitFieldObject()
7126           && RHSExpr->isOrdinaryOrBitFieldObject()
7127           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7128       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7129       if (commonRes.isInvalid())
7130         return ExprError();
7131       commonExpr = commonRes.get();
7132     }
7133 
7134     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7135                                                 commonExpr->getType(),
7136                                                 commonExpr->getValueKind(),
7137                                                 commonExpr->getObjectKind(),
7138                                                 commonExpr);
7139     LHSExpr = CondExpr = opaqueValue;
7140   }
7141 
7142   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7143   ExprValueKind VK = VK_RValue;
7144   ExprObjectKind OK = OK_Ordinary;
7145   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7146   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7147                                              VK, OK, QuestionLoc);
7148   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7149       RHS.isInvalid())
7150     return ExprError();
7151 
7152   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7153                                 RHS.get());
7154 
7155   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7156 
7157   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7158                                          Context);
7159 
7160   if (!commonExpr)
7161     return new (Context)
7162         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7163                             RHS.get(), result, VK, OK);
7164 
7165   return new (Context) BinaryConditionalOperator(
7166       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7167       ColonLoc, result, VK, OK);
7168 }
7169 
7170 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7171 // being closely modeled after the C99 spec:-). The odd characteristic of this
7172 // routine is it effectively iqnores the qualifiers on the top level pointee.
7173 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7174 // FIXME: add a couple examples in this comment.
7175 static Sema::AssignConvertType
7176 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7177   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7178   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7179 
7180   // get the "pointed to" type (ignoring qualifiers at the top level)
7181   const Type *lhptee, *rhptee;
7182   Qualifiers lhq, rhq;
7183   std::tie(lhptee, lhq) =
7184       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7185   std::tie(rhptee, rhq) =
7186       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7187 
7188   Sema::AssignConvertType ConvTy = Sema::Compatible;
7189 
7190   // C99 6.5.16.1p1: This following citation is common to constraints
7191   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7192   // qualifiers of the type *pointed to* by the right;
7193 
7194   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7195   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7196       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7197     // Ignore lifetime for further calculation.
7198     lhq.removeObjCLifetime();
7199     rhq.removeObjCLifetime();
7200   }
7201 
7202   if (!lhq.compatiblyIncludes(rhq)) {
7203     // Treat address-space mismatches as fatal.  TODO: address subspaces
7204     if (!lhq.isAddressSpaceSupersetOf(rhq))
7205       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7206 
7207     // It's okay to add or remove GC or lifetime qualifiers when converting to
7208     // and from void*.
7209     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7210                         .compatiblyIncludes(
7211                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7212              && (lhptee->isVoidType() || rhptee->isVoidType()))
7213       ; // keep old
7214 
7215     // Treat lifetime mismatches as fatal.
7216     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7217       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7218 
7219     // For GCC/MS compatibility, other qualifier mismatches are treated
7220     // as still compatible in C.
7221     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7222   }
7223 
7224   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7225   // incomplete type and the other is a pointer to a qualified or unqualified
7226   // version of void...
7227   if (lhptee->isVoidType()) {
7228     if (rhptee->isIncompleteOrObjectType())
7229       return ConvTy;
7230 
7231     // As an extension, we allow cast to/from void* to function pointer.
7232     assert(rhptee->isFunctionType());
7233     return Sema::FunctionVoidPointer;
7234   }
7235 
7236   if (rhptee->isVoidType()) {
7237     if (lhptee->isIncompleteOrObjectType())
7238       return ConvTy;
7239 
7240     // As an extension, we allow cast to/from void* to function pointer.
7241     assert(lhptee->isFunctionType());
7242     return Sema::FunctionVoidPointer;
7243   }
7244 
7245   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7246   // unqualified versions of compatible types, ...
7247   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7248   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7249     // Check if the pointee types are compatible ignoring the sign.
7250     // We explicitly check for char so that we catch "char" vs
7251     // "unsigned char" on systems where "char" is unsigned.
7252     if (lhptee->isCharType())
7253       ltrans = S.Context.UnsignedCharTy;
7254     else if (lhptee->hasSignedIntegerRepresentation())
7255       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7256 
7257     if (rhptee->isCharType())
7258       rtrans = S.Context.UnsignedCharTy;
7259     else if (rhptee->hasSignedIntegerRepresentation())
7260       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7261 
7262     if (ltrans == rtrans) {
7263       // Types are compatible ignoring the sign. Qualifier incompatibility
7264       // takes priority over sign incompatibility because the sign
7265       // warning can be disabled.
7266       if (ConvTy != Sema::Compatible)
7267         return ConvTy;
7268 
7269       return Sema::IncompatiblePointerSign;
7270     }
7271 
7272     // If we are a multi-level pointer, it's possible that our issue is simply
7273     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7274     // the eventual target type is the same and the pointers have the same
7275     // level of indirection, this must be the issue.
7276     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7277       do {
7278         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7279         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7280       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7281 
7282       if (lhptee == rhptee)
7283         return Sema::IncompatibleNestedPointerQualifiers;
7284     }
7285 
7286     // General pointer incompatibility takes priority over qualifiers.
7287     return Sema::IncompatiblePointer;
7288   }
7289   if (!S.getLangOpts().CPlusPlus &&
7290       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7291     return Sema::IncompatiblePointer;
7292   return ConvTy;
7293 }
7294 
7295 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7296 /// block pointer types are compatible or whether a block and normal pointer
7297 /// are compatible. It is more restrict than comparing two function pointer
7298 // types.
7299 static Sema::AssignConvertType
7300 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7301                                     QualType RHSType) {
7302   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7303   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7304 
7305   QualType lhptee, rhptee;
7306 
7307   // get the "pointed to" type (ignoring qualifiers at the top level)
7308   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7309   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7310 
7311   // In C++, the types have to match exactly.
7312   if (S.getLangOpts().CPlusPlus)
7313     return Sema::IncompatibleBlockPointer;
7314 
7315   Sema::AssignConvertType ConvTy = Sema::Compatible;
7316 
7317   // For blocks we enforce that qualifiers are identical.
7318   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7319     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7320 
7321   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7322     return Sema::IncompatibleBlockPointer;
7323 
7324   return ConvTy;
7325 }
7326 
7327 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7328 /// for assignment compatibility.
7329 static Sema::AssignConvertType
7330 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7331                                    QualType RHSType) {
7332   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7333   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7334 
7335   if (LHSType->isObjCBuiltinType()) {
7336     // Class is not compatible with ObjC object pointers.
7337     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7338         !RHSType->isObjCQualifiedClassType())
7339       return Sema::IncompatiblePointer;
7340     return Sema::Compatible;
7341   }
7342   if (RHSType->isObjCBuiltinType()) {
7343     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7344         !LHSType->isObjCQualifiedClassType())
7345       return Sema::IncompatiblePointer;
7346     return Sema::Compatible;
7347   }
7348   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7349   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7350 
7351   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7352       // make an exception for id<P>
7353       !LHSType->isObjCQualifiedIdType())
7354     return Sema::CompatiblePointerDiscardsQualifiers;
7355 
7356   if (S.Context.typesAreCompatible(LHSType, RHSType))
7357     return Sema::Compatible;
7358   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7359     return Sema::IncompatibleObjCQualifiedId;
7360   return Sema::IncompatiblePointer;
7361 }
7362 
7363 Sema::AssignConvertType
7364 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7365                                  QualType LHSType, QualType RHSType) {
7366   // Fake up an opaque expression.  We don't actually care about what
7367   // cast operations are required, so if CheckAssignmentConstraints
7368   // adds casts to this they'll be wasted, but fortunately that doesn't
7369   // usually happen on valid code.
7370   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7371   ExprResult RHSPtr = &RHSExpr;
7372   CastKind K = CK_Invalid;
7373 
7374   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7375 }
7376 
7377 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7378 /// has code to accommodate several GCC extensions when type checking
7379 /// pointers. Here are some objectionable examples that GCC considers warnings:
7380 ///
7381 ///  int a, *pint;
7382 ///  short *pshort;
7383 ///  struct foo *pfoo;
7384 ///
7385 ///  pint = pshort; // warning: assignment from incompatible pointer type
7386 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7387 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7388 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7389 ///
7390 /// As a result, the code for dealing with pointers is more complex than the
7391 /// C99 spec dictates.
7392 ///
7393 /// Sets 'Kind' for any result kind except Incompatible.
7394 Sema::AssignConvertType
7395 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7396                                  CastKind &Kind, bool ConvertRHS) {
7397   QualType RHSType = RHS.get()->getType();
7398   QualType OrigLHSType = LHSType;
7399 
7400   // Get canonical types.  We're not formatting these types, just comparing
7401   // them.
7402   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7403   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7404 
7405   // Common case: no conversion required.
7406   if (LHSType == RHSType) {
7407     Kind = CK_NoOp;
7408     return Compatible;
7409   }
7410 
7411   // If we have an atomic type, try a non-atomic assignment, then just add an
7412   // atomic qualification step.
7413   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7414     Sema::AssignConvertType result =
7415       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7416     if (result != Compatible)
7417       return result;
7418     if (Kind != CK_NoOp && ConvertRHS)
7419       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7420     Kind = CK_NonAtomicToAtomic;
7421     return Compatible;
7422   }
7423 
7424   // If the left-hand side is a reference type, then we are in a
7425   // (rare!) case where we've allowed the use of references in C,
7426   // e.g., as a parameter type in a built-in function. In this case,
7427   // just make sure that the type referenced is compatible with the
7428   // right-hand side type. The caller is responsible for adjusting
7429   // LHSType so that the resulting expression does not have reference
7430   // type.
7431   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7432     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7433       Kind = CK_LValueBitCast;
7434       return Compatible;
7435     }
7436     return Incompatible;
7437   }
7438 
7439   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7440   // to the same ExtVector type.
7441   if (LHSType->isExtVectorType()) {
7442     if (RHSType->isExtVectorType())
7443       return Incompatible;
7444     if (RHSType->isArithmeticType()) {
7445       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7446       if (ConvertRHS)
7447         RHS = prepareVectorSplat(LHSType, RHS.get());
7448       Kind = CK_VectorSplat;
7449       return Compatible;
7450     }
7451   }
7452 
7453   // Conversions to or from vector type.
7454   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7455     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7456       // Allow assignments of an AltiVec vector type to an equivalent GCC
7457       // vector type and vice versa
7458       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7459         Kind = CK_BitCast;
7460         return Compatible;
7461       }
7462 
7463       // If we are allowing lax vector conversions, and LHS and RHS are both
7464       // vectors, the total size only needs to be the same. This is a bitcast;
7465       // no bits are changed but the result type is different.
7466       if (isLaxVectorConversion(RHSType, LHSType)) {
7467         Kind = CK_BitCast;
7468         return IncompatibleVectors;
7469       }
7470     }
7471 
7472     // When the RHS comes from another lax conversion (e.g. binops between
7473     // scalars and vectors) the result is canonicalized as a vector. When the
7474     // LHS is also a vector, the lax is allowed by the condition above. Handle
7475     // the case where LHS is a scalar.
7476     if (LHSType->isScalarType()) {
7477       const VectorType *VecType = RHSType->getAs<VectorType>();
7478       if (VecType && VecType->getNumElements() == 1 &&
7479           isLaxVectorConversion(RHSType, LHSType)) {
7480         ExprResult *VecExpr = &RHS;
7481         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7482         Kind = CK_BitCast;
7483         return Compatible;
7484       }
7485     }
7486 
7487     return Incompatible;
7488   }
7489 
7490   // Diagnose attempts to convert between __float128 and long double where
7491   // such conversions currently can't be handled.
7492   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7493     return Incompatible;
7494 
7495   // Arithmetic conversions.
7496   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7497       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7498     if (ConvertRHS)
7499       Kind = PrepareScalarCast(RHS, LHSType);
7500     return Compatible;
7501   }
7502 
7503   // Conversions to normal pointers.
7504   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7505     // U* -> T*
7506     if (isa<PointerType>(RHSType)) {
7507       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7508       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7509       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7510       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7511     }
7512 
7513     // int -> T*
7514     if (RHSType->isIntegerType()) {
7515       Kind = CK_IntegralToPointer; // FIXME: null?
7516       return IntToPointer;
7517     }
7518 
7519     // C pointers are not compatible with ObjC object pointers,
7520     // with two exceptions:
7521     if (isa<ObjCObjectPointerType>(RHSType)) {
7522       //  - conversions to void*
7523       if (LHSPointer->getPointeeType()->isVoidType()) {
7524         Kind = CK_BitCast;
7525         return Compatible;
7526       }
7527 
7528       //  - conversions from 'Class' to the redefinition type
7529       if (RHSType->isObjCClassType() &&
7530           Context.hasSameType(LHSType,
7531                               Context.getObjCClassRedefinitionType())) {
7532         Kind = CK_BitCast;
7533         return Compatible;
7534       }
7535 
7536       Kind = CK_BitCast;
7537       return IncompatiblePointer;
7538     }
7539 
7540     // U^ -> void*
7541     if (RHSType->getAs<BlockPointerType>()) {
7542       if (LHSPointer->getPointeeType()->isVoidType()) {
7543         Kind = CK_BitCast;
7544         return Compatible;
7545       }
7546     }
7547 
7548     return Incompatible;
7549   }
7550 
7551   // Conversions to block pointers.
7552   if (isa<BlockPointerType>(LHSType)) {
7553     // U^ -> T^
7554     if (RHSType->isBlockPointerType()) {
7555       Kind = CK_BitCast;
7556       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7557     }
7558 
7559     // int or null -> T^
7560     if (RHSType->isIntegerType()) {
7561       Kind = CK_IntegralToPointer; // FIXME: null
7562       return IntToBlockPointer;
7563     }
7564 
7565     // id -> T^
7566     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7567       Kind = CK_AnyPointerToBlockPointerCast;
7568       return Compatible;
7569     }
7570 
7571     // void* -> T^
7572     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7573       if (RHSPT->getPointeeType()->isVoidType()) {
7574         Kind = CK_AnyPointerToBlockPointerCast;
7575         return Compatible;
7576       }
7577 
7578     return Incompatible;
7579   }
7580 
7581   // Conversions to Objective-C pointers.
7582   if (isa<ObjCObjectPointerType>(LHSType)) {
7583     // A* -> B*
7584     if (RHSType->isObjCObjectPointerType()) {
7585       Kind = CK_BitCast;
7586       Sema::AssignConvertType result =
7587         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7588       if (getLangOpts().ObjCAutoRefCount &&
7589           result == Compatible &&
7590           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7591         result = IncompatibleObjCWeakRef;
7592       return result;
7593     }
7594 
7595     // int or null -> A*
7596     if (RHSType->isIntegerType()) {
7597       Kind = CK_IntegralToPointer; // FIXME: null
7598       return IntToPointer;
7599     }
7600 
7601     // In general, C pointers are not compatible with ObjC object pointers,
7602     // with two exceptions:
7603     if (isa<PointerType>(RHSType)) {
7604       Kind = CK_CPointerToObjCPointerCast;
7605 
7606       //  - conversions from 'void*'
7607       if (RHSType->isVoidPointerType()) {
7608         return Compatible;
7609       }
7610 
7611       //  - conversions to 'Class' from its redefinition type
7612       if (LHSType->isObjCClassType() &&
7613           Context.hasSameType(RHSType,
7614                               Context.getObjCClassRedefinitionType())) {
7615         return Compatible;
7616       }
7617 
7618       return IncompatiblePointer;
7619     }
7620 
7621     // Only under strict condition T^ is compatible with an Objective-C pointer.
7622     if (RHSType->isBlockPointerType() &&
7623         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7624       if (ConvertRHS)
7625         maybeExtendBlockObject(RHS);
7626       Kind = CK_BlockPointerToObjCPointerCast;
7627       return Compatible;
7628     }
7629 
7630     return Incompatible;
7631   }
7632 
7633   // Conversions from pointers that are not covered by the above.
7634   if (isa<PointerType>(RHSType)) {
7635     // T* -> _Bool
7636     if (LHSType == Context.BoolTy) {
7637       Kind = CK_PointerToBoolean;
7638       return Compatible;
7639     }
7640 
7641     // T* -> int
7642     if (LHSType->isIntegerType()) {
7643       Kind = CK_PointerToIntegral;
7644       return PointerToInt;
7645     }
7646 
7647     return Incompatible;
7648   }
7649 
7650   // Conversions from Objective-C pointers that are not covered by the above.
7651   if (isa<ObjCObjectPointerType>(RHSType)) {
7652     // T* -> _Bool
7653     if (LHSType == Context.BoolTy) {
7654       Kind = CK_PointerToBoolean;
7655       return Compatible;
7656     }
7657 
7658     // T* -> int
7659     if (LHSType->isIntegerType()) {
7660       Kind = CK_PointerToIntegral;
7661       return PointerToInt;
7662     }
7663 
7664     return Incompatible;
7665   }
7666 
7667   // struct A -> struct B
7668   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7669     if (Context.typesAreCompatible(LHSType, RHSType)) {
7670       Kind = CK_NoOp;
7671       return Compatible;
7672     }
7673   }
7674 
7675   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7676     Kind = CK_IntToOCLSampler;
7677     return Compatible;
7678   }
7679 
7680   return Incompatible;
7681 }
7682 
7683 /// \brief Constructs a transparent union from an expression that is
7684 /// used to initialize the transparent union.
7685 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7686                                       ExprResult &EResult, QualType UnionType,
7687                                       FieldDecl *Field) {
7688   // Build an initializer list that designates the appropriate member
7689   // of the transparent union.
7690   Expr *E = EResult.get();
7691   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7692                                                    E, SourceLocation());
7693   Initializer->setType(UnionType);
7694   Initializer->setInitializedFieldInUnion(Field);
7695 
7696   // Build a compound literal constructing a value of the transparent
7697   // union type from this initializer list.
7698   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7699   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7700                                         VK_RValue, Initializer, false);
7701 }
7702 
7703 Sema::AssignConvertType
7704 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7705                                                ExprResult &RHS) {
7706   QualType RHSType = RHS.get()->getType();
7707 
7708   // If the ArgType is a Union type, we want to handle a potential
7709   // transparent_union GCC extension.
7710   const RecordType *UT = ArgType->getAsUnionType();
7711   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7712     return Incompatible;
7713 
7714   // The field to initialize within the transparent union.
7715   RecordDecl *UD = UT->getDecl();
7716   FieldDecl *InitField = nullptr;
7717   // It's compatible if the expression matches any of the fields.
7718   for (auto *it : UD->fields()) {
7719     if (it->getType()->isPointerType()) {
7720       // If the transparent union contains a pointer type, we allow:
7721       // 1) void pointer
7722       // 2) null pointer constant
7723       if (RHSType->isPointerType())
7724         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7725           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7726           InitField = it;
7727           break;
7728         }
7729 
7730       if (RHS.get()->isNullPointerConstant(Context,
7731                                            Expr::NPC_ValueDependentIsNull)) {
7732         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7733                                 CK_NullToPointer);
7734         InitField = it;
7735         break;
7736       }
7737     }
7738 
7739     CastKind Kind = CK_Invalid;
7740     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7741           == Compatible) {
7742       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7743       InitField = it;
7744       break;
7745     }
7746   }
7747 
7748   if (!InitField)
7749     return Incompatible;
7750 
7751   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7752   return Compatible;
7753 }
7754 
7755 Sema::AssignConvertType
7756 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7757                                        bool Diagnose,
7758                                        bool DiagnoseCFAudited,
7759                                        bool ConvertRHS) {
7760   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7761   // we can't avoid *all* modifications at the moment, so we need some somewhere
7762   // to put the updated value.
7763   ExprResult LocalRHS = CallerRHS;
7764   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7765 
7766   if (getLangOpts().CPlusPlus) {
7767     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7768       // C++ 5.17p3: If the left operand is not of class type, the
7769       // expression is implicitly converted (C++ 4) to the
7770       // cv-unqualified type of the left operand.
7771       ExprResult Res;
7772       if (Diagnose) {
7773         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7774                                         AA_Assigning);
7775       } else {
7776         ImplicitConversionSequence ICS =
7777             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7778                                   /*SuppressUserConversions=*/false,
7779                                   /*AllowExplicit=*/false,
7780                                   /*InOverloadResolution=*/false,
7781                                   /*CStyle=*/false,
7782                                   /*AllowObjCWritebackConversion=*/false);
7783         if (ICS.isFailure())
7784           return Incompatible;
7785         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7786                                         ICS, AA_Assigning);
7787       }
7788       if (Res.isInvalid())
7789         return Incompatible;
7790       Sema::AssignConvertType result = Compatible;
7791       if (getLangOpts().ObjCAutoRefCount &&
7792           !CheckObjCARCUnavailableWeakConversion(LHSType,
7793                                                  RHS.get()->getType()))
7794         result = IncompatibleObjCWeakRef;
7795       RHS = Res;
7796       return result;
7797     }
7798 
7799     // FIXME: Currently, we fall through and treat C++ classes like C
7800     // structures.
7801     // FIXME: We also fall through for atomics; not sure what should
7802     // happen there, though.
7803   } else if (RHS.get()->getType() == Context.OverloadTy) {
7804     // As a set of extensions to C, we support overloading on functions. These
7805     // functions need to be resolved here.
7806     DeclAccessPair DAP;
7807     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7808             RHS.get(), LHSType, /*Complain=*/false, DAP))
7809       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7810     else
7811       return Incompatible;
7812   }
7813 
7814   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7815   // a null pointer constant.
7816   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7817        LHSType->isBlockPointerType()) &&
7818       RHS.get()->isNullPointerConstant(Context,
7819                                        Expr::NPC_ValueDependentIsNull)) {
7820     if (Diagnose || ConvertRHS) {
7821       CastKind Kind;
7822       CXXCastPath Path;
7823       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7824                              /*IgnoreBaseAccess=*/false, Diagnose);
7825       if (ConvertRHS)
7826         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7827     }
7828     return Compatible;
7829   }
7830 
7831   // This check seems unnatural, however it is necessary to ensure the proper
7832   // conversion of functions/arrays. If the conversion were done for all
7833   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7834   // expressions that suppress this implicit conversion (&, sizeof).
7835   //
7836   // Suppress this for references: C++ 8.5.3p5.
7837   if (!LHSType->isReferenceType()) {
7838     // FIXME: We potentially allocate here even if ConvertRHS is false.
7839     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7840     if (RHS.isInvalid())
7841       return Incompatible;
7842   }
7843 
7844   Expr *PRE = RHS.get()->IgnoreParenCasts();
7845   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7846     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7847     if (PDecl && !PDecl->hasDefinition()) {
7848       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7849       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7850     }
7851   }
7852 
7853   CastKind Kind = CK_Invalid;
7854   Sema::AssignConvertType result =
7855     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7856 
7857   // C99 6.5.16.1p2: The value of the right operand is converted to the
7858   // type of the assignment expression.
7859   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7860   // so that we can use references in built-in functions even in C.
7861   // The getNonReferenceType() call makes sure that the resulting expression
7862   // does not have reference type.
7863   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7864     QualType Ty = LHSType.getNonLValueExprType(Context);
7865     Expr *E = RHS.get();
7866 
7867     // Check for various Objective-C errors. If we are not reporting
7868     // diagnostics and just checking for errors, e.g., during overload
7869     // resolution, return Incompatible to indicate the failure.
7870     if (getLangOpts().ObjCAutoRefCount &&
7871         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7872                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7873       if (!Diagnose)
7874         return Incompatible;
7875     }
7876     if (getLangOpts().ObjC1 &&
7877         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7878                                            E->getType(), E, Diagnose) ||
7879          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7880       if (!Diagnose)
7881         return Incompatible;
7882       // Replace the expression with a corrected version and continue so we
7883       // can find further errors.
7884       RHS = E;
7885       return Compatible;
7886     }
7887 
7888     if (ConvertRHS)
7889       RHS = ImpCastExprToType(E, Ty, Kind);
7890   }
7891   return result;
7892 }
7893 
7894 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7895                                ExprResult &RHS) {
7896   Diag(Loc, diag::err_typecheck_invalid_operands)
7897     << LHS.get()->getType() << RHS.get()->getType()
7898     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7899   return QualType();
7900 }
7901 
7902 /// Try to convert a value of non-vector type to a vector type by converting
7903 /// the type to the element type of the vector and then performing a splat.
7904 /// If the language is OpenCL, we only use conversions that promote scalar
7905 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7906 /// for float->int.
7907 ///
7908 /// \param scalar - if non-null, actually perform the conversions
7909 /// \return true if the operation fails (but without diagnosing the failure)
7910 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7911                                      QualType scalarTy,
7912                                      QualType vectorEltTy,
7913                                      QualType vectorTy) {
7914   // The conversion to apply to the scalar before splatting it,
7915   // if necessary.
7916   CastKind scalarCast = CK_Invalid;
7917 
7918   if (vectorEltTy->isIntegralType(S.Context)) {
7919     if (!scalarTy->isIntegralType(S.Context))
7920       return true;
7921     if (S.getLangOpts().OpenCL &&
7922         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7923       return true;
7924     scalarCast = CK_IntegralCast;
7925   } else if (vectorEltTy->isRealFloatingType()) {
7926     if (scalarTy->isRealFloatingType()) {
7927       if (S.getLangOpts().OpenCL &&
7928           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7929         return true;
7930       scalarCast = CK_FloatingCast;
7931     }
7932     else if (scalarTy->isIntegralType(S.Context))
7933       scalarCast = CK_IntegralToFloating;
7934     else
7935       return true;
7936   } else {
7937     return true;
7938   }
7939 
7940   // Adjust scalar if desired.
7941   if (scalar) {
7942     if (scalarCast != CK_Invalid)
7943       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7944     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7945   }
7946   return false;
7947 }
7948 
7949 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7950                                    SourceLocation Loc, bool IsCompAssign,
7951                                    bool AllowBothBool,
7952                                    bool AllowBoolConversions) {
7953   if (!IsCompAssign) {
7954     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7955     if (LHS.isInvalid())
7956       return QualType();
7957   }
7958   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7959   if (RHS.isInvalid())
7960     return QualType();
7961 
7962   // For conversion purposes, we ignore any qualifiers.
7963   // For example, "const float" and "float" are equivalent.
7964   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7965   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7966 
7967   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7968   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7969   assert(LHSVecType || RHSVecType);
7970 
7971   // AltiVec-style "vector bool op vector bool" combinations are allowed
7972   // for some operators but not others.
7973   if (!AllowBothBool &&
7974       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7975       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7976     return InvalidOperands(Loc, LHS, RHS);
7977 
7978   // If the vector types are identical, return.
7979   if (Context.hasSameType(LHSType, RHSType))
7980     return LHSType;
7981 
7982   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7983   if (LHSVecType && RHSVecType &&
7984       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7985     if (isa<ExtVectorType>(LHSVecType)) {
7986       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7987       return LHSType;
7988     }
7989 
7990     if (!IsCompAssign)
7991       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7992     return RHSType;
7993   }
7994 
7995   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7996   // can be mixed, with the result being the non-bool type.  The non-bool
7997   // operand must have integer element type.
7998   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7999       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8000       (Context.getTypeSize(LHSVecType->getElementType()) ==
8001        Context.getTypeSize(RHSVecType->getElementType()))) {
8002     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8003         LHSVecType->getElementType()->isIntegerType() &&
8004         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8005       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8006       return LHSType;
8007     }
8008     if (!IsCompAssign &&
8009         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8010         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8011         RHSVecType->getElementType()->isIntegerType()) {
8012       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8013       return RHSType;
8014     }
8015   }
8016 
8017   // If there's an ext-vector type and a scalar, try to convert the scalar to
8018   // the vector element type and splat.
8019   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8020     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8021                                   LHSVecType->getElementType(), LHSType))
8022       return LHSType;
8023   }
8024   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8025     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8026                                   LHSType, RHSVecType->getElementType(),
8027                                   RHSType))
8028       return RHSType;
8029   }
8030 
8031   // If we're allowing lax vector conversions, only the total (data) size needs
8032   // to be the same. If one of the types is scalar, the result is always the
8033   // vector type. Don't allow this if the scalar operand is an lvalue.
8034   QualType VecType = LHSVecType ? LHSType : RHSType;
8035   QualType ScalarType = LHSVecType ? RHSType : LHSType;
8036   ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS;
8037   if (isLaxVectorConversion(ScalarType, VecType) &&
8038       !ScalarExpr->get()->isLValue()) {
8039     *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast);
8040     return VecType;
8041   }
8042 
8043   // Okay, the expression is invalid.
8044 
8045   // If there's a non-vector, non-real operand, diagnose that.
8046   if ((!RHSVecType && !RHSType->isRealType()) ||
8047       (!LHSVecType && !LHSType->isRealType())) {
8048     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8049       << LHSType << RHSType
8050       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8051     return QualType();
8052   }
8053 
8054   // OpenCL V1.1 6.2.6.p1:
8055   // If the operands are of more than one vector type, then an error shall
8056   // occur. Implicit conversions between vector types are not permitted, per
8057   // section 6.2.1.
8058   if (getLangOpts().OpenCL &&
8059       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8060       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8061     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8062                                                            << RHSType;
8063     return QualType();
8064   }
8065 
8066   // Otherwise, use the generic diagnostic.
8067   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8068     << LHSType << RHSType
8069     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8070   return QualType();
8071 }
8072 
8073 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8074 // expression.  These are mainly cases where the null pointer is used as an
8075 // integer instead of a pointer.
8076 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8077                                 SourceLocation Loc, bool IsCompare) {
8078   // The canonical way to check for a GNU null is with isNullPointerConstant,
8079   // but we use a bit of a hack here for speed; this is a relatively
8080   // hot path, and isNullPointerConstant is slow.
8081   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8082   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8083 
8084   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8085 
8086   // Avoid analyzing cases where the result will either be invalid (and
8087   // diagnosed as such) or entirely valid and not something to warn about.
8088   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8089       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8090     return;
8091 
8092   // Comparison operations would not make sense with a null pointer no matter
8093   // what the other expression is.
8094   if (!IsCompare) {
8095     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8096         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8097         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8098     return;
8099   }
8100 
8101   // The rest of the operations only make sense with a null pointer
8102   // if the other expression is a pointer.
8103   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8104       NonNullType->canDecayToPointerType())
8105     return;
8106 
8107   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8108       << LHSNull /* LHS is NULL */ << NonNullType
8109       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8110 }
8111 
8112 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8113                                                ExprResult &RHS,
8114                                                SourceLocation Loc, bool IsDiv) {
8115   // Check for division/remainder by zero.
8116   llvm::APSInt RHSValue;
8117   if (!RHS.get()->isValueDependent() &&
8118       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8119     S.DiagRuntimeBehavior(Loc, RHS.get(),
8120                           S.PDiag(diag::warn_remainder_division_by_zero)
8121                             << IsDiv << RHS.get()->getSourceRange());
8122 }
8123 
8124 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8125                                            SourceLocation Loc,
8126                                            bool IsCompAssign, bool IsDiv) {
8127   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8128 
8129   if (LHS.get()->getType()->isVectorType() ||
8130       RHS.get()->getType()->isVectorType())
8131     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8132                                /*AllowBothBool*/getLangOpts().AltiVec,
8133                                /*AllowBoolConversions*/false);
8134 
8135   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8136   if (LHS.isInvalid() || RHS.isInvalid())
8137     return QualType();
8138 
8139 
8140   if (compType.isNull() || !compType->isArithmeticType())
8141     return InvalidOperands(Loc, LHS, RHS);
8142   if (IsDiv)
8143     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8144   return compType;
8145 }
8146 
8147 QualType Sema::CheckRemainderOperands(
8148   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8149   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8150 
8151   if (LHS.get()->getType()->isVectorType() ||
8152       RHS.get()->getType()->isVectorType()) {
8153     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8154         RHS.get()->getType()->hasIntegerRepresentation())
8155       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8156                                  /*AllowBothBool*/getLangOpts().AltiVec,
8157                                  /*AllowBoolConversions*/false);
8158     return InvalidOperands(Loc, LHS, RHS);
8159   }
8160 
8161   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8162   if (LHS.isInvalid() || RHS.isInvalid())
8163     return QualType();
8164 
8165   if (compType.isNull() || !compType->isIntegerType())
8166     return InvalidOperands(Loc, LHS, RHS);
8167   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8168   return compType;
8169 }
8170 
8171 /// \brief Diagnose invalid arithmetic on two void pointers.
8172 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8173                                                 Expr *LHSExpr, Expr *RHSExpr) {
8174   S.Diag(Loc, S.getLangOpts().CPlusPlus
8175                 ? diag::err_typecheck_pointer_arith_void_type
8176                 : diag::ext_gnu_void_ptr)
8177     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8178                             << RHSExpr->getSourceRange();
8179 }
8180 
8181 /// \brief Diagnose invalid arithmetic on a void pointer.
8182 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8183                                             Expr *Pointer) {
8184   S.Diag(Loc, S.getLangOpts().CPlusPlus
8185                 ? diag::err_typecheck_pointer_arith_void_type
8186                 : diag::ext_gnu_void_ptr)
8187     << 0 /* one pointer */ << Pointer->getSourceRange();
8188 }
8189 
8190 /// \brief Diagnose invalid arithmetic on two function pointers.
8191 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8192                                                     Expr *LHS, Expr *RHS) {
8193   assert(LHS->getType()->isAnyPointerType());
8194   assert(RHS->getType()->isAnyPointerType());
8195   S.Diag(Loc, S.getLangOpts().CPlusPlus
8196                 ? diag::err_typecheck_pointer_arith_function_type
8197                 : diag::ext_gnu_ptr_func_arith)
8198     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8199     // We only show the second type if it differs from the first.
8200     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8201                                                    RHS->getType())
8202     << RHS->getType()->getPointeeType()
8203     << LHS->getSourceRange() << RHS->getSourceRange();
8204 }
8205 
8206 /// \brief Diagnose invalid arithmetic on a function pointer.
8207 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8208                                                 Expr *Pointer) {
8209   assert(Pointer->getType()->isAnyPointerType());
8210   S.Diag(Loc, S.getLangOpts().CPlusPlus
8211                 ? diag::err_typecheck_pointer_arith_function_type
8212                 : diag::ext_gnu_ptr_func_arith)
8213     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8214     << 0 /* one pointer, so only one type */
8215     << Pointer->getSourceRange();
8216 }
8217 
8218 /// \brief Emit error if Operand is incomplete pointer type
8219 ///
8220 /// \returns True if pointer has incomplete type
8221 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8222                                                  Expr *Operand) {
8223   QualType ResType = Operand->getType();
8224   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8225     ResType = ResAtomicType->getValueType();
8226 
8227   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8228   QualType PointeeTy = ResType->getPointeeType();
8229   return S.RequireCompleteType(Loc, PointeeTy,
8230                                diag::err_typecheck_arithmetic_incomplete_type,
8231                                PointeeTy, Operand->getSourceRange());
8232 }
8233 
8234 /// \brief Check the validity of an arithmetic pointer operand.
8235 ///
8236 /// If the operand has pointer type, this code will check for pointer types
8237 /// which are invalid in arithmetic operations. These will be diagnosed
8238 /// appropriately, including whether or not the use is supported as an
8239 /// extension.
8240 ///
8241 /// \returns True when the operand is valid to use (even if as an extension).
8242 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8243                                             Expr *Operand) {
8244   QualType ResType = Operand->getType();
8245   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8246     ResType = ResAtomicType->getValueType();
8247 
8248   if (!ResType->isAnyPointerType()) return true;
8249 
8250   QualType PointeeTy = ResType->getPointeeType();
8251   if (PointeeTy->isVoidType()) {
8252     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8253     return !S.getLangOpts().CPlusPlus;
8254   }
8255   if (PointeeTy->isFunctionType()) {
8256     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8257     return !S.getLangOpts().CPlusPlus;
8258   }
8259 
8260   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8261 
8262   return true;
8263 }
8264 
8265 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8266 /// operands.
8267 ///
8268 /// This routine will diagnose any invalid arithmetic on pointer operands much
8269 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8270 /// for emitting a single diagnostic even for operations where both LHS and RHS
8271 /// are (potentially problematic) pointers.
8272 ///
8273 /// \returns True when the operand is valid to use (even if as an extension).
8274 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8275                                                 Expr *LHSExpr, Expr *RHSExpr) {
8276   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8277   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8278   if (!isLHSPointer && !isRHSPointer) return true;
8279 
8280   QualType LHSPointeeTy, RHSPointeeTy;
8281   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8282   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8283 
8284   // if both are pointers check if operation is valid wrt address spaces
8285   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8286     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8287     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8288     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8289       S.Diag(Loc,
8290              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8291           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8292           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8293       return false;
8294     }
8295   }
8296 
8297   // Check for arithmetic on pointers to incomplete types.
8298   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8299   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8300   if (isLHSVoidPtr || isRHSVoidPtr) {
8301     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8302     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8303     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8304 
8305     return !S.getLangOpts().CPlusPlus;
8306   }
8307 
8308   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8309   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8310   if (isLHSFuncPtr || isRHSFuncPtr) {
8311     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8312     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8313                                                                 RHSExpr);
8314     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8315 
8316     return !S.getLangOpts().CPlusPlus;
8317   }
8318 
8319   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8320     return false;
8321   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8322     return false;
8323 
8324   return true;
8325 }
8326 
8327 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8328 /// literal.
8329 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8330                                   Expr *LHSExpr, Expr *RHSExpr) {
8331   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8332   Expr* IndexExpr = RHSExpr;
8333   if (!StrExpr) {
8334     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8335     IndexExpr = LHSExpr;
8336   }
8337 
8338   bool IsStringPlusInt = StrExpr &&
8339       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8340   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8341     return;
8342 
8343   llvm::APSInt index;
8344   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8345     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8346     if (index.isNonNegative() &&
8347         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8348                               index.isUnsigned()))
8349       return;
8350   }
8351 
8352   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8353   Self.Diag(OpLoc, diag::warn_string_plus_int)
8354       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8355 
8356   // Only print a fixit for "str" + int, not for int + "str".
8357   if (IndexExpr == RHSExpr) {
8358     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8359     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8360         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8361         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8362         << FixItHint::CreateInsertion(EndLoc, "]");
8363   } else
8364     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8365 }
8366 
8367 /// \brief Emit a warning when adding a char literal to a string.
8368 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8369                                    Expr *LHSExpr, Expr *RHSExpr) {
8370   const Expr *StringRefExpr = LHSExpr;
8371   const CharacterLiteral *CharExpr =
8372       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8373 
8374   if (!CharExpr) {
8375     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8376     StringRefExpr = RHSExpr;
8377   }
8378 
8379   if (!CharExpr || !StringRefExpr)
8380     return;
8381 
8382   const QualType StringType = StringRefExpr->getType();
8383 
8384   // Return if not a PointerType.
8385   if (!StringType->isAnyPointerType())
8386     return;
8387 
8388   // Return if not a CharacterType.
8389   if (!StringType->getPointeeType()->isAnyCharacterType())
8390     return;
8391 
8392   ASTContext &Ctx = Self.getASTContext();
8393   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8394 
8395   const QualType CharType = CharExpr->getType();
8396   if (!CharType->isAnyCharacterType() &&
8397       CharType->isIntegerType() &&
8398       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8399     Self.Diag(OpLoc, diag::warn_string_plus_char)
8400         << DiagRange << Ctx.CharTy;
8401   } else {
8402     Self.Diag(OpLoc, diag::warn_string_plus_char)
8403         << DiagRange << CharExpr->getType();
8404   }
8405 
8406   // Only print a fixit for str + char, not for char + str.
8407   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8408     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8409     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8410         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8411         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8412         << FixItHint::CreateInsertion(EndLoc, "]");
8413   } else {
8414     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8415   }
8416 }
8417 
8418 /// \brief Emit error when two pointers are incompatible.
8419 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8420                                            Expr *LHSExpr, Expr *RHSExpr) {
8421   assert(LHSExpr->getType()->isAnyPointerType());
8422   assert(RHSExpr->getType()->isAnyPointerType());
8423   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8424     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8425     << RHSExpr->getSourceRange();
8426 }
8427 
8428 // C99 6.5.6
8429 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8430                                      SourceLocation Loc, BinaryOperatorKind Opc,
8431                                      QualType* CompLHSTy) {
8432   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8433 
8434   if (LHS.get()->getType()->isVectorType() ||
8435       RHS.get()->getType()->isVectorType()) {
8436     QualType compType = CheckVectorOperands(
8437         LHS, RHS, Loc, CompLHSTy,
8438         /*AllowBothBool*/getLangOpts().AltiVec,
8439         /*AllowBoolConversions*/getLangOpts().ZVector);
8440     if (CompLHSTy) *CompLHSTy = compType;
8441     return compType;
8442   }
8443 
8444   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8445   if (LHS.isInvalid() || RHS.isInvalid())
8446     return QualType();
8447 
8448   // Diagnose "string literal" '+' int and string '+' "char literal".
8449   if (Opc == BO_Add) {
8450     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8451     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8452   }
8453 
8454   // handle the common case first (both operands are arithmetic).
8455   if (!compType.isNull() && compType->isArithmeticType()) {
8456     if (CompLHSTy) *CompLHSTy = compType;
8457     return compType;
8458   }
8459 
8460   // Type-checking.  Ultimately the pointer's going to be in PExp;
8461   // note that we bias towards the LHS being the pointer.
8462   Expr *PExp = LHS.get(), *IExp = RHS.get();
8463 
8464   bool isObjCPointer;
8465   if (PExp->getType()->isPointerType()) {
8466     isObjCPointer = false;
8467   } else if (PExp->getType()->isObjCObjectPointerType()) {
8468     isObjCPointer = true;
8469   } else {
8470     std::swap(PExp, IExp);
8471     if (PExp->getType()->isPointerType()) {
8472       isObjCPointer = false;
8473     } else if (PExp->getType()->isObjCObjectPointerType()) {
8474       isObjCPointer = true;
8475     } else {
8476       return InvalidOperands(Loc, LHS, RHS);
8477     }
8478   }
8479   assert(PExp->getType()->isAnyPointerType());
8480 
8481   if (!IExp->getType()->isIntegerType())
8482     return InvalidOperands(Loc, LHS, RHS);
8483 
8484   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8485     return QualType();
8486 
8487   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8488     return QualType();
8489 
8490   // Check array bounds for pointer arithemtic
8491   CheckArrayAccess(PExp, IExp);
8492 
8493   if (CompLHSTy) {
8494     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8495     if (LHSTy.isNull()) {
8496       LHSTy = LHS.get()->getType();
8497       if (LHSTy->isPromotableIntegerType())
8498         LHSTy = Context.getPromotedIntegerType(LHSTy);
8499     }
8500     *CompLHSTy = LHSTy;
8501   }
8502 
8503   return PExp->getType();
8504 }
8505 
8506 // C99 6.5.6
8507 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8508                                         SourceLocation Loc,
8509                                         QualType* CompLHSTy) {
8510   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8511 
8512   if (LHS.get()->getType()->isVectorType() ||
8513       RHS.get()->getType()->isVectorType()) {
8514     QualType compType = CheckVectorOperands(
8515         LHS, RHS, Loc, CompLHSTy,
8516         /*AllowBothBool*/getLangOpts().AltiVec,
8517         /*AllowBoolConversions*/getLangOpts().ZVector);
8518     if (CompLHSTy) *CompLHSTy = compType;
8519     return compType;
8520   }
8521 
8522   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8523   if (LHS.isInvalid() || RHS.isInvalid())
8524     return QualType();
8525 
8526   // Enforce type constraints: C99 6.5.6p3.
8527 
8528   // Handle the common case first (both operands are arithmetic).
8529   if (!compType.isNull() && compType->isArithmeticType()) {
8530     if (CompLHSTy) *CompLHSTy = compType;
8531     return compType;
8532   }
8533 
8534   // Either ptr - int   or   ptr - ptr.
8535   if (LHS.get()->getType()->isAnyPointerType()) {
8536     QualType lpointee = LHS.get()->getType()->getPointeeType();
8537 
8538     // Diagnose bad cases where we step over interface counts.
8539     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8540         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8541       return QualType();
8542 
8543     // The result type of a pointer-int computation is the pointer type.
8544     if (RHS.get()->getType()->isIntegerType()) {
8545       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8546         return QualType();
8547 
8548       // Check array bounds for pointer arithemtic
8549       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8550                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8551 
8552       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8553       return LHS.get()->getType();
8554     }
8555 
8556     // Handle pointer-pointer subtractions.
8557     if (const PointerType *RHSPTy
8558           = RHS.get()->getType()->getAs<PointerType>()) {
8559       QualType rpointee = RHSPTy->getPointeeType();
8560 
8561       if (getLangOpts().CPlusPlus) {
8562         // Pointee types must be the same: C++ [expr.add]
8563         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8564           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8565         }
8566       } else {
8567         // Pointee types must be compatible C99 6.5.6p3
8568         if (!Context.typesAreCompatible(
8569                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8570                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8571           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8572           return QualType();
8573         }
8574       }
8575 
8576       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8577                                                LHS.get(), RHS.get()))
8578         return QualType();
8579 
8580       // The pointee type may have zero size.  As an extension, a structure or
8581       // union may have zero size or an array may have zero length.  In this
8582       // case subtraction does not make sense.
8583       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8584         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8585         if (ElementSize.isZero()) {
8586           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8587             << rpointee.getUnqualifiedType()
8588             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8589         }
8590       }
8591 
8592       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8593       return Context.getPointerDiffType();
8594     }
8595   }
8596 
8597   return InvalidOperands(Loc, LHS, RHS);
8598 }
8599 
8600 static bool isScopedEnumerationType(QualType T) {
8601   if (const EnumType *ET = T->getAs<EnumType>())
8602     return ET->getDecl()->isScoped();
8603   return false;
8604 }
8605 
8606 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8607                                    SourceLocation Loc, BinaryOperatorKind Opc,
8608                                    QualType LHSType) {
8609   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8610   // so skip remaining warnings as we don't want to modify values within Sema.
8611   if (S.getLangOpts().OpenCL)
8612     return;
8613 
8614   llvm::APSInt Right;
8615   // Check right/shifter operand
8616   if (RHS.get()->isValueDependent() ||
8617       !RHS.get()->EvaluateAsInt(Right, S.Context))
8618     return;
8619 
8620   if (Right.isNegative()) {
8621     S.DiagRuntimeBehavior(Loc, RHS.get(),
8622                           S.PDiag(diag::warn_shift_negative)
8623                             << RHS.get()->getSourceRange());
8624     return;
8625   }
8626   llvm::APInt LeftBits(Right.getBitWidth(),
8627                        S.Context.getTypeSize(LHS.get()->getType()));
8628   if (Right.uge(LeftBits)) {
8629     S.DiagRuntimeBehavior(Loc, RHS.get(),
8630                           S.PDiag(diag::warn_shift_gt_typewidth)
8631                             << RHS.get()->getSourceRange());
8632     return;
8633   }
8634   if (Opc != BO_Shl)
8635     return;
8636 
8637   // When left shifting an ICE which is signed, we can check for overflow which
8638   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8639   // integers have defined behavior modulo one more than the maximum value
8640   // representable in the result type, so never warn for those.
8641   llvm::APSInt Left;
8642   if (LHS.get()->isValueDependent() ||
8643       LHSType->hasUnsignedIntegerRepresentation() ||
8644       !LHS.get()->EvaluateAsInt(Left, S.Context))
8645     return;
8646 
8647   // If LHS does not have a signed type and non-negative value
8648   // then, the behavior is undefined. Warn about it.
8649   if (Left.isNegative()) {
8650     S.DiagRuntimeBehavior(Loc, LHS.get(),
8651                           S.PDiag(diag::warn_shift_lhs_negative)
8652                             << LHS.get()->getSourceRange());
8653     return;
8654   }
8655 
8656   llvm::APInt ResultBits =
8657       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8658   if (LeftBits.uge(ResultBits))
8659     return;
8660   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8661   Result = Result.shl(Right);
8662 
8663   // Print the bit representation of the signed integer as an unsigned
8664   // hexadecimal number.
8665   SmallString<40> HexResult;
8666   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8667 
8668   // If we are only missing a sign bit, this is less likely to result in actual
8669   // bugs -- if the result is cast back to an unsigned type, it will have the
8670   // expected value. Thus we place this behind a different warning that can be
8671   // turned off separately if needed.
8672   if (LeftBits == ResultBits - 1) {
8673     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8674         << HexResult << LHSType
8675         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8676     return;
8677   }
8678 
8679   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8680     << HexResult.str() << Result.getMinSignedBits() << LHSType
8681     << Left.getBitWidth() << LHS.get()->getSourceRange()
8682     << RHS.get()->getSourceRange();
8683 }
8684 
8685 /// \brief Return the resulting type when an OpenCL vector is shifted
8686 ///        by a scalar or vector shift amount.
8687 static QualType checkOpenCLVectorShift(Sema &S,
8688                                        ExprResult &LHS, ExprResult &RHS,
8689                                        SourceLocation Loc, bool IsCompAssign) {
8690   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8691   if (!LHS.get()->getType()->isVectorType()) {
8692     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8693       << RHS.get()->getType() << LHS.get()->getType()
8694       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8695     return QualType();
8696   }
8697 
8698   if (!IsCompAssign) {
8699     LHS = S.UsualUnaryConversions(LHS.get());
8700     if (LHS.isInvalid()) return QualType();
8701   }
8702 
8703   RHS = S.UsualUnaryConversions(RHS.get());
8704   if (RHS.isInvalid()) return QualType();
8705 
8706   QualType LHSType = LHS.get()->getType();
8707   const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8708   QualType LHSEleType = LHSVecTy->getElementType();
8709 
8710   // Note that RHS might not be a vector.
8711   QualType RHSType = RHS.get()->getType();
8712   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8713   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8714 
8715   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8716   if (!LHSEleType->isIntegerType()) {
8717     S.Diag(Loc, diag::err_typecheck_expect_int)
8718       << LHS.get()->getType() << LHS.get()->getSourceRange();
8719     return QualType();
8720   }
8721 
8722   if (!RHSEleType->isIntegerType()) {
8723     S.Diag(Loc, diag::err_typecheck_expect_int)
8724       << RHS.get()->getType() << RHS.get()->getSourceRange();
8725     return QualType();
8726   }
8727 
8728   if (RHSVecTy) {
8729     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8730     // are applied component-wise. So if RHS is a vector, then ensure
8731     // that the number of elements is the same as LHS...
8732     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8733       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8734         << LHS.get()->getType() << RHS.get()->getType()
8735         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8736       return QualType();
8737     }
8738   } else {
8739     // ...else expand RHS to match the number of elements in LHS.
8740     QualType VecTy =
8741       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8742     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8743   }
8744 
8745   return LHSType;
8746 }
8747 
8748 // C99 6.5.7
8749 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8750                                   SourceLocation Loc, BinaryOperatorKind Opc,
8751                                   bool IsCompAssign) {
8752   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8753 
8754   // Vector shifts promote their scalar inputs to vector type.
8755   if (LHS.get()->getType()->isVectorType() ||
8756       RHS.get()->getType()->isVectorType()) {
8757     if (LangOpts.OpenCL)
8758       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8759     if (LangOpts.ZVector) {
8760       // The shift operators for the z vector extensions work basically
8761       // like OpenCL shifts, except that neither the LHS nor the RHS is
8762       // allowed to be a "vector bool".
8763       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8764         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8765           return InvalidOperands(Loc, LHS, RHS);
8766       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8767         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8768           return InvalidOperands(Loc, LHS, RHS);
8769       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8770     }
8771     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8772                                /*AllowBothBool*/true,
8773                                /*AllowBoolConversions*/false);
8774   }
8775 
8776   // Shifts don't perform usual arithmetic conversions, they just do integer
8777   // promotions on each operand. C99 6.5.7p3
8778 
8779   // For the LHS, do usual unary conversions, but then reset them away
8780   // if this is a compound assignment.
8781   ExprResult OldLHS = LHS;
8782   LHS = UsualUnaryConversions(LHS.get());
8783   if (LHS.isInvalid())
8784     return QualType();
8785   QualType LHSType = LHS.get()->getType();
8786   if (IsCompAssign) LHS = OldLHS;
8787 
8788   // The RHS is simpler.
8789   RHS = UsualUnaryConversions(RHS.get());
8790   if (RHS.isInvalid())
8791     return QualType();
8792   QualType RHSType = RHS.get()->getType();
8793 
8794   // C99 6.5.7p2: Each of the operands shall have integer type.
8795   if (!LHSType->hasIntegerRepresentation() ||
8796       !RHSType->hasIntegerRepresentation())
8797     return InvalidOperands(Loc, LHS, RHS);
8798 
8799   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8800   // hasIntegerRepresentation() above instead of this.
8801   if (isScopedEnumerationType(LHSType) ||
8802       isScopedEnumerationType(RHSType)) {
8803     return InvalidOperands(Loc, LHS, RHS);
8804   }
8805   // Sanity-check shift operands
8806   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8807 
8808   // "The type of the result is that of the promoted left operand."
8809   return LHSType;
8810 }
8811 
8812 static bool IsWithinTemplateSpecialization(Decl *D) {
8813   if (DeclContext *DC = D->getDeclContext()) {
8814     if (isa<ClassTemplateSpecializationDecl>(DC))
8815       return true;
8816     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8817       return FD->isFunctionTemplateSpecialization();
8818   }
8819   return false;
8820 }
8821 
8822 /// If two different enums are compared, raise a warning.
8823 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8824                                 Expr *RHS) {
8825   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8826   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8827 
8828   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8829   if (!LHSEnumType)
8830     return;
8831   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8832   if (!RHSEnumType)
8833     return;
8834 
8835   // Ignore anonymous enums.
8836   if (!LHSEnumType->getDecl()->getIdentifier())
8837     return;
8838   if (!RHSEnumType->getDecl()->getIdentifier())
8839     return;
8840 
8841   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8842     return;
8843 
8844   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8845       << LHSStrippedType << RHSStrippedType
8846       << LHS->getSourceRange() << RHS->getSourceRange();
8847 }
8848 
8849 /// \brief Diagnose bad pointer comparisons.
8850 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8851                                               ExprResult &LHS, ExprResult &RHS,
8852                                               bool IsError) {
8853   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8854                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8855     << LHS.get()->getType() << RHS.get()->getType()
8856     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8857 }
8858 
8859 /// \brief Returns false if the pointers are converted to a composite type,
8860 /// true otherwise.
8861 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8862                                            ExprResult &LHS, ExprResult &RHS) {
8863   // C++ [expr.rel]p2:
8864   //   [...] Pointer conversions (4.10) and qualification
8865   //   conversions (4.4) are performed on pointer operands (or on
8866   //   a pointer operand and a null pointer constant) to bring
8867   //   them to their composite pointer type. [...]
8868   //
8869   // C++ [expr.eq]p1 uses the same notion for (in)equality
8870   // comparisons of pointers.
8871 
8872   // C++ [expr.eq]p2:
8873   //   In addition, pointers to members can be compared, or a pointer to
8874   //   member and a null pointer constant. Pointer to member conversions
8875   //   (4.11) and qualification conversions (4.4) are performed to bring
8876   //   them to a common type. If one operand is a null pointer constant,
8877   //   the common type is the type of the other operand. Otherwise, the
8878   //   common type is a pointer to member type similar (4.4) to the type
8879   //   of one of the operands, with a cv-qualification signature (4.4)
8880   //   that is the union of the cv-qualification signatures of the operand
8881   //   types.
8882 
8883   QualType LHSType = LHS.get()->getType();
8884   QualType RHSType = RHS.get()->getType();
8885   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8886          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8887 
8888   bool NonStandardCompositeType = false;
8889   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8890   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8891   if (T.isNull()) {
8892     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8893     return true;
8894   }
8895 
8896   if (NonStandardCompositeType)
8897     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8898       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8899       << RHS.get()->getSourceRange();
8900 
8901   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8902   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8903   return false;
8904 }
8905 
8906 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8907                                                     ExprResult &LHS,
8908                                                     ExprResult &RHS,
8909                                                     bool IsError) {
8910   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8911                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8912     << LHS.get()->getType() << RHS.get()->getType()
8913     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8914 }
8915 
8916 static bool isObjCObjectLiteral(ExprResult &E) {
8917   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8918   case Stmt::ObjCArrayLiteralClass:
8919   case Stmt::ObjCDictionaryLiteralClass:
8920   case Stmt::ObjCStringLiteralClass:
8921   case Stmt::ObjCBoxedExprClass:
8922     return true;
8923   default:
8924     // Note that ObjCBoolLiteral is NOT an object literal!
8925     return false;
8926   }
8927 }
8928 
8929 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8930   const ObjCObjectPointerType *Type =
8931     LHS->getType()->getAs<ObjCObjectPointerType>();
8932 
8933   // If this is not actually an Objective-C object, bail out.
8934   if (!Type)
8935     return false;
8936 
8937   // Get the LHS object's interface type.
8938   QualType InterfaceType = Type->getPointeeType();
8939 
8940   // If the RHS isn't an Objective-C object, bail out.
8941   if (!RHS->getType()->isObjCObjectPointerType())
8942     return false;
8943 
8944   // Try to find the -isEqual: method.
8945   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8946   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8947                                                       InterfaceType,
8948                                                       /*instance=*/true);
8949   if (!Method) {
8950     if (Type->isObjCIdType()) {
8951       // For 'id', just check the global pool.
8952       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8953                                                   /*receiverId=*/true);
8954     } else {
8955       // Check protocols.
8956       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8957                                              /*instance=*/true);
8958     }
8959   }
8960 
8961   if (!Method)
8962     return false;
8963 
8964   QualType T = Method->parameters()[0]->getType();
8965   if (!T->isObjCObjectPointerType())
8966     return false;
8967 
8968   QualType R = Method->getReturnType();
8969   if (!R->isScalarType())
8970     return false;
8971 
8972   return true;
8973 }
8974 
8975 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8976   FromE = FromE->IgnoreParenImpCasts();
8977   switch (FromE->getStmtClass()) {
8978     default:
8979       break;
8980     case Stmt::ObjCStringLiteralClass:
8981       // "string literal"
8982       return LK_String;
8983     case Stmt::ObjCArrayLiteralClass:
8984       // "array literal"
8985       return LK_Array;
8986     case Stmt::ObjCDictionaryLiteralClass:
8987       // "dictionary literal"
8988       return LK_Dictionary;
8989     case Stmt::BlockExprClass:
8990       return LK_Block;
8991     case Stmt::ObjCBoxedExprClass: {
8992       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8993       switch (Inner->getStmtClass()) {
8994         case Stmt::IntegerLiteralClass:
8995         case Stmt::FloatingLiteralClass:
8996         case Stmt::CharacterLiteralClass:
8997         case Stmt::ObjCBoolLiteralExprClass:
8998         case Stmt::CXXBoolLiteralExprClass:
8999           // "numeric literal"
9000           return LK_Numeric;
9001         case Stmt::ImplicitCastExprClass: {
9002           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9003           // Boolean literals can be represented by implicit casts.
9004           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9005             return LK_Numeric;
9006           break;
9007         }
9008         default:
9009           break;
9010       }
9011       return LK_Boxed;
9012     }
9013   }
9014   return LK_None;
9015 }
9016 
9017 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9018                                           ExprResult &LHS, ExprResult &RHS,
9019                                           BinaryOperator::Opcode Opc){
9020   Expr *Literal;
9021   Expr *Other;
9022   if (isObjCObjectLiteral(LHS)) {
9023     Literal = LHS.get();
9024     Other = RHS.get();
9025   } else {
9026     Literal = RHS.get();
9027     Other = LHS.get();
9028   }
9029 
9030   // Don't warn on comparisons against nil.
9031   Other = Other->IgnoreParenCasts();
9032   if (Other->isNullPointerConstant(S.getASTContext(),
9033                                    Expr::NPC_ValueDependentIsNotNull))
9034     return;
9035 
9036   // This should be kept in sync with warn_objc_literal_comparison.
9037   // LK_String should always be after the other literals, since it has its own
9038   // warning flag.
9039   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9040   assert(LiteralKind != Sema::LK_Block);
9041   if (LiteralKind == Sema::LK_None) {
9042     llvm_unreachable("Unknown Objective-C object literal kind");
9043   }
9044 
9045   if (LiteralKind == Sema::LK_String)
9046     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9047       << Literal->getSourceRange();
9048   else
9049     S.Diag(Loc, diag::warn_objc_literal_comparison)
9050       << LiteralKind << Literal->getSourceRange();
9051 
9052   if (BinaryOperator::isEqualityOp(Opc) &&
9053       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9054     SourceLocation Start = LHS.get()->getLocStart();
9055     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9056     CharSourceRange OpRange =
9057       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9058 
9059     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9060       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9061       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9062       << FixItHint::CreateInsertion(End, "]");
9063   }
9064 }
9065 
9066 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
9067                                                 ExprResult &RHS,
9068                                                 SourceLocation Loc,
9069                                                 BinaryOperatorKind Opc) {
9070   // Check that left hand side is !something.
9071   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9072   if (!UO || UO->getOpcode() != UO_LNot) return;
9073 
9074   // Only check if the right hand side is non-bool arithmetic type.
9075   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9076 
9077   // Make sure that the something in !something is not bool.
9078   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9079   if (SubExpr->isKnownToHaveBooleanValue()) return;
9080 
9081   // Emit warning.
9082   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
9083       << Loc;
9084 
9085   // First note suggest !(x < y)
9086   SourceLocation FirstOpen = SubExpr->getLocStart();
9087   SourceLocation FirstClose = RHS.get()->getLocEnd();
9088   FirstClose = S.getLocForEndOfToken(FirstClose);
9089   if (FirstClose.isInvalid())
9090     FirstOpen = SourceLocation();
9091   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9092       << FixItHint::CreateInsertion(FirstOpen, "(")
9093       << FixItHint::CreateInsertion(FirstClose, ")");
9094 
9095   // Second note suggests (!x) < y
9096   SourceLocation SecondOpen = LHS.get()->getLocStart();
9097   SourceLocation SecondClose = LHS.get()->getLocEnd();
9098   SecondClose = S.getLocForEndOfToken(SecondClose);
9099   if (SecondClose.isInvalid())
9100     SecondOpen = SourceLocation();
9101   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9102       << FixItHint::CreateInsertion(SecondOpen, "(")
9103       << FixItHint::CreateInsertion(SecondClose, ")");
9104 }
9105 
9106 // Get the decl for a simple expression: a reference to a variable,
9107 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9108 static ValueDecl *getCompareDecl(Expr *E) {
9109   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9110     return DR->getDecl();
9111   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9112     if (Ivar->isFreeIvar())
9113       return Ivar->getDecl();
9114   }
9115   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9116     if (Mem->isImplicitAccess())
9117       return Mem->getMemberDecl();
9118   }
9119   return nullptr;
9120 }
9121 
9122 // C99 6.5.8, C++ [expr.rel]
9123 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9124                                     SourceLocation Loc, BinaryOperatorKind Opc,
9125                                     bool IsRelational) {
9126   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9127 
9128   // Handle vector comparisons separately.
9129   if (LHS.get()->getType()->isVectorType() ||
9130       RHS.get()->getType()->isVectorType())
9131     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9132 
9133   QualType LHSType = LHS.get()->getType();
9134   QualType RHSType = RHS.get()->getType();
9135 
9136   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9137   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9138 
9139   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9140   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9141 
9142   if (!LHSType->hasFloatingRepresentation() &&
9143       !(LHSType->isBlockPointerType() && IsRelational) &&
9144       !LHS.get()->getLocStart().isMacroID() &&
9145       !RHS.get()->getLocStart().isMacroID() &&
9146       ActiveTemplateInstantiations.empty()) {
9147     // For non-floating point types, check for self-comparisons of the form
9148     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9149     // often indicate logic errors in the program.
9150     //
9151     // NOTE: Don't warn about comparison expressions resulting from macro
9152     // expansion. Also don't warn about comparisons which are only self
9153     // comparisons within a template specialization. The warnings should catch
9154     // obvious cases in the definition of the template anyways. The idea is to
9155     // warn when the typed comparison operator will always evaluate to the same
9156     // result.
9157     ValueDecl *DL = getCompareDecl(LHSStripped);
9158     ValueDecl *DR = getCompareDecl(RHSStripped);
9159     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9160       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9161                           << 0 // self-
9162                           << (Opc == BO_EQ
9163                               || Opc == BO_LE
9164                               || Opc == BO_GE));
9165     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9166                !DL->getType()->isReferenceType() &&
9167                !DR->getType()->isReferenceType()) {
9168         // what is it always going to eval to?
9169         char always_evals_to;
9170         switch(Opc) {
9171         case BO_EQ: // e.g. array1 == array2
9172           always_evals_to = 0; // false
9173           break;
9174         case BO_NE: // e.g. array1 != array2
9175           always_evals_to = 1; // true
9176           break;
9177         default:
9178           // best we can say is 'a constant'
9179           always_evals_to = 2; // e.g. array1 <= array2
9180           break;
9181         }
9182         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9183                             << 1 // array
9184                             << always_evals_to);
9185     }
9186 
9187     if (isa<CastExpr>(LHSStripped))
9188       LHSStripped = LHSStripped->IgnoreParenCasts();
9189     if (isa<CastExpr>(RHSStripped))
9190       RHSStripped = RHSStripped->IgnoreParenCasts();
9191 
9192     // Warn about comparisons against a string constant (unless the other
9193     // operand is null), the user probably wants strcmp.
9194     Expr *literalString = nullptr;
9195     Expr *literalStringStripped = nullptr;
9196     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9197         !RHSStripped->isNullPointerConstant(Context,
9198                                             Expr::NPC_ValueDependentIsNull)) {
9199       literalString = LHS.get();
9200       literalStringStripped = LHSStripped;
9201     } else if ((isa<StringLiteral>(RHSStripped) ||
9202                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9203                !LHSStripped->isNullPointerConstant(Context,
9204                                             Expr::NPC_ValueDependentIsNull)) {
9205       literalString = RHS.get();
9206       literalStringStripped = RHSStripped;
9207     }
9208 
9209     if (literalString) {
9210       DiagRuntimeBehavior(Loc, nullptr,
9211         PDiag(diag::warn_stringcompare)
9212           << isa<ObjCEncodeExpr>(literalStringStripped)
9213           << literalString->getSourceRange());
9214     }
9215   }
9216 
9217   // C99 6.5.8p3 / C99 6.5.9p4
9218   UsualArithmeticConversions(LHS, RHS);
9219   if (LHS.isInvalid() || RHS.isInvalid())
9220     return QualType();
9221 
9222   LHSType = LHS.get()->getType();
9223   RHSType = RHS.get()->getType();
9224 
9225   // The result of comparisons is 'bool' in C++, 'int' in C.
9226   QualType ResultTy = Context.getLogicalOperationType();
9227 
9228   if (IsRelational) {
9229     if (LHSType->isRealType() && RHSType->isRealType())
9230       return ResultTy;
9231   } else {
9232     // Check for comparisons of floating point operands using != and ==.
9233     if (LHSType->hasFloatingRepresentation())
9234       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9235 
9236     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9237       return ResultTy;
9238   }
9239 
9240   const Expr::NullPointerConstantKind LHSNullKind =
9241       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9242   const Expr::NullPointerConstantKind RHSNullKind =
9243       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9244   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9245   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9246 
9247   if (!IsRelational && LHSIsNull != RHSIsNull) {
9248     bool IsEquality = Opc == BO_EQ;
9249     if (RHSIsNull)
9250       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9251                                    RHS.get()->getSourceRange());
9252     else
9253       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9254                                    LHS.get()->getSourceRange());
9255   }
9256 
9257   // All of the following pointer-related warnings are GCC extensions, except
9258   // when handling null pointer constants.
9259   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9260     QualType LCanPointeeTy =
9261       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9262     QualType RCanPointeeTy =
9263       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9264 
9265     if (getLangOpts().CPlusPlus) {
9266       if (LCanPointeeTy == RCanPointeeTy)
9267         return ResultTy;
9268       if (!IsRelational &&
9269           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9270         // Valid unless comparison between non-null pointer and function pointer
9271         // This is a gcc extension compatibility comparison.
9272         // In a SFINAE context, we treat this as a hard error to maintain
9273         // conformance with the C++ standard.
9274         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9275             && !LHSIsNull && !RHSIsNull) {
9276           diagnoseFunctionPointerToVoidComparison(
9277               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9278 
9279           if (isSFINAEContext())
9280             return QualType();
9281 
9282           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9283           return ResultTy;
9284         }
9285       }
9286 
9287       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9288         return QualType();
9289       else
9290         return ResultTy;
9291     }
9292     // C99 6.5.9p2 and C99 6.5.8p2
9293     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9294                                    RCanPointeeTy.getUnqualifiedType())) {
9295       // Valid unless a relational comparison of function pointers
9296       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9297         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9298           << LHSType << RHSType << LHS.get()->getSourceRange()
9299           << RHS.get()->getSourceRange();
9300       }
9301     } else if (!IsRelational &&
9302                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9303       // Valid unless comparison between non-null pointer and function pointer
9304       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9305           && !LHSIsNull && !RHSIsNull)
9306         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9307                                                 /*isError*/false);
9308     } else {
9309       // Invalid
9310       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9311     }
9312     if (LCanPointeeTy != RCanPointeeTy) {
9313       // Treat NULL constant as a special case in OpenCL.
9314       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9315         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9316         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9317           Diag(Loc,
9318                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9319               << LHSType << RHSType << 0 /* comparison */
9320               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9321         }
9322       }
9323       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9324       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9325       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9326                                                : CK_BitCast;
9327       if (LHSIsNull && !RHSIsNull)
9328         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9329       else
9330         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9331     }
9332     return ResultTy;
9333   }
9334 
9335   if (getLangOpts().CPlusPlus) {
9336     // Comparison of nullptr_t with itself.
9337     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9338       return ResultTy;
9339 
9340     // Comparison of pointers with null pointer constants and equality
9341     // comparisons of member pointers to null pointer constants.
9342     if (RHSIsNull &&
9343         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9344          (!IsRelational &&
9345           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9346       RHS = ImpCastExprToType(RHS.get(), LHSType,
9347                         LHSType->isMemberPointerType()
9348                           ? CK_NullToMemberPointer
9349                           : CK_NullToPointer);
9350       return ResultTy;
9351     }
9352     if (LHSIsNull &&
9353         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9354          (!IsRelational &&
9355           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9356       LHS = ImpCastExprToType(LHS.get(), RHSType,
9357                         RHSType->isMemberPointerType()
9358                           ? CK_NullToMemberPointer
9359                           : CK_NullToPointer);
9360       return ResultTy;
9361     }
9362 
9363     // Comparison of member pointers.
9364     if (!IsRelational &&
9365         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9366       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9367         return QualType();
9368       else
9369         return ResultTy;
9370     }
9371 
9372     // Handle scoped enumeration types specifically, since they don't promote
9373     // to integers.
9374     if (LHS.get()->getType()->isEnumeralType() &&
9375         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9376                                        RHS.get()->getType()))
9377       return ResultTy;
9378   }
9379 
9380   // Handle block pointer types.
9381   if (!IsRelational && LHSType->isBlockPointerType() &&
9382       RHSType->isBlockPointerType()) {
9383     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9384     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9385 
9386     if (!LHSIsNull && !RHSIsNull &&
9387         !Context.typesAreCompatible(lpointee, rpointee)) {
9388       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9389         << LHSType << RHSType << LHS.get()->getSourceRange()
9390         << RHS.get()->getSourceRange();
9391     }
9392     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9393     return ResultTy;
9394   }
9395 
9396   // Allow block pointers to be compared with null pointer constants.
9397   if (!IsRelational
9398       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9399           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9400     if (!LHSIsNull && !RHSIsNull) {
9401       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9402              ->getPointeeType()->isVoidType())
9403             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9404                 ->getPointeeType()->isVoidType())))
9405         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9406           << LHSType << RHSType << LHS.get()->getSourceRange()
9407           << RHS.get()->getSourceRange();
9408     }
9409     if (LHSIsNull && !RHSIsNull)
9410       LHS = ImpCastExprToType(LHS.get(), RHSType,
9411                               RHSType->isPointerType() ? CK_BitCast
9412                                 : CK_AnyPointerToBlockPointerCast);
9413     else
9414       RHS = ImpCastExprToType(RHS.get(), LHSType,
9415                               LHSType->isPointerType() ? CK_BitCast
9416                                 : CK_AnyPointerToBlockPointerCast);
9417     return ResultTy;
9418   }
9419 
9420   if (LHSType->isObjCObjectPointerType() ||
9421       RHSType->isObjCObjectPointerType()) {
9422     const PointerType *LPT = LHSType->getAs<PointerType>();
9423     const PointerType *RPT = RHSType->getAs<PointerType>();
9424     if (LPT || RPT) {
9425       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9426       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9427 
9428       if (!LPtrToVoid && !RPtrToVoid &&
9429           !Context.typesAreCompatible(LHSType, RHSType)) {
9430         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9431                                           /*isError*/false);
9432       }
9433       if (LHSIsNull && !RHSIsNull) {
9434         Expr *E = LHS.get();
9435         if (getLangOpts().ObjCAutoRefCount)
9436           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9437         LHS = ImpCastExprToType(E, RHSType,
9438                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9439       }
9440       else {
9441         Expr *E = RHS.get();
9442         if (getLangOpts().ObjCAutoRefCount)
9443           CheckObjCARCConversion(SourceRange(), LHSType, E,
9444                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9445                                  /*DiagnoseCFAudited=*/false, Opc);
9446         RHS = ImpCastExprToType(E, LHSType,
9447                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9448       }
9449       return ResultTy;
9450     }
9451     if (LHSType->isObjCObjectPointerType() &&
9452         RHSType->isObjCObjectPointerType()) {
9453       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9454         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9455                                           /*isError*/false);
9456       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9457         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9458 
9459       if (LHSIsNull && !RHSIsNull)
9460         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9461       else
9462         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9463       return ResultTy;
9464     }
9465   }
9466   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9467       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9468     unsigned DiagID = 0;
9469     bool isError = false;
9470     if (LangOpts.DebuggerSupport) {
9471       // Under a debugger, allow the comparison of pointers to integers,
9472       // since users tend to want to compare addresses.
9473     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9474         (RHSIsNull && RHSType->isIntegerType())) {
9475       if (IsRelational && !getLangOpts().CPlusPlus)
9476         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9477     } else if (IsRelational && !getLangOpts().CPlusPlus)
9478       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9479     else if (getLangOpts().CPlusPlus) {
9480       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9481       isError = true;
9482     } else
9483       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9484 
9485     if (DiagID) {
9486       Diag(Loc, DiagID)
9487         << LHSType << RHSType << LHS.get()->getSourceRange()
9488         << RHS.get()->getSourceRange();
9489       if (isError)
9490         return QualType();
9491     }
9492 
9493     if (LHSType->isIntegerType())
9494       LHS = ImpCastExprToType(LHS.get(), RHSType,
9495                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9496     else
9497       RHS = ImpCastExprToType(RHS.get(), LHSType,
9498                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9499     return ResultTy;
9500   }
9501 
9502   // Handle block pointers.
9503   if (!IsRelational && RHSIsNull
9504       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9505     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9506     return ResultTy;
9507   }
9508   if (!IsRelational && LHSIsNull
9509       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9510     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9511     return ResultTy;
9512   }
9513 
9514   return InvalidOperands(Loc, LHS, RHS);
9515 }
9516 
9517 
9518 // Return a signed type that is of identical size and number of elements.
9519 // For floating point vectors, return an integer type of identical size
9520 // and number of elements.
9521 QualType Sema::GetSignedVectorType(QualType V) {
9522   const VectorType *VTy = V->getAs<VectorType>();
9523   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9524   if (TypeSize == Context.getTypeSize(Context.CharTy))
9525     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9526   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9527     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9528   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9529     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9530   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9531     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9532   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9533          "Unhandled vector element size in vector compare");
9534   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9535 }
9536 
9537 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9538 /// operates on extended vector types.  Instead of producing an IntTy result,
9539 /// like a scalar comparison, a vector comparison produces a vector of integer
9540 /// types.
9541 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9542                                           SourceLocation Loc,
9543                                           bool IsRelational) {
9544   // Check to make sure we're operating on vectors of the same type and width,
9545   // Allowing one side to be a scalar of element type.
9546   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9547                               /*AllowBothBool*/true,
9548                               /*AllowBoolConversions*/getLangOpts().ZVector);
9549   if (vType.isNull())
9550     return vType;
9551 
9552   QualType LHSType = LHS.get()->getType();
9553 
9554   // If AltiVec, the comparison results in a numeric type, i.e.
9555   // bool for C++, int for C
9556   if (getLangOpts().AltiVec &&
9557       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9558     return Context.getLogicalOperationType();
9559 
9560   // For non-floating point types, check for self-comparisons of the form
9561   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9562   // often indicate logic errors in the program.
9563   if (!LHSType->hasFloatingRepresentation() &&
9564       ActiveTemplateInstantiations.empty()) {
9565     if (DeclRefExpr* DRL
9566           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9567       if (DeclRefExpr* DRR
9568             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9569         if (DRL->getDecl() == DRR->getDecl())
9570           DiagRuntimeBehavior(Loc, nullptr,
9571                               PDiag(diag::warn_comparison_always)
9572                                 << 0 // self-
9573                                 << 2 // "a constant"
9574                               );
9575   }
9576 
9577   // Check for comparisons of floating point operands using != and ==.
9578   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9579     assert (RHS.get()->getType()->hasFloatingRepresentation());
9580     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9581   }
9582 
9583   // Return a signed type for the vector.
9584   return GetSignedVectorType(vType);
9585 }
9586 
9587 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9588                                           SourceLocation Loc) {
9589   // Ensure that either both operands are of the same vector type, or
9590   // one operand is of a vector type and the other is of its element type.
9591   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9592                                        /*AllowBothBool*/true,
9593                                        /*AllowBoolConversions*/false);
9594   if (vType.isNull())
9595     return InvalidOperands(Loc, LHS, RHS);
9596   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9597       vType->hasFloatingRepresentation())
9598     return InvalidOperands(Loc, LHS, RHS);
9599 
9600   return GetSignedVectorType(LHS.get()->getType());
9601 }
9602 
9603 inline QualType Sema::CheckBitwiseOperands(
9604   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9605   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9606 
9607   if (LHS.get()->getType()->isVectorType() ||
9608       RHS.get()->getType()->isVectorType()) {
9609     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9610         RHS.get()->getType()->hasIntegerRepresentation())
9611       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9612                         /*AllowBothBool*/true,
9613                         /*AllowBoolConversions*/getLangOpts().ZVector);
9614     return InvalidOperands(Loc, LHS, RHS);
9615   }
9616 
9617   ExprResult LHSResult = LHS, RHSResult = RHS;
9618   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9619                                                  IsCompAssign);
9620   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9621     return QualType();
9622   LHS = LHSResult.get();
9623   RHS = RHSResult.get();
9624 
9625   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9626     return compType;
9627   return InvalidOperands(Loc, LHS, RHS);
9628 }
9629 
9630 // C99 6.5.[13,14]
9631 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9632                                            SourceLocation Loc,
9633                                            BinaryOperatorKind Opc) {
9634   // Check vector operands differently.
9635   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9636     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9637 
9638   // Diagnose cases where the user write a logical and/or but probably meant a
9639   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9640   // is a constant.
9641   if (LHS.get()->getType()->isIntegerType() &&
9642       !LHS.get()->getType()->isBooleanType() &&
9643       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9644       // Don't warn in macros or template instantiations.
9645       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9646     // If the RHS can be constant folded, and if it constant folds to something
9647     // that isn't 0 or 1 (which indicate a potential logical operation that
9648     // happened to fold to true/false) then warn.
9649     // Parens on the RHS are ignored.
9650     llvm::APSInt Result;
9651     if (RHS.get()->EvaluateAsInt(Result, Context))
9652       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9653            !RHS.get()->getExprLoc().isMacroID()) ||
9654           (Result != 0 && Result != 1)) {
9655         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9656           << RHS.get()->getSourceRange()
9657           << (Opc == BO_LAnd ? "&&" : "||");
9658         // Suggest replacing the logical operator with the bitwise version
9659         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9660             << (Opc == BO_LAnd ? "&" : "|")
9661             << FixItHint::CreateReplacement(SourceRange(
9662                                                  Loc, getLocForEndOfToken(Loc)),
9663                                             Opc == BO_LAnd ? "&" : "|");
9664         if (Opc == BO_LAnd)
9665           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9666           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9667               << FixItHint::CreateRemoval(
9668                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9669                               RHS.get()->getLocEnd()));
9670       }
9671   }
9672 
9673   if (!Context.getLangOpts().CPlusPlus) {
9674     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9675     // not operate on the built-in scalar and vector float types.
9676     if (Context.getLangOpts().OpenCL &&
9677         Context.getLangOpts().OpenCLVersion < 120) {
9678       if (LHS.get()->getType()->isFloatingType() ||
9679           RHS.get()->getType()->isFloatingType())
9680         return InvalidOperands(Loc, LHS, RHS);
9681     }
9682 
9683     LHS = UsualUnaryConversions(LHS.get());
9684     if (LHS.isInvalid())
9685       return QualType();
9686 
9687     RHS = UsualUnaryConversions(RHS.get());
9688     if (RHS.isInvalid())
9689       return QualType();
9690 
9691     if (!LHS.get()->getType()->isScalarType() ||
9692         !RHS.get()->getType()->isScalarType())
9693       return InvalidOperands(Loc, LHS, RHS);
9694 
9695     return Context.IntTy;
9696   }
9697 
9698   // The following is safe because we only use this method for
9699   // non-overloadable operands.
9700 
9701   // C++ [expr.log.and]p1
9702   // C++ [expr.log.or]p1
9703   // The operands are both contextually converted to type bool.
9704   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9705   if (LHSRes.isInvalid())
9706     return InvalidOperands(Loc, LHS, RHS);
9707   LHS = LHSRes;
9708 
9709   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9710   if (RHSRes.isInvalid())
9711     return InvalidOperands(Loc, LHS, RHS);
9712   RHS = RHSRes;
9713 
9714   // C++ [expr.log.and]p2
9715   // C++ [expr.log.or]p2
9716   // The result is a bool.
9717   return Context.BoolTy;
9718 }
9719 
9720 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9721   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9722   if (!ME) return false;
9723   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9724   ObjCMessageExpr *Base =
9725     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9726   if (!Base) return false;
9727   return Base->getMethodDecl() != nullptr;
9728 }
9729 
9730 /// Is the given expression (which must be 'const') a reference to a
9731 /// variable which was originally non-const, but which has become
9732 /// 'const' due to being captured within a block?
9733 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9734 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9735   assert(E->isLValue() && E->getType().isConstQualified());
9736   E = E->IgnoreParens();
9737 
9738   // Must be a reference to a declaration from an enclosing scope.
9739   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9740   if (!DRE) return NCCK_None;
9741   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9742 
9743   // The declaration must be a variable which is not declared 'const'.
9744   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9745   if (!var) return NCCK_None;
9746   if (var->getType().isConstQualified()) return NCCK_None;
9747   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9748 
9749   // Decide whether the first capture was for a block or a lambda.
9750   DeclContext *DC = S.CurContext, *Prev = nullptr;
9751   // Decide whether the first capture was for a block or a lambda.
9752   while (DC) {
9753     // For init-capture, it is possible that the variable belongs to the
9754     // template pattern of the current context.
9755     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9756       if (var->isInitCapture() &&
9757           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9758         break;
9759     if (DC == var->getDeclContext())
9760       break;
9761     Prev = DC;
9762     DC = DC->getParent();
9763   }
9764   // Unless we have an init-capture, we've gone one step too far.
9765   if (!var->isInitCapture())
9766     DC = Prev;
9767   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9768 }
9769 
9770 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9771   Ty = Ty.getNonReferenceType();
9772   if (IsDereference && Ty->isPointerType())
9773     Ty = Ty->getPointeeType();
9774   return !Ty.isConstQualified();
9775 }
9776 
9777 /// Emit the "read-only variable not assignable" error and print notes to give
9778 /// more information about why the variable is not assignable, such as pointing
9779 /// to the declaration of a const variable, showing that a method is const, or
9780 /// that the function is returning a const reference.
9781 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9782                                     SourceLocation Loc) {
9783   // Update err_typecheck_assign_const and note_typecheck_assign_const
9784   // when this enum is changed.
9785   enum {
9786     ConstFunction,
9787     ConstVariable,
9788     ConstMember,
9789     ConstMethod,
9790     ConstUnknown,  // Keep as last element
9791   };
9792 
9793   SourceRange ExprRange = E->getSourceRange();
9794 
9795   // Only emit one error on the first const found.  All other consts will emit
9796   // a note to the error.
9797   bool DiagnosticEmitted = false;
9798 
9799   // Track if the current expression is the result of a derefence, and if the
9800   // next checked expression is the result of a derefence.
9801   bool IsDereference = false;
9802   bool NextIsDereference = false;
9803 
9804   // Loop to process MemberExpr chains.
9805   while (true) {
9806     IsDereference = NextIsDereference;
9807     NextIsDereference = false;
9808 
9809     E = E->IgnoreParenImpCasts();
9810     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9811       NextIsDereference = ME->isArrow();
9812       const ValueDecl *VD = ME->getMemberDecl();
9813       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9814         // Mutable fields can be modified even if the class is const.
9815         if (Field->isMutable()) {
9816           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9817           break;
9818         }
9819 
9820         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9821           if (!DiagnosticEmitted) {
9822             S.Diag(Loc, diag::err_typecheck_assign_const)
9823                 << ExprRange << ConstMember << false /*static*/ << Field
9824                 << Field->getType();
9825             DiagnosticEmitted = true;
9826           }
9827           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9828               << ConstMember << false /*static*/ << Field << Field->getType()
9829               << Field->getSourceRange();
9830         }
9831         E = ME->getBase();
9832         continue;
9833       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9834         if (VDecl->getType().isConstQualified()) {
9835           if (!DiagnosticEmitted) {
9836             S.Diag(Loc, diag::err_typecheck_assign_const)
9837                 << ExprRange << ConstMember << true /*static*/ << VDecl
9838                 << VDecl->getType();
9839             DiagnosticEmitted = true;
9840           }
9841           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9842               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9843               << VDecl->getSourceRange();
9844         }
9845         // Static fields do not inherit constness from parents.
9846         break;
9847       }
9848       break;
9849     } // End MemberExpr
9850     break;
9851   }
9852 
9853   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9854     // Function calls
9855     const FunctionDecl *FD = CE->getDirectCallee();
9856     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9857       if (!DiagnosticEmitted) {
9858         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9859                                                       << ConstFunction << FD;
9860         DiagnosticEmitted = true;
9861       }
9862       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9863              diag::note_typecheck_assign_const)
9864           << ConstFunction << FD << FD->getReturnType()
9865           << FD->getReturnTypeSourceRange();
9866     }
9867   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9868     // Point to variable declaration.
9869     if (const ValueDecl *VD = DRE->getDecl()) {
9870       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9871         if (!DiagnosticEmitted) {
9872           S.Diag(Loc, diag::err_typecheck_assign_const)
9873               << ExprRange << ConstVariable << VD << VD->getType();
9874           DiagnosticEmitted = true;
9875         }
9876         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9877             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9878       }
9879     }
9880   } else if (isa<CXXThisExpr>(E)) {
9881     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9882       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9883         if (MD->isConst()) {
9884           if (!DiagnosticEmitted) {
9885             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9886                                                           << ConstMethod << MD;
9887             DiagnosticEmitted = true;
9888           }
9889           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9890               << ConstMethod << MD << MD->getSourceRange();
9891         }
9892       }
9893     }
9894   }
9895 
9896   if (DiagnosticEmitted)
9897     return;
9898 
9899   // Can't determine a more specific message, so display the generic error.
9900   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9901 }
9902 
9903 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9904 /// emit an error and return true.  If so, return false.
9905 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9906   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9907 
9908   S.CheckShadowingDeclModification(E, Loc);
9909 
9910   SourceLocation OrigLoc = Loc;
9911   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9912                                                               &Loc);
9913   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9914     IsLV = Expr::MLV_InvalidMessageExpression;
9915   if (IsLV == Expr::MLV_Valid)
9916     return false;
9917 
9918   unsigned DiagID = 0;
9919   bool NeedType = false;
9920   switch (IsLV) { // C99 6.5.16p2
9921   case Expr::MLV_ConstQualified:
9922     // Use a specialized diagnostic when we're assigning to an object
9923     // from an enclosing function or block.
9924     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9925       if (NCCK == NCCK_Block)
9926         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9927       else
9928         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9929       break;
9930     }
9931 
9932     // In ARC, use some specialized diagnostics for occasions where we
9933     // infer 'const'.  These are always pseudo-strong variables.
9934     if (S.getLangOpts().ObjCAutoRefCount) {
9935       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9936       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9937         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9938 
9939         // Use the normal diagnostic if it's pseudo-__strong but the
9940         // user actually wrote 'const'.
9941         if (var->isARCPseudoStrong() &&
9942             (!var->getTypeSourceInfo() ||
9943              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9944           // There are two pseudo-strong cases:
9945           //  - self
9946           ObjCMethodDecl *method = S.getCurMethodDecl();
9947           if (method && var == method->getSelfDecl())
9948             DiagID = method->isClassMethod()
9949               ? diag::err_typecheck_arc_assign_self_class_method
9950               : diag::err_typecheck_arc_assign_self;
9951 
9952           //  - fast enumeration variables
9953           else
9954             DiagID = diag::err_typecheck_arr_assign_enumeration;
9955 
9956           SourceRange Assign;
9957           if (Loc != OrigLoc)
9958             Assign = SourceRange(OrigLoc, OrigLoc);
9959           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9960           // We need to preserve the AST regardless, so migration tool
9961           // can do its job.
9962           return false;
9963         }
9964       }
9965     }
9966 
9967     // If none of the special cases above are triggered, then this is a
9968     // simple const assignment.
9969     if (DiagID == 0) {
9970       DiagnoseConstAssignment(S, E, Loc);
9971       return true;
9972     }
9973 
9974     break;
9975   case Expr::MLV_ConstAddrSpace:
9976     DiagnoseConstAssignment(S, E, Loc);
9977     return true;
9978   case Expr::MLV_ArrayType:
9979   case Expr::MLV_ArrayTemporary:
9980     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9981     NeedType = true;
9982     break;
9983   case Expr::MLV_NotObjectType:
9984     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9985     NeedType = true;
9986     break;
9987   case Expr::MLV_LValueCast:
9988     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9989     break;
9990   case Expr::MLV_Valid:
9991     llvm_unreachable("did not take early return for MLV_Valid");
9992   case Expr::MLV_InvalidExpression:
9993   case Expr::MLV_MemberFunction:
9994   case Expr::MLV_ClassTemporary:
9995     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9996     break;
9997   case Expr::MLV_IncompleteType:
9998   case Expr::MLV_IncompleteVoidType:
9999     return S.RequireCompleteType(Loc, E->getType(),
10000              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10001   case Expr::MLV_DuplicateVectorComponents:
10002     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10003     break;
10004   case Expr::MLV_NoSetterProperty:
10005     llvm_unreachable("readonly properties should be processed differently");
10006   case Expr::MLV_InvalidMessageExpression:
10007     DiagID = diag::error_readonly_message_assignment;
10008     break;
10009   case Expr::MLV_SubObjCPropertySetting:
10010     DiagID = diag::error_no_subobject_property_setting;
10011     break;
10012   }
10013 
10014   SourceRange Assign;
10015   if (Loc != OrigLoc)
10016     Assign = SourceRange(OrigLoc, OrigLoc);
10017   if (NeedType)
10018     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10019   else
10020     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10021   return true;
10022 }
10023 
10024 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10025                                          SourceLocation Loc,
10026                                          Sema &Sema) {
10027   // C / C++ fields
10028   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10029   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10030   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10031     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10032       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10033   }
10034 
10035   // Objective-C instance variables
10036   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10037   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10038   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10039     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10040     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10041     if (RL && RR && RL->getDecl() == RR->getDecl())
10042       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10043   }
10044 }
10045 
10046 // C99 6.5.16.1
10047 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10048                                        SourceLocation Loc,
10049                                        QualType CompoundType) {
10050   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10051 
10052   // Verify that LHS is a modifiable lvalue, and emit error if not.
10053   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10054     return QualType();
10055 
10056   QualType LHSType = LHSExpr->getType();
10057   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10058                                              CompoundType;
10059   AssignConvertType ConvTy;
10060   if (CompoundType.isNull()) {
10061     Expr *RHSCheck = RHS.get();
10062 
10063     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10064 
10065     QualType LHSTy(LHSType);
10066     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10067     if (RHS.isInvalid())
10068       return QualType();
10069     // Special case of NSObject attributes on c-style pointer types.
10070     if (ConvTy == IncompatiblePointer &&
10071         ((Context.isObjCNSObjectType(LHSType) &&
10072           RHSType->isObjCObjectPointerType()) ||
10073          (Context.isObjCNSObjectType(RHSType) &&
10074           LHSType->isObjCObjectPointerType())))
10075       ConvTy = Compatible;
10076 
10077     if (ConvTy == Compatible &&
10078         LHSType->isObjCObjectType())
10079         Diag(Loc, diag::err_objc_object_assignment)
10080           << LHSType;
10081 
10082     // If the RHS is a unary plus or minus, check to see if they = and + are
10083     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10084     // instead of "x += 4".
10085     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10086       RHSCheck = ICE->getSubExpr();
10087     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10088       if ((UO->getOpcode() == UO_Plus ||
10089            UO->getOpcode() == UO_Minus) &&
10090           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10091           // Only if the two operators are exactly adjacent.
10092           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10093           // And there is a space or other character before the subexpr of the
10094           // unary +/-.  We don't want to warn on "x=-1".
10095           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10096           UO->getSubExpr()->getLocStart().isFileID()) {
10097         Diag(Loc, diag::warn_not_compound_assign)
10098           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10099           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10100       }
10101     }
10102 
10103     if (ConvTy == Compatible) {
10104       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10105         // Warn about retain cycles where a block captures the LHS, but
10106         // not if the LHS is a simple variable into which the block is
10107         // being stored...unless that variable can be captured by reference!
10108         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10109         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10110         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10111           checkRetainCycles(LHSExpr, RHS.get());
10112 
10113         // It is safe to assign a weak reference into a strong variable.
10114         // Although this code can still have problems:
10115         //   id x = self.weakProp;
10116         //   id y = self.weakProp;
10117         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10118         // paths through the function. This should be revisited if
10119         // -Wrepeated-use-of-weak is made flow-sensitive.
10120         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10121                              RHS.get()->getLocStart()))
10122           getCurFunction()->markSafeWeakUse(RHS.get());
10123 
10124       } else if (getLangOpts().ObjCAutoRefCount) {
10125         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10126       }
10127     }
10128   } else {
10129     // Compound assignment "x += y"
10130     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10131   }
10132 
10133   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10134                                RHS.get(), AA_Assigning))
10135     return QualType();
10136 
10137   CheckForNullPointerDereference(*this, LHSExpr);
10138 
10139   // C99 6.5.16p3: The type of an assignment expression is the type of the
10140   // left operand unless the left operand has qualified type, in which case
10141   // it is the unqualified version of the type of the left operand.
10142   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10143   // is converted to the type of the assignment expression (above).
10144   // C++ 5.17p1: the type of the assignment expression is that of its left
10145   // operand.
10146   return (getLangOpts().CPlusPlus
10147           ? LHSType : LHSType.getUnqualifiedType());
10148 }
10149 
10150 // Only ignore explicit casts to void.
10151 static bool IgnoreCommaOperand(const Expr *E) {
10152   E = E->IgnoreParens();
10153 
10154   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10155     if (CE->getCastKind() == CK_ToVoid) {
10156       return true;
10157     }
10158   }
10159 
10160   return false;
10161 }
10162 
10163 // Look for instances where it is likely the comma operator is confused with
10164 // another operator.  There is a whitelist of acceptable expressions for the
10165 // left hand side of the comma operator, otherwise emit a warning.
10166 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10167   // No warnings in macros
10168   if (Loc.isMacroID())
10169     return;
10170 
10171   // Don't warn in template instantiations.
10172   if (!ActiveTemplateInstantiations.empty())
10173     return;
10174 
10175   // Scope isn't fine-grained enough to whitelist the specific cases, so
10176   // instead, skip more than needed, then call back into here with the
10177   // CommaVisitor in SemaStmt.cpp.
10178   // The whitelisted locations are the initialization and increment portions
10179   // of a for loop.  The additional checks are on the condition of
10180   // if statements, do/while loops, and for loops.
10181   const unsigned ForIncrementFlags =
10182       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10183   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10184   const unsigned ScopeFlags = getCurScope()->getFlags();
10185   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10186       (ScopeFlags & ForInitFlags) == ForInitFlags)
10187     return;
10188 
10189   // If there are multiple comma operators used together, get the RHS of the
10190   // of the comma operator as the LHS.
10191   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10192     if (BO->getOpcode() != BO_Comma)
10193       break;
10194     LHS = BO->getRHS();
10195   }
10196 
10197   // Only allow some expressions on LHS to not warn.
10198   if (IgnoreCommaOperand(LHS))
10199     return;
10200 
10201   Diag(Loc, diag::warn_comma_operator);
10202   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10203       << LHS->getSourceRange()
10204       << FixItHint::CreateInsertion(LHS->getLocStart(),
10205                                     LangOpts.CPlusPlus ? "static_cast<void>("
10206                                                        : "(void)(")
10207       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10208                                     ")");
10209 }
10210 
10211 // C99 6.5.17
10212 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10213                                    SourceLocation Loc) {
10214   LHS = S.CheckPlaceholderExpr(LHS.get());
10215   RHS = S.CheckPlaceholderExpr(RHS.get());
10216   if (LHS.isInvalid() || RHS.isInvalid())
10217     return QualType();
10218 
10219   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10220   // operands, but not unary promotions.
10221   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10222 
10223   // So we treat the LHS as a ignored value, and in C++ we allow the
10224   // containing site to determine what should be done with the RHS.
10225   LHS = S.IgnoredValueConversions(LHS.get());
10226   if (LHS.isInvalid())
10227     return QualType();
10228 
10229   S.DiagnoseUnusedExprResult(LHS.get());
10230 
10231   if (!S.getLangOpts().CPlusPlus) {
10232     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10233     if (RHS.isInvalid())
10234       return QualType();
10235     if (!RHS.get()->getType()->isVoidType())
10236       S.RequireCompleteType(Loc, RHS.get()->getType(),
10237                             diag::err_incomplete_type);
10238   }
10239 
10240   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10241     S.DiagnoseCommaOperator(LHS.get(), Loc);
10242 
10243   return RHS.get()->getType();
10244 }
10245 
10246 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10247 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10248 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10249                                                ExprValueKind &VK,
10250                                                ExprObjectKind &OK,
10251                                                SourceLocation OpLoc,
10252                                                bool IsInc, bool IsPrefix) {
10253   if (Op->isTypeDependent())
10254     return S.Context.DependentTy;
10255 
10256   QualType ResType = Op->getType();
10257   // Atomic types can be used for increment / decrement where the non-atomic
10258   // versions can, so ignore the _Atomic() specifier for the purpose of
10259   // checking.
10260   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10261     ResType = ResAtomicType->getValueType();
10262 
10263   assert(!ResType.isNull() && "no type for increment/decrement expression");
10264 
10265   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10266     // Decrement of bool is not allowed.
10267     if (!IsInc) {
10268       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10269       return QualType();
10270     }
10271     // Increment of bool sets it to true, but is deprecated.
10272     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10273                                               : diag::warn_increment_bool)
10274       << Op->getSourceRange();
10275   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10276     // Error on enum increments and decrements in C++ mode
10277     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10278     return QualType();
10279   } else if (ResType->isRealType()) {
10280     // OK!
10281   } else if (ResType->isPointerType()) {
10282     // C99 6.5.2.4p2, 6.5.6p2
10283     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10284       return QualType();
10285   } else if (ResType->isObjCObjectPointerType()) {
10286     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10287     // Otherwise, we just need a complete type.
10288     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10289         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10290       return QualType();
10291   } else if (ResType->isAnyComplexType()) {
10292     // C99 does not support ++/-- on complex types, we allow as an extension.
10293     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10294       << ResType << Op->getSourceRange();
10295   } else if (ResType->isPlaceholderType()) {
10296     ExprResult PR = S.CheckPlaceholderExpr(Op);
10297     if (PR.isInvalid()) return QualType();
10298     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10299                                           IsInc, IsPrefix);
10300   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10301     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10302   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10303              (ResType->getAs<VectorType>()->getVectorKind() !=
10304               VectorType::AltiVecBool)) {
10305     // The z vector extensions allow ++ and -- for non-bool vectors.
10306   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10307             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10308     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10309   } else {
10310     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10311       << ResType << int(IsInc) << Op->getSourceRange();
10312     return QualType();
10313   }
10314   // At this point, we know we have a real, complex or pointer type.
10315   // Now make sure the operand is a modifiable lvalue.
10316   if (CheckForModifiableLvalue(Op, OpLoc, S))
10317     return QualType();
10318   // In C++, a prefix increment is the same type as the operand. Otherwise
10319   // (in C or with postfix), the increment is the unqualified type of the
10320   // operand.
10321   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10322     VK = VK_LValue;
10323     OK = Op->getObjectKind();
10324     return ResType;
10325   } else {
10326     VK = VK_RValue;
10327     return ResType.getUnqualifiedType();
10328   }
10329 }
10330 
10331 
10332 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10333 /// This routine allows us to typecheck complex/recursive expressions
10334 /// where the declaration is needed for type checking. We only need to
10335 /// handle cases when the expression references a function designator
10336 /// or is an lvalue. Here are some examples:
10337 ///  - &(x) => x
10338 ///  - &*****f => f for f a function designator.
10339 ///  - &s.xx => s
10340 ///  - &s.zz[1].yy -> s, if zz is an array
10341 ///  - *(x + 1) -> x, if x is an array
10342 ///  - &"123"[2] -> 0
10343 ///  - & __real__ x -> x
10344 static ValueDecl *getPrimaryDecl(Expr *E) {
10345   switch (E->getStmtClass()) {
10346   case Stmt::DeclRefExprClass:
10347     return cast<DeclRefExpr>(E)->getDecl();
10348   case Stmt::MemberExprClass:
10349     // If this is an arrow operator, the address is an offset from
10350     // the base's value, so the object the base refers to is
10351     // irrelevant.
10352     if (cast<MemberExpr>(E)->isArrow())
10353       return nullptr;
10354     // Otherwise, the expression refers to a part of the base
10355     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10356   case Stmt::ArraySubscriptExprClass: {
10357     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10358     // promotion of register arrays earlier.
10359     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10360     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10361       if (ICE->getSubExpr()->getType()->isArrayType())
10362         return getPrimaryDecl(ICE->getSubExpr());
10363     }
10364     return nullptr;
10365   }
10366   case Stmt::UnaryOperatorClass: {
10367     UnaryOperator *UO = cast<UnaryOperator>(E);
10368 
10369     switch(UO->getOpcode()) {
10370     case UO_Real:
10371     case UO_Imag:
10372     case UO_Extension:
10373       return getPrimaryDecl(UO->getSubExpr());
10374     default:
10375       return nullptr;
10376     }
10377   }
10378   case Stmt::ParenExprClass:
10379     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10380   case Stmt::ImplicitCastExprClass:
10381     // If the result of an implicit cast is an l-value, we care about
10382     // the sub-expression; otherwise, the result here doesn't matter.
10383     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10384   default:
10385     return nullptr;
10386   }
10387 }
10388 
10389 namespace {
10390   enum {
10391     AO_Bit_Field = 0,
10392     AO_Vector_Element = 1,
10393     AO_Property_Expansion = 2,
10394     AO_Register_Variable = 3,
10395     AO_No_Error = 4
10396   };
10397 }
10398 /// \brief Diagnose invalid operand for address of operations.
10399 ///
10400 /// \param Type The type of operand which cannot have its address taken.
10401 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10402                                          Expr *E, unsigned Type) {
10403   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10404 }
10405 
10406 /// CheckAddressOfOperand - The operand of & must be either a function
10407 /// designator or an lvalue designating an object. If it is an lvalue, the
10408 /// object cannot be declared with storage class register or be a bit field.
10409 /// Note: The usual conversions are *not* applied to the operand of the &
10410 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10411 /// In C++, the operand might be an overloaded function name, in which case
10412 /// we allow the '&' but retain the overloaded-function type.
10413 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10414   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10415     if (PTy->getKind() == BuiltinType::Overload) {
10416       Expr *E = OrigOp.get()->IgnoreParens();
10417       if (!isa<OverloadExpr>(E)) {
10418         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10419         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10420           << OrigOp.get()->getSourceRange();
10421         return QualType();
10422       }
10423 
10424       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10425       if (isa<UnresolvedMemberExpr>(Ovl))
10426         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10427           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10428             << OrigOp.get()->getSourceRange();
10429           return QualType();
10430         }
10431 
10432       return Context.OverloadTy;
10433     }
10434 
10435     if (PTy->getKind() == BuiltinType::UnknownAny)
10436       return Context.UnknownAnyTy;
10437 
10438     if (PTy->getKind() == BuiltinType::BoundMember) {
10439       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10440         << OrigOp.get()->getSourceRange();
10441       return QualType();
10442     }
10443 
10444     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10445     if (OrigOp.isInvalid()) return QualType();
10446   }
10447 
10448   if (OrigOp.get()->isTypeDependent())
10449     return Context.DependentTy;
10450 
10451   assert(!OrigOp.get()->getType()->isPlaceholderType());
10452 
10453   // Make sure to ignore parentheses in subsequent checks
10454   Expr *op = OrigOp.get()->IgnoreParens();
10455 
10456   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10457   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10458     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10459     return QualType();
10460   }
10461 
10462   if (getLangOpts().C99) {
10463     // Implement C99-only parts of addressof rules.
10464     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10465       if (uOp->getOpcode() == UO_Deref)
10466         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10467         // (assuming the deref expression is valid).
10468         return uOp->getSubExpr()->getType();
10469     }
10470     // Technically, there should be a check for array subscript
10471     // expressions here, but the result of one is always an lvalue anyway.
10472   }
10473   ValueDecl *dcl = getPrimaryDecl(op);
10474 
10475   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10476     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10477                                            op->getLocStart()))
10478       return QualType();
10479 
10480   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10481   unsigned AddressOfError = AO_No_Error;
10482 
10483   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10484     bool sfinae = (bool)isSFINAEContext();
10485     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10486                                   : diag::ext_typecheck_addrof_temporary)
10487       << op->getType() << op->getSourceRange();
10488     if (sfinae)
10489       return QualType();
10490     // Materialize the temporary as an lvalue so that we can take its address.
10491     OrigOp = op =
10492         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10493   } else if (isa<ObjCSelectorExpr>(op)) {
10494     return Context.getPointerType(op->getType());
10495   } else if (lval == Expr::LV_MemberFunction) {
10496     // If it's an instance method, make a member pointer.
10497     // The expression must have exactly the form &A::foo.
10498 
10499     // If the underlying expression isn't a decl ref, give up.
10500     if (!isa<DeclRefExpr>(op)) {
10501       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10502         << OrigOp.get()->getSourceRange();
10503       return QualType();
10504     }
10505     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10506     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10507 
10508     // The id-expression was parenthesized.
10509     if (OrigOp.get() != DRE) {
10510       Diag(OpLoc, diag::err_parens_pointer_member_function)
10511         << OrigOp.get()->getSourceRange();
10512 
10513     // The method was named without a qualifier.
10514     } else if (!DRE->getQualifier()) {
10515       if (MD->getParent()->getName().empty())
10516         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10517           << op->getSourceRange();
10518       else {
10519         SmallString<32> Str;
10520         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10521         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10522           << op->getSourceRange()
10523           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10524       }
10525     }
10526 
10527     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10528     if (isa<CXXDestructorDecl>(MD))
10529       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10530 
10531     QualType MPTy = Context.getMemberPointerType(
10532         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10533     // Under the MS ABI, lock down the inheritance model now.
10534     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10535       (void)isCompleteType(OpLoc, MPTy);
10536     return MPTy;
10537   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10538     // C99 6.5.3.2p1
10539     // The operand must be either an l-value or a function designator
10540     if (!op->getType()->isFunctionType()) {
10541       // Use a special diagnostic for loads from property references.
10542       if (isa<PseudoObjectExpr>(op)) {
10543         AddressOfError = AO_Property_Expansion;
10544       } else {
10545         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10546           << op->getType() << op->getSourceRange();
10547         return QualType();
10548       }
10549     }
10550   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10551     // The operand cannot be a bit-field
10552     AddressOfError = AO_Bit_Field;
10553   } else if (op->getObjectKind() == OK_VectorComponent) {
10554     // The operand cannot be an element of a vector
10555     AddressOfError = AO_Vector_Element;
10556   } else if (dcl) { // C99 6.5.3.2p1
10557     // We have an lvalue with a decl. Make sure the decl is not declared
10558     // with the register storage-class specifier.
10559     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10560       // in C++ it is not error to take address of a register
10561       // variable (c++03 7.1.1P3)
10562       if (vd->getStorageClass() == SC_Register &&
10563           !getLangOpts().CPlusPlus) {
10564         AddressOfError = AO_Register_Variable;
10565       }
10566     } else if (isa<MSPropertyDecl>(dcl)) {
10567       AddressOfError = AO_Property_Expansion;
10568     } else if (isa<FunctionTemplateDecl>(dcl)) {
10569       return Context.OverloadTy;
10570     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10571       // Okay: we can take the address of a field.
10572       // Could be a pointer to member, though, if there is an explicit
10573       // scope qualifier for the class.
10574       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10575         DeclContext *Ctx = dcl->getDeclContext();
10576         if (Ctx && Ctx->isRecord()) {
10577           if (dcl->getType()->isReferenceType()) {
10578             Diag(OpLoc,
10579                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10580               << dcl->getDeclName() << dcl->getType();
10581             return QualType();
10582           }
10583 
10584           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10585             Ctx = Ctx->getParent();
10586 
10587           QualType MPTy = Context.getMemberPointerType(
10588               op->getType(),
10589               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10590           // Under the MS ABI, lock down the inheritance model now.
10591           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10592             (void)isCompleteType(OpLoc, MPTy);
10593           return MPTy;
10594         }
10595       }
10596     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10597                !isa<BindingDecl>(dcl))
10598       llvm_unreachable("Unknown/unexpected decl type");
10599   }
10600 
10601   if (AddressOfError != AO_No_Error) {
10602     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10603     return QualType();
10604   }
10605 
10606   if (lval == Expr::LV_IncompleteVoidType) {
10607     // Taking the address of a void variable is technically illegal, but we
10608     // allow it in cases which are otherwise valid.
10609     // Example: "extern void x; void* y = &x;".
10610     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10611   }
10612 
10613   // If the operand has type "type", the result has type "pointer to type".
10614   if (op->getType()->isObjCObjectType())
10615     return Context.getObjCObjectPointerType(op->getType());
10616 
10617   return Context.getPointerType(op->getType());
10618 }
10619 
10620 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10621   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10622   if (!DRE)
10623     return;
10624   const Decl *D = DRE->getDecl();
10625   if (!D)
10626     return;
10627   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10628   if (!Param)
10629     return;
10630   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10631     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10632       return;
10633   if (FunctionScopeInfo *FD = S.getCurFunction())
10634     if (!FD->ModifiedNonNullParams.count(Param))
10635       FD->ModifiedNonNullParams.insert(Param);
10636 }
10637 
10638 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10639 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10640                                         SourceLocation OpLoc) {
10641   if (Op->isTypeDependent())
10642     return S.Context.DependentTy;
10643 
10644   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10645   if (ConvResult.isInvalid())
10646     return QualType();
10647   Op = ConvResult.get();
10648   QualType OpTy = Op->getType();
10649   QualType Result;
10650 
10651   if (isa<CXXReinterpretCastExpr>(Op)) {
10652     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10653     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10654                                      Op->getSourceRange());
10655   }
10656 
10657   if (const PointerType *PT = OpTy->getAs<PointerType>())
10658   {
10659     Result = PT->getPointeeType();
10660   }
10661   else if (const ObjCObjectPointerType *OPT =
10662              OpTy->getAs<ObjCObjectPointerType>())
10663     Result = OPT->getPointeeType();
10664   else {
10665     ExprResult PR = S.CheckPlaceholderExpr(Op);
10666     if (PR.isInvalid()) return QualType();
10667     if (PR.get() != Op)
10668       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10669   }
10670 
10671   if (Result.isNull()) {
10672     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10673       << OpTy << Op->getSourceRange();
10674     return QualType();
10675   }
10676 
10677   // Note that per both C89 and C99, indirection is always legal, even if Result
10678   // is an incomplete type or void.  It would be possible to warn about
10679   // dereferencing a void pointer, but it's completely well-defined, and such a
10680   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10681   // for pointers to 'void' but is fine for any other pointer type:
10682   //
10683   // C++ [expr.unary.op]p1:
10684   //   [...] the expression to which [the unary * operator] is applied shall
10685   //   be a pointer to an object type, or a pointer to a function type
10686   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10687     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10688       << OpTy << Op->getSourceRange();
10689 
10690   // Dereferences are usually l-values...
10691   VK = VK_LValue;
10692 
10693   // ...except that certain expressions are never l-values in C.
10694   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10695     VK = VK_RValue;
10696 
10697   return Result;
10698 }
10699 
10700 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10701   BinaryOperatorKind Opc;
10702   switch (Kind) {
10703   default: llvm_unreachable("Unknown binop!");
10704   case tok::periodstar:           Opc = BO_PtrMemD; break;
10705   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10706   case tok::star:                 Opc = BO_Mul; break;
10707   case tok::slash:                Opc = BO_Div; break;
10708   case tok::percent:              Opc = BO_Rem; break;
10709   case tok::plus:                 Opc = BO_Add; break;
10710   case tok::minus:                Opc = BO_Sub; break;
10711   case tok::lessless:             Opc = BO_Shl; break;
10712   case tok::greatergreater:       Opc = BO_Shr; break;
10713   case tok::lessequal:            Opc = BO_LE; break;
10714   case tok::less:                 Opc = BO_LT; break;
10715   case tok::greaterequal:         Opc = BO_GE; break;
10716   case tok::greater:              Opc = BO_GT; break;
10717   case tok::exclaimequal:         Opc = BO_NE; break;
10718   case tok::equalequal:           Opc = BO_EQ; break;
10719   case tok::amp:                  Opc = BO_And; break;
10720   case tok::caret:                Opc = BO_Xor; break;
10721   case tok::pipe:                 Opc = BO_Or; break;
10722   case tok::ampamp:               Opc = BO_LAnd; break;
10723   case tok::pipepipe:             Opc = BO_LOr; break;
10724   case tok::equal:                Opc = BO_Assign; break;
10725   case tok::starequal:            Opc = BO_MulAssign; break;
10726   case tok::slashequal:           Opc = BO_DivAssign; break;
10727   case tok::percentequal:         Opc = BO_RemAssign; break;
10728   case tok::plusequal:            Opc = BO_AddAssign; break;
10729   case tok::minusequal:           Opc = BO_SubAssign; break;
10730   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10731   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10732   case tok::ampequal:             Opc = BO_AndAssign; break;
10733   case tok::caretequal:           Opc = BO_XorAssign; break;
10734   case tok::pipeequal:            Opc = BO_OrAssign; break;
10735   case tok::comma:                Opc = BO_Comma; break;
10736   }
10737   return Opc;
10738 }
10739 
10740 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10741   tok::TokenKind Kind) {
10742   UnaryOperatorKind Opc;
10743   switch (Kind) {
10744   default: llvm_unreachable("Unknown unary op!");
10745   case tok::plusplus:     Opc = UO_PreInc; break;
10746   case tok::minusminus:   Opc = UO_PreDec; break;
10747   case tok::amp:          Opc = UO_AddrOf; break;
10748   case tok::star:         Opc = UO_Deref; break;
10749   case tok::plus:         Opc = UO_Plus; break;
10750   case tok::minus:        Opc = UO_Minus; break;
10751   case tok::tilde:        Opc = UO_Not; break;
10752   case tok::exclaim:      Opc = UO_LNot; break;
10753   case tok::kw___real:    Opc = UO_Real; break;
10754   case tok::kw___imag:    Opc = UO_Imag; break;
10755   case tok::kw___extension__: Opc = UO_Extension; break;
10756   }
10757   return Opc;
10758 }
10759 
10760 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10761 /// This warning is only emitted for builtin assignment operations. It is also
10762 /// suppressed in the event of macro expansions.
10763 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10764                                    SourceLocation OpLoc) {
10765   if (!S.ActiveTemplateInstantiations.empty())
10766     return;
10767   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10768     return;
10769   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10770   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10771   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10772   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10773   if (!LHSDeclRef || !RHSDeclRef ||
10774       LHSDeclRef->getLocation().isMacroID() ||
10775       RHSDeclRef->getLocation().isMacroID())
10776     return;
10777   const ValueDecl *LHSDecl =
10778     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10779   const ValueDecl *RHSDecl =
10780     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10781   if (LHSDecl != RHSDecl)
10782     return;
10783   if (LHSDecl->getType().isVolatileQualified())
10784     return;
10785   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10786     if (RefTy->getPointeeType().isVolatileQualified())
10787       return;
10788 
10789   S.Diag(OpLoc, diag::warn_self_assignment)
10790       << LHSDeclRef->getType()
10791       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10792 }
10793 
10794 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10795 /// is usually indicative of introspection within the Objective-C pointer.
10796 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10797                                           SourceLocation OpLoc) {
10798   if (!S.getLangOpts().ObjC1)
10799     return;
10800 
10801   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10802   const Expr *LHS = L.get();
10803   const Expr *RHS = R.get();
10804 
10805   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10806     ObjCPointerExpr = LHS;
10807     OtherExpr = RHS;
10808   }
10809   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10810     ObjCPointerExpr = RHS;
10811     OtherExpr = LHS;
10812   }
10813 
10814   // This warning is deliberately made very specific to reduce false
10815   // positives with logic that uses '&' for hashing.  This logic mainly
10816   // looks for code trying to introspect into tagged pointers, which
10817   // code should generally never do.
10818   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10819     unsigned Diag = diag::warn_objc_pointer_masking;
10820     // Determine if we are introspecting the result of performSelectorXXX.
10821     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10822     // Special case messages to -performSelector and friends, which
10823     // can return non-pointer values boxed in a pointer value.
10824     // Some clients may wish to silence warnings in this subcase.
10825     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10826       Selector S = ME->getSelector();
10827       StringRef SelArg0 = S.getNameForSlot(0);
10828       if (SelArg0.startswith("performSelector"))
10829         Diag = diag::warn_objc_pointer_masking_performSelector;
10830     }
10831 
10832     S.Diag(OpLoc, Diag)
10833       << ObjCPointerExpr->getSourceRange();
10834   }
10835 }
10836 
10837 static NamedDecl *getDeclFromExpr(Expr *E) {
10838   if (!E)
10839     return nullptr;
10840   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10841     return DRE->getDecl();
10842   if (auto *ME = dyn_cast<MemberExpr>(E))
10843     return ME->getMemberDecl();
10844   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10845     return IRE->getDecl();
10846   return nullptr;
10847 }
10848 
10849 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10850 /// operator @p Opc at location @c TokLoc. This routine only supports
10851 /// built-in operations; ActOnBinOp handles overloaded operators.
10852 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10853                                     BinaryOperatorKind Opc,
10854                                     Expr *LHSExpr, Expr *RHSExpr) {
10855   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10856     // The syntax only allows initializer lists on the RHS of assignment,
10857     // so we don't need to worry about accepting invalid code for
10858     // non-assignment operators.
10859     // C++11 5.17p9:
10860     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10861     //   of x = {} is x = T().
10862     InitializationKind Kind =
10863         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10864     InitializedEntity Entity =
10865         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10866     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10867     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10868     if (Init.isInvalid())
10869       return Init;
10870     RHSExpr = Init.get();
10871   }
10872 
10873   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10874   QualType ResultTy;     // Result type of the binary operator.
10875   // The following two variables are used for compound assignment operators
10876   QualType CompLHSTy;    // Type of LHS after promotions for computation
10877   QualType CompResultTy; // Type of computation result
10878   ExprValueKind VK = VK_RValue;
10879   ExprObjectKind OK = OK_Ordinary;
10880 
10881   if (!getLangOpts().CPlusPlus) {
10882     // C cannot handle TypoExpr nodes on either side of a binop because it
10883     // doesn't handle dependent types properly, so make sure any TypoExprs have
10884     // been dealt with before checking the operands.
10885     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10886     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10887       if (Opc != BO_Assign)
10888         return ExprResult(E);
10889       // Avoid correcting the RHS to the same Expr as the LHS.
10890       Decl *D = getDeclFromExpr(E);
10891       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10892     });
10893     if (!LHS.isUsable() || !RHS.isUsable())
10894       return ExprError();
10895   }
10896 
10897   if (getLangOpts().OpenCL) {
10898     QualType LHSTy = LHSExpr->getType();
10899     QualType RHSTy = RHSExpr->getType();
10900     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10901     // the ATOMIC_VAR_INIT macro.
10902     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10903       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10904       if (BO_Assign == Opc)
10905         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10906       else
10907         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10908       return ExprError();
10909     }
10910 
10911     // OpenCL special types - image, sampler, pipe, and blocks are to be used
10912     // only with a builtin functions and therefore should be disallowed here.
10913     if (LHSTy->isImageType() || RHSTy->isImageType() ||
10914         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
10915         LHSTy->isPipeType() || RHSTy->isPipeType() ||
10916         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
10917       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10918       return ExprError();
10919     }
10920   }
10921 
10922   switch (Opc) {
10923   case BO_Assign:
10924     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10925     if (getLangOpts().CPlusPlus &&
10926         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10927       VK = LHS.get()->getValueKind();
10928       OK = LHS.get()->getObjectKind();
10929     }
10930     if (!ResultTy.isNull()) {
10931       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10932       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10933     }
10934     RecordModifiableNonNullParam(*this, LHS.get());
10935     break;
10936   case BO_PtrMemD:
10937   case BO_PtrMemI:
10938     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10939                                             Opc == BO_PtrMemI);
10940     break;
10941   case BO_Mul:
10942   case BO_Div:
10943     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10944                                            Opc == BO_Div);
10945     break;
10946   case BO_Rem:
10947     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10948     break;
10949   case BO_Add:
10950     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10951     break;
10952   case BO_Sub:
10953     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10954     break;
10955   case BO_Shl:
10956   case BO_Shr:
10957     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10958     break;
10959   case BO_LE:
10960   case BO_LT:
10961   case BO_GE:
10962   case BO_GT:
10963     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10964     break;
10965   case BO_EQ:
10966   case BO_NE:
10967     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10968     break;
10969   case BO_And:
10970     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10971   case BO_Xor:
10972   case BO_Or:
10973     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10974     break;
10975   case BO_LAnd:
10976   case BO_LOr:
10977     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10978     break;
10979   case BO_MulAssign:
10980   case BO_DivAssign:
10981     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10982                                                Opc == BO_DivAssign);
10983     CompLHSTy = CompResultTy;
10984     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10985       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10986     break;
10987   case BO_RemAssign:
10988     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10989     CompLHSTy = CompResultTy;
10990     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10991       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10992     break;
10993   case BO_AddAssign:
10994     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10995     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10996       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10997     break;
10998   case BO_SubAssign:
10999     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11000     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11001       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11002     break;
11003   case BO_ShlAssign:
11004   case BO_ShrAssign:
11005     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11006     CompLHSTy = CompResultTy;
11007     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11008       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11009     break;
11010   case BO_AndAssign:
11011   case BO_OrAssign: // fallthrough
11012     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11013   case BO_XorAssign:
11014     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
11015     CompLHSTy = CompResultTy;
11016     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11017       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11018     break;
11019   case BO_Comma:
11020     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11021     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11022       VK = RHS.get()->getValueKind();
11023       OK = RHS.get()->getObjectKind();
11024     }
11025     break;
11026   }
11027   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11028     return ExprError();
11029 
11030   // Check for array bounds violations for both sides of the BinaryOperator
11031   CheckArrayAccess(LHS.get());
11032   CheckArrayAccess(RHS.get());
11033 
11034   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11035     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11036                                                  &Context.Idents.get("object_setClass"),
11037                                                  SourceLocation(), LookupOrdinaryName);
11038     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11039       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11040       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11041       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11042       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11043       FixItHint::CreateInsertion(RHSLocEnd, ")");
11044     }
11045     else
11046       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11047   }
11048   else if (const ObjCIvarRefExpr *OIRE =
11049            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11050     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11051 
11052   if (CompResultTy.isNull())
11053     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11054                                         OK, OpLoc, FPFeatures.fp_contract);
11055   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11056       OK_ObjCProperty) {
11057     VK = VK_LValue;
11058     OK = LHS.get()->getObjectKind();
11059   }
11060   return new (Context) CompoundAssignOperator(
11061       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11062       OpLoc, FPFeatures.fp_contract);
11063 }
11064 
11065 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11066 /// operators are mixed in a way that suggests that the programmer forgot that
11067 /// comparison operators have higher precedence. The most typical example of
11068 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11069 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11070                                       SourceLocation OpLoc, Expr *LHSExpr,
11071                                       Expr *RHSExpr) {
11072   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11073   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11074 
11075   // Check that one of the sides is a comparison operator and the other isn't.
11076   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11077   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11078   if (isLeftComp == isRightComp)
11079     return;
11080 
11081   // Bitwise operations are sometimes used as eager logical ops.
11082   // Don't diagnose this.
11083   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11084   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11085   if (isLeftBitwise || isRightBitwise)
11086     return;
11087 
11088   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11089                                                    OpLoc)
11090                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11091   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11092   SourceRange ParensRange = isLeftComp ?
11093       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11094     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11095 
11096   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11097     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11098   SuggestParentheses(Self, OpLoc,
11099     Self.PDiag(diag::note_precedence_silence) << OpStr,
11100     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11101   SuggestParentheses(Self, OpLoc,
11102     Self.PDiag(diag::note_precedence_bitwise_first)
11103       << BinaryOperator::getOpcodeStr(Opc),
11104     ParensRange);
11105 }
11106 
11107 /// \brief It accepts a '&&' expr that is inside a '||' one.
11108 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11109 /// in parentheses.
11110 static void
11111 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11112                                        BinaryOperator *Bop) {
11113   assert(Bop->getOpcode() == BO_LAnd);
11114   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11115       << Bop->getSourceRange() << OpLoc;
11116   SuggestParentheses(Self, Bop->getOperatorLoc(),
11117     Self.PDiag(diag::note_precedence_silence)
11118       << Bop->getOpcodeStr(),
11119     Bop->getSourceRange());
11120 }
11121 
11122 /// \brief Returns true if the given expression can be evaluated as a constant
11123 /// 'true'.
11124 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11125   bool Res;
11126   return !E->isValueDependent() &&
11127          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11128 }
11129 
11130 /// \brief Returns true if the given expression can be evaluated as a constant
11131 /// 'false'.
11132 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11133   bool Res;
11134   return !E->isValueDependent() &&
11135          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11136 }
11137 
11138 /// \brief Look for '&&' in the left hand of a '||' expr.
11139 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11140                                              Expr *LHSExpr, Expr *RHSExpr) {
11141   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11142     if (Bop->getOpcode() == BO_LAnd) {
11143       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11144       if (EvaluatesAsFalse(S, RHSExpr))
11145         return;
11146       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11147       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11148         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11149     } else if (Bop->getOpcode() == BO_LOr) {
11150       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11151         // If it's "a || b && 1 || c" we didn't warn earlier for
11152         // "a || b && 1", but warn now.
11153         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11154           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11155       }
11156     }
11157   }
11158 }
11159 
11160 /// \brief Look for '&&' in the right hand of a '||' expr.
11161 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11162                                              Expr *LHSExpr, Expr *RHSExpr) {
11163   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11164     if (Bop->getOpcode() == BO_LAnd) {
11165       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11166       if (EvaluatesAsFalse(S, LHSExpr))
11167         return;
11168       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11169       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11170         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11171     }
11172   }
11173 }
11174 
11175 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11176 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11177 /// the '&' expression in parentheses.
11178 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11179                                          SourceLocation OpLoc, Expr *SubExpr) {
11180   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11181     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11182       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11183         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11184         << Bop->getSourceRange() << OpLoc;
11185       SuggestParentheses(S, Bop->getOperatorLoc(),
11186         S.PDiag(diag::note_precedence_silence)
11187           << Bop->getOpcodeStr(),
11188         Bop->getSourceRange());
11189     }
11190   }
11191 }
11192 
11193 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11194                                     Expr *SubExpr, StringRef Shift) {
11195   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11196     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11197       StringRef Op = Bop->getOpcodeStr();
11198       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11199           << Bop->getSourceRange() << OpLoc << Shift << Op;
11200       SuggestParentheses(S, Bop->getOperatorLoc(),
11201           S.PDiag(diag::note_precedence_silence) << Op,
11202           Bop->getSourceRange());
11203     }
11204   }
11205 }
11206 
11207 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11208                                  Expr *LHSExpr, Expr *RHSExpr) {
11209   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11210   if (!OCE)
11211     return;
11212 
11213   FunctionDecl *FD = OCE->getDirectCallee();
11214   if (!FD || !FD->isOverloadedOperator())
11215     return;
11216 
11217   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11218   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11219     return;
11220 
11221   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11222       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11223       << (Kind == OO_LessLess);
11224   SuggestParentheses(S, OCE->getOperatorLoc(),
11225                      S.PDiag(diag::note_precedence_silence)
11226                          << (Kind == OO_LessLess ? "<<" : ">>"),
11227                      OCE->getSourceRange());
11228   SuggestParentheses(S, OpLoc,
11229                      S.PDiag(diag::note_evaluate_comparison_first),
11230                      SourceRange(OCE->getArg(1)->getLocStart(),
11231                                  RHSExpr->getLocEnd()));
11232 }
11233 
11234 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11235 /// precedence.
11236 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11237                                     SourceLocation OpLoc, Expr *LHSExpr,
11238                                     Expr *RHSExpr){
11239   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11240   if (BinaryOperator::isBitwiseOp(Opc))
11241     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11242 
11243   // Diagnose "arg1 & arg2 | arg3"
11244   if ((Opc == BO_Or || Opc == BO_Xor) &&
11245       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11246     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11247     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11248   }
11249 
11250   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11251   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11252   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11253     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11254     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11255   }
11256 
11257   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11258       || Opc == BO_Shr) {
11259     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11260     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11261     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11262   }
11263 
11264   // Warn on overloaded shift operators and comparisons, such as:
11265   // cout << 5 == 4;
11266   if (BinaryOperator::isComparisonOp(Opc))
11267     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11268 }
11269 
11270 // Binary Operators.  'Tok' is the token for the operator.
11271 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11272                             tok::TokenKind Kind,
11273                             Expr *LHSExpr, Expr *RHSExpr) {
11274   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11275   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11276   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11277 
11278   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11279   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11280 
11281   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11282 }
11283 
11284 /// Build an overloaded binary operator expression in the given scope.
11285 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11286                                        BinaryOperatorKind Opc,
11287                                        Expr *LHS, Expr *RHS) {
11288   // Find all of the overloaded operators visible from this
11289   // point. We perform both an operator-name lookup from the local
11290   // scope and an argument-dependent lookup based on the types of
11291   // the arguments.
11292   UnresolvedSet<16> Functions;
11293   OverloadedOperatorKind OverOp
11294     = BinaryOperator::getOverloadedOperator(Opc);
11295   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11296     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11297                                    RHS->getType(), Functions);
11298 
11299   // Build the (potentially-overloaded, potentially-dependent)
11300   // binary operation.
11301   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11302 }
11303 
11304 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11305                             BinaryOperatorKind Opc,
11306                             Expr *LHSExpr, Expr *RHSExpr) {
11307   // We want to end up calling one of checkPseudoObjectAssignment
11308   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11309   // both expressions are overloadable or either is type-dependent),
11310   // or CreateBuiltinBinOp (in any other case).  We also want to get
11311   // any placeholder types out of the way.
11312 
11313   // Handle pseudo-objects in the LHS.
11314   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11315     // Assignments with a pseudo-object l-value need special analysis.
11316     if (pty->getKind() == BuiltinType::PseudoObject &&
11317         BinaryOperator::isAssignmentOp(Opc))
11318       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11319 
11320     // Don't resolve overloads if the other type is overloadable.
11321     if (pty->getKind() == BuiltinType::Overload) {
11322       // We can't actually test that if we still have a placeholder,
11323       // though.  Fortunately, none of the exceptions we see in that
11324       // code below are valid when the LHS is an overload set.  Note
11325       // that an overload set can be dependently-typed, but it never
11326       // instantiates to having an overloadable type.
11327       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11328       if (resolvedRHS.isInvalid()) return ExprError();
11329       RHSExpr = resolvedRHS.get();
11330 
11331       if (RHSExpr->isTypeDependent() ||
11332           RHSExpr->getType()->isOverloadableType())
11333         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11334     }
11335 
11336     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11337     if (LHS.isInvalid()) return ExprError();
11338     LHSExpr = LHS.get();
11339   }
11340 
11341   // Handle pseudo-objects in the RHS.
11342   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11343     // An overload in the RHS can potentially be resolved by the type
11344     // being assigned to.
11345     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11346       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11347         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11348 
11349       if (LHSExpr->getType()->isOverloadableType())
11350         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11351 
11352       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11353     }
11354 
11355     // Don't resolve overloads if the other type is overloadable.
11356     if (pty->getKind() == BuiltinType::Overload &&
11357         LHSExpr->getType()->isOverloadableType())
11358       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11359 
11360     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11361     if (!resolvedRHS.isUsable()) return ExprError();
11362     RHSExpr = resolvedRHS.get();
11363   }
11364 
11365   if (getLangOpts().CPlusPlus) {
11366     // If either expression is type-dependent, always build an
11367     // overloaded op.
11368     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11369       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11370 
11371     // Otherwise, build an overloaded op if either expression has an
11372     // overloadable type.
11373     if (LHSExpr->getType()->isOverloadableType() ||
11374         RHSExpr->getType()->isOverloadableType())
11375       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11376   }
11377 
11378   // Build a built-in binary operation.
11379   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11380 }
11381 
11382 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11383                                       UnaryOperatorKind Opc,
11384                                       Expr *InputExpr) {
11385   ExprResult Input = InputExpr;
11386   ExprValueKind VK = VK_RValue;
11387   ExprObjectKind OK = OK_Ordinary;
11388   QualType resultType;
11389   if (getLangOpts().OpenCL) {
11390     QualType Ty = InputExpr->getType();
11391     // The only legal unary operation for atomics is '&'.
11392     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11393     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11394     // only with a builtin functions and therefore should be disallowed here.
11395         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11396         || Ty->isBlockPointerType())) {
11397       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11398                        << InputExpr->getType()
11399                        << Input.get()->getSourceRange());
11400     }
11401   }
11402   switch (Opc) {
11403   case UO_PreInc:
11404   case UO_PreDec:
11405   case UO_PostInc:
11406   case UO_PostDec:
11407     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11408                                                 OpLoc,
11409                                                 Opc == UO_PreInc ||
11410                                                 Opc == UO_PostInc,
11411                                                 Opc == UO_PreInc ||
11412                                                 Opc == UO_PreDec);
11413     break;
11414   case UO_AddrOf:
11415     resultType = CheckAddressOfOperand(Input, OpLoc);
11416     RecordModifiableNonNullParam(*this, InputExpr);
11417     break;
11418   case UO_Deref: {
11419     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11420     if (Input.isInvalid()) return ExprError();
11421     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11422     break;
11423   }
11424   case UO_Plus:
11425   case UO_Minus:
11426     Input = UsualUnaryConversions(Input.get());
11427     if (Input.isInvalid()) return ExprError();
11428     resultType = Input.get()->getType();
11429     if (resultType->isDependentType())
11430       break;
11431     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11432       break;
11433     else if (resultType->isVectorType() &&
11434              // The z vector extensions don't allow + or - with bool vectors.
11435              (!Context.getLangOpts().ZVector ||
11436               resultType->getAs<VectorType>()->getVectorKind() !=
11437               VectorType::AltiVecBool))
11438       break;
11439     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11440              Opc == UO_Plus &&
11441              resultType->isPointerType())
11442       break;
11443 
11444     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11445       << resultType << Input.get()->getSourceRange());
11446 
11447   case UO_Not: // bitwise complement
11448     Input = UsualUnaryConversions(Input.get());
11449     if (Input.isInvalid())
11450       return ExprError();
11451     resultType = Input.get()->getType();
11452     if (resultType->isDependentType())
11453       break;
11454     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11455     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11456       // C99 does not support '~' for complex conjugation.
11457       Diag(OpLoc, diag::ext_integer_complement_complex)
11458           << resultType << Input.get()->getSourceRange();
11459     else if (resultType->hasIntegerRepresentation())
11460       break;
11461     else if (resultType->isExtVectorType()) {
11462       if (Context.getLangOpts().OpenCL) {
11463         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11464         // on vector float types.
11465         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11466         if (!T->isIntegerType())
11467           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11468                            << resultType << Input.get()->getSourceRange());
11469       }
11470       break;
11471     } else {
11472       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11473                        << resultType << Input.get()->getSourceRange());
11474     }
11475     break;
11476 
11477   case UO_LNot: // logical negation
11478     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11479     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11480     if (Input.isInvalid()) return ExprError();
11481     resultType = Input.get()->getType();
11482 
11483     // Though we still have to promote half FP to float...
11484     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11485       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11486       resultType = Context.FloatTy;
11487     }
11488 
11489     if (resultType->isDependentType())
11490       break;
11491     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11492       // C99 6.5.3.3p1: ok, fallthrough;
11493       if (Context.getLangOpts().CPlusPlus) {
11494         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11495         // operand contextually converted to bool.
11496         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11497                                   ScalarTypeToBooleanCastKind(resultType));
11498       } else if (Context.getLangOpts().OpenCL &&
11499                  Context.getLangOpts().OpenCLVersion < 120) {
11500         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11501         // operate on scalar float types.
11502         if (!resultType->isIntegerType())
11503           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11504                            << resultType << Input.get()->getSourceRange());
11505       }
11506     } else if (resultType->isExtVectorType()) {
11507       if (Context.getLangOpts().OpenCL &&
11508           Context.getLangOpts().OpenCLVersion < 120) {
11509         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11510         // operate on vector float types.
11511         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11512         if (!T->isIntegerType())
11513           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11514                            << resultType << Input.get()->getSourceRange());
11515       }
11516       // Vector logical not returns the signed variant of the operand type.
11517       resultType = GetSignedVectorType(resultType);
11518       break;
11519     } else {
11520       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11521         << resultType << Input.get()->getSourceRange());
11522     }
11523 
11524     // LNot always has type int. C99 6.5.3.3p5.
11525     // In C++, it's bool. C++ 5.3.1p8
11526     resultType = Context.getLogicalOperationType();
11527     break;
11528   case UO_Real:
11529   case UO_Imag:
11530     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11531     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11532     // complex l-values to ordinary l-values and all other values to r-values.
11533     if (Input.isInvalid()) return ExprError();
11534     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11535       if (Input.get()->getValueKind() != VK_RValue &&
11536           Input.get()->getObjectKind() == OK_Ordinary)
11537         VK = Input.get()->getValueKind();
11538     } else if (!getLangOpts().CPlusPlus) {
11539       // In C, a volatile scalar is read by __imag. In C++, it is not.
11540       Input = DefaultLvalueConversion(Input.get());
11541     }
11542     break;
11543   case UO_Extension:
11544   case UO_Coawait:
11545     resultType = Input.get()->getType();
11546     VK = Input.get()->getValueKind();
11547     OK = Input.get()->getObjectKind();
11548     break;
11549   }
11550   if (resultType.isNull() || Input.isInvalid())
11551     return ExprError();
11552 
11553   // Check for array bounds violations in the operand of the UnaryOperator,
11554   // except for the '*' and '&' operators that have to be handled specially
11555   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11556   // that are explicitly defined as valid by the standard).
11557   if (Opc != UO_AddrOf && Opc != UO_Deref)
11558     CheckArrayAccess(Input.get());
11559 
11560   return new (Context)
11561       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11562 }
11563 
11564 /// \brief Determine whether the given expression is a qualified member
11565 /// access expression, of a form that could be turned into a pointer to member
11566 /// with the address-of operator.
11567 static bool isQualifiedMemberAccess(Expr *E) {
11568   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11569     if (!DRE->getQualifier())
11570       return false;
11571 
11572     ValueDecl *VD = DRE->getDecl();
11573     if (!VD->isCXXClassMember())
11574       return false;
11575 
11576     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11577       return true;
11578     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11579       return Method->isInstance();
11580 
11581     return false;
11582   }
11583 
11584   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11585     if (!ULE->getQualifier())
11586       return false;
11587 
11588     for (NamedDecl *D : ULE->decls()) {
11589       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11590         if (Method->isInstance())
11591           return true;
11592       } else {
11593         // Overload set does not contain methods.
11594         break;
11595       }
11596     }
11597 
11598     return false;
11599   }
11600 
11601   return false;
11602 }
11603 
11604 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11605                               UnaryOperatorKind Opc, Expr *Input) {
11606   // First things first: handle placeholders so that the
11607   // overloaded-operator check considers the right type.
11608   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11609     // Increment and decrement of pseudo-object references.
11610     if (pty->getKind() == BuiltinType::PseudoObject &&
11611         UnaryOperator::isIncrementDecrementOp(Opc))
11612       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11613 
11614     // extension is always a builtin operator.
11615     if (Opc == UO_Extension)
11616       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11617 
11618     // & gets special logic for several kinds of placeholder.
11619     // The builtin code knows what to do.
11620     if (Opc == UO_AddrOf &&
11621         (pty->getKind() == BuiltinType::Overload ||
11622          pty->getKind() == BuiltinType::UnknownAny ||
11623          pty->getKind() == BuiltinType::BoundMember))
11624       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11625 
11626     // Anything else needs to be handled now.
11627     ExprResult Result = CheckPlaceholderExpr(Input);
11628     if (Result.isInvalid()) return ExprError();
11629     Input = Result.get();
11630   }
11631 
11632   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11633       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11634       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11635     // Find all of the overloaded operators visible from this
11636     // point. We perform both an operator-name lookup from the local
11637     // scope and an argument-dependent lookup based on the types of
11638     // the arguments.
11639     UnresolvedSet<16> Functions;
11640     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11641     if (S && OverOp != OO_None)
11642       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11643                                    Functions);
11644 
11645     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11646   }
11647 
11648   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11649 }
11650 
11651 // Unary Operators.  'Tok' is the token for the operator.
11652 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11653                               tok::TokenKind Op, Expr *Input) {
11654   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11655 }
11656 
11657 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11658 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11659                                 LabelDecl *TheDecl) {
11660   TheDecl->markUsed(Context);
11661   // Create the AST node.  The address of a label always has type 'void*'.
11662   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11663                                      Context.getPointerType(Context.VoidTy));
11664 }
11665 
11666 /// Given the last statement in a statement-expression, check whether
11667 /// the result is a producing expression (like a call to an
11668 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11669 /// release out of the full-expression.  Otherwise, return null.
11670 /// Cannot fail.
11671 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11672   // Should always be wrapped with one of these.
11673   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11674   if (!cleanups) return nullptr;
11675 
11676   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11677   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11678     return nullptr;
11679 
11680   // Splice out the cast.  This shouldn't modify any interesting
11681   // features of the statement.
11682   Expr *producer = cast->getSubExpr();
11683   assert(producer->getType() == cast->getType());
11684   assert(producer->getValueKind() == cast->getValueKind());
11685   cleanups->setSubExpr(producer);
11686   return cleanups;
11687 }
11688 
11689 void Sema::ActOnStartStmtExpr() {
11690   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11691 }
11692 
11693 void Sema::ActOnStmtExprError() {
11694   // Note that function is also called by TreeTransform when leaving a
11695   // StmtExpr scope without rebuilding anything.
11696 
11697   DiscardCleanupsInEvaluationContext();
11698   PopExpressionEvaluationContext();
11699 }
11700 
11701 ExprResult
11702 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11703                     SourceLocation RPLoc) { // "({..})"
11704   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11705   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11706 
11707   if (hasAnyUnrecoverableErrorsInThisFunction())
11708     DiscardCleanupsInEvaluationContext();
11709   assert(!Cleanup.exprNeedsCleanups() &&
11710          "cleanups within StmtExpr not correctly bound!");
11711   PopExpressionEvaluationContext();
11712 
11713   // FIXME: there are a variety of strange constraints to enforce here, for
11714   // example, it is not possible to goto into a stmt expression apparently.
11715   // More semantic analysis is needed.
11716 
11717   // If there are sub-stmts in the compound stmt, take the type of the last one
11718   // as the type of the stmtexpr.
11719   QualType Ty = Context.VoidTy;
11720   bool StmtExprMayBindToTemp = false;
11721   if (!Compound->body_empty()) {
11722     Stmt *LastStmt = Compound->body_back();
11723     LabelStmt *LastLabelStmt = nullptr;
11724     // If LastStmt is a label, skip down through into the body.
11725     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11726       LastLabelStmt = Label;
11727       LastStmt = Label->getSubStmt();
11728     }
11729 
11730     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11731       // Do function/array conversion on the last expression, but not
11732       // lvalue-to-rvalue.  However, initialize an unqualified type.
11733       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11734       if (LastExpr.isInvalid())
11735         return ExprError();
11736       Ty = LastExpr.get()->getType().getUnqualifiedType();
11737 
11738       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11739         // In ARC, if the final expression ends in a consume, splice
11740         // the consume out and bind it later.  In the alternate case
11741         // (when dealing with a retainable type), the result
11742         // initialization will create a produce.  In both cases the
11743         // result will be +1, and we'll need to balance that out with
11744         // a bind.
11745         if (Expr *rebuiltLastStmt
11746               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11747           LastExpr = rebuiltLastStmt;
11748         } else {
11749           LastExpr = PerformCopyInitialization(
11750                             InitializedEntity::InitializeResult(LPLoc,
11751                                                                 Ty,
11752                                                                 false),
11753                                                    SourceLocation(),
11754                                                LastExpr);
11755         }
11756 
11757         if (LastExpr.isInvalid())
11758           return ExprError();
11759         if (LastExpr.get() != nullptr) {
11760           if (!LastLabelStmt)
11761             Compound->setLastStmt(LastExpr.get());
11762           else
11763             LastLabelStmt->setSubStmt(LastExpr.get());
11764           StmtExprMayBindToTemp = true;
11765         }
11766       }
11767     }
11768   }
11769 
11770   // FIXME: Check that expression type is complete/non-abstract; statement
11771   // expressions are not lvalues.
11772   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11773   if (StmtExprMayBindToTemp)
11774     return MaybeBindToTemporary(ResStmtExpr);
11775   return ResStmtExpr;
11776 }
11777 
11778 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11779                                       TypeSourceInfo *TInfo,
11780                                       ArrayRef<OffsetOfComponent> Components,
11781                                       SourceLocation RParenLoc) {
11782   QualType ArgTy = TInfo->getType();
11783   bool Dependent = ArgTy->isDependentType();
11784   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11785 
11786   // We must have at least one component that refers to the type, and the first
11787   // one is known to be a field designator.  Verify that the ArgTy represents
11788   // a struct/union/class.
11789   if (!Dependent && !ArgTy->isRecordType())
11790     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11791                        << ArgTy << TypeRange);
11792 
11793   // Type must be complete per C99 7.17p3 because a declaring a variable
11794   // with an incomplete type would be ill-formed.
11795   if (!Dependent
11796       && RequireCompleteType(BuiltinLoc, ArgTy,
11797                              diag::err_offsetof_incomplete_type, TypeRange))
11798     return ExprError();
11799 
11800   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11801   // GCC extension, diagnose them.
11802   // FIXME: This diagnostic isn't actually visible because the location is in
11803   // a system header!
11804   if (Components.size() != 1)
11805     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11806       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11807 
11808   bool DidWarnAboutNonPOD = false;
11809   QualType CurrentType = ArgTy;
11810   SmallVector<OffsetOfNode, 4> Comps;
11811   SmallVector<Expr*, 4> Exprs;
11812   for (const OffsetOfComponent &OC : Components) {
11813     if (OC.isBrackets) {
11814       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11815       if (!CurrentType->isDependentType()) {
11816         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11817         if(!AT)
11818           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11819                            << CurrentType);
11820         CurrentType = AT->getElementType();
11821       } else
11822         CurrentType = Context.DependentTy;
11823 
11824       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11825       if (IdxRval.isInvalid())
11826         return ExprError();
11827       Expr *Idx = IdxRval.get();
11828 
11829       // The expression must be an integral expression.
11830       // FIXME: An integral constant expression?
11831       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11832           !Idx->getType()->isIntegerType())
11833         return ExprError(Diag(Idx->getLocStart(),
11834                               diag::err_typecheck_subscript_not_integer)
11835                          << Idx->getSourceRange());
11836 
11837       // Record this array index.
11838       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11839       Exprs.push_back(Idx);
11840       continue;
11841     }
11842 
11843     // Offset of a field.
11844     if (CurrentType->isDependentType()) {
11845       // We have the offset of a field, but we can't look into the dependent
11846       // type. Just record the identifier of the field.
11847       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11848       CurrentType = Context.DependentTy;
11849       continue;
11850     }
11851 
11852     // We need to have a complete type to look into.
11853     if (RequireCompleteType(OC.LocStart, CurrentType,
11854                             diag::err_offsetof_incomplete_type))
11855       return ExprError();
11856 
11857     // Look for the designated field.
11858     const RecordType *RC = CurrentType->getAs<RecordType>();
11859     if (!RC)
11860       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11861                        << CurrentType);
11862     RecordDecl *RD = RC->getDecl();
11863 
11864     // C++ [lib.support.types]p5:
11865     //   The macro offsetof accepts a restricted set of type arguments in this
11866     //   International Standard. type shall be a POD structure or a POD union
11867     //   (clause 9).
11868     // C++11 [support.types]p4:
11869     //   If type is not a standard-layout class (Clause 9), the results are
11870     //   undefined.
11871     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11872       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11873       unsigned DiagID =
11874         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11875                             : diag::ext_offsetof_non_pod_type;
11876 
11877       if (!IsSafe && !DidWarnAboutNonPOD &&
11878           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11879                               PDiag(DiagID)
11880                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11881                               << CurrentType))
11882         DidWarnAboutNonPOD = true;
11883     }
11884 
11885     // Look for the field.
11886     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11887     LookupQualifiedName(R, RD);
11888     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11889     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11890     if (!MemberDecl) {
11891       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11892         MemberDecl = IndirectMemberDecl->getAnonField();
11893     }
11894 
11895     if (!MemberDecl)
11896       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11897                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11898                                                               OC.LocEnd));
11899 
11900     // C99 7.17p3:
11901     //   (If the specified member is a bit-field, the behavior is undefined.)
11902     //
11903     // We diagnose this as an error.
11904     if (MemberDecl->isBitField()) {
11905       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11906         << MemberDecl->getDeclName()
11907         << SourceRange(BuiltinLoc, RParenLoc);
11908       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11909       return ExprError();
11910     }
11911 
11912     RecordDecl *Parent = MemberDecl->getParent();
11913     if (IndirectMemberDecl)
11914       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11915 
11916     // If the member was found in a base class, introduce OffsetOfNodes for
11917     // the base class indirections.
11918     CXXBasePaths Paths;
11919     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11920                       Paths)) {
11921       if (Paths.getDetectedVirtual()) {
11922         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11923           << MemberDecl->getDeclName()
11924           << SourceRange(BuiltinLoc, RParenLoc);
11925         return ExprError();
11926       }
11927 
11928       CXXBasePath &Path = Paths.front();
11929       for (const CXXBasePathElement &B : Path)
11930         Comps.push_back(OffsetOfNode(B.Base));
11931     }
11932 
11933     if (IndirectMemberDecl) {
11934       for (auto *FI : IndirectMemberDecl->chain()) {
11935         assert(isa<FieldDecl>(FI));
11936         Comps.push_back(OffsetOfNode(OC.LocStart,
11937                                      cast<FieldDecl>(FI), OC.LocEnd));
11938       }
11939     } else
11940       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11941 
11942     CurrentType = MemberDecl->getType().getNonReferenceType();
11943   }
11944 
11945   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11946                               Comps, Exprs, RParenLoc);
11947 }
11948 
11949 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11950                                       SourceLocation BuiltinLoc,
11951                                       SourceLocation TypeLoc,
11952                                       ParsedType ParsedArgTy,
11953                                       ArrayRef<OffsetOfComponent> Components,
11954                                       SourceLocation RParenLoc) {
11955 
11956   TypeSourceInfo *ArgTInfo;
11957   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11958   if (ArgTy.isNull())
11959     return ExprError();
11960 
11961   if (!ArgTInfo)
11962     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11963 
11964   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11965 }
11966 
11967 
11968 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11969                                  Expr *CondExpr,
11970                                  Expr *LHSExpr, Expr *RHSExpr,
11971                                  SourceLocation RPLoc) {
11972   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11973 
11974   ExprValueKind VK = VK_RValue;
11975   ExprObjectKind OK = OK_Ordinary;
11976   QualType resType;
11977   bool ValueDependent = false;
11978   bool CondIsTrue = false;
11979   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11980     resType = Context.DependentTy;
11981     ValueDependent = true;
11982   } else {
11983     // The conditional expression is required to be a constant expression.
11984     llvm::APSInt condEval(32);
11985     ExprResult CondICE
11986       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11987           diag::err_typecheck_choose_expr_requires_constant, false);
11988     if (CondICE.isInvalid())
11989       return ExprError();
11990     CondExpr = CondICE.get();
11991     CondIsTrue = condEval.getZExtValue();
11992 
11993     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11994     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11995 
11996     resType = ActiveExpr->getType();
11997     ValueDependent = ActiveExpr->isValueDependent();
11998     VK = ActiveExpr->getValueKind();
11999     OK = ActiveExpr->getObjectKind();
12000   }
12001 
12002   return new (Context)
12003       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12004                  CondIsTrue, resType->isDependentType(), ValueDependent);
12005 }
12006 
12007 //===----------------------------------------------------------------------===//
12008 // Clang Extensions.
12009 //===----------------------------------------------------------------------===//
12010 
12011 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12012 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12013   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12014 
12015   if (LangOpts.CPlusPlus) {
12016     Decl *ManglingContextDecl;
12017     if (MangleNumberingContext *MCtx =
12018             getCurrentMangleNumberContext(Block->getDeclContext(),
12019                                           ManglingContextDecl)) {
12020       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12021       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12022     }
12023   }
12024 
12025   PushBlockScope(CurScope, Block);
12026   CurContext->addDecl(Block);
12027   if (CurScope)
12028     PushDeclContext(CurScope, Block);
12029   else
12030     CurContext = Block;
12031 
12032   getCurBlock()->HasImplicitReturnType = true;
12033 
12034   // Enter a new evaluation context to insulate the block from any
12035   // cleanups from the enclosing full-expression.
12036   PushExpressionEvaluationContext(PotentiallyEvaluated);
12037 }
12038 
12039 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12040                                Scope *CurScope) {
12041   assert(ParamInfo.getIdentifier() == nullptr &&
12042          "block-id should have no identifier!");
12043   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12044   BlockScopeInfo *CurBlock = getCurBlock();
12045 
12046   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12047   QualType T = Sig->getType();
12048 
12049   // FIXME: We should allow unexpanded parameter packs here, but that would,
12050   // in turn, make the block expression contain unexpanded parameter packs.
12051   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12052     // Drop the parameters.
12053     FunctionProtoType::ExtProtoInfo EPI;
12054     EPI.HasTrailingReturn = false;
12055     EPI.TypeQuals |= DeclSpec::TQ_const;
12056     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12057     Sig = Context.getTrivialTypeSourceInfo(T);
12058   }
12059 
12060   // GetTypeForDeclarator always produces a function type for a block
12061   // literal signature.  Furthermore, it is always a FunctionProtoType
12062   // unless the function was written with a typedef.
12063   assert(T->isFunctionType() &&
12064          "GetTypeForDeclarator made a non-function block signature");
12065 
12066   // Look for an explicit signature in that function type.
12067   FunctionProtoTypeLoc ExplicitSignature;
12068 
12069   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12070   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12071 
12072     // Check whether that explicit signature was synthesized by
12073     // GetTypeForDeclarator.  If so, don't save that as part of the
12074     // written signature.
12075     if (ExplicitSignature.getLocalRangeBegin() ==
12076         ExplicitSignature.getLocalRangeEnd()) {
12077       // This would be much cheaper if we stored TypeLocs instead of
12078       // TypeSourceInfos.
12079       TypeLoc Result = ExplicitSignature.getReturnLoc();
12080       unsigned Size = Result.getFullDataSize();
12081       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12082       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12083 
12084       ExplicitSignature = FunctionProtoTypeLoc();
12085     }
12086   }
12087 
12088   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12089   CurBlock->FunctionType = T;
12090 
12091   const FunctionType *Fn = T->getAs<FunctionType>();
12092   QualType RetTy = Fn->getReturnType();
12093   bool isVariadic =
12094     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12095 
12096   CurBlock->TheDecl->setIsVariadic(isVariadic);
12097 
12098   // Context.DependentTy is used as a placeholder for a missing block
12099   // return type.  TODO:  what should we do with declarators like:
12100   //   ^ * { ... }
12101   // If the answer is "apply template argument deduction"....
12102   if (RetTy != Context.DependentTy) {
12103     CurBlock->ReturnType = RetTy;
12104     CurBlock->TheDecl->setBlockMissingReturnType(false);
12105     CurBlock->HasImplicitReturnType = false;
12106   }
12107 
12108   // Push block parameters from the declarator if we had them.
12109   SmallVector<ParmVarDecl*, 8> Params;
12110   if (ExplicitSignature) {
12111     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12112       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12113       if (Param->getIdentifier() == nullptr &&
12114           !Param->isImplicit() &&
12115           !Param->isInvalidDecl() &&
12116           !getLangOpts().CPlusPlus)
12117         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12118       Params.push_back(Param);
12119     }
12120 
12121   // Fake up parameter variables if we have a typedef, like
12122   //   ^ fntype { ... }
12123   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12124     for (const auto &I : Fn->param_types()) {
12125       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12126           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12127       Params.push_back(Param);
12128     }
12129   }
12130 
12131   // Set the parameters on the block decl.
12132   if (!Params.empty()) {
12133     CurBlock->TheDecl->setParams(Params);
12134     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12135                              /*CheckParameterNames=*/false);
12136   }
12137 
12138   // Finally we can process decl attributes.
12139   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12140 
12141   // Put the parameter variables in scope.
12142   for (auto AI : CurBlock->TheDecl->parameters()) {
12143     AI->setOwningFunction(CurBlock->TheDecl);
12144 
12145     // If this has an identifier, add it to the scope stack.
12146     if (AI->getIdentifier()) {
12147       CheckShadow(CurBlock->TheScope, AI);
12148 
12149       PushOnScopeChains(AI, CurBlock->TheScope);
12150     }
12151   }
12152 }
12153 
12154 /// ActOnBlockError - If there is an error parsing a block, this callback
12155 /// is invoked to pop the information about the block from the action impl.
12156 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12157   // Leave the expression-evaluation context.
12158   DiscardCleanupsInEvaluationContext();
12159   PopExpressionEvaluationContext();
12160 
12161   // Pop off CurBlock, handle nested blocks.
12162   PopDeclContext();
12163   PopFunctionScopeInfo();
12164 }
12165 
12166 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12167 /// literal was successfully completed.  ^(int x){...}
12168 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12169                                     Stmt *Body, Scope *CurScope) {
12170   // If blocks are disabled, emit an error.
12171   if (!LangOpts.Blocks)
12172     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12173 
12174   // Leave the expression-evaluation context.
12175   if (hasAnyUnrecoverableErrorsInThisFunction())
12176     DiscardCleanupsInEvaluationContext();
12177   assert(!Cleanup.exprNeedsCleanups() &&
12178          "cleanups within block not correctly bound!");
12179   PopExpressionEvaluationContext();
12180 
12181   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12182 
12183   if (BSI->HasImplicitReturnType)
12184     deduceClosureReturnType(*BSI);
12185 
12186   PopDeclContext();
12187 
12188   QualType RetTy = Context.VoidTy;
12189   if (!BSI->ReturnType.isNull())
12190     RetTy = BSI->ReturnType;
12191 
12192   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12193   QualType BlockTy;
12194 
12195   // Set the captured variables on the block.
12196   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12197   SmallVector<BlockDecl::Capture, 4> Captures;
12198   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12199     if (Cap.isThisCapture())
12200       continue;
12201     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12202                               Cap.isNested(), Cap.getInitExpr());
12203     Captures.push_back(NewCap);
12204   }
12205   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12206 
12207   // If the user wrote a function type in some form, try to use that.
12208   if (!BSI->FunctionType.isNull()) {
12209     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12210 
12211     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12212     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12213 
12214     // Turn protoless block types into nullary block types.
12215     if (isa<FunctionNoProtoType>(FTy)) {
12216       FunctionProtoType::ExtProtoInfo EPI;
12217       EPI.ExtInfo = Ext;
12218       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12219 
12220     // Otherwise, if we don't need to change anything about the function type,
12221     // preserve its sugar structure.
12222     } else if (FTy->getReturnType() == RetTy &&
12223                (!NoReturn || FTy->getNoReturnAttr())) {
12224       BlockTy = BSI->FunctionType;
12225 
12226     // Otherwise, make the minimal modifications to the function type.
12227     } else {
12228       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12229       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12230       EPI.TypeQuals = 0; // FIXME: silently?
12231       EPI.ExtInfo = Ext;
12232       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12233     }
12234 
12235   // If we don't have a function type, just build one from nothing.
12236   } else {
12237     FunctionProtoType::ExtProtoInfo EPI;
12238     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12239     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12240   }
12241 
12242   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12243   BlockTy = Context.getBlockPointerType(BlockTy);
12244 
12245   // If needed, diagnose invalid gotos and switches in the block.
12246   if (getCurFunction()->NeedsScopeChecking() &&
12247       !PP.isCodeCompletionEnabled())
12248     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12249 
12250   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12251 
12252   // Try to apply the named return value optimization. We have to check again
12253   // if we can do this, though, because blocks keep return statements around
12254   // to deduce an implicit return type.
12255   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12256       !BSI->TheDecl->isDependentContext())
12257     computeNRVO(Body, BSI);
12258 
12259   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12260   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12261   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12262 
12263   // If the block isn't obviously global, i.e. it captures anything at
12264   // all, then we need to do a few things in the surrounding context:
12265   if (Result->getBlockDecl()->hasCaptures()) {
12266     // First, this expression has a new cleanup object.
12267     ExprCleanupObjects.push_back(Result->getBlockDecl());
12268     Cleanup.setExprNeedsCleanups(true);
12269 
12270     // It also gets a branch-protected scope if any of the captured
12271     // variables needs destruction.
12272     for (const auto &CI : Result->getBlockDecl()->captures()) {
12273       const VarDecl *var = CI.getVariable();
12274       if (var->getType().isDestructedType() != QualType::DK_none) {
12275         getCurFunction()->setHasBranchProtectedScope();
12276         break;
12277       }
12278     }
12279   }
12280 
12281   return Result;
12282 }
12283 
12284 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12285                             SourceLocation RPLoc) {
12286   TypeSourceInfo *TInfo;
12287   GetTypeFromParser(Ty, &TInfo);
12288   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12289 }
12290 
12291 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12292                                 Expr *E, TypeSourceInfo *TInfo,
12293                                 SourceLocation RPLoc) {
12294   Expr *OrigExpr = E;
12295   bool IsMS = false;
12296 
12297   // CUDA device code does not support varargs.
12298   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12299     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12300       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12301       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12302         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12303     }
12304   }
12305 
12306   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12307   // as Microsoft ABI on an actual Microsoft platform, where
12308   // __builtin_ms_va_list and __builtin_va_list are the same.)
12309   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12310       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12311     QualType MSVaListType = Context.getBuiltinMSVaListType();
12312     if (Context.hasSameType(MSVaListType, E->getType())) {
12313       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12314         return ExprError();
12315       IsMS = true;
12316     }
12317   }
12318 
12319   // Get the va_list type
12320   QualType VaListType = Context.getBuiltinVaListType();
12321   if (!IsMS) {
12322     if (VaListType->isArrayType()) {
12323       // Deal with implicit array decay; for example, on x86-64,
12324       // va_list is an array, but it's supposed to decay to
12325       // a pointer for va_arg.
12326       VaListType = Context.getArrayDecayedType(VaListType);
12327       // Make sure the input expression also decays appropriately.
12328       ExprResult Result = UsualUnaryConversions(E);
12329       if (Result.isInvalid())
12330         return ExprError();
12331       E = Result.get();
12332     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12333       // If va_list is a record type and we are compiling in C++ mode,
12334       // check the argument using reference binding.
12335       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12336           Context, Context.getLValueReferenceType(VaListType), false);
12337       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12338       if (Init.isInvalid())
12339         return ExprError();
12340       E = Init.getAs<Expr>();
12341     } else {
12342       // Otherwise, the va_list argument must be an l-value because
12343       // it is modified by va_arg.
12344       if (!E->isTypeDependent() &&
12345           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12346         return ExprError();
12347     }
12348   }
12349 
12350   if (!IsMS && !E->isTypeDependent() &&
12351       !Context.hasSameType(VaListType, E->getType()))
12352     return ExprError(Diag(E->getLocStart(),
12353                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12354       << OrigExpr->getType() << E->getSourceRange());
12355 
12356   if (!TInfo->getType()->isDependentType()) {
12357     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12358                             diag::err_second_parameter_to_va_arg_incomplete,
12359                             TInfo->getTypeLoc()))
12360       return ExprError();
12361 
12362     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12363                                TInfo->getType(),
12364                                diag::err_second_parameter_to_va_arg_abstract,
12365                                TInfo->getTypeLoc()))
12366       return ExprError();
12367 
12368     if (!TInfo->getType().isPODType(Context)) {
12369       Diag(TInfo->getTypeLoc().getBeginLoc(),
12370            TInfo->getType()->isObjCLifetimeType()
12371              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12372              : diag::warn_second_parameter_to_va_arg_not_pod)
12373         << TInfo->getType()
12374         << TInfo->getTypeLoc().getSourceRange();
12375     }
12376 
12377     // Check for va_arg where arguments of the given type will be promoted
12378     // (i.e. this va_arg is guaranteed to have undefined behavior).
12379     QualType PromoteType;
12380     if (TInfo->getType()->isPromotableIntegerType()) {
12381       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12382       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12383         PromoteType = QualType();
12384     }
12385     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12386       PromoteType = Context.DoubleTy;
12387     if (!PromoteType.isNull())
12388       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12389                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12390                           << TInfo->getType()
12391                           << PromoteType
12392                           << TInfo->getTypeLoc().getSourceRange());
12393   }
12394 
12395   QualType T = TInfo->getType().getNonLValueExprType(Context);
12396   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12397 }
12398 
12399 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12400   // The type of __null will be int or long, depending on the size of
12401   // pointers on the target.
12402   QualType Ty;
12403   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12404   if (pw == Context.getTargetInfo().getIntWidth())
12405     Ty = Context.IntTy;
12406   else if (pw == Context.getTargetInfo().getLongWidth())
12407     Ty = Context.LongTy;
12408   else if (pw == Context.getTargetInfo().getLongLongWidth())
12409     Ty = Context.LongLongTy;
12410   else {
12411     llvm_unreachable("I don't know size of pointer!");
12412   }
12413 
12414   return new (Context) GNUNullExpr(Ty, TokenLoc);
12415 }
12416 
12417 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12418                                               bool Diagnose) {
12419   if (!getLangOpts().ObjC1)
12420     return false;
12421 
12422   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12423   if (!PT)
12424     return false;
12425 
12426   if (!PT->isObjCIdType()) {
12427     // Check if the destination is the 'NSString' interface.
12428     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12429     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12430       return false;
12431   }
12432 
12433   // Ignore any parens, implicit casts (should only be
12434   // array-to-pointer decays), and not-so-opaque values.  The last is
12435   // important for making this trigger for property assignments.
12436   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12437   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12438     if (OV->getSourceExpr())
12439       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12440 
12441   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12442   if (!SL || !SL->isAscii())
12443     return false;
12444   if (Diagnose) {
12445     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12446       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12447     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12448   }
12449   return true;
12450 }
12451 
12452 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12453                                               const Expr *SrcExpr) {
12454   if (!DstType->isFunctionPointerType() ||
12455       !SrcExpr->getType()->isFunctionType())
12456     return false;
12457 
12458   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12459   if (!DRE)
12460     return false;
12461 
12462   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12463   if (!FD)
12464     return false;
12465 
12466   return !S.checkAddressOfFunctionIsAvailable(FD,
12467                                               /*Complain=*/true,
12468                                               SrcExpr->getLocStart());
12469 }
12470 
12471 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12472                                     SourceLocation Loc,
12473                                     QualType DstType, QualType SrcType,
12474                                     Expr *SrcExpr, AssignmentAction Action,
12475                                     bool *Complained) {
12476   if (Complained)
12477     *Complained = false;
12478 
12479   // Decode the result (notice that AST's are still created for extensions).
12480   bool CheckInferredResultType = false;
12481   bool isInvalid = false;
12482   unsigned DiagKind = 0;
12483   FixItHint Hint;
12484   ConversionFixItGenerator ConvHints;
12485   bool MayHaveConvFixit = false;
12486   bool MayHaveFunctionDiff = false;
12487   const ObjCInterfaceDecl *IFace = nullptr;
12488   const ObjCProtocolDecl *PDecl = nullptr;
12489 
12490   switch (ConvTy) {
12491   case Compatible:
12492       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12493       return false;
12494 
12495   case PointerToInt:
12496     DiagKind = diag::ext_typecheck_convert_pointer_int;
12497     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12498     MayHaveConvFixit = true;
12499     break;
12500   case IntToPointer:
12501     DiagKind = diag::ext_typecheck_convert_int_pointer;
12502     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12503     MayHaveConvFixit = true;
12504     break;
12505   case IncompatiblePointer:
12506     if (Action == AA_Passing_CFAudited)
12507       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12508     else if (SrcType->isFunctionPointerType() &&
12509              DstType->isFunctionPointerType())
12510       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12511     else
12512       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12513 
12514     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12515       SrcType->isObjCObjectPointerType();
12516     if (Hint.isNull() && !CheckInferredResultType) {
12517       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12518     }
12519     else if (CheckInferredResultType) {
12520       SrcType = SrcType.getUnqualifiedType();
12521       DstType = DstType.getUnqualifiedType();
12522     }
12523     MayHaveConvFixit = true;
12524     break;
12525   case IncompatiblePointerSign:
12526     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12527     break;
12528   case FunctionVoidPointer:
12529     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12530     break;
12531   case IncompatiblePointerDiscardsQualifiers: {
12532     // Perform array-to-pointer decay if necessary.
12533     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12534 
12535     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12536     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12537     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12538       DiagKind = diag::err_typecheck_incompatible_address_space;
12539       break;
12540 
12541 
12542     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12543       DiagKind = diag::err_typecheck_incompatible_ownership;
12544       break;
12545     }
12546 
12547     llvm_unreachable("unknown error case for discarding qualifiers!");
12548     // fallthrough
12549   }
12550   case CompatiblePointerDiscardsQualifiers:
12551     // If the qualifiers lost were because we were applying the
12552     // (deprecated) C++ conversion from a string literal to a char*
12553     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12554     // Ideally, this check would be performed in
12555     // checkPointerTypesForAssignment. However, that would require a
12556     // bit of refactoring (so that the second argument is an
12557     // expression, rather than a type), which should be done as part
12558     // of a larger effort to fix checkPointerTypesForAssignment for
12559     // C++ semantics.
12560     if (getLangOpts().CPlusPlus &&
12561         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12562       return false;
12563     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12564     break;
12565   case IncompatibleNestedPointerQualifiers:
12566     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12567     break;
12568   case IntToBlockPointer:
12569     DiagKind = diag::err_int_to_block_pointer;
12570     break;
12571   case IncompatibleBlockPointer:
12572     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12573     break;
12574   case IncompatibleObjCQualifiedId: {
12575     if (SrcType->isObjCQualifiedIdType()) {
12576       const ObjCObjectPointerType *srcOPT =
12577                 SrcType->getAs<ObjCObjectPointerType>();
12578       for (auto *srcProto : srcOPT->quals()) {
12579         PDecl = srcProto;
12580         break;
12581       }
12582       if (const ObjCInterfaceType *IFaceT =
12583             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12584         IFace = IFaceT->getDecl();
12585     }
12586     else if (DstType->isObjCQualifiedIdType()) {
12587       const ObjCObjectPointerType *dstOPT =
12588         DstType->getAs<ObjCObjectPointerType>();
12589       for (auto *dstProto : dstOPT->quals()) {
12590         PDecl = dstProto;
12591         break;
12592       }
12593       if (const ObjCInterfaceType *IFaceT =
12594             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12595         IFace = IFaceT->getDecl();
12596     }
12597     DiagKind = diag::warn_incompatible_qualified_id;
12598     break;
12599   }
12600   case IncompatibleVectors:
12601     DiagKind = diag::warn_incompatible_vectors;
12602     break;
12603   case IncompatibleObjCWeakRef:
12604     DiagKind = diag::err_arc_weak_unavailable_assign;
12605     break;
12606   case Incompatible:
12607     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12608       if (Complained)
12609         *Complained = true;
12610       return true;
12611     }
12612 
12613     DiagKind = diag::err_typecheck_convert_incompatible;
12614     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12615     MayHaveConvFixit = true;
12616     isInvalid = true;
12617     MayHaveFunctionDiff = true;
12618     break;
12619   }
12620 
12621   QualType FirstType, SecondType;
12622   switch (Action) {
12623   case AA_Assigning:
12624   case AA_Initializing:
12625     // The destination type comes first.
12626     FirstType = DstType;
12627     SecondType = SrcType;
12628     break;
12629 
12630   case AA_Returning:
12631   case AA_Passing:
12632   case AA_Passing_CFAudited:
12633   case AA_Converting:
12634   case AA_Sending:
12635   case AA_Casting:
12636     // The source type comes first.
12637     FirstType = SrcType;
12638     SecondType = DstType;
12639     break;
12640   }
12641 
12642   PartialDiagnostic FDiag = PDiag(DiagKind);
12643   if (Action == AA_Passing_CFAudited)
12644     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12645   else
12646     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12647 
12648   // If we can fix the conversion, suggest the FixIts.
12649   assert(ConvHints.isNull() || Hint.isNull());
12650   if (!ConvHints.isNull()) {
12651     for (FixItHint &H : ConvHints.Hints)
12652       FDiag << H;
12653   } else {
12654     FDiag << Hint;
12655   }
12656   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12657 
12658   if (MayHaveFunctionDiff)
12659     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12660 
12661   Diag(Loc, FDiag);
12662   if (DiagKind == diag::warn_incompatible_qualified_id &&
12663       PDecl && IFace && !IFace->hasDefinition())
12664       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12665         << IFace->getName() << PDecl->getName();
12666 
12667   if (SecondType == Context.OverloadTy)
12668     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12669                               FirstType, /*TakingAddress=*/true);
12670 
12671   if (CheckInferredResultType)
12672     EmitRelatedResultTypeNote(SrcExpr);
12673 
12674   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12675     EmitRelatedResultTypeNoteForReturn(DstType);
12676 
12677   if (Complained)
12678     *Complained = true;
12679   return isInvalid;
12680 }
12681 
12682 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12683                                                  llvm::APSInt *Result) {
12684   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12685   public:
12686     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12687       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12688     }
12689   } Diagnoser;
12690 
12691   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12692 }
12693 
12694 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12695                                                  llvm::APSInt *Result,
12696                                                  unsigned DiagID,
12697                                                  bool AllowFold) {
12698   class IDDiagnoser : public VerifyICEDiagnoser {
12699     unsigned DiagID;
12700 
12701   public:
12702     IDDiagnoser(unsigned DiagID)
12703       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12704 
12705     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12706       S.Diag(Loc, DiagID) << SR;
12707     }
12708   } Diagnoser(DiagID);
12709 
12710   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12711 }
12712 
12713 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12714                                             SourceRange SR) {
12715   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12716 }
12717 
12718 ExprResult
12719 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12720                                       VerifyICEDiagnoser &Diagnoser,
12721                                       bool AllowFold) {
12722   SourceLocation DiagLoc = E->getLocStart();
12723 
12724   if (getLangOpts().CPlusPlus11) {
12725     // C++11 [expr.const]p5:
12726     //   If an expression of literal class type is used in a context where an
12727     //   integral constant expression is required, then that class type shall
12728     //   have a single non-explicit conversion function to an integral or
12729     //   unscoped enumeration type
12730     ExprResult Converted;
12731     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12732     public:
12733       CXX11ConvertDiagnoser(bool Silent)
12734           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12735                                 Silent, true) {}
12736 
12737       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12738                                            QualType T) override {
12739         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12740       }
12741 
12742       SemaDiagnosticBuilder diagnoseIncomplete(
12743           Sema &S, SourceLocation Loc, QualType T) override {
12744         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12745       }
12746 
12747       SemaDiagnosticBuilder diagnoseExplicitConv(
12748           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12749         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12750       }
12751 
12752       SemaDiagnosticBuilder noteExplicitConv(
12753           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12754         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12755                  << ConvTy->isEnumeralType() << ConvTy;
12756       }
12757 
12758       SemaDiagnosticBuilder diagnoseAmbiguous(
12759           Sema &S, SourceLocation Loc, QualType T) override {
12760         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12761       }
12762 
12763       SemaDiagnosticBuilder noteAmbiguous(
12764           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12765         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12766                  << ConvTy->isEnumeralType() << ConvTy;
12767       }
12768 
12769       SemaDiagnosticBuilder diagnoseConversion(
12770           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12771         llvm_unreachable("conversion functions are permitted");
12772       }
12773     } ConvertDiagnoser(Diagnoser.Suppress);
12774 
12775     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12776                                                     ConvertDiagnoser);
12777     if (Converted.isInvalid())
12778       return Converted;
12779     E = Converted.get();
12780     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12781       return ExprError();
12782   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12783     // An ICE must be of integral or unscoped enumeration type.
12784     if (!Diagnoser.Suppress)
12785       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12786     return ExprError();
12787   }
12788 
12789   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12790   // in the non-ICE case.
12791   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12792     if (Result)
12793       *Result = E->EvaluateKnownConstInt(Context);
12794     return E;
12795   }
12796 
12797   Expr::EvalResult EvalResult;
12798   SmallVector<PartialDiagnosticAt, 8> Notes;
12799   EvalResult.Diag = &Notes;
12800 
12801   // Try to evaluate the expression, and produce diagnostics explaining why it's
12802   // not a constant expression as a side-effect.
12803   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12804                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12805 
12806   // In C++11, we can rely on diagnostics being produced for any expression
12807   // which is not a constant expression. If no diagnostics were produced, then
12808   // this is a constant expression.
12809   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12810     if (Result)
12811       *Result = EvalResult.Val.getInt();
12812     return E;
12813   }
12814 
12815   // If our only note is the usual "invalid subexpression" note, just point
12816   // the caret at its location rather than producing an essentially
12817   // redundant note.
12818   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12819         diag::note_invalid_subexpr_in_const_expr) {
12820     DiagLoc = Notes[0].first;
12821     Notes.clear();
12822   }
12823 
12824   if (!Folded || !AllowFold) {
12825     if (!Diagnoser.Suppress) {
12826       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12827       for (const PartialDiagnosticAt &Note : Notes)
12828         Diag(Note.first, Note.second);
12829     }
12830 
12831     return ExprError();
12832   }
12833 
12834   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12835   for (const PartialDiagnosticAt &Note : Notes)
12836     Diag(Note.first, Note.second);
12837 
12838   if (Result)
12839     *Result = EvalResult.Val.getInt();
12840   return E;
12841 }
12842 
12843 namespace {
12844   // Handle the case where we conclude a expression which we speculatively
12845   // considered to be unevaluated is actually evaluated.
12846   class TransformToPE : public TreeTransform<TransformToPE> {
12847     typedef TreeTransform<TransformToPE> BaseTransform;
12848 
12849   public:
12850     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12851 
12852     // Make sure we redo semantic analysis
12853     bool AlwaysRebuild() { return true; }
12854 
12855     // Make sure we handle LabelStmts correctly.
12856     // FIXME: This does the right thing, but maybe we need a more general
12857     // fix to TreeTransform?
12858     StmtResult TransformLabelStmt(LabelStmt *S) {
12859       S->getDecl()->setStmt(nullptr);
12860       return BaseTransform::TransformLabelStmt(S);
12861     }
12862 
12863     // We need to special-case DeclRefExprs referring to FieldDecls which
12864     // are not part of a member pointer formation; normal TreeTransforming
12865     // doesn't catch this case because of the way we represent them in the AST.
12866     // FIXME: This is a bit ugly; is it really the best way to handle this
12867     // case?
12868     //
12869     // Error on DeclRefExprs referring to FieldDecls.
12870     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12871       if (isa<FieldDecl>(E->getDecl()) &&
12872           !SemaRef.isUnevaluatedContext())
12873         return SemaRef.Diag(E->getLocation(),
12874                             diag::err_invalid_non_static_member_use)
12875             << E->getDecl() << E->getSourceRange();
12876 
12877       return BaseTransform::TransformDeclRefExpr(E);
12878     }
12879 
12880     // Exception: filter out member pointer formation
12881     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12882       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12883         return E;
12884 
12885       return BaseTransform::TransformUnaryOperator(E);
12886     }
12887 
12888     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12889       // Lambdas never need to be transformed.
12890       return E;
12891     }
12892   };
12893 }
12894 
12895 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12896   assert(isUnevaluatedContext() &&
12897          "Should only transform unevaluated expressions");
12898   ExprEvalContexts.back().Context =
12899       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12900   if (isUnevaluatedContext())
12901     return E;
12902   return TransformToPE(*this).TransformExpr(E);
12903 }
12904 
12905 void
12906 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12907                                       Decl *LambdaContextDecl,
12908                                       bool IsDecltype) {
12909   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
12910                                 LambdaContextDecl, IsDecltype);
12911   Cleanup.reset();
12912   if (!MaybeODRUseExprs.empty())
12913     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12914 }
12915 
12916 void
12917 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12918                                       ReuseLambdaContextDecl_t,
12919                                       bool IsDecltype) {
12920   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12921   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12922 }
12923 
12924 void Sema::PopExpressionEvaluationContext() {
12925   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12926   unsigned NumTypos = Rec.NumTypos;
12927 
12928   if (!Rec.Lambdas.empty()) {
12929     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12930       unsigned D;
12931       if (Rec.isUnevaluated()) {
12932         // C++11 [expr.prim.lambda]p2:
12933         //   A lambda-expression shall not appear in an unevaluated operand
12934         //   (Clause 5).
12935         D = diag::err_lambda_unevaluated_operand;
12936       } else {
12937         // C++1y [expr.const]p2:
12938         //   A conditional-expression e is a core constant expression unless the
12939         //   evaluation of e, following the rules of the abstract machine, would
12940         //   evaluate [...] a lambda-expression.
12941         D = diag::err_lambda_in_constant_expression;
12942       }
12943       for (const auto *L : Rec.Lambdas)
12944         Diag(L->getLocStart(), D);
12945     } else {
12946       // Mark the capture expressions odr-used. This was deferred
12947       // during lambda expression creation.
12948       for (auto *Lambda : Rec.Lambdas) {
12949         for (auto *C : Lambda->capture_inits())
12950           MarkDeclarationsReferencedInExpr(C);
12951       }
12952     }
12953   }
12954 
12955   // When are coming out of an unevaluated context, clear out any
12956   // temporaries that we may have created as part of the evaluation of
12957   // the expression in that context: they aren't relevant because they
12958   // will never be constructed.
12959   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12960     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12961                              ExprCleanupObjects.end());
12962     Cleanup = Rec.ParentCleanup;
12963     CleanupVarDeclMarking();
12964     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12965   // Otherwise, merge the contexts together.
12966   } else {
12967     Cleanup.mergeFrom(Rec.ParentCleanup);
12968     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12969                             Rec.SavedMaybeODRUseExprs.end());
12970   }
12971 
12972   // Pop the current expression evaluation context off the stack.
12973   ExprEvalContexts.pop_back();
12974 
12975   if (!ExprEvalContexts.empty())
12976     ExprEvalContexts.back().NumTypos += NumTypos;
12977   else
12978     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12979                             "last ExpressionEvaluationContextRecord");
12980 }
12981 
12982 void Sema::DiscardCleanupsInEvaluationContext() {
12983   ExprCleanupObjects.erase(
12984          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12985          ExprCleanupObjects.end());
12986   Cleanup.reset();
12987   MaybeODRUseExprs.clear();
12988 }
12989 
12990 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12991   if (!E->getType()->isVariablyModifiedType())
12992     return E;
12993   return TransformToPotentiallyEvaluated(E);
12994 }
12995 
12996 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12997   // Do not mark anything as "used" within a dependent context; wait for
12998   // an instantiation.
12999   if (SemaRef.CurContext->isDependentContext())
13000     return false;
13001 
13002   switch (SemaRef.ExprEvalContexts.back().Context) {
13003     case Sema::Unevaluated:
13004     case Sema::UnevaluatedAbstract:
13005       // We are in an expression that is not potentially evaluated; do nothing.
13006       // (Depending on how you read the standard, we actually do need to do
13007       // something here for null pointer constants, but the standard's
13008       // definition of a null pointer constant is completely crazy.)
13009       return false;
13010 
13011     case Sema::DiscardedStatement:
13012       // These are technically a potentially evaluated but they have the effect
13013       // of suppressing use marking.
13014       return false;
13015 
13016     case Sema::ConstantEvaluated:
13017     case Sema::PotentiallyEvaluated:
13018       // We are in a potentially evaluated expression (or a constant-expression
13019       // in C++03); we need to do implicit template instantiation, implicitly
13020       // define class members, and mark most declarations as used.
13021       return true;
13022 
13023     case Sema::PotentiallyEvaluatedIfUsed:
13024       // Referenced declarations will only be used if the construct in the
13025       // containing expression is used.
13026       return false;
13027   }
13028   llvm_unreachable("Invalid context");
13029 }
13030 
13031 /// \brief Mark a function referenced, and check whether it is odr-used
13032 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13033 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13034                                   bool MightBeOdrUse) {
13035   assert(Func && "No function?");
13036 
13037   Func->setReferenced();
13038 
13039   // C++11 [basic.def.odr]p3:
13040   //   A function whose name appears as a potentially-evaluated expression is
13041   //   odr-used if it is the unique lookup result or the selected member of a
13042   //   set of overloaded functions [...].
13043   //
13044   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13045   // can just check that here.
13046   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13047 
13048   // Determine whether we require a function definition to exist, per
13049   // C++11 [temp.inst]p3:
13050   //   Unless a function template specialization has been explicitly
13051   //   instantiated or explicitly specialized, the function template
13052   //   specialization is implicitly instantiated when the specialization is
13053   //   referenced in a context that requires a function definition to exist.
13054   //
13055   // We consider constexpr function templates to be referenced in a context
13056   // that requires a definition to exist whenever they are referenced.
13057   //
13058   // FIXME: This instantiates constexpr functions too frequently. If this is
13059   // really an unevaluated context (and we're not just in the definition of a
13060   // function template or overload resolution or other cases which we
13061   // incorrectly consider to be unevaluated contexts), and we're not in a
13062   // subexpression which we actually need to evaluate (for instance, a
13063   // template argument, array bound or an expression in a braced-init-list),
13064   // we are not permitted to instantiate this constexpr function definition.
13065   //
13066   // FIXME: This also implicitly defines special members too frequently. They
13067   // are only supposed to be implicitly defined if they are odr-used, but they
13068   // are not odr-used from constant expressions in unevaluated contexts.
13069   // However, they cannot be referenced if they are deleted, and they are
13070   // deleted whenever the implicit definition of the special member would
13071   // fail (with very few exceptions).
13072   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13073   bool NeedDefinition =
13074       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13075                                          (MD && !MD->isUserProvided())));
13076 
13077   // C++14 [temp.expl.spec]p6:
13078   //   If a template [...] is explicitly specialized then that specialization
13079   //   shall be declared before the first use of that specialization that would
13080   //   cause an implicit instantiation to take place, in every translation unit
13081   //   in which such a use occurs
13082   if (NeedDefinition &&
13083       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13084        Func->getMemberSpecializationInfo()))
13085     checkSpecializationVisibility(Loc, Func);
13086 
13087   // If we don't need to mark the function as used, and we don't need to
13088   // try to provide a definition, there's nothing more to do.
13089   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13090       (!NeedDefinition || Func->getBody()))
13091     return;
13092 
13093   // Note that this declaration has been used.
13094   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13095     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13096     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13097       if (Constructor->isDefaultConstructor()) {
13098         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13099           return;
13100         DefineImplicitDefaultConstructor(Loc, Constructor);
13101       } else if (Constructor->isCopyConstructor()) {
13102         DefineImplicitCopyConstructor(Loc, Constructor);
13103       } else if (Constructor->isMoveConstructor()) {
13104         DefineImplicitMoveConstructor(Loc, Constructor);
13105       }
13106     } else if (Constructor->getInheritedConstructor()) {
13107       DefineInheritingConstructor(Loc, Constructor);
13108     }
13109   } else if (CXXDestructorDecl *Destructor =
13110                  dyn_cast<CXXDestructorDecl>(Func)) {
13111     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13112     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13113       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13114         return;
13115       DefineImplicitDestructor(Loc, Destructor);
13116     }
13117     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13118       MarkVTableUsed(Loc, Destructor->getParent());
13119   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13120     if (MethodDecl->isOverloadedOperator() &&
13121         MethodDecl->getOverloadedOperator() == OO_Equal) {
13122       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13123       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13124         if (MethodDecl->isCopyAssignmentOperator())
13125           DefineImplicitCopyAssignment(Loc, MethodDecl);
13126         else if (MethodDecl->isMoveAssignmentOperator())
13127           DefineImplicitMoveAssignment(Loc, MethodDecl);
13128       }
13129     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13130                MethodDecl->getParent()->isLambda()) {
13131       CXXConversionDecl *Conversion =
13132           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13133       if (Conversion->isLambdaToBlockPointerConversion())
13134         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13135       else
13136         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13137     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13138       MarkVTableUsed(Loc, MethodDecl->getParent());
13139   }
13140 
13141   // Recursive functions should be marked when used from another function.
13142   // FIXME: Is this really right?
13143   if (CurContext == Func) return;
13144 
13145   // Resolve the exception specification for any function which is
13146   // used: CodeGen will need it.
13147   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13148   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13149     ResolveExceptionSpec(Loc, FPT);
13150 
13151   // Implicit instantiation of function templates and member functions of
13152   // class templates.
13153   if (Func->isImplicitlyInstantiable()) {
13154     bool AlreadyInstantiated = false;
13155     SourceLocation PointOfInstantiation = Loc;
13156     if (FunctionTemplateSpecializationInfo *SpecInfo
13157                               = Func->getTemplateSpecializationInfo()) {
13158       if (SpecInfo->getPointOfInstantiation().isInvalid())
13159         SpecInfo->setPointOfInstantiation(Loc);
13160       else if (SpecInfo->getTemplateSpecializationKind()
13161                  == TSK_ImplicitInstantiation) {
13162         AlreadyInstantiated = true;
13163         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13164       }
13165     } else if (MemberSpecializationInfo *MSInfo
13166                                 = Func->getMemberSpecializationInfo()) {
13167       if (MSInfo->getPointOfInstantiation().isInvalid())
13168         MSInfo->setPointOfInstantiation(Loc);
13169       else if (MSInfo->getTemplateSpecializationKind()
13170                  == TSK_ImplicitInstantiation) {
13171         AlreadyInstantiated = true;
13172         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13173       }
13174     }
13175 
13176     if (!AlreadyInstantiated || Func->isConstexpr()) {
13177       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13178           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13179           ActiveTemplateInstantiations.size())
13180         PendingLocalImplicitInstantiations.push_back(
13181             std::make_pair(Func, PointOfInstantiation));
13182       else if (Func->isConstexpr())
13183         // Do not defer instantiations of constexpr functions, to avoid the
13184         // expression evaluator needing to call back into Sema if it sees a
13185         // call to such a function.
13186         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13187       else {
13188         PendingInstantiations.push_back(std::make_pair(Func,
13189                                                        PointOfInstantiation));
13190         // Notify the consumer that a function was implicitly instantiated.
13191         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13192       }
13193     }
13194   } else {
13195     // Walk redefinitions, as some of them may be instantiable.
13196     for (auto i : Func->redecls()) {
13197       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13198         MarkFunctionReferenced(Loc, i, OdrUse);
13199     }
13200   }
13201 
13202   if (!OdrUse) return;
13203 
13204   // Keep track of used but undefined functions.
13205   if (!Func->isDefined()) {
13206     if (mightHaveNonExternalLinkage(Func))
13207       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13208     else if (Func->getMostRecentDecl()->isInlined() &&
13209              !LangOpts.GNUInline &&
13210              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13211       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13212   }
13213 
13214   Func->markUsed(Context);
13215 }
13216 
13217 static void
13218 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13219                                    VarDecl *var, DeclContext *DC) {
13220   DeclContext *VarDC = var->getDeclContext();
13221 
13222   //  If the parameter still belongs to the translation unit, then
13223   //  we're actually just using one parameter in the declaration of
13224   //  the next.
13225   if (isa<ParmVarDecl>(var) &&
13226       isa<TranslationUnitDecl>(VarDC))
13227     return;
13228 
13229   // For C code, don't diagnose about capture if we're not actually in code
13230   // right now; it's impossible to write a non-constant expression outside of
13231   // function context, so we'll get other (more useful) diagnostics later.
13232   //
13233   // For C++, things get a bit more nasty... it would be nice to suppress this
13234   // diagnostic for certain cases like using a local variable in an array bound
13235   // for a member of a local class, but the correct predicate is not obvious.
13236   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13237     return;
13238 
13239   if (isa<CXXMethodDecl>(VarDC) &&
13240       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13241     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
13242       << var->getIdentifier();
13243   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
13244     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
13245       << var->getIdentifier() << fn->getDeclName();
13246   } else if (isa<BlockDecl>(VarDC)) {
13247     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
13248       << var->getIdentifier();
13249   } else {
13250     // FIXME: Is there any other context where a local variable can be
13251     // declared?
13252     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
13253       << var->getIdentifier();
13254   }
13255 
13256   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13257       << var->getIdentifier();
13258 
13259   // FIXME: Add additional diagnostic info about class etc. which prevents
13260   // capture.
13261 }
13262 
13263 
13264 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13265                                       bool &SubCapturesAreNested,
13266                                       QualType &CaptureType,
13267                                       QualType &DeclRefType) {
13268    // Check whether we've already captured it.
13269   if (CSI->CaptureMap.count(Var)) {
13270     // If we found a capture, any subcaptures are nested.
13271     SubCapturesAreNested = true;
13272 
13273     // Retrieve the capture type for this variable.
13274     CaptureType = CSI->getCapture(Var).getCaptureType();
13275 
13276     // Compute the type of an expression that refers to this variable.
13277     DeclRefType = CaptureType.getNonReferenceType();
13278 
13279     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13280     // are mutable in the sense that user can change their value - they are
13281     // private instances of the captured declarations.
13282     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13283     if (Cap.isCopyCapture() &&
13284         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13285         !(isa<CapturedRegionScopeInfo>(CSI) &&
13286           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13287       DeclRefType.addConst();
13288     return true;
13289   }
13290   return false;
13291 }
13292 
13293 // Only block literals, captured statements, and lambda expressions can
13294 // capture; other scopes don't work.
13295 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13296                                  SourceLocation Loc,
13297                                  const bool Diagnose, Sema &S) {
13298   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13299     return getLambdaAwareParentOfDeclContext(DC);
13300   else if (Var->hasLocalStorage()) {
13301     if (Diagnose)
13302        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13303   }
13304   return nullptr;
13305 }
13306 
13307 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13308 // certain types of variables (unnamed, variably modified types etc.)
13309 // so check for eligibility.
13310 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13311                                  SourceLocation Loc,
13312                                  const bool Diagnose, Sema &S) {
13313 
13314   bool IsBlock = isa<BlockScopeInfo>(CSI);
13315   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13316 
13317   // Lambdas are not allowed to capture unnamed variables
13318   // (e.g. anonymous unions).
13319   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13320   // assuming that's the intent.
13321   if (IsLambda && !Var->getDeclName()) {
13322     if (Diagnose) {
13323       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13324       S.Diag(Var->getLocation(), diag::note_declared_at);
13325     }
13326     return false;
13327   }
13328 
13329   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13330   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13331     if (Diagnose) {
13332       S.Diag(Loc, diag::err_ref_vm_type);
13333       S.Diag(Var->getLocation(), diag::note_previous_decl)
13334         << Var->getDeclName();
13335     }
13336     return false;
13337   }
13338   // Prohibit structs with flexible array members too.
13339   // We cannot capture what is in the tail end of the struct.
13340   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13341     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13342       if (Diagnose) {
13343         if (IsBlock)
13344           S.Diag(Loc, diag::err_ref_flexarray_type);
13345         else
13346           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13347             << Var->getDeclName();
13348         S.Diag(Var->getLocation(), diag::note_previous_decl)
13349           << Var->getDeclName();
13350       }
13351       return false;
13352     }
13353   }
13354   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13355   // Lambdas and captured statements are not allowed to capture __block
13356   // variables; they don't support the expected semantics.
13357   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13358     if (Diagnose) {
13359       S.Diag(Loc, diag::err_capture_block_variable)
13360         << Var->getDeclName() << !IsLambda;
13361       S.Diag(Var->getLocation(), diag::note_previous_decl)
13362         << Var->getDeclName();
13363     }
13364     return false;
13365   }
13366 
13367   return true;
13368 }
13369 
13370 // Returns true if the capture by block was successful.
13371 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13372                                  SourceLocation Loc,
13373                                  const bool BuildAndDiagnose,
13374                                  QualType &CaptureType,
13375                                  QualType &DeclRefType,
13376                                  const bool Nested,
13377                                  Sema &S) {
13378   Expr *CopyExpr = nullptr;
13379   bool ByRef = false;
13380 
13381   // Blocks are not allowed to capture arrays.
13382   if (CaptureType->isArrayType()) {
13383     if (BuildAndDiagnose) {
13384       S.Diag(Loc, diag::err_ref_array_type);
13385       S.Diag(Var->getLocation(), diag::note_previous_decl)
13386       << Var->getDeclName();
13387     }
13388     return false;
13389   }
13390 
13391   // Forbid the block-capture of autoreleasing variables.
13392   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13393     if (BuildAndDiagnose) {
13394       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13395         << /*block*/ 0;
13396       S.Diag(Var->getLocation(), diag::note_previous_decl)
13397         << Var->getDeclName();
13398     }
13399     return false;
13400   }
13401   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13402   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13403       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13404     // Block capture by reference does not change the capture or
13405     // declaration reference types.
13406     ByRef = true;
13407   } else {
13408     // Block capture by copy introduces 'const'.
13409     CaptureType = CaptureType.getNonReferenceType().withConst();
13410     DeclRefType = CaptureType;
13411 
13412     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13413       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13414         // The capture logic needs the destructor, so make sure we mark it.
13415         // Usually this is unnecessary because most local variables have
13416         // their destructors marked at declaration time, but parameters are
13417         // an exception because it's technically only the call site that
13418         // actually requires the destructor.
13419         if (isa<ParmVarDecl>(Var))
13420           S.FinalizeVarWithDestructor(Var, Record);
13421 
13422         // Enter a new evaluation context to insulate the copy
13423         // full-expression.
13424         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13425 
13426         // According to the blocks spec, the capture of a variable from
13427         // the stack requires a const copy constructor.  This is not true
13428         // of the copy/move done to move a __block variable to the heap.
13429         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13430                                                   DeclRefType.withConst(),
13431                                                   VK_LValue, Loc);
13432 
13433         ExprResult Result
13434           = S.PerformCopyInitialization(
13435               InitializedEntity::InitializeBlock(Var->getLocation(),
13436                                                   CaptureType, false),
13437               Loc, DeclRef);
13438 
13439         // Build a full-expression copy expression if initialization
13440         // succeeded and used a non-trivial constructor.  Recover from
13441         // errors by pretending that the copy isn't necessary.
13442         if (!Result.isInvalid() &&
13443             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13444                 ->isTrivial()) {
13445           Result = S.MaybeCreateExprWithCleanups(Result);
13446           CopyExpr = Result.get();
13447         }
13448       }
13449     }
13450   }
13451 
13452   // Actually capture the variable.
13453   if (BuildAndDiagnose)
13454     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13455                     SourceLocation(), CaptureType, CopyExpr);
13456 
13457   return true;
13458 
13459 }
13460 
13461 
13462 /// \brief Capture the given variable in the captured region.
13463 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13464                                     VarDecl *Var,
13465                                     SourceLocation Loc,
13466                                     const bool BuildAndDiagnose,
13467                                     QualType &CaptureType,
13468                                     QualType &DeclRefType,
13469                                     const bool RefersToCapturedVariable,
13470                                     Sema &S) {
13471   // By default, capture variables by reference.
13472   bool ByRef = true;
13473   // Using an LValue reference type is consistent with Lambdas (see below).
13474   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13475     if (S.IsOpenMPCapturedDecl(Var))
13476       DeclRefType = DeclRefType.getUnqualifiedType();
13477     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13478   }
13479 
13480   if (ByRef)
13481     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13482   else
13483     CaptureType = DeclRefType;
13484 
13485   Expr *CopyExpr = nullptr;
13486   if (BuildAndDiagnose) {
13487     // The current implementation assumes that all variables are captured
13488     // by references. Since there is no capture by copy, no expression
13489     // evaluation will be needed.
13490     RecordDecl *RD = RSI->TheRecordDecl;
13491 
13492     FieldDecl *Field
13493       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13494                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13495                           nullptr, false, ICIS_NoInit);
13496     Field->setImplicit(true);
13497     Field->setAccess(AS_private);
13498     RD->addDecl(Field);
13499 
13500     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13501                                             DeclRefType, VK_LValue, Loc);
13502     Var->setReferenced(true);
13503     Var->markUsed(S.Context);
13504   }
13505 
13506   // Actually capture the variable.
13507   if (BuildAndDiagnose)
13508     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13509                     SourceLocation(), CaptureType, CopyExpr);
13510 
13511 
13512   return true;
13513 }
13514 
13515 /// \brief Create a field within the lambda class for the variable
13516 /// being captured.
13517 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13518                                     QualType FieldType, QualType DeclRefType,
13519                                     SourceLocation Loc,
13520                                     bool RefersToCapturedVariable) {
13521   CXXRecordDecl *Lambda = LSI->Lambda;
13522 
13523   // Build the non-static data member.
13524   FieldDecl *Field
13525     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13526                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13527                         nullptr, false, ICIS_NoInit);
13528   Field->setImplicit(true);
13529   Field->setAccess(AS_private);
13530   Lambda->addDecl(Field);
13531 }
13532 
13533 /// \brief Capture the given variable in the lambda.
13534 static bool captureInLambda(LambdaScopeInfo *LSI,
13535                             VarDecl *Var,
13536                             SourceLocation Loc,
13537                             const bool BuildAndDiagnose,
13538                             QualType &CaptureType,
13539                             QualType &DeclRefType,
13540                             const bool RefersToCapturedVariable,
13541                             const Sema::TryCaptureKind Kind,
13542                             SourceLocation EllipsisLoc,
13543                             const bool IsTopScope,
13544                             Sema &S) {
13545 
13546   // Determine whether we are capturing by reference or by value.
13547   bool ByRef = false;
13548   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13549     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13550   } else {
13551     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13552   }
13553 
13554   // Compute the type of the field that will capture this variable.
13555   if (ByRef) {
13556     // C++11 [expr.prim.lambda]p15:
13557     //   An entity is captured by reference if it is implicitly or
13558     //   explicitly captured but not captured by copy. It is
13559     //   unspecified whether additional unnamed non-static data
13560     //   members are declared in the closure type for entities
13561     //   captured by reference.
13562     //
13563     // FIXME: It is not clear whether we want to build an lvalue reference
13564     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13565     // to do the former, while EDG does the latter. Core issue 1249 will
13566     // clarify, but for now we follow GCC because it's a more permissive and
13567     // easily defensible position.
13568     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13569   } else {
13570     // C++11 [expr.prim.lambda]p14:
13571     //   For each entity captured by copy, an unnamed non-static
13572     //   data member is declared in the closure type. The
13573     //   declaration order of these members is unspecified. The type
13574     //   of such a data member is the type of the corresponding
13575     //   captured entity if the entity is not a reference to an
13576     //   object, or the referenced type otherwise. [Note: If the
13577     //   captured entity is a reference to a function, the
13578     //   corresponding data member is also a reference to a
13579     //   function. - end note ]
13580     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13581       if (!RefType->getPointeeType()->isFunctionType())
13582         CaptureType = RefType->getPointeeType();
13583     }
13584 
13585     // Forbid the lambda copy-capture of autoreleasing variables.
13586     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13587       if (BuildAndDiagnose) {
13588         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13589         S.Diag(Var->getLocation(), diag::note_previous_decl)
13590           << Var->getDeclName();
13591       }
13592       return false;
13593     }
13594 
13595     // Make sure that by-copy captures are of a complete and non-abstract type.
13596     if (BuildAndDiagnose) {
13597       if (!CaptureType->isDependentType() &&
13598           S.RequireCompleteType(Loc, CaptureType,
13599                                 diag::err_capture_of_incomplete_type,
13600                                 Var->getDeclName()))
13601         return false;
13602 
13603       if (S.RequireNonAbstractType(Loc, CaptureType,
13604                                    diag::err_capture_of_abstract_type))
13605         return false;
13606     }
13607   }
13608 
13609   // Capture this variable in the lambda.
13610   if (BuildAndDiagnose)
13611     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13612                             RefersToCapturedVariable);
13613 
13614   // Compute the type of a reference to this captured variable.
13615   if (ByRef)
13616     DeclRefType = CaptureType.getNonReferenceType();
13617   else {
13618     // C++ [expr.prim.lambda]p5:
13619     //   The closure type for a lambda-expression has a public inline
13620     //   function call operator [...]. This function call operator is
13621     //   declared const (9.3.1) if and only if the lambda-expression’s
13622     //   parameter-declaration-clause is not followed by mutable.
13623     DeclRefType = CaptureType.getNonReferenceType();
13624     if (!LSI->Mutable && !CaptureType->isReferenceType())
13625       DeclRefType.addConst();
13626   }
13627 
13628   // Add the capture.
13629   if (BuildAndDiagnose)
13630     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13631                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13632 
13633   return true;
13634 }
13635 
13636 bool Sema::tryCaptureVariable(
13637     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13638     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13639     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13640   // An init-capture is notionally from the context surrounding its
13641   // declaration, but its parent DC is the lambda class.
13642   DeclContext *VarDC = Var->getDeclContext();
13643   if (Var->isInitCapture())
13644     VarDC = VarDC->getParent();
13645 
13646   DeclContext *DC = CurContext;
13647   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13648       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13649   // We need to sync up the Declaration Context with the
13650   // FunctionScopeIndexToStopAt
13651   if (FunctionScopeIndexToStopAt) {
13652     unsigned FSIndex = FunctionScopes.size() - 1;
13653     while (FSIndex != MaxFunctionScopesIndex) {
13654       DC = getLambdaAwareParentOfDeclContext(DC);
13655       --FSIndex;
13656     }
13657   }
13658 
13659 
13660   // If the variable is declared in the current context, there is no need to
13661   // capture it.
13662   if (VarDC == DC) return true;
13663 
13664   // Capture global variables if it is required to use private copy of this
13665   // variable.
13666   bool IsGlobal = !Var->hasLocalStorage();
13667   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13668     return true;
13669 
13670   // Walk up the stack to determine whether we can capture the variable,
13671   // performing the "simple" checks that don't depend on type. We stop when
13672   // we've either hit the declared scope of the variable or find an existing
13673   // capture of that variable.  We start from the innermost capturing-entity
13674   // (the DC) and ensure that all intervening capturing-entities
13675   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13676   // declcontext can either capture the variable or have already captured
13677   // the variable.
13678   CaptureType = Var->getType();
13679   DeclRefType = CaptureType.getNonReferenceType();
13680   bool Nested = false;
13681   bool Explicit = (Kind != TryCapture_Implicit);
13682   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13683   do {
13684     // Only block literals, captured statements, and lambda expressions can
13685     // capture; other scopes don't work.
13686     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13687                                                               ExprLoc,
13688                                                               BuildAndDiagnose,
13689                                                               *this);
13690     // We need to check for the parent *first* because, if we *have*
13691     // private-captured a global variable, we need to recursively capture it in
13692     // intermediate blocks, lambdas, etc.
13693     if (!ParentDC) {
13694       if (IsGlobal) {
13695         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13696         break;
13697       }
13698       return true;
13699     }
13700 
13701     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13702     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13703 
13704 
13705     // Check whether we've already captured it.
13706     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13707                                              DeclRefType))
13708       break;
13709     // If we are instantiating a generic lambda call operator body,
13710     // we do not want to capture new variables.  What was captured
13711     // during either a lambdas transformation or initial parsing
13712     // should be used.
13713     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13714       if (BuildAndDiagnose) {
13715         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13716         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13717           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13718           Diag(Var->getLocation(), diag::note_previous_decl)
13719              << Var->getDeclName();
13720           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13721         } else
13722           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13723       }
13724       return true;
13725     }
13726     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13727     // certain types of variables (unnamed, variably modified types etc.)
13728     // so check for eligibility.
13729     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13730        return true;
13731 
13732     // Try to capture variable-length arrays types.
13733     if (Var->getType()->isVariablyModifiedType()) {
13734       // We're going to walk down into the type and look for VLA
13735       // expressions.
13736       QualType QTy = Var->getType();
13737       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13738         QTy = PVD->getOriginalType();
13739       captureVariablyModifiedType(Context, QTy, CSI);
13740     }
13741 
13742     if (getLangOpts().OpenMP) {
13743       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13744         // OpenMP private variables should not be captured in outer scope, so
13745         // just break here. Similarly, global variables that are captured in a
13746         // target region should not be captured outside the scope of the region.
13747         if (RSI->CapRegionKind == CR_OpenMP) {
13748           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13749           // When we detect target captures we are looking from inside the
13750           // target region, therefore we need to propagate the capture from the
13751           // enclosing region. Therefore, the capture is not initially nested.
13752           if (IsTargetCap)
13753             FunctionScopesIndex--;
13754 
13755           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13756             Nested = !IsTargetCap;
13757             DeclRefType = DeclRefType.getUnqualifiedType();
13758             CaptureType = Context.getLValueReferenceType(DeclRefType);
13759             break;
13760           }
13761         }
13762       }
13763     }
13764     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13765       // No capture-default, and this is not an explicit capture
13766       // so cannot capture this variable.
13767       if (BuildAndDiagnose) {
13768         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13769         Diag(Var->getLocation(), diag::note_previous_decl)
13770           << Var->getDeclName();
13771         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13772           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13773                diag::note_lambda_decl);
13774         // FIXME: If we error out because an outer lambda can not implicitly
13775         // capture a variable that an inner lambda explicitly captures, we
13776         // should have the inner lambda do the explicit capture - because
13777         // it makes for cleaner diagnostics later.  This would purely be done
13778         // so that the diagnostic does not misleadingly claim that a variable
13779         // can not be captured by a lambda implicitly even though it is captured
13780         // explicitly.  Suggestion:
13781         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13782         //    at the function head
13783         //  - cache the StartingDeclContext - this must be a lambda
13784         //  - captureInLambda in the innermost lambda the variable.
13785       }
13786       return true;
13787     }
13788 
13789     FunctionScopesIndex--;
13790     DC = ParentDC;
13791     Explicit = false;
13792   } while (!VarDC->Equals(DC));
13793 
13794   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13795   // computing the type of the capture at each step, checking type-specific
13796   // requirements, and adding captures if requested.
13797   // If the variable had already been captured previously, we start capturing
13798   // at the lambda nested within that one.
13799   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13800        ++I) {
13801     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13802 
13803     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13804       if (!captureInBlock(BSI, Var, ExprLoc,
13805                           BuildAndDiagnose, CaptureType,
13806                           DeclRefType, Nested, *this))
13807         return true;
13808       Nested = true;
13809     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13810       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13811                                    BuildAndDiagnose, CaptureType,
13812                                    DeclRefType, Nested, *this))
13813         return true;
13814       Nested = true;
13815     } else {
13816       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13817       if (!captureInLambda(LSI, Var, ExprLoc,
13818                            BuildAndDiagnose, CaptureType,
13819                            DeclRefType, Nested, Kind, EllipsisLoc,
13820                             /*IsTopScope*/I == N - 1, *this))
13821         return true;
13822       Nested = true;
13823     }
13824   }
13825   return false;
13826 }
13827 
13828 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13829                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13830   QualType CaptureType;
13831   QualType DeclRefType;
13832   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13833                             /*BuildAndDiagnose=*/true, CaptureType,
13834                             DeclRefType, nullptr);
13835 }
13836 
13837 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13838   QualType CaptureType;
13839   QualType DeclRefType;
13840   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13841                              /*BuildAndDiagnose=*/false, CaptureType,
13842                              DeclRefType, nullptr);
13843 }
13844 
13845 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13846   QualType CaptureType;
13847   QualType DeclRefType;
13848 
13849   // Determine whether we can capture this variable.
13850   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13851                          /*BuildAndDiagnose=*/false, CaptureType,
13852                          DeclRefType, nullptr))
13853     return QualType();
13854 
13855   return DeclRefType;
13856 }
13857 
13858 
13859 
13860 // If either the type of the variable or the initializer is dependent,
13861 // return false. Otherwise, determine whether the variable is a constant
13862 // expression. Use this if you need to know if a variable that might or
13863 // might not be dependent is truly a constant expression.
13864 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13865     ASTContext &Context) {
13866 
13867   if (Var->getType()->isDependentType())
13868     return false;
13869   const VarDecl *DefVD = nullptr;
13870   Var->getAnyInitializer(DefVD);
13871   if (!DefVD)
13872     return false;
13873   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13874   Expr *Init = cast<Expr>(Eval->Value);
13875   if (Init->isValueDependent())
13876     return false;
13877   return IsVariableAConstantExpression(Var, Context);
13878 }
13879 
13880 
13881 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13882   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13883   // an object that satisfies the requirements for appearing in a
13884   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13885   // is immediately applied."  This function handles the lvalue-to-rvalue
13886   // conversion part.
13887   MaybeODRUseExprs.erase(E->IgnoreParens());
13888 
13889   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13890   // to a variable that is a constant expression, and if so, identify it as
13891   // a reference to a variable that does not involve an odr-use of that
13892   // variable.
13893   if (LambdaScopeInfo *LSI = getCurLambda()) {
13894     Expr *SansParensExpr = E->IgnoreParens();
13895     VarDecl *Var = nullptr;
13896     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13897       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13898     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13899       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13900 
13901     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13902       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13903   }
13904 }
13905 
13906 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13907   Res = CorrectDelayedTyposInExpr(Res);
13908 
13909   if (!Res.isUsable())
13910     return Res;
13911 
13912   // If a constant-expression is a reference to a variable where we delay
13913   // deciding whether it is an odr-use, just assume we will apply the
13914   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13915   // (a non-type template argument), we have special handling anyway.
13916   UpdateMarkingForLValueToRValue(Res.get());
13917   return Res;
13918 }
13919 
13920 void Sema::CleanupVarDeclMarking() {
13921   for (Expr *E : MaybeODRUseExprs) {
13922     VarDecl *Var;
13923     SourceLocation Loc;
13924     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13925       Var = cast<VarDecl>(DRE->getDecl());
13926       Loc = DRE->getLocation();
13927     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13928       Var = cast<VarDecl>(ME->getMemberDecl());
13929       Loc = ME->getMemberLoc();
13930     } else {
13931       llvm_unreachable("Unexpected expression");
13932     }
13933 
13934     MarkVarDeclODRUsed(Var, Loc, *this,
13935                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13936   }
13937 
13938   MaybeODRUseExprs.clear();
13939 }
13940 
13941 
13942 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13943                                     VarDecl *Var, Expr *E) {
13944   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13945          "Invalid Expr argument to DoMarkVarDeclReferenced");
13946   Var->setReferenced();
13947 
13948   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13949   bool MarkODRUsed = true;
13950 
13951   // If the context is not potentially evaluated, this is not an odr-use and
13952   // does not trigger instantiation.
13953   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13954     if (SemaRef.isUnevaluatedContext())
13955       return;
13956 
13957     // If we don't yet know whether this context is going to end up being an
13958     // evaluated context, and we're referencing a variable from an enclosing
13959     // scope, add a potential capture.
13960     //
13961     // FIXME: Is this necessary? These contexts are only used for default
13962     // arguments, where local variables can't be used.
13963     const bool RefersToEnclosingScope =
13964         (SemaRef.CurContext != Var->getDeclContext() &&
13965          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13966     if (RefersToEnclosingScope) {
13967       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13968         // If a variable could potentially be odr-used, defer marking it so
13969         // until we finish analyzing the full expression for any
13970         // lvalue-to-rvalue
13971         // or discarded value conversions that would obviate odr-use.
13972         // Add it to the list of potential captures that will be analyzed
13973         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13974         // unless the variable is a reference that was initialized by a constant
13975         // expression (this will never need to be captured or odr-used).
13976         assert(E && "Capture variable should be used in an expression.");
13977         if (!Var->getType()->isReferenceType() ||
13978             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13979           LSI->addPotentialCapture(E->IgnoreParens());
13980       }
13981     }
13982 
13983     if (!isTemplateInstantiation(TSK))
13984       return;
13985 
13986     // Instantiate, but do not mark as odr-used, variable templates.
13987     MarkODRUsed = false;
13988   }
13989 
13990   VarTemplateSpecializationDecl *VarSpec =
13991       dyn_cast<VarTemplateSpecializationDecl>(Var);
13992   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13993          "Can't instantiate a partial template specialization.");
13994 
13995   // If this might be a member specialization of a static data member, check
13996   // the specialization is visible. We already did the checks for variable
13997   // template specializations when we created them.
13998   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
13999     SemaRef.checkSpecializationVisibility(Loc, Var);
14000 
14001   // Perform implicit instantiation of static data members, static data member
14002   // templates of class templates, and variable template specializations. Delay
14003   // instantiations of variable templates, except for those that could be used
14004   // in a constant expression.
14005   if (isTemplateInstantiation(TSK)) {
14006     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14007 
14008     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14009       if (Var->getPointOfInstantiation().isInvalid()) {
14010         // This is a modification of an existing AST node. Notify listeners.
14011         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14012           L->StaticDataMemberInstantiated(Var);
14013       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14014         // Don't bother trying to instantiate it again, unless we might need
14015         // its initializer before we get to the end of the TU.
14016         TryInstantiating = false;
14017     }
14018 
14019     if (Var->getPointOfInstantiation().isInvalid())
14020       Var->setTemplateSpecializationKind(TSK, Loc);
14021 
14022     if (TryInstantiating) {
14023       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14024       bool InstantiationDependent = false;
14025       bool IsNonDependent =
14026           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14027                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14028                   : true;
14029 
14030       // Do not instantiate specializations that are still type-dependent.
14031       if (IsNonDependent) {
14032         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14033           // Do not defer instantiations of variables which could be used in a
14034           // constant expression.
14035           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14036         } else {
14037           SemaRef.PendingInstantiations
14038               .push_back(std::make_pair(Var, PointOfInstantiation));
14039         }
14040       }
14041     }
14042   }
14043 
14044   if (!MarkODRUsed)
14045     return;
14046 
14047   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14048   // the requirements for appearing in a constant expression (5.19) and, if
14049   // it is an object, the lvalue-to-rvalue conversion (4.1)
14050   // is immediately applied."  We check the first part here, and
14051   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14052   // Note that we use the C++11 definition everywhere because nothing in
14053   // C++03 depends on whether we get the C++03 version correct. The second
14054   // part does not apply to references, since they are not objects.
14055   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14056     // A reference initialized by a constant expression can never be
14057     // odr-used, so simply ignore it.
14058     if (!Var->getType()->isReferenceType())
14059       SemaRef.MaybeODRUseExprs.insert(E);
14060   } else
14061     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14062                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14063 }
14064 
14065 /// \brief Mark a variable referenced, and check whether it is odr-used
14066 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14067 /// used directly for normal expressions referring to VarDecl.
14068 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14069   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14070 }
14071 
14072 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14073                                Decl *D, Expr *E, bool MightBeOdrUse) {
14074   if (SemaRef.isInOpenMPDeclareTargetContext())
14075     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14076 
14077   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14078     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14079     return;
14080   }
14081 
14082   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14083 
14084   // If this is a call to a method via a cast, also mark the method in the
14085   // derived class used in case codegen can devirtualize the call.
14086   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14087   if (!ME)
14088     return;
14089   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14090   if (!MD)
14091     return;
14092   // Only attempt to devirtualize if this is truly a virtual call.
14093   bool IsVirtualCall = MD->isVirtual() &&
14094                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14095   if (!IsVirtualCall)
14096     return;
14097   const Expr *Base = ME->getBase();
14098   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14099   if (!MostDerivedClassDecl)
14100     return;
14101   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14102   if (!DM || DM->isPure())
14103     return;
14104   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14105 }
14106 
14107 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14108 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14109   // TODO: update this with DR# once a defect report is filed.
14110   // C++11 defect. The address of a pure member should not be an ODR use, even
14111   // if it's a qualified reference.
14112   bool OdrUse = true;
14113   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14114     if (Method->isVirtual())
14115       OdrUse = false;
14116   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14117 }
14118 
14119 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14120 void Sema::MarkMemberReferenced(MemberExpr *E) {
14121   // C++11 [basic.def.odr]p2:
14122   //   A non-overloaded function whose name appears as a potentially-evaluated
14123   //   expression or a member of a set of candidate functions, if selected by
14124   //   overload resolution when referred to from a potentially-evaluated
14125   //   expression, is odr-used, unless it is a pure virtual function and its
14126   //   name is not explicitly qualified.
14127   bool MightBeOdrUse = true;
14128   if (E->performsVirtualDispatch(getLangOpts())) {
14129     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14130       if (Method->isPure())
14131         MightBeOdrUse = false;
14132   }
14133   SourceLocation Loc = E->getMemberLoc().isValid() ?
14134                             E->getMemberLoc() : E->getLocStart();
14135   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14136 }
14137 
14138 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14139 /// marks the declaration referenced, and performs odr-use checking for
14140 /// functions and variables. This method should not be used when building a
14141 /// normal expression which refers to a variable.
14142 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14143                                  bool MightBeOdrUse) {
14144   if (MightBeOdrUse) {
14145     if (auto *VD = dyn_cast<VarDecl>(D)) {
14146       MarkVariableReferenced(Loc, VD);
14147       return;
14148     }
14149   }
14150   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14151     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14152     return;
14153   }
14154   D->setReferenced();
14155 }
14156 
14157 namespace {
14158   // Mark all of the declarations referenced
14159   // FIXME: Not fully implemented yet! We need to have a better understanding
14160   // of when we're entering
14161   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14162     Sema &S;
14163     SourceLocation Loc;
14164 
14165   public:
14166     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14167 
14168     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14169 
14170     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14171     bool TraverseRecordType(RecordType *T);
14172   };
14173 }
14174 
14175 bool MarkReferencedDecls::TraverseTemplateArgument(
14176     const TemplateArgument &Arg) {
14177   if (Arg.getKind() == TemplateArgument::Declaration) {
14178     if (Decl *D = Arg.getAsDecl())
14179       S.MarkAnyDeclReferenced(Loc, D, true);
14180   }
14181 
14182   return Inherited::TraverseTemplateArgument(Arg);
14183 }
14184 
14185 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14186   if (ClassTemplateSpecializationDecl *Spec
14187                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14188     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14189     return TraverseTemplateArguments(Args.data(), Args.size());
14190   }
14191 
14192   return true;
14193 }
14194 
14195 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14196   MarkReferencedDecls Marker(*this, Loc);
14197   Marker.TraverseType(Context.getCanonicalType(T));
14198 }
14199 
14200 namespace {
14201   /// \brief Helper class that marks all of the declarations referenced by
14202   /// potentially-evaluated subexpressions as "referenced".
14203   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14204     Sema &S;
14205     bool SkipLocalVariables;
14206 
14207   public:
14208     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14209 
14210     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14211       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14212 
14213     void VisitDeclRefExpr(DeclRefExpr *E) {
14214       // If we were asked not to visit local variables, don't.
14215       if (SkipLocalVariables) {
14216         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14217           if (VD->hasLocalStorage())
14218             return;
14219       }
14220 
14221       S.MarkDeclRefReferenced(E);
14222     }
14223 
14224     void VisitMemberExpr(MemberExpr *E) {
14225       S.MarkMemberReferenced(E);
14226       Inherited::VisitMemberExpr(E);
14227     }
14228 
14229     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14230       S.MarkFunctionReferenced(E->getLocStart(),
14231             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14232       Visit(E->getSubExpr());
14233     }
14234 
14235     void VisitCXXNewExpr(CXXNewExpr *E) {
14236       if (E->getOperatorNew())
14237         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14238       if (E->getOperatorDelete())
14239         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14240       Inherited::VisitCXXNewExpr(E);
14241     }
14242 
14243     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14244       if (E->getOperatorDelete())
14245         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14246       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14247       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14248         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14249         S.MarkFunctionReferenced(E->getLocStart(),
14250                                     S.LookupDestructor(Record));
14251       }
14252 
14253       Inherited::VisitCXXDeleteExpr(E);
14254     }
14255 
14256     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14257       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14258       Inherited::VisitCXXConstructExpr(E);
14259     }
14260 
14261     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14262       Visit(E->getExpr());
14263     }
14264 
14265     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14266       Inherited::VisitImplicitCastExpr(E);
14267 
14268       if (E->getCastKind() == CK_LValueToRValue)
14269         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14270     }
14271   };
14272 }
14273 
14274 /// \brief Mark any declarations that appear within this expression or any
14275 /// potentially-evaluated subexpressions as "referenced".
14276 ///
14277 /// \param SkipLocalVariables If true, don't mark local variables as
14278 /// 'referenced'.
14279 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14280                                             bool SkipLocalVariables) {
14281   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14282 }
14283 
14284 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14285 /// of the program being compiled.
14286 ///
14287 /// This routine emits the given diagnostic when the code currently being
14288 /// type-checked is "potentially evaluated", meaning that there is a
14289 /// possibility that the code will actually be executable. Code in sizeof()
14290 /// expressions, code used only during overload resolution, etc., are not
14291 /// potentially evaluated. This routine will suppress such diagnostics or,
14292 /// in the absolutely nutty case of potentially potentially evaluated
14293 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14294 /// later.
14295 ///
14296 /// This routine should be used for all diagnostics that describe the run-time
14297 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14298 /// Failure to do so will likely result in spurious diagnostics or failures
14299 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14300 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14301                                const PartialDiagnostic &PD) {
14302   switch (ExprEvalContexts.back().Context) {
14303   case Unevaluated:
14304   case UnevaluatedAbstract:
14305   case DiscardedStatement:
14306     // The argument will never be evaluated, so don't complain.
14307     break;
14308 
14309   case ConstantEvaluated:
14310     // Relevant diagnostics should be produced by constant evaluation.
14311     break;
14312 
14313   case PotentiallyEvaluated:
14314   case PotentiallyEvaluatedIfUsed:
14315     if (Statement && getCurFunctionOrMethodDecl()) {
14316       FunctionScopes.back()->PossiblyUnreachableDiags.
14317         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14318     }
14319     else
14320       Diag(Loc, PD);
14321 
14322     return true;
14323   }
14324 
14325   return false;
14326 }
14327 
14328 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14329                                CallExpr *CE, FunctionDecl *FD) {
14330   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14331     return false;
14332 
14333   // If we're inside a decltype's expression, don't check for a valid return
14334   // type or construct temporaries until we know whether this is the last call.
14335   if (ExprEvalContexts.back().IsDecltype) {
14336     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14337     return false;
14338   }
14339 
14340   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14341     FunctionDecl *FD;
14342     CallExpr *CE;
14343 
14344   public:
14345     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14346       : FD(FD), CE(CE) { }
14347 
14348     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14349       if (!FD) {
14350         S.Diag(Loc, diag::err_call_incomplete_return)
14351           << T << CE->getSourceRange();
14352         return;
14353       }
14354 
14355       S.Diag(Loc, diag::err_call_function_incomplete_return)
14356         << CE->getSourceRange() << FD->getDeclName() << T;
14357       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14358           << FD->getDeclName();
14359     }
14360   } Diagnoser(FD, CE);
14361 
14362   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14363     return true;
14364 
14365   return false;
14366 }
14367 
14368 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14369 // will prevent this condition from triggering, which is what we want.
14370 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14371   SourceLocation Loc;
14372 
14373   unsigned diagnostic = diag::warn_condition_is_assignment;
14374   bool IsOrAssign = false;
14375 
14376   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14377     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14378       return;
14379 
14380     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14381 
14382     // Greylist some idioms by putting them into a warning subcategory.
14383     if (ObjCMessageExpr *ME
14384           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14385       Selector Sel = ME->getSelector();
14386 
14387       // self = [<foo> init...]
14388       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14389         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14390 
14391       // <foo> = [<bar> nextObject]
14392       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14393         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14394     }
14395 
14396     Loc = Op->getOperatorLoc();
14397   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14398     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14399       return;
14400 
14401     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14402     Loc = Op->getOperatorLoc();
14403   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14404     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14405   else {
14406     // Not an assignment.
14407     return;
14408   }
14409 
14410   Diag(Loc, diagnostic) << E->getSourceRange();
14411 
14412   SourceLocation Open = E->getLocStart();
14413   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14414   Diag(Loc, diag::note_condition_assign_silence)
14415         << FixItHint::CreateInsertion(Open, "(")
14416         << FixItHint::CreateInsertion(Close, ")");
14417 
14418   if (IsOrAssign)
14419     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14420       << FixItHint::CreateReplacement(Loc, "!=");
14421   else
14422     Diag(Loc, diag::note_condition_assign_to_comparison)
14423       << FixItHint::CreateReplacement(Loc, "==");
14424 }
14425 
14426 /// \brief Redundant parentheses over an equality comparison can indicate
14427 /// that the user intended an assignment used as condition.
14428 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14429   // Don't warn if the parens came from a macro.
14430   SourceLocation parenLoc = ParenE->getLocStart();
14431   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14432     return;
14433   // Don't warn for dependent expressions.
14434   if (ParenE->isTypeDependent())
14435     return;
14436 
14437   Expr *E = ParenE->IgnoreParens();
14438 
14439   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14440     if (opE->getOpcode() == BO_EQ &&
14441         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14442                                                            == Expr::MLV_Valid) {
14443       SourceLocation Loc = opE->getOperatorLoc();
14444 
14445       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14446       SourceRange ParenERange = ParenE->getSourceRange();
14447       Diag(Loc, diag::note_equality_comparison_silence)
14448         << FixItHint::CreateRemoval(ParenERange.getBegin())
14449         << FixItHint::CreateRemoval(ParenERange.getEnd());
14450       Diag(Loc, diag::note_equality_comparison_to_assign)
14451         << FixItHint::CreateReplacement(Loc, "=");
14452     }
14453 }
14454 
14455 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14456                                        bool IsConstexpr) {
14457   DiagnoseAssignmentAsCondition(E);
14458   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14459     DiagnoseEqualityWithExtraParens(parenE);
14460 
14461   ExprResult result = CheckPlaceholderExpr(E);
14462   if (result.isInvalid()) return ExprError();
14463   E = result.get();
14464 
14465   if (!E->isTypeDependent()) {
14466     if (getLangOpts().CPlusPlus)
14467       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14468 
14469     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14470     if (ERes.isInvalid())
14471       return ExprError();
14472     E = ERes.get();
14473 
14474     QualType T = E->getType();
14475     if (!T->isScalarType()) { // C99 6.8.4.1p1
14476       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14477         << T << E->getSourceRange();
14478       return ExprError();
14479     }
14480     CheckBoolLikeConversion(E, Loc);
14481   }
14482 
14483   return E;
14484 }
14485 
14486 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14487                                            Expr *SubExpr, ConditionKind CK) {
14488   // Empty conditions are valid in for-statements.
14489   if (!SubExpr)
14490     return ConditionResult();
14491 
14492   ExprResult Cond;
14493   switch (CK) {
14494   case ConditionKind::Boolean:
14495     Cond = CheckBooleanCondition(Loc, SubExpr);
14496     break;
14497 
14498   case ConditionKind::ConstexprIf:
14499     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14500     break;
14501 
14502   case ConditionKind::Switch:
14503     Cond = CheckSwitchCondition(Loc, SubExpr);
14504     break;
14505   }
14506   if (Cond.isInvalid())
14507     return ConditionError();
14508 
14509   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14510   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14511   if (!FullExpr.get())
14512     return ConditionError();
14513 
14514   return ConditionResult(*this, nullptr, FullExpr,
14515                          CK == ConditionKind::ConstexprIf);
14516 }
14517 
14518 namespace {
14519   /// A visitor for rebuilding a call to an __unknown_any expression
14520   /// to have an appropriate type.
14521   struct RebuildUnknownAnyFunction
14522     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14523 
14524     Sema &S;
14525 
14526     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14527 
14528     ExprResult VisitStmt(Stmt *S) {
14529       llvm_unreachable("unexpected statement!");
14530     }
14531 
14532     ExprResult VisitExpr(Expr *E) {
14533       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14534         << E->getSourceRange();
14535       return ExprError();
14536     }
14537 
14538     /// Rebuild an expression which simply semantically wraps another
14539     /// expression which it shares the type and value kind of.
14540     template <class T> ExprResult rebuildSugarExpr(T *E) {
14541       ExprResult SubResult = Visit(E->getSubExpr());
14542       if (SubResult.isInvalid()) return ExprError();
14543 
14544       Expr *SubExpr = SubResult.get();
14545       E->setSubExpr(SubExpr);
14546       E->setType(SubExpr->getType());
14547       E->setValueKind(SubExpr->getValueKind());
14548       assert(E->getObjectKind() == OK_Ordinary);
14549       return E;
14550     }
14551 
14552     ExprResult VisitParenExpr(ParenExpr *E) {
14553       return rebuildSugarExpr(E);
14554     }
14555 
14556     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14557       return rebuildSugarExpr(E);
14558     }
14559 
14560     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14561       ExprResult SubResult = Visit(E->getSubExpr());
14562       if (SubResult.isInvalid()) return ExprError();
14563 
14564       Expr *SubExpr = SubResult.get();
14565       E->setSubExpr(SubExpr);
14566       E->setType(S.Context.getPointerType(SubExpr->getType()));
14567       assert(E->getValueKind() == VK_RValue);
14568       assert(E->getObjectKind() == OK_Ordinary);
14569       return E;
14570     }
14571 
14572     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14573       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14574 
14575       E->setType(VD->getType());
14576 
14577       assert(E->getValueKind() == VK_RValue);
14578       if (S.getLangOpts().CPlusPlus &&
14579           !(isa<CXXMethodDecl>(VD) &&
14580             cast<CXXMethodDecl>(VD)->isInstance()))
14581         E->setValueKind(VK_LValue);
14582 
14583       return E;
14584     }
14585 
14586     ExprResult VisitMemberExpr(MemberExpr *E) {
14587       return resolveDecl(E, E->getMemberDecl());
14588     }
14589 
14590     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14591       return resolveDecl(E, E->getDecl());
14592     }
14593   };
14594 }
14595 
14596 /// Given a function expression of unknown-any type, try to rebuild it
14597 /// to have a function type.
14598 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14599   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14600   if (Result.isInvalid()) return ExprError();
14601   return S.DefaultFunctionArrayConversion(Result.get());
14602 }
14603 
14604 namespace {
14605   /// A visitor for rebuilding an expression of type __unknown_anytype
14606   /// into one which resolves the type directly on the referring
14607   /// expression.  Strict preservation of the original source
14608   /// structure is not a goal.
14609   struct RebuildUnknownAnyExpr
14610     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14611 
14612     Sema &S;
14613 
14614     /// The current destination type.
14615     QualType DestType;
14616 
14617     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14618       : S(S), DestType(CastType) {}
14619 
14620     ExprResult VisitStmt(Stmt *S) {
14621       llvm_unreachable("unexpected statement!");
14622     }
14623 
14624     ExprResult VisitExpr(Expr *E) {
14625       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14626         << E->getSourceRange();
14627       return ExprError();
14628     }
14629 
14630     ExprResult VisitCallExpr(CallExpr *E);
14631     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14632 
14633     /// Rebuild an expression which simply semantically wraps another
14634     /// expression which it shares the type and value kind of.
14635     template <class T> ExprResult rebuildSugarExpr(T *E) {
14636       ExprResult SubResult = Visit(E->getSubExpr());
14637       if (SubResult.isInvalid()) return ExprError();
14638       Expr *SubExpr = SubResult.get();
14639       E->setSubExpr(SubExpr);
14640       E->setType(SubExpr->getType());
14641       E->setValueKind(SubExpr->getValueKind());
14642       assert(E->getObjectKind() == OK_Ordinary);
14643       return E;
14644     }
14645 
14646     ExprResult VisitParenExpr(ParenExpr *E) {
14647       return rebuildSugarExpr(E);
14648     }
14649 
14650     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14651       return rebuildSugarExpr(E);
14652     }
14653 
14654     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14655       const PointerType *Ptr = DestType->getAs<PointerType>();
14656       if (!Ptr) {
14657         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14658           << E->getSourceRange();
14659         return ExprError();
14660       }
14661       assert(E->getValueKind() == VK_RValue);
14662       assert(E->getObjectKind() == OK_Ordinary);
14663       E->setType(DestType);
14664 
14665       // Build the sub-expression as if it were an object of the pointee type.
14666       DestType = Ptr->getPointeeType();
14667       ExprResult SubResult = Visit(E->getSubExpr());
14668       if (SubResult.isInvalid()) return ExprError();
14669       E->setSubExpr(SubResult.get());
14670       return E;
14671     }
14672 
14673     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14674 
14675     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14676 
14677     ExprResult VisitMemberExpr(MemberExpr *E) {
14678       return resolveDecl(E, E->getMemberDecl());
14679     }
14680 
14681     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14682       return resolveDecl(E, E->getDecl());
14683     }
14684   };
14685 }
14686 
14687 /// Rebuilds a call expression which yielded __unknown_anytype.
14688 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14689   Expr *CalleeExpr = E->getCallee();
14690 
14691   enum FnKind {
14692     FK_MemberFunction,
14693     FK_FunctionPointer,
14694     FK_BlockPointer
14695   };
14696 
14697   FnKind Kind;
14698   QualType CalleeType = CalleeExpr->getType();
14699   if (CalleeType == S.Context.BoundMemberTy) {
14700     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14701     Kind = FK_MemberFunction;
14702     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14703   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14704     CalleeType = Ptr->getPointeeType();
14705     Kind = FK_FunctionPointer;
14706   } else {
14707     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14708     Kind = FK_BlockPointer;
14709   }
14710   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14711 
14712   // Verify that this is a legal result type of a function.
14713   if (DestType->isArrayType() || DestType->isFunctionType()) {
14714     unsigned diagID = diag::err_func_returning_array_function;
14715     if (Kind == FK_BlockPointer)
14716       diagID = diag::err_block_returning_array_function;
14717 
14718     S.Diag(E->getExprLoc(), diagID)
14719       << DestType->isFunctionType() << DestType;
14720     return ExprError();
14721   }
14722 
14723   // Otherwise, go ahead and set DestType as the call's result.
14724   E->setType(DestType.getNonLValueExprType(S.Context));
14725   E->setValueKind(Expr::getValueKindForType(DestType));
14726   assert(E->getObjectKind() == OK_Ordinary);
14727 
14728   // Rebuild the function type, replacing the result type with DestType.
14729   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14730   if (Proto) {
14731     // __unknown_anytype(...) is a special case used by the debugger when
14732     // it has no idea what a function's signature is.
14733     //
14734     // We want to build this call essentially under the K&R
14735     // unprototyped rules, but making a FunctionNoProtoType in C++
14736     // would foul up all sorts of assumptions.  However, we cannot
14737     // simply pass all arguments as variadic arguments, nor can we
14738     // portably just call the function under a non-variadic type; see
14739     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14740     // However, it turns out that in practice it is generally safe to
14741     // call a function declared as "A foo(B,C,D);" under the prototype
14742     // "A foo(B,C,D,...);".  The only known exception is with the
14743     // Windows ABI, where any variadic function is implicitly cdecl
14744     // regardless of its normal CC.  Therefore we change the parameter
14745     // types to match the types of the arguments.
14746     //
14747     // This is a hack, but it is far superior to moving the
14748     // corresponding target-specific code from IR-gen to Sema/AST.
14749 
14750     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14751     SmallVector<QualType, 8> ArgTypes;
14752     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14753       ArgTypes.reserve(E->getNumArgs());
14754       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14755         Expr *Arg = E->getArg(i);
14756         QualType ArgType = Arg->getType();
14757         if (E->isLValue()) {
14758           ArgType = S.Context.getLValueReferenceType(ArgType);
14759         } else if (E->isXValue()) {
14760           ArgType = S.Context.getRValueReferenceType(ArgType);
14761         }
14762         ArgTypes.push_back(ArgType);
14763       }
14764       ParamTypes = ArgTypes;
14765     }
14766     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14767                                          Proto->getExtProtoInfo());
14768   } else {
14769     DestType = S.Context.getFunctionNoProtoType(DestType,
14770                                                 FnType->getExtInfo());
14771   }
14772 
14773   // Rebuild the appropriate pointer-to-function type.
14774   switch (Kind) {
14775   case FK_MemberFunction:
14776     // Nothing to do.
14777     break;
14778 
14779   case FK_FunctionPointer:
14780     DestType = S.Context.getPointerType(DestType);
14781     break;
14782 
14783   case FK_BlockPointer:
14784     DestType = S.Context.getBlockPointerType(DestType);
14785     break;
14786   }
14787 
14788   // Finally, we can recurse.
14789   ExprResult CalleeResult = Visit(CalleeExpr);
14790   if (!CalleeResult.isUsable()) return ExprError();
14791   E->setCallee(CalleeResult.get());
14792 
14793   // Bind a temporary if necessary.
14794   return S.MaybeBindToTemporary(E);
14795 }
14796 
14797 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14798   // Verify that this is a legal result type of a call.
14799   if (DestType->isArrayType() || DestType->isFunctionType()) {
14800     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14801       << DestType->isFunctionType() << DestType;
14802     return ExprError();
14803   }
14804 
14805   // Rewrite the method result type if available.
14806   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14807     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14808     Method->setReturnType(DestType);
14809   }
14810 
14811   // Change the type of the message.
14812   E->setType(DestType.getNonReferenceType());
14813   E->setValueKind(Expr::getValueKindForType(DestType));
14814 
14815   return S.MaybeBindToTemporary(E);
14816 }
14817 
14818 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14819   // The only case we should ever see here is a function-to-pointer decay.
14820   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14821     assert(E->getValueKind() == VK_RValue);
14822     assert(E->getObjectKind() == OK_Ordinary);
14823 
14824     E->setType(DestType);
14825 
14826     // Rebuild the sub-expression as the pointee (function) type.
14827     DestType = DestType->castAs<PointerType>()->getPointeeType();
14828 
14829     ExprResult Result = Visit(E->getSubExpr());
14830     if (!Result.isUsable()) return ExprError();
14831 
14832     E->setSubExpr(Result.get());
14833     return E;
14834   } else if (E->getCastKind() == CK_LValueToRValue) {
14835     assert(E->getValueKind() == VK_RValue);
14836     assert(E->getObjectKind() == OK_Ordinary);
14837 
14838     assert(isa<BlockPointerType>(E->getType()));
14839 
14840     E->setType(DestType);
14841 
14842     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14843     DestType = S.Context.getLValueReferenceType(DestType);
14844 
14845     ExprResult Result = Visit(E->getSubExpr());
14846     if (!Result.isUsable()) return ExprError();
14847 
14848     E->setSubExpr(Result.get());
14849     return E;
14850   } else {
14851     llvm_unreachable("Unhandled cast type!");
14852   }
14853 }
14854 
14855 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14856   ExprValueKind ValueKind = VK_LValue;
14857   QualType Type = DestType;
14858 
14859   // We know how to make this work for certain kinds of decls:
14860 
14861   //  - functions
14862   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14863     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14864       DestType = Ptr->getPointeeType();
14865       ExprResult Result = resolveDecl(E, VD);
14866       if (Result.isInvalid()) return ExprError();
14867       return S.ImpCastExprToType(Result.get(), Type,
14868                                  CK_FunctionToPointerDecay, VK_RValue);
14869     }
14870 
14871     if (!Type->isFunctionType()) {
14872       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14873         << VD << E->getSourceRange();
14874       return ExprError();
14875     }
14876     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14877       // We must match the FunctionDecl's type to the hack introduced in
14878       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14879       // type. See the lengthy commentary in that routine.
14880       QualType FDT = FD->getType();
14881       const FunctionType *FnType = FDT->castAs<FunctionType>();
14882       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14883       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14884       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14885         SourceLocation Loc = FD->getLocation();
14886         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14887                                       FD->getDeclContext(),
14888                                       Loc, Loc, FD->getNameInfo().getName(),
14889                                       DestType, FD->getTypeSourceInfo(),
14890                                       SC_None, false/*isInlineSpecified*/,
14891                                       FD->hasPrototype(),
14892                                       false/*isConstexprSpecified*/);
14893 
14894         if (FD->getQualifier())
14895           NewFD->setQualifierInfo(FD->getQualifierLoc());
14896 
14897         SmallVector<ParmVarDecl*, 16> Params;
14898         for (const auto &AI : FT->param_types()) {
14899           ParmVarDecl *Param =
14900             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14901           Param->setScopeInfo(0, Params.size());
14902           Params.push_back(Param);
14903         }
14904         NewFD->setParams(Params);
14905         DRE->setDecl(NewFD);
14906         VD = DRE->getDecl();
14907       }
14908     }
14909 
14910     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14911       if (MD->isInstance()) {
14912         ValueKind = VK_RValue;
14913         Type = S.Context.BoundMemberTy;
14914       }
14915 
14916     // Function references aren't l-values in C.
14917     if (!S.getLangOpts().CPlusPlus)
14918       ValueKind = VK_RValue;
14919 
14920   //  - variables
14921   } else if (isa<VarDecl>(VD)) {
14922     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14923       Type = RefTy->getPointeeType();
14924     } else if (Type->isFunctionType()) {
14925       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14926         << VD << E->getSourceRange();
14927       return ExprError();
14928     }
14929 
14930   //  - nothing else
14931   } else {
14932     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14933       << VD << E->getSourceRange();
14934     return ExprError();
14935   }
14936 
14937   // Modifying the declaration like this is friendly to IR-gen but
14938   // also really dangerous.
14939   VD->setType(DestType);
14940   E->setType(Type);
14941   E->setValueKind(ValueKind);
14942   return E;
14943 }
14944 
14945 /// Check a cast of an unknown-any type.  We intentionally only
14946 /// trigger this for C-style casts.
14947 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14948                                      Expr *CastExpr, CastKind &CastKind,
14949                                      ExprValueKind &VK, CXXCastPath &Path) {
14950   // The type we're casting to must be either void or complete.
14951   if (!CastType->isVoidType() &&
14952       RequireCompleteType(TypeRange.getBegin(), CastType,
14953                           diag::err_typecheck_cast_to_incomplete))
14954     return ExprError();
14955 
14956   // Rewrite the casted expression from scratch.
14957   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14958   if (!result.isUsable()) return ExprError();
14959 
14960   CastExpr = result.get();
14961   VK = CastExpr->getValueKind();
14962   CastKind = CK_NoOp;
14963 
14964   return CastExpr;
14965 }
14966 
14967 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14968   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14969 }
14970 
14971 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14972                                     Expr *arg, QualType &paramType) {
14973   // If the syntactic form of the argument is not an explicit cast of
14974   // any sort, just do default argument promotion.
14975   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14976   if (!castArg) {
14977     ExprResult result = DefaultArgumentPromotion(arg);
14978     if (result.isInvalid()) return ExprError();
14979     paramType = result.get()->getType();
14980     return result;
14981   }
14982 
14983   // Otherwise, use the type that was written in the explicit cast.
14984   assert(!arg->hasPlaceholderType());
14985   paramType = castArg->getTypeAsWritten();
14986 
14987   // Copy-initialize a parameter of that type.
14988   InitializedEntity entity =
14989     InitializedEntity::InitializeParameter(Context, paramType,
14990                                            /*consumed*/ false);
14991   return PerformCopyInitialization(entity, callLoc, arg);
14992 }
14993 
14994 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14995   Expr *orig = E;
14996   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14997   while (true) {
14998     E = E->IgnoreParenImpCasts();
14999     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15000       E = call->getCallee();
15001       diagID = diag::err_uncasted_call_of_unknown_any;
15002     } else {
15003       break;
15004     }
15005   }
15006 
15007   SourceLocation loc;
15008   NamedDecl *d;
15009   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15010     loc = ref->getLocation();
15011     d = ref->getDecl();
15012   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15013     loc = mem->getMemberLoc();
15014     d = mem->getMemberDecl();
15015   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15016     diagID = diag::err_uncasted_call_of_unknown_any;
15017     loc = msg->getSelectorStartLoc();
15018     d = msg->getMethodDecl();
15019     if (!d) {
15020       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15021         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15022         << orig->getSourceRange();
15023       return ExprError();
15024     }
15025   } else {
15026     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15027       << E->getSourceRange();
15028     return ExprError();
15029   }
15030 
15031   S.Diag(loc, diagID) << d << orig->getSourceRange();
15032 
15033   // Never recoverable.
15034   return ExprError();
15035 }
15036 
15037 /// Check for operands with placeholder types and complain if found.
15038 /// Returns true if there was an error and no recovery was possible.
15039 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15040   if (!getLangOpts().CPlusPlus) {
15041     // C cannot handle TypoExpr nodes on either side of a binop because it
15042     // doesn't handle dependent types properly, so make sure any TypoExprs have
15043     // been dealt with before checking the operands.
15044     ExprResult Result = CorrectDelayedTyposInExpr(E);
15045     if (!Result.isUsable()) return ExprError();
15046     E = Result.get();
15047   }
15048 
15049   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15050   if (!placeholderType) return E;
15051 
15052   switch (placeholderType->getKind()) {
15053 
15054   // Overloaded expressions.
15055   case BuiltinType::Overload: {
15056     // Try to resolve a single function template specialization.
15057     // This is obligatory.
15058     ExprResult Result = E;
15059     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15060       return Result;
15061 
15062     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15063     // leaves Result unchanged on failure.
15064     Result = E;
15065     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15066       return Result;
15067 
15068     // If that failed, try to recover with a call.
15069     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15070                          /*complain*/ true);
15071     return Result;
15072   }
15073 
15074   // Bound member functions.
15075   case BuiltinType::BoundMember: {
15076     ExprResult result = E;
15077     const Expr *BME = E->IgnoreParens();
15078     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15079     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15080     if (isa<CXXPseudoDestructorExpr>(BME)) {
15081       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15082     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15083       if (ME->getMemberNameInfo().getName().getNameKind() ==
15084           DeclarationName::CXXDestructorName)
15085         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15086     }
15087     tryToRecoverWithCall(result, PD,
15088                          /*complain*/ true);
15089     return result;
15090   }
15091 
15092   // ARC unbridged casts.
15093   case BuiltinType::ARCUnbridgedCast: {
15094     Expr *realCast = stripARCUnbridgedCast(E);
15095     diagnoseARCUnbridgedCast(realCast);
15096     return realCast;
15097   }
15098 
15099   // Expressions of unknown type.
15100   case BuiltinType::UnknownAny:
15101     return diagnoseUnknownAnyExpr(*this, E);
15102 
15103   // Pseudo-objects.
15104   case BuiltinType::PseudoObject:
15105     return checkPseudoObjectRValue(E);
15106 
15107   case BuiltinType::BuiltinFn: {
15108     // Accept __noop without parens by implicitly converting it to a call expr.
15109     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15110     if (DRE) {
15111       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15112       if (FD->getBuiltinID() == Builtin::BI__noop) {
15113         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15114                               CK_BuiltinFnToFnPtr).get();
15115         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15116                                       VK_RValue, SourceLocation());
15117       }
15118     }
15119 
15120     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15121     return ExprError();
15122   }
15123 
15124   // Expressions of unknown type.
15125   case BuiltinType::OMPArraySection:
15126     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15127     return ExprError();
15128 
15129   // Everything else should be impossible.
15130 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15131   case BuiltinType::Id:
15132 #include "clang/Basic/OpenCLImageTypes.def"
15133 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15134 #define PLACEHOLDER_TYPE(Id, SingletonId)
15135 #include "clang/AST/BuiltinTypes.def"
15136     break;
15137   }
15138 
15139   llvm_unreachable("invalid placeholder type!");
15140 }
15141 
15142 bool Sema::CheckCaseExpression(Expr *E) {
15143   if (E->isTypeDependent())
15144     return true;
15145   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15146     return E->getType()->isIntegralOrEnumerationType();
15147   return false;
15148 }
15149 
15150 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15151 ExprResult
15152 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15153   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15154          "Unknown Objective-C Boolean value!");
15155   QualType BoolT = Context.ObjCBuiltinBoolTy;
15156   if (!Context.getBOOLDecl()) {
15157     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15158                         Sema::LookupOrdinaryName);
15159     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15160       NamedDecl *ND = Result.getFoundDecl();
15161       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15162         Context.setBOOLDecl(TD);
15163     }
15164   }
15165   if (Context.getBOOLDecl())
15166     BoolT = Context.getBOOLType();
15167   return new (Context)
15168       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15169 }
15170 
15171 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15172     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15173     SourceLocation RParen) {
15174 
15175   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15176 
15177   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15178                            [&](const AvailabilitySpec &Spec) {
15179                              return Spec.getPlatform() == Platform;
15180                            });
15181 
15182   VersionTuple Version;
15183   if (Spec != AvailSpecs.end())
15184     Version = Spec->getVersion();
15185   else
15186     // This is the '*' case in @available. We should diagnose this; the
15187     // programmer should explicitly account for this case if they target this
15188     // platform.
15189     Diag(AtLoc, diag::warn_available_using_star_case) << RParen << Platform;
15190 
15191   return new (Context)
15192       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15193 }
15194