1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97 
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105 
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message);
109 
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message);
117         continue;
118       }
119     }
120     break;
121   }
122 
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message);
128     }
129   }
130 
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message);
136     }
137 
138   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142 
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158 
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161 
162   return Result;
163 }
164 
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173 
174     if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
175       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
176       return;
177     }
178 
179     const ObjCPropertyDecl *ObjCPDecl = nullptr;
180     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183         if (PDeclResult == Result)
184           ObjCPDecl = PD;
185       }
186     }
187 
188     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189                               ObjCPDecl, ObjCPropertyAccess);
190   }
191 }
192 
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195   assert(Decl->isDeleted());
196 
197   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
198 
199   if (Method && Method->isDeleted() && Method->isDefaulted()) {
200     // If the method was explicitly defaulted, point at that declaration.
201     if (!Method->isImplicit())
202       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
203 
204     // Try to diagnose why this special member function was implicitly
205     // deleted. This might fail, if that reason no longer applies.
206     CXXSpecialMember CSM = getSpecialMember(Method);
207     if (CSM != CXXInvalid)
208       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
209 
210     return;
211   }
212 
213   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214   if (Ctor && Ctor->isInheritingConstructor())
215     return NoteDeletedInheritingConstructor(Ctor);
216 
217   Diag(Decl->getLocation(), diag::note_availability_specified_here)
218     << Decl << true;
219 }
220 
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224   for (auto I : D->redecls()) {
225     if (I->getStorageClass() != SC_None)
226       return true;
227   }
228   return false;
229 }
230 
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
233 ///
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
240                                                       const NamedDecl *D,
241                                                       SourceLocation Loc) {
242   // This is disabled under C++; there are too many ways for this to fire in
243   // contexts where the warning is a false positive, or where it is technically
244   // correct but benign.
245   if (S.getLangOpts().CPlusPlus)
246     return;
247 
248   // Check if this is an inlined function or method.
249   FunctionDecl *Current = S.getCurFunctionDecl();
250   if (!Current)
251     return;
252   if (!Current->isInlined())
253     return;
254   if (!Current->isExternallyVisible())
255     return;
256 
257   // Check if the decl has internal linkage.
258   if (D->getFormalLinkage() != InternalLinkage)
259     return;
260 
261   // Downgrade from ExtWarn to Extension if
262   //  (1) the supposedly external inline function is in the main file,
263   //      and probably won't be included anywhere else.
264   //  (2) the thing we're referencing is a pure function.
265   //  (3) the thing we're referencing is another inline function.
266   // This last can give us false negatives, but it's better than warning on
267   // wrappers for simple C library functions.
268   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270   if (!DowngradeWarning && UsedFn)
271     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
272 
273   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274                                : diag::ext_internal_in_extern_inline)
275     << /*IsVar=*/!UsedFn << D;
276 
277   S.MaybeSuggestAddingStaticToDecl(Current);
278 
279   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
280       << D;
281 }
282 
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284   const FunctionDecl *First = Cur->getFirstDecl();
285 
286   // Suggest "static" on the function, if possible.
287   if (!hasAnyExplicitStorageClass(First)) {
288     SourceLocation DeclBegin = First->getSourceRange().getBegin();
289     Diag(DeclBegin, diag::note_convert_inline_to_static)
290       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
291   }
292 }
293 
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
296 ///
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
302 ///
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
305 ///
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307                              const ObjCInterfaceDecl *UnknownObjCClass,
308                              bool ObjCPropertyAccess) {
309   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310     // If there were any diagnostics suppressed by template argument deduction,
311     // emit them now.
312     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313     if (Pos != SuppressedDiagnostics.end()) {
314       for (const PartialDiagnosticAt &Suppressed : Pos->second)
315         Diag(Suppressed.first, Suppressed.second);
316 
317       // Clear out the list of suppressed diagnostics, so that we don't emit
318       // them again for this specialization. However, we don't obsolete this
319       // entry from the table, because we want to avoid ever emitting these
320       // diagnostics again.
321       Pos->second.clear();
322     }
323 
324     // C++ [basic.start.main]p3:
325     //   The function 'main' shall not be used within a program.
326     if (cast<FunctionDecl>(D)->isMain())
327       Diag(Loc, diag::ext_main_used);
328   }
329 
330   // See if this is an auto-typed variable whose initializer we are parsing.
331   if (ParsingInitForAutoVars.count(D)) {
332     if (isa<BindingDecl>(D)) {
333       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
334         << D->getDeclName();
335     } else {
336       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
337 
338       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339         << D->getDeclName() << (unsigned)AT->getKeyword();
340     }
341     return true;
342   }
343 
344   // See if this is a deleted function.
345   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346     if (FD->isDeleted()) {
347       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
348       if (Ctor && Ctor->isInheritingConstructor())
349         Diag(Loc, diag::err_deleted_inherited_ctor_use)
350             << Ctor->getParent()
351             << Ctor->getInheritedConstructor().getConstructor()->getParent();
352       else
353         Diag(Loc, diag::err_deleted_function_use);
354       NoteDeletedFunction(FD);
355       return true;
356     }
357 
358     // If the function has a deduced return type, and we can't deduce it,
359     // then we can't use it either.
360     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
361         DeduceReturnType(FD, Loc))
362       return true;
363 
364     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
365       return true;
366   }
367 
368   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
369   // Only the variables omp_in and omp_out are allowed in the combiner.
370   // Only the variables omp_priv and omp_orig are allowed in the
371   // initializer-clause.
372   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
373   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
374       isa<VarDecl>(D)) {
375     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
376         << getCurFunction()->HasOMPDeclareReductionCombiner;
377     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
378     return true;
379   }
380   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
381                              ObjCPropertyAccess);
382 
383   DiagnoseUnusedOfDecl(*this, D, Loc);
384 
385   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
386 
387   return false;
388 }
389 
390 /// \brief Retrieve the message suffix that should be added to a
391 /// diagnostic complaining about the given function being deleted or
392 /// unavailable.
393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
394   std::string Message;
395   if (FD->getAvailability(&Message))
396     return ": " + Message;
397 
398   return std::string();
399 }
400 
401 /// DiagnoseSentinelCalls - This routine checks whether a call or
402 /// message-send is to a declaration with the sentinel attribute, and
403 /// if so, it checks that the requirements of the sentinel are
404 /// satisfied.
405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
406                                  ArrayRef<Expr *> Args) {
407   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
408   if (!attr)
409     return;
410 
411   // The number of formal parameters of the declaration.
412   unsigned numFormalParams;
413 
414   // The kind of declaration.  This is also an index into a %select in
415   // the diagnostic.
416   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417 
418   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
419     numFormalParams = MD->param_size();
420     calleeType = CT_Method;
421   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422     numFormalParams = FD->param_size();
423     calleeType = CT_Function;
424   } else if (isa<VarDecl>(D)) {
425     QualType type = cast<ValueDecl>(D)->getType();
426     const FunctionType *fn = nullptr;
427     if (const PointerType *ptr = type->getAs<PointerType>()) {
428       fn = ptr->getPointeeType()->getAs<FunctionType>();
429       if (!fn) return;
430       calleeType = CT_Function;
431     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432       fn = ptr->getPointeeType()->castAs<FunctionType>();
433       calleeType = CT_Block;
434     } else {
435       return;
436     }
437 
438     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
439       numFormalParams = proto->getNumParams();
440     } else {
441       numFormalParams = 0;
442     }
443   } else {
444     return;
445   }
446 
447   // "nullPos" is the number of formal parameters at the end which
448   // effectively count as part of the variadic arguments.  This is
449   // useful if you would prefer to not have *any* formal parameters,
450   // but the language forces you to have at least one.
451   unsigned nullPos = attr->getNullPos();
452   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
453   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454 
455   // The number of arguments which should follow the sentinel.
456   unsigned numArgsAfterSentinel = attr->getSentinel();
457 
458   // If there aren't enough arguments for all the formal parameters,
459   // the sentinel, and the args after the sentinel, complain.
460   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
461     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
463     return;
464   }
465 
466   // Otherwise, find the sentinel expression.
467   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
468   if (!sentinelExpr) return;
469   if (sentinelExpr->isValueDependent()) return;
470   if (Context.isSentinelNullExpr(sentinelExpr)) return;
471 
472   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
473   // or 'NULL' if those are actually defined in the context.  Only use
474   // 'nil' for ObjC methods, where it's much more likely that the
475   // variadic arguments form a list of object pointers.
476   SourceLocation MissingNilLoc
477     = getLocForEndOfToken(sentinelExpr->getLocEnd());
478   std::string NullValue;
479   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
480     NullValue = "nil";
481   else if (getLangOpts().CPlusPlus11)
482     NullValue = "nullptr";
483   else if (PP.isMacroDefined("NULL"))
484     NullValue = "NULL";
485   else
486     NullValue = "(void*) 0";
487 
488   if (MissingNilLoc.isInvalid())
489     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
490   else
491     Diag(MissingNilLoc, diag::warn_missing_sentinel)
492       << int(calleeType)
493       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
494   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
495 }
496 
497 SourceRange Sema::getExprRange(Expr *E) const {
498   return E ? E->getSourceRange() : SourceRange();
499 }
500 
501 //===----------------------------------------------------------------------===//
502 //  Standard Promotions and Conversions
503 //===----------------------------------------------------------------------===//
504 
505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
507   // Handle any placeholder expressions which made it here.
508   if (E->getType()->isPlaceholderType()) {
509     ExprResult result = CheckPlaceholderExpr(E);
510     if (result.isInvalid()) return ExprError();
511     E = result.get();
512   }
513 
514   QualType Ty = E->getType();
515   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
516 
517   if (Ty->isFunctionType()) {
518     // If we are here, we are not calling a function but taking
519     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
520     if (getLangOpts().OpenCL) {
521       if (Diagnose)
522         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
523       return ExprError();
524     }
525 
526     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
527       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
528         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
529           return ExprError();
530 
531     E = ImpCastExprToType(E, Context.getPointerType(Ty),
532                           CK_FunctionToPointerDecay).get();
533   } else if (Ty->isArrayType()) {
534     // In C90 mode, arrays only promote to pointers if the array expression is
535     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
536     // type 'array of type' is converted to an expression that has type 'pointer
537     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
538     // that has type 'array of type' ...".  The relevant change is "an lvalue"
539     // (C90) to "an expression" (C99).
540     //
541     // C++ 4.2p1:
542     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
543     // T" can be converted to an rvalue of type "pointer to T".
544     //
545     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
546       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
547                             CK_ArrayToPointerDecay).get();
548   }
549   return E;
550 }
551 
552 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
553   // Check to see if we are dereferencing a null pointer.  If so,
554   // and if not volatile-qualified, this is undefined behavior that the
555   // optimizer will delete, so warn about it.  People sometimes try to use this
556   // to get a deterministic trap and are surprised by clang's behavior.  This
557   // only handles the pattern "*null", which is a very syntactic check.
558   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
559     if (UO->getOpcode() == UO_Deref &&
560         UO->getSubExpr()->IgnoreParenCasts()->
561           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
562         !UO->getType().isVolatileQualified()) {
563     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564                           S.PDiag(diag::warn_indirection_through_null)
565                             << UO->getSubExpr()->getSourceRange());
566     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567                         S.PDiag(diag::note_indirection_through_null));
568   }
569 }
570 
571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
572                                     SourceLocation AssignLoc,
573                                     const Expr* RHS) {
574   const ObjCIvarDecl *IV = OIRE->getDecl();
575   if (!IV)
576     return;
577 
578   DeclarationName MemberName = IV->getDeclName();
579   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
580   if (!Member || !Member->isStr("isa"))
581     return;
582 
583   const Expr *Base = OIRE->getBase();
584   QualType BaseType = Base->getType();
585   if (OIRE->isArrow())
586     BaseType = BaseType->getPointeeType();
587   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
588     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
589       ObjCInterfaceDecl *ClassDeclared = nullptr;
590       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
591       if (!ClassDeclared->getSuperClass()
592           && (*ClassDeclared->ivar_begin()) == IV) {
593         if (RHS) {
594           NamedDecl *ObjectSetClass =
595             S.LookupSingleName(S.TUScope,
596                                &S.Context.Idents.get("object_setClass"),
597                                SourceLocation(), S.LookupOrdinaryName);
598           if (ObjectSetClass) {
599             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
600             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
601             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
602             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
603                                                      AssignLoc), ",") <<
604             FixItHint::CreateInsertion(RHSLocEnd, ")");
605           }
606           else
607             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
608         } else {
609           NamedDecl *ObjectGetClass =
610             S.LookupSingleName(S.TUScope,
611                                &S.Context.Idents.get("object_getClass"),
612                                SourceLocation(), S.LookupOrdinaryName);
613           if (ObjectGetClass)
614             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
615             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
616             FixItHint::CreateReplacement(
617                                          SourceRange(OIRE->getOpLoc(),
618                                                      OIRE->getLocEnd()), ")");
619           else
620             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
621         }
622         S.Diag(IV->getLocation(), diag::note_ivar_decl);
623       }
624     }
625 }
626 
627 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
628   // Handle any placeholder expressions which made it here.
629   if (E->getType()->isPlaceholderType()) {
630     ExprResult result = CheckPlaceholderExpr(E);
631     if (result.isInvalid()) return ExprError();
632     E = result.get();
633   }
634 
635   // C++ [conv.lval]p1:
636   //   A glvalue of a non-function, non-array type T can be
637   //   converted to a prvalue.
638   if (!E->isGLValue()) return E;
639 
640   QualType T = E->getType();
641   assert(!T.isNull() && "r-value conversion on typeless expression?");
642 
643   // We don't want to throw lvalue-to-rvalue casts on top of
644   // expressions of certain types in C++.
645   if (getLangOpts().CPlusPlus &&
646       (E->getType() == Context.OverloadTy ||
647        T->isDependentType() ||
648        T->isRecordType()))
649     return E;
650 
651   // The C standard is actually really unclear on this point, and
652   // DR106 tells us what the result should be but not why.  It's
653   // generally best to say that void types just doesn't undergo
654   // lvalue-to-rvalue at all.  Note that expressions of unqualified
655   // 'void' type are never l-values, but qualified void can be.
656   if (T->isVoidType())
657     return E;
658 
659   // OpenCL usually rejects direct accesses to values of 'half' type.
660   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
661       T->isHalfType()) {
662     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663       << 0 << T;
664     return ExprError();
665   }
666 
667   CheckForNullPointerDereference(*this, E);
668   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670                                      &Context.Idents.get("object_getClass"),
671                                      SourceLocation(), LookupOrdinaryName);
672     if (ObjectGetClass)
673       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
674         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
675         FixItHint::CreateReplacement(
676                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677     else
678       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679   }
680   else if (const ObjCIvarRefExpr *OIRE =
681             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683 
684   // C++ [conv.lval]p1:
685   //   [...] If T is a non-class type, the type of the prvalue is the
686   //   cv-unqualified version of T. Otherwise, the type of the
687   //   rvalue is T.
688   //
689   // C99 6.3.2.1p2:
690   //   If the lvalue has qualified type, the value has the unqualified
691   //   version of the type of the lvalue; otherwise, the value has the
692   //   type of the lvalue.
693   if (T.hasQualifiers())
694     T = T.getUnqualifiedType();
695 
696   // Under the MS ABI, lock down the inheritance model now.
697   if (T->isMemberPointerType() &&
698       Context.getTargetInfo().getCXXABI().isMicrosoft())
699     (void)isCompleteType(E->getExprLoc(), T);
700 
701   UpdateMarkingForLValueToRValue(E);
702 
703   // Loading a __weak object implicitly retains the value, so we need a cleanup to
704   // balance that.
705   if (getLangOpts().ObjCAutoRefCount &&
706       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
707     Cleanup.setExprNeedsCleanups(true);
708 
709   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
710                                             nullptr, VK_RValue);
711 
712   // C11 6.3.2.1p2:
713   //   ... if the lvalue has atomic type, the value has the non-atomic version
714   //   of the type of the lvalue ...
715   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
716     T = Atomic->getValueType().getUnqualifiedType();
717     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
718                                    nullptr, VK_RValue);
719   }
720 
721   return Res;
722 }
723 
724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
725   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
726   if (Res.isInvalid())
727     return ExprError();
728   Res = DefaultLvalueConversion(Res.get());
729   if (Res.isInvalid())
730     return ExprError();
731   return Res;
732 }
733 
734 /// CallExprUnaryConversions - a special case of an unary conversion
735 /// performed on a function designator of a call expression.
736 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
737   QualType Ty = E->getType();
738   ExprResult Res = E;
739   // Only do implicit cast for a function type, but not for a pointer
740   // to function type.
741   if (Ty->isFunctionType()) {
742     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
743                             CK_FunctionToPointerDecay).get();
744     if (Res.isInvalid())
745       return ExprError();
746   }
747   Res = DefaultLvalueConversion(Res.get());
748   if (Res.isInvalid())
749     return ExprError();
750   return Res.get();
751 }
752 
753 /// UsualUnaryConversions - Performs various conversions that are common to most
754 /// operators (C99 6.3). The conversions of array and function types are
755 /// sometimes suppressed. For example, the array->pointer conversion doesn't
756 /// apply if the array is an argument to the sizeof or address (&) operators.
757 /// In these instances, this routine should *not* be called.
758 ExprResult Sema::UsualUnaryConversions(Expr *E) {
759   // First, convert to an r-value.
760   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
761   if (Res.isInvalid())
762     return ExprError();
763   E = Res.get();
764 
765   QualType Ty = E->getType();
766   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
767 
768   // Half FP have to be promoted to float unless it is natively supported
769   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
770     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
771 
772   // Try to perform integral promotions if the object has a theoretically
773   // promotable type.
774   if (Ty->isIntegralOrUnscopedEnumerationType()) {
775     // C99 6.3.1.1p2:
776     //
777     //   The following may be used in an expression wherever an int or
778     //   unsigned int may be used:
779     //     - an object or expression with an integer type whose integer
780     //       conversion rank is less than or equal to the rank of int
781     //       and unsigned int.
782     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
783     //
784     //   If an int can represent all values of the original type, the
785     //   value is converted to an int; otherwise, it is converted to an
786     //   unsigned int. These are called the integer promotions. All
787     //   other types are unchanged by the integer promotions.
788 
789     QualType PTy = Context.isPromotableBitField(E);
790     if (!PTy.isNull()) {
791       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
792       return E;
793     }
794     if (Ty->isPromotableIntegerType()) {
795       QualType PT = Context.getPromotedIntegerType(Ty);
796       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
797       return E;
798     }
799   }
800   return E;
801 }
802 
803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
804 /// do not have a prototype. Arguments that have type float or __fp16
805 /// are promoted to double. All other argument types are converted by
806 /// UsualUnaryConversions().
807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
808   QualType Ty = E->getType();
809   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
810 
811   ExprResult Res = UsualUnaryConversions(E);
812   if (Res.isInvalid())
813     return ExprError();
814   E = Res.get();
815 
816   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
817   // double.
818   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
819   if (BTy && (BTy->getKind() == BuiltinType::Half ||
820               BTy->getKind() == BuiltinType::Float))
821     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
822 
823   // C++ performs lvalue-to-rvalue conversion as a default argument
824   // promotion, even on class types, but note:
825   //   C++11 [conv.lval]p2:
826   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
827   //     operand or a subexpression thereof the value contained in the
828   //     referenced object is not accessed. Otherwise, if the glvalue
829   //     has a class type, the conversion copy-initializes a temporary
830   //     of type T from the glvalue and the result of the conversion
831   //     is a prvalue for the temporary.
832   // FIXME: add some way to gate this entire thing for correctness in
833   // potentially potentially evaluated contexts.
834   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835     ExprResult Temp = PerformCopyInitialization(
836                        InitializedEntity::InitializeTemporary(E->getType()),
837                                                 E->getExprLoc(), E);
838     if (Temp.isInvalid())
839       return ExprError();
840     E = Temp.get();
841   }
842 
843   return E;
844 }
845 
846 /// Determine the degree of POD-ness for an expression.
847 /// Incomplete types are considered POD, since this check can be performed
848 /// when we're in an unevaluated context.
849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850   if (Ty->isIncompleteType()) {
851     // C++11 [expr.call]p7:
852     //   After these conversions, if the argument does not have arithmetic,
853     //   enumeration, pointer, pointer to member, or class type, the program
854     //   is ill-formed.
855     //
856     // Since we've already performed array-to-pointer and function-to-pointer
857     // decay, the only such type in C++ is cv void. This also handles
858     // initializer lists as variadic arguments.
859     if (Ty->isVoidType())
860       return VAK_Invalid;
861 
862     if (Ty->isObjCObjectType())
863       return VAK_Invalid;
864     return VAK_Valid;
865   }
866 
867   if (Ty.isCXX98PODType(Context))
868     return VAK_Valid;
869 
870   // C++11 [expr.call]p7:
871   //   Passing a potentially-evaluated argument of class type (Clause 9)
872   //   having a non-trivial copy constructor, a non-trivial move constructor,
873   //   or a non-trivial destructor, with no corresponding parameter,
874   //   is conditionally-supported with implementation-defined semantics.
875   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
876     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
877       if (!Record->hasNonTrivialCopyConstructor() &&
878           !Record->hasNonTrivialMoveConstructor() &&
879           !Record->hasNonTrivialDestructor())
880         return VAK_ValidInCXX11;
881 
882   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
883     return VAK_Valid;
884 
885   if (Ty->isObjCObjectType())
886     return VAK_Invalid;
887 
888   if (getLangOpts().MSVCCompat)
889     return VAK_MSVCUndefined;
890 
891   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
892   // permitted to reject them. We should consider doing so.
893   return VAK_Undefined;
894 }
895 
896 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
897   // Don't allow one to pass an Objective-C interface to a vararg.
898   const QualType &Ty = E->getType();
899   VarArgKind VAK = isValidVarArgType(Ty);
900 
901   // Complain about passing non-POD types through varargs.
902   switch (VAK) {
903   case VAK_ValidInCXX11:
904     DiagRuntimeBehavior(
905         E->getLocStart(), nullptr,
906         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
907           << Ty << CT);
908     // Fall through.
909   case VAK_Valid:
910     if (Ty->isRecordType()) {
911       // This is unlikely to be what the user intended. If the class has a
912       // 'c_str' member function, the user probably meant to call that.
913       DiagRuntimeBehavior(E->getLocStart(), nullptr,
914                           PDiag(diag::warn_pass_class_arg_to_vararg)
915                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
916     }
917     break;
918 
919   case VAK_Undefined:
920   case VAK_MSVCUndefined:
921     DiagRuntimeBehavior(
922         E->getLocStart(), nullptr,
923         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
924           << getLangOpts().CPlusPlus11 << Ty << CT);
925     break;
926 
927   case VAK_Invalid:
928     if (Ty->isObjCObjectType())
929       DiagRuntimeBehavior(
930           E->getLocStart(), nullptr,
931           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
932             << Ty << CT);
933     else
934       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
935         << isa<InitListExpr>(E) << Ty << CT;
936     break;
937   }
938 }
939 
940 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
941 /// will create a trap if the resulting type is not a POD type.
942 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
943                                                   FunctionDecl *FDecl) {
944   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
945     // Strip the unbridged-cast placeholder expression off, if applicable.
946     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
947         (CT == VariadicMethod ||
948          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
949       E = stripARCUnbridgedCast(E);
950 
951     // Otherwise, do normal placeholder checking.
952     } else {
953       ExprResult ExprRes = CheckPlaceholderExpr(E);
954       if (ExprRes.isInvalid())
955         return ExprError();
956       E = ExprRes.get();
957     }
958   }
959 
960   ExprResult ExprRes = DefaultArgumentPromotion(E);
961   if (ExprRes.isInvalid())
962     return ExprError();
963   E = ExprRes.get();
964 
965   // Diagnostics regarding non-POD argument types are
966   // emitted along with format string checking in Sema::CheckFunctionCall().
967   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
968     // Turn this into a trap.
969     CXXScopeSpec SS;
970     SourceLocation TemplateKWLoc;
971     UnqualifiedId Name;
972     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
973                        E->getLocStart());
974     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
975                                           Name, true, false);
976     if (TrapFn.isInvalid())
977       return ExprError();
978 
979     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
980                                     E->getLocStart(), None,
981                                     E->getLocEnd());
982     if (Call.isInvalid())
983       return ExprError();
984 
985     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
986                                   Call.get(), E);
987     if (Comma.isInvalid())
988       return ExprError();
989     return Comma.get();
990   }
991 
992   if (!getLangOpts().CPlusPlus &&
993       RequireCompleteType(E->getExprLoc(), E->getType(),
994                           diag::err_call_incomplete_argument))
995     return ExprError();
996 
997   return E;
998 }
999 
1000 /// \brief Converts an integer to complex float type.  Helper function of
1001 /// UsualArithmeticConversions()
1002 ///
1003 /// \return false if the integer expression is an integer type and is
1004 /// successfully converted to the complex type.
1005 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1006                                                   ExprResult &ComplexExpr,
1007                                                   QualType IntTy,
1008                                                   QualType ComplexTy,
1009                                                   bool SkipCast) {
1010   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1011   if (SkipCast) return false;
1012   if (IntTy->isIntegerType()) {
1013     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1014     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1015     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1016                                   CK_FloatingRealToComplex);
1017   } else {
1018     assert(IntTy->isComplexIntegerType());
1019     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1020                                   CK_IntegralComplexToFloatingComplex);
1021   }
1022   return false;
1023 }
1024 
1025 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1026 /// UsualArithmeticConversions()
1027 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1028                                              ExprResult &RHS, QualType LHSType,
1029                                              QualType RHSType,
1030                                              bool IsCompAssign) {
1031   // if we have an integer operand, the result is the complex type.
1032   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1033                                              /*skipCast*/false))
1034     return LHSType;
1035   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1036                                              /*skipCast*/IsCompAssign))
1037     return RHSType;
1038 
1039   // This handles complex/complex, complex/float, or float/complex.
1040   // When both operands are complex, the shorter operand is converted to the
1041   // type of the longer, and that is the type of the result. This corresponds
1042   // to what is done when combining two real floating-point operands.
1043   // The fun begins when size promotion occur across type domains.
1044   // From H&S 6.3.4: When one operand is complex and the other is a real
1045   // floating-point type, the less precise type is converted, within it's
1046   // real or complex domain, to the precision of the other type. For example,
1047   // when combining a "long double" with a "double _Complex", the
1048   // "double _Complex" is promoted to "long double _Complex".
1049 
1050   // Compute the rank of the two types, regardless of whether they are complex.
1051   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1052 
1053   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1054   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1055   QualType LHSElementType =
1056       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1057   QualType RHSElementType =
1058       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1059 
1060   QualType ResultType = S.Context.getComplexType(LHSElementType);
1061   if (Order < 0) {
1062     // Promote the precision of the LHS if not an assignment.
1063     ResultType = S.Context.getComplexType(RHSElementType);
1064     if (!IsCompAssign) {
1065       if (LHSComplexType)
1066         LHS =
1067             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1068       else
1069         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1070     }
1071   } else if (Order > 0) {
1072     // Promote the precision of the RHS.
1073     if (RHSComplexType)
1074       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1075     else
1076       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1077   }
1078   return ResultType;
1079 }
1080 
1081 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1082 /// of UsualArithmeticConversions()
1083 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1084                                            ExprResult &IntExpr,
1085                                            QualType FloatTy, QualType IntTy,
1086                                            bool ConvertFloat, bool ConvertInt) {
1087   if (IntTy->isIntegerType()) {
1088     if (ConvertInt)
1089       // Convert intExpr to the lhs floating point type.
1090       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1091                                     CK_IntegralToFloating);
1092     return FloatTy;
1093   }
1094 
1095   // Convert both sides to the appropriate complex float.
1096   assert(IntTy->isComplexIntegerType());
1097   QualType result = S.Context.getComplexType(FloatTy);
1098 
1099   // _Complex int -> _Complex float
1100   if (ConvertInt)
1101     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1102                                   CK_IntegralComplexToFloatingComplex);
1103 
1104   // float -> _Complex float
1105   if (ConvertFloat)
1106     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1107                                     CK_FloatingRealToComplex);
1108 
1109   return result;
1110 }
1111 
1112 /// \brief Handle arithmethic conversion with floating point types.  Helper
1113 /// function of UsualArithmeticConversions()
1114 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1115                                       ExprResult &RHS, QualType LHSType,
1116                                       QualType RHSType, bool IsCompAssign) {
1117   bool LHSFloat = LHSType->isRealFloatingType();
1118   bool RHSFloat = RHSType->isRealFloatingType();
1119 
1120   // If we have two real floating types, convert the smaller operand
1121   // to the bigger result.
1122   if (LHSFloat && RHSFloat) {
1123     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1124     if (order > 0) {
1125       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1126       return LHSType;
1127     }
1128 
1129     assert(order < 0 && "illegal float comparison");
1130     if (!IsCompAssign)
1131       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1132     return RHSType;
1133   }
1134 
1135   if (LHSFloat) {
1136     // Half FP has to be promoted to float unless it is natively supported
1137     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1138       LHSType = S.Context.FloatTy;
1139 
1140     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1141                                       /*convertFloat=*/!IsCompAssign,
1142                                       /*convertInt=*/ true);
1143   }
1144   assert(RHSFloat);
1145   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1146                                     /*convertInt=*/ true,
1147                                     /*convertFloat=*/!IsCompAssign);
1148 }
1149 
1150 /// \brief Diagnose attempts to convert between __float128 and long double if
1151 /// there is no support for such conversion. Helper function of
1152 /// UsualArithmeticConversions().
1153 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1154                                       QualType RHSType) {
1155   /*  No issue converting if at least one of the types is not a floating point
1156       type or the two types have the same rank.
1157   */
1158   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1159       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1160     return false;
1161 
1162   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1163          "The remaining types must be floating point types.");
1164 
1165   auto *LHSComplex = LHSType->getAs<ComplexType>();
1166   auto *RHSComplex = RHSType->getAs<ComplexType>();
1167 
1168   QualType LHSElemType = LHSComplex ?
1169     LHSComplex->getElementType() : LHSType;
1170   QualType RHSElemType = RHSComplex ?
1171     RHSComplex->getElementType() : RHSType;
1172 
1173   // No issue if the two types have the same representation
1174   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1175       &S.Context.getFloatTypeSemantics(RHSElemType))
1176     return false;
1177 
1178   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1179                                 RHSElemType == S.Context.LongDoubleTy);
1180   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1181                             RHSElemType == S.Context.Float128Ty);
1182 
1183   /* We've handled the situation where __float128 and long double have the same
1184      representation. The only other allowable conversion is if long double is
1185      really just double.
1186   */
1187   return Float128AndLongDouble &&
1188     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1189      &llvm::APFloat::IEEEdouble);
1190 }
1191 
1192 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1193 
1194 namespace {
1195 /// These helper callbacks are placed in an anonymous namespace to
1196 /// permit their use as function template parameters.
1197 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1198   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1199 }
1200 
1201 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1202   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1203                              CK_IntegralComplexCast);
1204 }
1205 }
1206 
1207 /// \brief Handle integer arithmetic conversions.  Helper function of
1208 /// UsualArithmeticConversions()
1209 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1210 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1211                                         ExprResult &RHS, QualType LHSType,
1212                                         QualType RHSType, bool IsCompAssign) {
1213   // The rules for this case are in C99 6.3.1.8
1214   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1215   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1216   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1217   if (LHSSigned == RHSSigned) {
1218     // Same signedness; use the higher-ranked type
1219     if (order >= 0) {
1220       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1221       return LHSType;
1222     } else if (!IsCompAssign)
1223       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1224     return RHSType;
1225   } else if (order != (LHSSigned ? 1 : -1)) {
1226     // The unsigned type has greater than or equal rank to the
1227     // signed type, so use the unsigned type
1228     if (RHSSigned) {
1229       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1230       return LHSType;
1231     } else if (!IsCompAssign)
1232       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1233     return RHSType;
1234   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1235     // The two types are different widths; if we are here, that
1236     // means the signed type is larger than the unsigned type, so
1237     // use the signed type.
1238     if (LHSSigned) {
1239       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240       return LHSType;
1241     } else if (!IsCompAssign)
1242       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243     return RHSType;
1244   } else {
1245     // The signed type is higher-ranked than the unsigned type,
1246     // but isn't actually any bigger (like unsigned int and long
1247     // on most 32-bit systems).  Use the unsigned type corresponding
1248     // to the signed type.
1249     QualType result =
1250       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1251     RHS = (*doRHSCast)(S, RHS.get(), result);
1252     if (!IsCompAssign)
1253       LHS = (*doLHSCast)(S, LHS.get(), result);
1254     return result;
1255   }
1256 }
1257 
1258 /// \brief Handle conversions with GCC complex int extension.  Helper function
1259 /// of UsualArithmeticConversions()
1260 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1261                                            ExprResult &RHS, QualType LHSType,
1262                                            QualType RHSType,
1263                                            bool IsCompAssign) {
1264   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1265   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1266 
1267   if (LHSComplexInt && RHSComplexInt) {
1268     QualType LHSEltType = LHSComplexInt->getElementType();
1269     QualType RHSEltType = RHSComplexInt->getElementType();
1270     QualType ScalarType =
1271       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1272         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1273 
1274     return S.Context.getComplexType(ScalarType);
1275   }
1276 
1277   if (LHSComplexInt) {
1278     QualType LHSEltType = LHSComplexInt->getElementType();
1279     QualType ScalarType =
1280       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1281         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1282     QualType ComplexType = S.Context.getComplexType(ScalarType);
1283     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1284                               CK_IntegralRealToComplex);
1285 
1286     return ComplexType;
1287   }
1288 
1289   assert(RHSComplexInt);
1290 
1291   QualType RHSEltType = RHSComplexInt->getElementType();
1292   QualType ScalarType =
1293     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1294       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1295   QualType ComplexType = S.Context.getComplexType(ScalarType);
1296 
1297   if (!IsCompAssign)
1298     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1299                               CK_IntegralRealToComplex);
1300   return ComplexType;
1301 }
1302 
1303 /// UsualArithmeticConversions - Performs various conversions that are common to
1304 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1305 /// routine returns the first non-arithmetic type found. The client is
1306 /// responsible for emitting appropriate error diagnostics.
1307 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1308                                           bool IsCompAssign) {
1309   if (!IsCompAssign) {
1310     LHS = UsualUnaryConversions(LHS.get());
1311     if (LHS.isInvalid())
1312       return QualType();
1313   }
1314 
1315   RHS = UsualUnaryConversions(RHS.get());
1316   if (RHS.isInvalid())
1317     return QualType();
1318 
1319   // For conversion purposes, we ignore any qualifiers.
1320   // For example, "const float" and "float" are equivalent.
1321   QualType LHSType =
1322     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1323   QualType RHSType =
1324     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1325 
1326   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1327   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1328     LHSType = AtomicLHS->getValueType();
1329 
1330   // If both types are identical, no conversion is needed.
1331   if (LHSType == RHSType)
1332     return LHSType;
1333 
1334   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1335   // The caller can deal with this (e.g. pointer + int).
1336   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1337     return QualType();
1338 
1339   // Apply unary and bitfield promotions to the LHS's type.
1340   QualType LHSUnpromotedType = LHSType;
1341   if (LHSType->isPromotableIntegerType())
1342     LHSType = Context.getPromotedIntegerType(LHSType);
1343   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1344   if (!LHSBitfieldPromoteTy.isNull())
1345     LHSType = LHSBitfieldPromoteTy;
1346   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1347     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1348 
1349   // If both types are identical, no conversion is needed.
1350   if (LHSType == RHSType)
1351     return LHSType;
1352 
1353   // At this point, we have two different arithmetic types.
1354 
1355   // Diagnose attempts to convert between __float128 and long double where
1356   // such conversions currently can't be handled.
1357   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1358     return QualType();
1359 
1360   // Handle complex types first (C99 6.3.1.8p1).
1361   if (LHSType->isComplexType() || RHSType->isComplexType())
1362     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1363                                         IsCompAssign);
1364 
1365   // Now handle "real" floating types (i.e. float, double, long double).
1366   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1367     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1368                                  IsCompAssign);
1369 
1370   // Handle GCC complex int extension.
1371   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1372     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1373                                       IsCompAssign);
1374 
1375   // Finally, we have two differing integer types.
1376   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1377            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1378 }
1379 
1380 
1381 //===----------------------------------------------------------------------===//
1382 //  Semantic Analysis for various Expression Types
1383 //===----------------------------------------------------------------------===//
1384 
1385 
1386 ExprResult
1387 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1388                                 SourceLocation DefaultLoc,
1389                                 SourceLocation RParenLoc,
1390                                 Expr *ControllingExpr,
1391                                 ArrayRef<ParsedType> ArgTypes,
1392                                 ArrayRef<Expr *> ArgExprs) {
1393   unsigned NumAssocs = ArgTypes.size();
1394   assert(NumAssocs == ArgExprs.size());
1395 
1396   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1397   for (unsigned i = 0; i < NumAssocs; ++i) {
1398     if (ArgTypes[i])
1399       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1400     else
1401       Types[i] = nullptr;
1402   }
1403 
1404   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1405                                              ControllingExpr,
1406                                              llvm::makeArrayRef(Types, NumAssocs),
1407                                              ArgExprs);
1408   delete [] Types;
1409   return ER;
1410 }
1411 
1412 ExprResult
1413 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1414                                  SourceLocation DefaultLoc,
1415                                  SourceLocation RParenLoc,
1416                                  Expr *ControllingExpr,
1417                                  ArrayRef<TypeSourceInfo *> Types,
1418                                  ArrayRef<Expr *> Exprs) {
1419   unsigned NumAssocs = Types.size();
1420   assert(NumAssocs == Exprs.size());
1421 
1422   // Decay and strip qualifiers for the controlling expression type, and handle
1423   // placeholder type replacement. See committee discussion from WG14 DR423.
1424   {
1425     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1426     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1427     if (R.isInvalid())
1428       return ExprError();
1429     ControllingExpr = R.get();
1430   }
1431 
1432   // The controlling expression is an unevaluated operand, so side effects are
1433   // likely unintended.
1434   if (ActiveTemplateInstantiations.empty() &&
1435       ControllingExpr->HasSideEffects(Context, false))
1436     Diag(ControllingExpr->getExprLoc(),
1437          diag::warn_side_effects_unevaluated_context);
1438 
1439   bool TypeErrorFound = false,
1440        IsResultDependent = ControllingExpr->isTypeDependent(),
1441        ContainsUnexpandedParameterPack
1442          = ControllingExpr->containsUnexpandedParameterPack();
1443 
1444   for (unsigned i = 0; i < NumAssocs; ++i) {
1445     if (Exprs[i]->containsUnexpandedParameterPack())
1446       ContainsUnexpandedParameterPack = true;
1447 
1448     if (Types[i]) {
1449       if (Types[i]->getType()->containsUnexpandedParameterPack())
1450         ContainsUnexpandedParameterPack = true;
1451 
1452       if (Types[i]->getType()->isDependentType()) {
1453         IsResultDependent = true;
1454       } else {
1455         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1456         // complete object type other than a variably modified type."
1457         unsigned D = 0;
1458         if (Types[i]->getType()->isIncompleteType())
1459           D = diag::err_assoc_type_incomplete;
1460         else if (!Types[i]->getType()->isObjectType())
1461           D = diag::err_assoc_type_nonobject;
1462         else if (Types[i]->getType()->isVariablyModifiedType())
1463           D = diag::err_assoc_type_variably_modified;
1464 
1465         if (D != 0) {
1466           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1467             << Types[i]->getTypeLoc().getSourceRange()
1468             << Types[i]->getType();
1469           TypeErrorFound = true;
1470         }
1471 
1472         // C11 6.5.1.1p2 "No two generic associations in the same generic
1473         // selection shall specify compatible types."
1474         for (unsigned j = i+1; j < NumAssocs; ++j)
1475           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1476               Context.typesAreCompatible(Types[i]->getType(),
1477                                          Types[j]->getType())) {
1478             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1479                  diag::err_assoc_compatible_types)
1480               << Types[j]->getTypeLoc().getSourceRange()
1481               << Types[j]->getType()
1482               << Types[i]->getType();
1483             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1484                  diag::note_compat_assoc)
1485               << Types[i]->getTypeLoc().getSourceRange()
1486               << Types[i]->getType();
1487             TypeErrorFound = true;
1488           }
1489       }
1490     }
1491   }
1492   if (TypeErrorFound)
1493     return ExprError();
1494 
1495   // If we determined that the generic selection is result-dependent, don't
1496   // try to compute the result expression.
1497   if (IsResultDependent)
1498     return new (Context) GenericSelectionExpr(
1499         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1500         ContainsUnexpandedParameterPack);
1501 
1502   SmallVector<unsigned, 1> CompatIndices;
1503   unsigned DefaultIndex = -1U;
1504   for (unsigned i = 0; i < NumAssocs; ++i) {
1505     if (!Types[i])
1506       DefaultIndex = i;
1507     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1508                                         Types[i]->getType()))
1509       CompatIndices.push_back(i);
1510   }
1511 
1512   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1513   // type compatible with at most one of the types named in its generic
1514   // association list."
1515   if (CompatIndices.size() > 1) {
1516     // We strip parens here because the controlling expression is typically
1517     // parenthesized in macro definitions.
1518     ControllingExpr = ControllingExpr->IgnoreParens();
1519     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1520       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1521       << (unsigned) CompatIndices.size();
1522     for (unsigned I : CompatIndices) {
1523       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1524            diag::note_compat_assoc)
1525         << Types[I]->getTypeLoc().getSourceRange()
1526         << Types[I]->getType();
1527     }
1528     return ExprError();
1529   }
1530 
1531   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1532   // its controlling expression shall have type compatible with exactly one of
1533   // the types named in its generic association list."
1534   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1535     // We strip parens here because the controlling expression is typically
1536     // parenthesized in macro definitions.
1537     ControllingExpr = ControllingExpr->IgnoreParens();
1538     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1539       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1540     return ExprError();
1541   }
1542 
1543   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1544   // type name that is compatible with the type of the controlling expression,
1545   // then the result expression of the generic selection is the expression
1546   // in that generic association. Otherwise, the result expression of the
1547   // generic selection is the expression in the default generic association."
1548   unsigned ResultIndex =
1549     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1550 
1551   return new (Context) GenericSelectionExpr(
1552       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1553       ContainsUnexpandedParameterPack, ResultIndex);
1554 }
1555 
1556 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1557 /// location of the token and the offset of the ud-suffix within it.
1558 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1559                                      unsigned Offset) {
1560   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1561                                         S.getLangOpts());
1562 }
1563 
1564 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1565 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1566 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1567                                                  IdentifierInfo *UDSuffix,
1568                                                  SourceLocation UDSuffixLoc,
1569                                                  ArrayRef<Expr*> Args,
1570                                                  SourceLocation LitEndLoc) {
1571   assert(Args.size() <= 2 && "too many arguments for literal operator");
1572 
1573   QualType ArgTy[2];
1574   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1575     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1576     if (ArgTy[ArgIdx]->isArrayType())
1577       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1578   }
1579 
1580   DeclarationName OpName =
1581     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1582   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1583   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1584 
1585   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1586   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1587                               /*AllowRaw*/false, /*AllowTemplate*/false,
1588                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1589     return ExprError();
1590 
1591   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1592 }
1593 
1594 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1595 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1596 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1597 /// multiple tokens.  However, the common case is that StringToks points to one
1598 /// string.
1599 ///
1600 ExprResult
1601 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1602   assert(!StringToks.empty() && "Must have at least one string!");
1603 
1604   StringLiteralParser Literal(StringToks, PP);
1605   if (Literal.hadError)
1606     return ExprError();
1607 
1608   SmallVector<SourceLocation, 4> StringTokLocs;
1609   for (const Token &Tok : StringToks)
1610     StringTokLocs.push_back(Tok.getLocation());
1611 
1612   QualType CharTy = Context.CharTy;
1613   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1614   if (Literal.isWide()) {
1615     CharTy = Context.getWideCharType();
1616     Kind = StringLiteral::Wide;
1617   } else if (Literal.isUTF8()) {
1618     Kind = StringLiteral::UTF8;
1619   } else if (Literal.isUTF16()) {
1620     CharTy = Context.Char16Ty;
1621     Kind = StringLiteral::UTF16;
1622   } else if (Literal.isUTF32()) {
1623     CharTy = Context.Char32Ty;
1624     Kind = StringLiteral::UTF32;
1625   } else if (Literal.isPascal()) {
1626     CharTy = Context.UnsignedCharTy;
1627   }
1628 
1629   QualType CharTyConst = CharTy;
1630   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1631   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1632     CharTyConst.addConst();
1633 
1634   // Get an array type for the string, according to C99 6.4.5.  This includes
1635   // the nul terminator character as well as the string length for pascal
1636   // strings.
1637   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1638                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1639                                  ArrayType::Normal, 0);
1640 
1641   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1642   if (getLangOpts().OpenCL) {
1643     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1644   }
1645 
1646   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1647   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1648                                              Kind, Literal.Pascal, StrTy,
1649                                              &StringTokLocs[0],
1650                                              StringTokLocs.size());
1651   if (Literal.getUDSuffix().empty())
1652     return Lit;
1653 
1654   // We're building a user-defined literal.
1655   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1656   SourceLocation UDSuffixLoc =
1657     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1658                    Literal.getUDSuffixOffset());
1659 
1660   // Make sure we're allowed user-defined literals here.
1661   if (!UDLScope)
1662     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1663 
1664   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1665   //   operator "" X (str, len)
1666   QualType SizeType = Context.getSizeType();
1667 
1668   DeclarationName OpName =
1669     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1670   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1671   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1672 
1673   QualType ArgTy[] = {
1674     Context.getArrayDecayedType(StrTy), SizeType
1675   };
1676 
1677   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1678   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1679                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1680                                 /*AllowStringTemplate*/true)) {
1681 
1682   case LOLR_Cooked: {
1683     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1684     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1685                                                     StringTokLocs[0]);
1686     Expr *Args[] = { Lit, LenArg };
1687 
1688     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1689   }
1690 
1691   case LOLR_StringTemplate: {
1692     TemplateArgumentListInfo ExplicitArgs;
1693 
1694     unsigned CharBits = Context.getIntWidth(CharTy);
1695     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1696     llvm::APSInt Value(CharBits, CharIsUnsigned);
1697 
1698     TemplateArgument TypeArg(CharTy);
1699     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1700     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1701 
1702     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1703       Value = Lit->getCodeUnit(I);
1704       TemplateArgument Arg(Context, Value, CharTy);
1705       TemplateArgumentLocInfo ArgInfo;
1706       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1707     }
1708     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1709                                     &ExplicitArgs);
1710   }
1711   case LOLR_Raw:
1712   case LOLR_Template:
1713     llvm_unreachable("unexpected literal operator lookup result");
1714   case LOLR_Error:
1715     return ExprError();
1716   }
1717   llvm_unreachable("unexpected literal operator lookup result");
1718 }
1719 
1720 ExprResult
1721 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1722                        SourceLocation Loc,
1723                        const CXXScopeSpec *SS) {
1724   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1725   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1726 }
1727 
1728 /// BuildDeclRefExpr - Build an expression that references a
1729 /// declaration that does not require a closure capture.
1730 ExprResult
1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1732                        const DeclarationNameInfo &NameInfo,
1733                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1734                        const TemplateArgumentListInfo *TemplateArgs) {
1735   bool RefersToCapturedVariable =
1736       isa<VarDecl>(D) &&
1737       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1738 
1739   DeclRefExpr *E;
1740   if (isa<VarTemplateSpecializationDecl>(D)) {
1741     VarTemplateSpecializationDecl *VarSpec =
1742         cast<VarTemplateSpecializationDecl>(D);
1743 
1744     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1745                                         : NestedNameSpecifierLoc(),
1746                             VarSpec->getTemplateKeywordLoc(), D,
1747                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1748                             FoundD, TemplateArgs);
1749   } else {
1750     assert(!TemplateArgs && "No template arguments for non-variable"
1751                             " template specialization references");
1752     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1753                                         : NestedNameSpecifierLoc(),
1754                             SourceLocation(), D, RefersToCapturedVariable,
1755                             NameInfo, Ty, VK, FoundD);
1756   }
1757 
1758   MarkDeclRefReferenced(E);
1759 
1760   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1761       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1762       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1763       recordUseOfEvaluatedWeak(E);
1764 
1765   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1766     UnusedPrivateFields.remove(FD);
1767     // Just in case we're building an illegal pointer-to-member.
1768     if (FD->isBitField())
1769       E->setObjectKind(OK_BitField);
1770   }
1771 
1772   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1773   // designates a bit-field.
1774   if (auto *BD = dyn_cast<BindingDecl>(D))
1775     if (auto *BE = BD->getBinding())
1776       E->setObjectKind(BE->getObjectKind());
1777 
1778   return E;
1779 }
1780 
1781 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1782 /// possibly a list of template arguments.
1783 ///
1784 /// If this produces template arguments, it is permitted to call
1785 /// DecomposeTemplateName.
1786 ///
1787 /// This actually loses a lot of source location information for
1788 /// non-standard name kinds; we should consider preserving that in
1789 /// some way.
1790 void
1791 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1792                              TemplateArgumentListInfo &Buffer,
1793                              DeclarationNameInfo &NameInfo,
1794                              const TemplateArgumentListInfo *&TemplateArgs) {
1795   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1796     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1797     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1798 
1799     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1800                                        Id.TemplateId->NumArgs);
1801     translateTemplateArguments(TemplateArgsPtr, Buffer);
1802 
1803     TemplateName TName = Id.TemplateId->Template.get();
1804     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1805     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1806     TemplateArgs = &Buffer;
1807   } else {
1808     NameInfo = GetNameFromUnqualifiedId(Id);
1809     TemplateArgs = nullptr;
1810   }
1811 }
1812 
1813 static void emitEmptyLookupTypoDiagnostic(
1814     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1815     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1816     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1817   DeclContext *Ctx =
1818       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1819   if (!TC) {
1820     // Emit a special diagnostic for failed member lookups.
1821     // FIXME: computing the declaration context might fail here (?)
1822     if (Ctx)
1823       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1824                                                  << SS.getRange();
1825     else
1826       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1827     return;
1828   }
1829 
1830   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1831   bool DroppedSpecifier =
1832       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1833   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1834                         ? diag::note_implicit_param_decl
1835                         : diag::note_previous_decl;
1836   if (!Ctx)
1837     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1838                          SemaRef.PDiag(NoteID));
1839   else
1840     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1841                                  << Typo << Ctx << DroppedSpecifier
1842                                  << SS.getRange(),
1843                          SemaRef.PDiag(NoteID));
1844 }
1845 
1846 /// Diagnose an empty lookup.
1847 ///
1848 /// \return false if new lookup candidates were found
1849 bool
1850 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1851                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1852                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1853                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1854   DeclarationName Name = R.getLookupName();
1855 
1856   unsigned diagnostic = diag::err_undeclared_var_use;
1857   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1858   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1859       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1860       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1861     diagnostic = diag::err_undeclared_use;
1862     diagnostic_suggest = diag::err_undeclared_use_suggest;
1863   }
1864 
1865   // If the original lookup was an unqualified lookup, fake an
1866   // unqualified lookup.  This is useful when (for example) the
1867   // original lookup would not have found something because it was a
1868   // dependent name.
1869   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1870   while (DC) {
1871     if (isa<CXXRecordDecl>(DC)) {
1872       LookupQualifiedName(R, DC);
1873 
1874       if (!R.empty()) {
1875         // Don't give errors about ambiguities in this lookup.
1876         R.suppressDiagnostics();
1877 
1878         // During a default argument instantiation the CurContext points
1879         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1880         // function parameter list, hence add an explicit check.
1881         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1882                               ActiveTemplateInstantiations.back().Kind ==
1883             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1884         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1885         bool isInstance = CurMethod &&
1886                           CurMethod->isInstance() &&
1887                           DC == CurMethod->getParent() && !isDefaultArgument;
1888 
1889         // Give a code modification hint to insert 'this->'.
1890         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1891         // Actually quite difficult!
1892         if (getLangOpts().MSVCCompat)
1893           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1894         if (isInstance) {
1895           Diag(R.getNameLoc(), diagnostic) << Name
1896             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1897           CheckCXXThisCapture(R.getNameLoc());
1898         } else {
1899           Diag(R.getNameLoc(), diagnostic) << Name;
1900         }
1901 
1902         // Do we really want to note all of these?
1903         for (NamedDecl *D : R)
1904           Diag(D->getLocation(), diag::note_dependent_var_use);
1905 
1906         // Return true if we are inside a default argument instantiation
1907         // and the found name refers to an instance member function, otherwise
1908         // the function calling DiagnoseEmptyLookup will try to create an
1909         // implicit member call and this is wrong for default argument.
1910         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1911           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1912           return true;
1913         }
1914 
1915         // Tell the callee to try to recover.
1916         return false;
1917       }
1918 
1919       R.clear();
1920     }
1921 
1922     // In Microsoft mode, if we are performing lookup from within a friend
1923     // function definition declared at class scope then we must set
1924     // DC to the lexical parent to be able to search into the parent
1925     // class.
1926     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1927         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1928         DC->getLexicalParent()->isRecord())
1929       DC = DC->getLexicalParent();
1930     else
1931       DC = DC->getParent();
1932   }
1933 
1934   // We didn't find anything, so try to correct for a typo.
1935   TypoCorrection Corrected;
1936   if (S && Out) {
1937     SourceLocation TypoLoc = R.getNameLoc();
1938     assert(!ExplicitTemplateArgs &&
1939            "Diagnosing an empty lookup with explicit template args!");
1940     *Out = CorrectTypoDelayed(
1941         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1942         [=](const TypoCorrection &TC) {
1943           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1944                                         diagnostic, diagnostic_suggest);
1945         },
1946         nullptr, CTK_ErrorRecovery);
1947     if (*Out)
1948       return true;
1949   } else if (S && (Corrected =
1950                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1951                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1952     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1953     bool DroppedSpecifier =
1954         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1955     R.setLookupName(Corrected.getCorrection());
1956 
1957     bool AcceptableWithRecovery = false;
1958     bool AcceptableWithoutRecovery = false;
1959     NamedDecl *ND = Corrected.getFoundDecl();
1960     if (ND) {
1961       if (Corrected.isOverloaded()) {
1962         OverloadCandidateSet OCS(R.getNameLoc(),
1963                                  OverloadCandidateSet::CSK_Normal);
1964         OverloadCandidateSet::iterator Best;
1965         for (NamedDecl *CD : Corrected) {
1966           if (FunctionTemplateDecl *FTD =
1967                    dyn_cast<FunctionTemplateDecl>(CD))
1968             AddTemplateOverloadCandidate(
1969                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1970                 Args, OCS);
1971           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1972             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1973               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1974                                    Args, OCS);
1975         }
1976         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1977         case OR_Success:
1978           ND = Best->FoundDecl;
1979           Corrected.setCorrectionDecl(ND);
1980           break;
1981         default:
1982           // FIXME: Arbitrarily pick the first declaration for the note.
1983           Corrected.setCorrectionDecl(ND);
1984           break;
1985         }
1986       }
1987       R.addDecl(ND);
1988       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1989         CXXRecordDecl *Record = nullptr;
1990         if (Corrected.getCorrectionSpecifier()) {
1991           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1992           Record = Ty->getAsCXXRecordDecl();
1993         }
1994         if (!Record)
1995           Record = cast<CXXRecordDecl>(
1996               ND->getDeclContext()->getRedeclContext());
1997         R.setNamingClass(Record);
1998       }
1999 
2000       auto *UnderlyingND = ND->getUnderlyingDecl();
2001       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2002                                isa<FunctionTemplateDecl>(UnderlyingND);
2003       // FIXME: If we ended up with a typo for a type name or
2004       // Objective-C class name, we're in trouble because the parser
2005       // is in the wrong place to recover. Suggest the typo
2006       // correction, but don't make it a fix-it since we're not going
2007       // to recover well anyway.
2008       AcceptableWithoutRecovery =
2009           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2010     } else {
2011       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2012       // because we aren't able to recover.
2013       AcceptableWithoutRecovery = true;
2014     }
2015 
2016     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2017       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2018                             ? diag::note_implicit_param_decl
2019                             : diag::note_previous_decl;
2020       if (SS.isEmpty())
2021         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2022                      PDiag(NoteID), AcceptableWithRecovery);
2023       else
2024         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2025                                   << Name << computeDeclContext(SS, false)
2026                                   << DroppedSpecifier << SS.getRange(),
2027                      PDiag(NoteID), AcceptableWithRecovery);
2028 
2029       // Tell the callee whether to try to recover.
2030       return !AcceptableWithRecovery;
2031     }
2032   }
2033   R.clear();
2034 
2035   // Emit a special diagnostic for failed member lookups.
2036   // FIXME: computing the declaration context might fail here (?)
2037   if (!SS.isEmpty()) {
2038     Diag(R.getNameLoc(), diag::err_no_member)
2039       << Name << computeDeclContext(SS, false)
2040       << SS.getRange();
2041     return true;
2042   }
2043 
2044   // Give up, we can't recover.
2045   Diag(R.getNameLoc(), diagnostic) << Name;
2046   return true;
2047 }
2048 
2049 /// In Microsoft mode, if we are inside a template class whose parent class has
2050 /// dependent base classes, and we can't resolve an unqualified identifier, then
2051 /// assume the identifier is a member of a dependent base class.  We can only
2052 /// recover successfully in static methods, instance methods, and other contexts
2053 /// where 'this' is available.  This doesn't precisely match MSVC's
2054 /// instantiation model, but it's close enough.
2055 static Expr *
2056 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2057                                DeclarationNameInfo &NameInfo,
2058                                SourceLocation TemplateKWLoc,
2059                                const TemplateArgumentListInfo *TemplateArgs) {
2060   // Only try to recover from lookup into dependent bases in static methods or
2061   // contexts where 'this' is available.
2062   QualType ThisType = S.getCurrentThisType();
2063   const CXXRecordDecl *RD = nullptr;
2064   if (!ThisType.isNull())
2065     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2066   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2067     RD = MD->getParent();
2068   if (!RD || !RD->hasAnyDependentBases())
2069     return nullptr;
2070 
2071   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2072   // is available, suggest inserting 'this->' as a fixit.
2073   SourceLocation Loc = NameInfo.getLoc();
2074   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2075   DB << NameInfo.getName() << RD;
2076 
2077   if (!ThisType.isNull()) {
2078     DB << FixItHint::CreateInsertion(Loc, "this->");
2079     return CXXDependentScopeMemberExpr::Create(
2080         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2081         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2082         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2083   }
2084 
2085   // Synthesize a fake NNS that points to the derived class.  This will
2086   // perform name lookup during template instantiation.
2087   CXXScopeSpec SS;
2088   auto *NNS =
2089       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2090   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2091   return DependentScopeDeclRefExpr::Create(
2092       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2093       TemplateArgs);
2094 }
2095 
2096 ExprResult
2097 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2098                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2099                         bool HasTrailingLParen, bool IsAddressOfOperand,
2100                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2101                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2102   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2103          "cannot be direct & operand and have a trailing lparen");
2104   if (SS.isInvalid())
2105     return ExprError();
2106 
2107   TemplateArgumentListInfo TemplateArgsBuffer;
2108 
2109   // Decompose the UnqualifiedId into the following data.
2110   DeclarationNameInfo NameInfo;
2111   const TemplateArgumentListInfo *TemplateArgs;
2112   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2113 
2114   DeclarationName Name = NameInfo.getName();
2115   IdentifierInfo *II = Name.getAsIdentifierInfo();
2116   SourceLocation NameLoc = NameInfo.getLoc();
2117 
2118   // C++ [temp.dep.expr]p3:
2119   //   An id-expression is type-dependent if it contains:
2120   //     -- an identifier that was declared with a dependent type,
2121   //        (note: handled after lookup)
2122   //     -- a template-id that is dependent,
2123   //        (note: handled in BuildTemplateIdExpr)
2124   //     -- a conversion-function-id that specifies a dependent type,
2125   //     -- a nested-name-specifier that contains a class-name that
2126   //        names a dependent type.
2127   // Determine whether this is a member of an unknown specialization;
2128   // we need to handle these differently.
2129   bool DependentID = false;
2130   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2131       Name.getCXXNameType()->isDependentType()) {
2132     DependentID = true;
2133   } else if (SS.isSet()) {
2134     if (DeclContext *DC = computeDeclContext(SS, false)) {
2135       if (RequireCompleteDeclContext(SS, DC))
2136         return ExprError();
2137     } else {
2138       DependentID = true;
2139     }
2140   }
2141 
2142   if (DependentID)
2143     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2144                                       IsAddressOfOperand, TemplateArgs);
2145 
2146   // Perform the required lookup.
2147   LookupResult R(*this, NameInfo,
2148                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2149                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2150   if (TemplateArgs) {
2151     // Lookup the template name again to correctly establish the context in
2152     // which it was found. This is really unfortunate as we already did the
2153     // lookup to determine that it was a template name in the first place. If
2154     // this becomes a performance hit, we can work harder to preserve those
2155     // results until we get here but it's likely not worth it.
2156     bool MemberOfUnknownSpecialization;
2157     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2158                        MemberOfUnknownSpecialization);
2159 
2160     if (MemberOfUnknownSpecialization ||
2161         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2162       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2163                                         IsAddressOfOperand, TemplateArgs);
2164   } else {
2165     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2166     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2167 
2168     // If the result might be in a dependent base class, this is a dependent
2169     // id-expression.
2170     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2171       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2172                                         IsAddressOfOperand, TemplateArgs);
2173 
2174     // If this reference is in an Objective-C method, then we need to do
2175     // some special Objective-C lookup, too.
2176     if (IvarLookupFollowUp) {
2177       ExprResult E(LookupInObjCMethod(R, S, II, true));
2178       if (E.isInvalid())
2179         return ExprError();
2180 
2181       if (Expr *Ex = E.getAs<Expr>())
2182         return Ex;
2183     }
2184   }
2185 
2186   if (R.isAmbiguous())
2187     return ExprError();
2188 
2189   // This could be an implicitly declared function reference (legal in C90,
2190   // extension in C99, forbidden in C++).
2191   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2192     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2193     if (D) R.addDecl(D);
2194   }
2195 
2196   // Determine whether this name might be a candidate for
2197   // argument-dependent lookup.
2198   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2199 
2200   if (R.empty() && !ADL) {
2201     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2202       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2203                                                    TemplateKWLoc, TemplateArgs))
2204         return E;
2205     }
2206 
2207     // Don't diagnose an empty lookup for inline assembly.
2208     if (IsInlineAsmIdentifier)
2209       return ExprError();
2210 
2211     // If this name wasn't predeclared and if this is not a function
2212     // call, diagnose the problem.
2213     TypoExpr *TE = nullptr;
2214     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2215         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2216     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2217     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2218            "Typo correction callback misconfigured");
2219     if (CCC) {
2220       // Make sure the callback knows what the typo being diagnosed is.
2221       CCC->setTypoName(II);
2222       if (SS.isValid())
2223         CCC->setTypoNNS(SS.getScopeRep());
2224     }
2225     if (DiagnoseEmptyLookup(S, SS, R,
2226                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2227                             nullptr, None, &TE)) {
2228       if (TE && KeywordReplacement) {
2229         auto &State = getTypoExprState(TE);
2230         auto BestTC = State.Consumer->getNextCorrection();
2231         if (BestTC.isKeyword()) {
2232           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2233           if (State.DiagHandler)
2234             State.DiagHandler(BestTC);
2235           KeywordReplacement->startToken();
2236           KeywordReplacement->setKind(II->getTokenID());
2237           KeywordReplacement->setIdentifierInfo(II);
2238           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2239           // Clean up the state associated with the TypoExpr, since it has
2240           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2241           clearDelayedTypo(TE);
2242           // Signal that a correction to a keyword was performed by returning a
2243           // valid-but-null ExprResult.
2244           return (Expr*)nullptr;
2245         }
2246         State.Consumer->resetCorrectionStream();
2247       }
2248       return TE ? TE : ExprError();
2249     }
2250 
2251     assert(!R.empty() &&
2252            "DiagnoseEmptyLookup returned false but added no results");
2253 
2254     // If we found an Objective-C instance variable, let
2255     // LookupInObjCMethod build the appropriate expression to
2256     // reference the ivar.
2257     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2258       R.clear();
2259       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2260       // In a hopelessly buggy code, Objective-C instance variable
2261       // lookup fails and no expression will be built to reference it.
2262       if (!E.isInvalid() && !E.get())
2263         return ExprError();
2264       return E;
2265     }
2266   }
2267 
2268   // This is guaranteed from this point on.
2269   assert(!R.empty() || ADL);
2270 
2271   // Check whether this might be a C++ implicit instance member access.
2272   // C++ [class.mfct.non-static]p3:
2273   //   When an id-expression that is not part of a class member access
2274   //   syntax and not used to form a pointer to member is used in the
2275   //   body of a non-static member function of class X, if name lookup
2276   //   resolves the name in the id-expression to a non-static non-type
2277   //   member of some class C, the id-expression is transformed into a
2278   //   class member access expression using (*this) as the
2279   //   postfix-expression to the left of the . operator.
2280   //
2281   // But we don't actually need to do this for '&' operands if R
2282   // resolved to a function or overloaded function set, because the
2283   // expression is ill-formed if it actually works out to be a
2284   // non-static member function:
2285   //
2286   // C++ [expr.ref]p4:
2287   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2288   //   [t]he expression can be used only as the left-hand operand of a
2289   //   member function call.
2290   //
2291   // There are other safeguards against such uses, but it's important
2292   // to get this right here so that we don't end up making a
2293   // spuriously dependent expression if we're inside a dependent
2294   // instance method.
2295   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2296     bool MightBeImplicitMember;
2297     if (!IsAddressOfOperand)
2298       MightBeImplicitMember = true;
2299     else if (!SS.isEmpty())
2300       MightBeImplicitMember = false;
2301     else if (R.isOverloadedResult())
2302       MightBeImplicitMember = false;
2303     else if (R.isUnresolvableResult())
2304       MightBeImplicitMember = true;
2305     else
2306       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2307                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2308                               isa<MSPropertyDecl>(R.getFoundDecl());
2309 
2310     if (MightBeImplicitMember)
2311       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2312                                              R, TemplateArgs, S);
2313   }
2314 
2315   if (TemplateArgs || TemplateKWLoc.isValid()) {
2316 
2317     // In C++1y, if this is a variable template id, then check it
2318     // in BuildTemplateIdExpr().
2319     // The single lookup result must be a variable template declaration.
2320     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2321         Id.TemplateId->Kind == TNK_Var_template) {
2322       assert(R.getAsSingle<VarTemplateDecl>() &&
2323              "There should only be one declaration found.");
2324     }
2325 
2326     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2327   }
2328 
2329   return BuildDeclarationNameExpr(SS, R, ADL);
2330 }
2331 
2332 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2333 /// declaration name, generally during template instantiation.
2334 /// There's a large number of things which don't need to be done along
2335 /// this path.
2336 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2337     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2338     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2339   DeclContext *DC = computeDeclContext(SS, false);
2340   if (!DC)
2341     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2342                                      NameInfo, /*TemplateArgs=*/nullptr);
2343 
2344   if (RequireCompleteDeclContext(SS, DC))
2345     return ExprError();
2346 
2347   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2348   LookupQualifiedName(R, DC);
2349 
2350   if (R.isAmbiguous())
2351     return ExprError();
2352 
2353   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2354     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2355                                      NameInfo, /*TemplateArgs=*/nullptr);
2356 
2357   if (R.empty()) {
2358     Diag(NameInfo.getLoc(), diag::err_no_member)
2359       << NameInfo.getName() << DC << SS.getRange();
2360     return ExprError();
2361   }
2362 
2363   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2364     // Diagnose a missing typename if this resolved unambiguously to a type in
2365     // a dependent context.  If we can recover with a type, downgrade this to
2366     // a warning in Microsoft compatibility mode.
2367     unsigned DiagID = diag::err_typename_missing;
2368     if (RecoveryTSI && getLangOpts().MSVCCompat)
2369       DiagID = diag::ext_typename_missing;
2370     SourceLocation Loc = SS.getBeginLoc();
2371     auto D = Diag(Loc, DiagID);
2372     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2373       << SourceRange(Loc, NameInfo.getEndLoc());
2374 
2375     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2376     // context.
2377     if (!RecoveryTSI)
2378       return ExprError();
2379 
2380     // Only issue the fixit if we're prepared to recover.
2381     D << FixItHint::CreateInsertion(Loc, "typename ");
2382 
2383     // Recover by pretending this was an elaborated type.
2384     QualType Ty = Context.getTypeDeclType(TD);
2385     TypeLocBuilder TLB;
2386     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2387 
2388     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2389     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2390     QTL.setElaboratedKeywordLoc(SourceLocation());
2391     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2392 
2393     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2394 
2395     return ExprEmpty();
2396   }
2397 
2398   // Defend against this resolving to an implicit member access. We usually
2399   // won't get here if this might be a legitimate a class member (we end up in
2400   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2401   // a pointer-to-member or in an unevaluated context in C++11.
2402   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2403     return BuildPossibleImplicitMemberExpr(SS,
2404                                            /*TemplateKWLoc=*/SourceLocation(),
2405                                            R, /*TemplateArgs=*/nullptr, S);
2406 
2407   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2408 }
2409 
2410 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2411 /// detected that we're currently inside an ObjC method.  Perform some
2412 /// additional lookup.
2413 ///
2414 /// Ideally, most of this would be done by lookup, but there's
2415 /// actually quite a lot of extra work involved.
2416 ///
2417 /// Returns a null sentinel to indicate trivial success.
2418 ExprResult
2419 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2420                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2421   SourceLocation Loc = Lookup.getNameLoc();
2422   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2423 
2424   // Check for error condition which is already reported.
2425   if (!CurMethod)
2426     return ExprError();
2427 
2428   // There are two cases to handle here.  1) scoped lookup could have failed,
2429   // in which case we should look for an ivar.  2) scoped lookup could have
2430   // found a decl, but that decl is outside the current instance method (i.e.
2431   // a global variable).  In these two cases, we do a lookup for an ivar with
2432   // this name, if the lookup sucedes, we replace it our current decl.
2433 
2434   // If we're in a class method, we don't normally want to look for
2435   // ivars.  But if we don't find anything else, and there's an
2436   // ivar, that's an error.
2437   bool IsClassMethod = CurMethod->isClassMethod();
2438 
2439   bool LookForIvars;
2440   if (Lookup.empty())
2441     LookForIvars = true;
2442   else if (IsClassMethod)
2443     LookForIvars = false;
2444   else
2445     LookForIvars = (Lookup.isSingleResult() &&
2446                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2447   ObjCInterfaceDecl *IFace = nullptr;
2448   if (LookForIvars) {
2449     IFace = CurMethod->getClassInterface();
2450     ObjCInterfaceDecl *ClassDeclared;
2451     ObjCIvarDecl *IV = nullptr;
2452     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2453       // Diagnose using an ivar in a class method.
2454       if (IsClassMethod)
2455         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2456                          << IV->getDeclName());
2457 
2458       // If we're referencing an invalid decl, just return this as a silent
2459       // error node.  The error diagnostic was already emitted on the decl.
2460       if (IV->isInvalidDecl())
2461         return ExprError();
2462 
2463       // Check if referencing a field with __attribute__((deprecated)).
2464       if (DiagnoseUseOfDecl(IV, Loc))
2465         return ExprError();
2466 
2467       // Diagnose the use of an ivar outside of the declaring class.
2468       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2469           !declaresSameEntity(ClassDeclared, IFace) &&
2470           !getLangOpts().DebuggerSupport)
2471         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2472 
2473       // FIXME: This should use a new expr for a direct reference, don't
2474       // turn this into Self->ivar, just return a BareIVarExpr or something.
2475       IdentifierInfo &II = Context.Idents.get("self");
2476       UnqualifiedId SelfName;
2477       SelfName.setIdentifier(&II, SourceLocation());
2478       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2479       CXXScopeSpec SelfScopeSpec;
2480       SourceLocation TemplateKWLoc;
2481       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2482                                               SelfName, false, false);
2483       if (SelfExpr.isInvalid())
2484         return ExprError();
2485 
2486       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2487       if (SelfExpr.isInvalid())
2488         return ExprError();
2489 
2490       MarkAnyDeclReferenced(Loc, IV, true);
2491 
2492       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2493       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2494           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2495         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2496 
2497       ObjCIvarRefExpr *Result = new (Context)
2498           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2499                           IV->getLocation(), SelfExpr.get(), true, true);
2500 
2501       if (getLangOpts().ObjCAutoRefCount) {
2502         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2503           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2504             recordUseOfEvaluatedWeak(Result);
2505         }
2506         if (CurContext->isClosure())
2507           Diag(Loc, diag::warn_implicitly_retains_self)
2508             << FixItHint::CreateInsertion(Loc, "self->");
2509       }
2510 
2511       return Result;
2512     }
2513   } else if (CurMethod->isInstanceMethod()) {
2514     // We should warn if a local variable hides an ivar.
2515     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2516       ObjCInterfaceDecl *ClassDeclared;
2517       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2518         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2519             declaresSameEntity(IFace, ClassDeclared))
2520           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2521       }
2522     }
2523   } else if (Lookup.isSingleResult() &&
2524              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2525     // If accessing a stand-alone ivar in a class method, this is an error.
2526     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2527       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2528                        << IV->getDeclName());
2529   }
2530 
2531   if (Lookup.empty() && II && AllowBuiltinCreation) {
2532     // FIXME. Consolidate this with similar code in LookupName.
2533     if (unsigned BuiltinID = II->getBuiltinID()) {
2534       if (!(getLangOpts().CPlusPlus &&
2535             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2536         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2537                                            S, Lookup.isForRedeclaration(),
2538                                            Lookup.getNameLoc());
2539         if (D) Lookup.addDecl(D);
2540       }
2541     }
2542   }
2543   // Sentinel value saying that we didn't do anything special.
2544   return ExprResult((Expr *)nullptr);
2545 }
2546 
2547 /// \brief Cast a base object to a member's actual type.
2548 ///
2549 /// Logically this happens in three phases:
2550 ///
2551 /// * First we cast from the base type to the naming class.
2552 ///   The naming class is the class into which we were looking
2553 ///   when we found the member;  it's the qualifier type if a
2554 ///   qualifier was provided, and otherwise it's the base type.
2555 ///
2556 /// * Next we cast from the naming class to the declaring class.
2557 ///   If the member we found was brought into a class's scope by
2558 ///   a using declaration, this is that class;  otherwise it's
2559 ///   the class declaring the member.
2560 ///
2561 /// * Finally we cast from the declaring class to the "true"
2562 ///   declaring class of the member.  This conversion does not
2563 ///   obey access control.
2564 ExprResult
2565 Sema::PerformObjectMemberConversion(Expr *From,
2566                                     NestedNameSpecifier *Qualifier,
2567                                     NamedDecl *FoundDecl,
2568                                     NamedDecl *Member) {
2569   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2570   if (!RD)
2571     return From;
2572 
2573   QualType DestRecordType;
2574   QualType DestType;
2575   QualType FromRecordType;
2576   QualType FromType = From->getType();
2577   bool PointerConversions = false;
2578   if (isa<FieldDecl>(Member)) {
2579     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2580 
2581     if (FromType->getAs<PointerType>()) {
2582       DestType = Context.getPointerType(DestRecordType);
2583       FromRecordType = FromType->getPointeeType();
2584       PointerConversions = true;
2585     } else {
2586       DestType = DestRecordType;
2587       FromRecordType = FromType;
2588     }
2589   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2590     if (Method->isStatic())
2591       return From;
2592 
2593     DestType = Method->getThisType(Context);
2594     DestRecordType = DestType->getPointeeType();
2595 
2596     if (FromType->getAs<PointerType>()) {
2597       FromRecordType = FromType->getPointeeType();
2598       PointerConversions = true;
2599     } else {
2600       FromRecordType = FromType;
2601       DestType = DestRecordType;
2602     }
2603   } else {
2604     // No conversion necessary.
2605     return From;
2606   }
2607 
2608   if (DestType->isDependentType() || FromType->isDependentType())
2609     return From;
2610 
2611   // If the unqualified types are the same, no conversion is necessary.
2612   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2613     return From;
2614 
2615   SourceRange FromRange = From->getSourceRange();
2616   SourceLocation FromLoc = FromRange.getBegin();
2617 
2618   ExprValueKind VK = From->getValueKind();
2619 
2620   // C++ [class.member.lookup]p8:
2621   //   [...] Ambiguities can often be resolved by qualifying a name with its
2622   //   class name.
2623   //
2624   // If the member was a qualified name and the qualified referred to a
2625   // specific base subobject type, we'll cast to that intermediate type
2626   // first and then to the object in which the member is declared. That allows
2627   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2628   //
2629   //   class Base { public: int x; };
2630   //   class Derived1 : public Base { };
2631   //   class Derived2 : public Base { };
2632   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2633   //
2634   //   void VeryDerived::f() {
2635   //     x = 17; // error: ambiguous base subobjects
2636   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2637   //   }
2638   if (Qualifier && Qualifier->getAsType()) {
2639     QualType QType = QualType(Qualifier->getAsType(), 0);
2640     assert(QType->isRecordType() && "lookup done with non-record type");
2641 
2642     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2643 
2644     // In C++98, the qualifier type doesn't actually have to be a base
2645     // type of the object type, in which case we just ignore it.
2646     // Otherwise build the appropriate casts.
2647     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2648       CXXCastPath BasePath;
2649       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2650                                        FromLoc, FromRange, &BasePath))
2651         return ExprError();
2652 
2653       if (PointerConversions)
2654         QType = Context.getPointerType(QType);
2655       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2656                                VK, &BasePath).get();
2657 
2658       FromType = QType;
2659       FromRecordType = QRecordType;
2660 
2661       // If the qualifier type was the same as the destination type,
2662       // we're done.
2663       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2664         return From;
2665     }
2666   }
2667 
2668   bool IgnoreAccess = false;
2669 
2670   // If we actually found the member through a using declaration, cast
2671   // down to the using declaration's type.
2672   //
2673   // Pointer equality is fine here because only one declaration of a
2674   // class ever has member declarations.
2675   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2676     assert(isa<UsingShadowDecl>(FoundDecl));
2677     QualType URecordType = Context.getTypeDeclType(
2678                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2679 
2680     // We only need to do this if the naming-class to declaring-class
2681     // conversion is non-trivial.
2682     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2683       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2684       CXXCastPath BasePath;
2685       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2686                                        FromLoc, FromRange, &BasePath))
2687         return ExprError();
2688 
2689       QualType UType = URecordType;
2690       if (PointerConversions)
2691         UType = Context.getPointerType(UType);
2692       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2693                                VK, &BasePath).get();
2694       FromType = UType;
2695       FromRecordType = URecordType;
2696     }
2697 
2698     // We don't do access control for the conversion from the
2699     // declaring class to the true declaring class.
2700     IgnoreAccess = true;
2701   }
2702 
2703   CXXCastPath BasePath;
2704   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2705                                    FromLoc, FromRange, &BasePath,
2706                                    IgnoreAccess))
2707     return ExprError();
2708 
2709   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2710                            VK, &BasePath);
2711 }
2712 
2713 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2714                                       const LookupResult &R,
2715                                       bool HasTrailingLParen) {
2716   // Only when used directly as the postfix-expression of a call.
2717   if (!HasTrailingLParen)
2718     return false;
2719 
2720   // Never if a scope specifier was provided.
2721   if (SS.isSet())
2722     return false;
2723 
2724   // Only in C++ or ObjC++.
2725   if (!getLangOpts().CPlusPlus)
2726     return false;
2727 
2728   // Turn off ADL when we find certain kinds of declarations during
2729   // normal lookup:
2730   for (NamedDecl *D : R) {
2731     // C++0x [basic.lookup.argdep]p3:
2732     //     -- a declaration of a class member
2733     // Since using decls preserve this property, we check this on the
2734     // original decl.
2735     if (D->isCXXClassMember())
2736       return false;
2737 
2738     // C++0x [basic.lookup.argdep]p3:
2739     //     -- a block-scope function declaration that is not a
2740     //        using-declaration
2741     // NOTE: we also trigger this for function templates (in fact, we
2742     // don't check the decl type at all, since all other decl types
2743     // turn off ADL anyway).
2744     if (isa<UsingShadowDecl>(D))
2745       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2746     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2747       return false;
2748 
2749     // C++0x [basic.lookup.argdep]p3:
2750     //     -- a declaration that is neither a function or a function
2751     //        template
2752     // And also for builtin functions.
2753     if (isa<FunctionDecl>(D)) {
2754       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2755 
2756       // But also builtin functions.
2757       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2758         return false;
2759     } else if (!isa<FunctionTemplateDecl>(D))
2760       return false;
2761   }
2762 
2763   return true;
2764 }
2765 
2766 
2767 /// Diagnoses obvious problems with the use of the given declaration
2768 /// as an expression.  This is only actually called for lookups that
2769 /// were not overloaded, and it doesn't promise that the declaration
2770 /// will in fact be used.
2771 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2772   if (isa<TypedefNameDecl>(D)) {
2773     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2774     return true;
2775   }
2776 
2777   if (isa<ObjCInterfaceDecl>(D)) {
2778     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2779     return true;
2780   }
2781 
2782   if (isa<NamespaceDecl>(D)) {
2783     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2784     return true;
2785   }
2786 
2787   return false;
2788 }
2789 
2790 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2791                                           LookupResult &R, bool NeedsADL,
2792                                           bool AcceptInvalidDecl) {
2793   // If this is a single, fully-resolved result and we don't need ADL,
2794   // just build an ordinary singleton decl ref.
2795   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2796     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2797                                     R.getRepresentativeDecl(), nullptr,
2798                                     AcceptInvalidDecl);
2799 
2800   // We only need to check the declaration if there's exactly one
2801   // result, because in the overloaded case the results can only be
2802   // functions and function templates.
2803   if (R.isSingleResult() &&
2804       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2805     return ExprError();
2806 
2807   // Otherwise, just build an unresolved lookup expression.  Suppress
2808   // any lookup-related diagnostics; we'll hash these out later, when
2809   // we've picked a target.
2810   R.suppressDiagnostics();
2811 
2812   UnresolvedLookupExpr *ULE
2813     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2814                                    SS.getWithLocInContext(Context),
2815                                    R.getLookupNameInfo(),
2816                                    NeedsADL, R.isOverloadedResult(),
2817                                    R.begin(), R.end());
2818 
2819   return ULE;
2820 }
2821 
2822 static void
2823 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2824                                    ValueDecl *var, DeclContext *DC);
2825 
2826 /// \brief Complete semantic analysis for a reference to the given declaration.
2827 ExprResult Sema::BuildDeclarationNameExpr(
2828     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2829     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2830     bool AcceptInvalidDecl) {
2831   assert(D && "Cannot refer to a NULL declaration");
2832   assert(!isa<FunctionTemplateDecl>(D) &&
2833          "Cannot refer unambiguously to a function template");
2834 
2835   SourceLocation Loc = NameInfo.getLoc();
2836   if (CheckDeclInExpr(*this, Loc, D))
2837     return ExprError();
2838 
2839   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2840     // Specifically diagnose references to class templates that are missing
2841     // a template argument list.
2842     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2843                                            << Template << SS.getRange();
2844     Diag(Template->getLocation(), diag::note_template_decl_here);
2845     return ExprError();
2846   }
2847 
2848   // Make sure that we're referring to a value.
2849   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2850   if (!VD) {
2851     Diag(Loc, diag::err_ref_non_value)
2852       << D << SS.getRange();
2853     Diag(D->getLocation(), diag::note_declared_at);
2854     return ExprError();
2855   }
2856 
2857   // Check whether this declaration can be used. Note that we suppress
2858   // this check when we're going to perform argument-dependent lookup
2859   // on this function name, because this might not be the function
2860   // that overload resolution actually selects.
2861   if (DiagnoseUseOfDecl(VD, Loc))
2862     return ExprError();
2863 
2864   // Only create DeclRefExpr's for valid Decl's.
2865   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2866     return ExprError();
2867 
2868   // Handle members of anonymous structs and unions.  If we got here,
2869   // and the reference is to a class member indirect field, then this
2870   // must be the subject of a pointer-to-member expression.
2871   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2872     if (!indirectField->isCXXClassMember())
2873       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2874                                                       indirectField);
2875 
2876   {
2877     QualType type = VD->getType();
2878     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2879       // C++ [except.spec]p17:
2880       //   An exception-specification is considered to be needed when:
2881       //   - in an expression, the function is the unique lookup result or
2882       //     the selected member of a set of overloaded functions.
2883       ResolveExceptionSpec(Loc, FPT);
2884       type = VD->getType();
2885     }
2886     ExprValueKind valueKind = VK_RValue;
2887 
2888     switch (D->getKind()) {
2889     // Ignore all the non-ValueDecl kinds.
2890 #define ABSTRACT_DECL(kind)
2891 #define VALUE(type, base)
2892 #define DECL(type, base) \
2893     case Decl::type:
2894 #include "clang/AST/DeclNodes.inc"
2895       llvm_unreachable("invalid value decl kind");
2896 
2897     // These shouldn't make it here.
2898     case Decl::ObjCAtDefsField:
2899     case Decl::ObjCIvar:
2900       llvm_unreachable("forming non-member reference to ivar?");
2901 
2902     // Enum constants are always r-values and never references.
2903     // Unresolved using declarations are dependent.
2904     case Decl::EnumConstant:
2905     case Decl::UnresolvedUsingValue:
2906     case Decl::OMPDeclareReduction:
2907       valueKind = VK_RValue;
2908       break;
2909 
2910     // Fields and indirect fields that got here must be for
2911     // pointer-to-member expressions; we just call them l-values for
2912     // internal consistency, because this subexpression doesn't really
2913     // exist in the high-level semantics.
2914     case Decl::Field:
2915     case Decl::IndirectField:
2916       assert(getLangOpts().CPlusPlus &&
2917              "building reference to field in C?");
2918 
2919       // These can't have reference type in well-formed programs, but
2920       // for internal consistency we do this anyway.
2921       type = type.getNonReferenceType();
2922       valueKind = VK_LValue;
2923       break;
2924 
2925     // Non-type template parameters are either l-values or r-values
2926     // depending on the type.
2927     case Decl::NonTypeTemplateParm: {
2928       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2929         type = reftype->getPointeeType();
2930         valueKind = VK_LValue; // even if the parameter is an r-value reference
2931         break;
2932       }
2933 
2934       // For non-references, we need to strip qualifiers just in case
2935       // the template parameter was declared as 'const int' or whatever.
2936       valueKind = VK_RValue;
2937       type = type.getUnqualifiedType();
2938       break;
2939     }
2940 
2941     case Decl::Var:
2942     case Decl::VarTemplateSpecialization:
2943     case Decl::VarTemplatePartialSpecialization:
2944     case Decl::Decomposition:
2945     case Decl::OMPCapturedExpr:
2946       // In C, "extern void blah;" is valid and is an r-value.
2947       if (!getLangOpts().CPlusPlus &&
2948           !type.hasQualifiers() &&
2949           type->isVoidType()) {
2950         valueKind = VK_RValue;
2951         break;
2952       }
2953       // fallthrough
2954 
2955     case Decl::ImplicitParam:
2956     case Decl::ParmVar: {
2957       // These are always l-values.
2958       valueKind = VK_LValue;
2959       type = type.getNonReferenceType();
2960 
2961       // FIXME: Does the addition of const really only apply in
2962       // potentially-evaluated contexts? Since the variable isn't actually
2963       // captured in an unevaluated context, it seems that the answer is no.
2964       if (!isUnevaluatedContext()) {
2965         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2966         if (!CapturedType.isNull())
2967           type = CapturedType;
2968       }
2969 
2970       break;
2971     }
2972 
2973     case Decl::Binding: {
2974       // These are always lvalues.
2975       valueKind = VK_LValue;
2976       type = type.getNonReferenceType();
2977       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2978       // decides how that's supposed to work.
2979       auto *BD = cast<BindingDecl>(VD);
2980       if (BD->getDeclContext()->isFunctionOrMethod() &&
2981           BD->getDeclContext() != CurContext)
2982         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2983       break;
2984     }
2985 
2986     case Decl::Function: {
2987       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2988         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2989           type = Context.BuiltinFnTy;
2990           valueKind = VK_RValue;
2991           break;
2992         }
2993       }
2994 
2995       const FunctionType *fty = type->castAs<FunctionType>();
2996 
2997       // If we're referring to a function with an __unknown_anytype
2998       // result type, make the entire expression __unknown_anytype.
2999       if (fty->getReturnType() == Context.UnknownAnyTy) {
3000         type = Context.UnknownAnyTy;
3001         valueKind = VK_RValue;
3002         break;
3003       }
3004 
3005       // Functions are l-values in C++.
3006       if (getLangOpts().CPlusPlus) {
3007         valueKind = VK_LValue;
3008         break;
3009       }
3010 
3011       // C99 DR 316 says that, if a function type comes from a
3012       // function definition (without a prototype), that type is only
3013       // used for checking compatibility. Therefore, when referencing
3014       // the function, we pretend that we don't have the full function
3015       // type.
3016       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3017           isa<FunctionProtoType>(fty))
3018         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3019                                               fty->getExtInfo());
3020 
3021       // Functions are r-values in C.
3022       valueKind = VK_RValue;
3023       break;
3024     }
3025 
3026     case Decl::MSProperty:
3027       valueKind = VK_LValue;
3028       break;
3029 
3030     case Decl::CXXMethod:
3031       // If we're referring to a method with an __unknown_anytype
3032       // result type, make the entire expression __unknown_anytype.
3033       // This should only be possible with a type written directly.
3034       if (const FunctionProtoType *proto
3035             = dyn_cast<FunctionProtoType>(VD->getType()))
3036         if (proto->getReturnType() == Context.UnknownAnyTy) {
3037           type = Context.UnknownAnyTy;
3038           valueKind = VK_RValue;
3039           break;
3040         }
3041 
3042       // C++ methods are l-values if static, r-values if non-static.
3043       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3044         valueKind = VK_LValue;
3045         break;
3046       }
3047       // fallthrough
3048 
3049     case Decl::CXXConversion:
3050     case Decl::CXXDestructor:
3051     case Decl::CXXConstructor:
3052       valueKind = VK_RValue;
3053       break;
3054     }
3055 
3056     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3057                             TemplateArgs);
3058   }
3059 }
3060 
3061 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3062                                     SmallString<32> &Target) {
3063   Target.resize(CharByteWidth * (Source.size() + 1));
3064   char *ResultPtr = &Target[0];
3065   const llvm::UTF8 *ErrorPtr;
3066   bool success =
3067       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3068   (void)success;
3069   assert(success);
3070   Target.resize(ResultPtr - &Target[0]);
3071 }
3072 
3073 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3074                                      PredefinedExpr::IdentType IT) {
3075   // Pick the current block, lambda, captured statement or function.
3076   Decl *currentDecl = nullptr;
3077   if (const BlockScopeInfo *BSI = getCurBlock())
3078     currentDecl = BSI->TheDecl;
3079   else if (const LambdaScopeInfo *LSI = getCurLambda())
3080     currentDecl = LSI->CallOperator;
3081   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3082     currentDecl = CSI->TheCapturedDecl;
3083   else
3084     currentDecl = getCurFunctionOrMethodDecl();
3085 
3086   if (!currentDecl) {
3087     Diag(Loc, diag::ext_predef_outside_function);
3088     currentDecl = Context.getTranslationUnitDecl();
3089   }
3090 
3091   QualType ResTy;
3092   StringLiteral *SL = nullptr;
3093   if (cast<DeclContext>(currentDecl)->isDependentContext())
3094     ResTy = Context.DependentTy;
3095   else {
3096     // Pre-defined identifiers are of type char[x], where x is the length of
3097     // the string.
3098     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3099     unsigned Length = Str.length();
3100 
3101     llvm::APInt LengthI(32, Length + 1);
3102     if (IT == PredefinedExpr::LFunction) {
3103       ResTy = Context.WideCharTy.withConst();
3104       SmallString<32> RawChars;
3105       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3106                               Str, RawChars);
3107       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3108                                            /*IndexTypeQuals*/ 0);
3109       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3110                                  /*Pascal*/ false, ResTy, Loc);
3111     } else {
3112       ResTy = Context.CharTy.withConst();
3113       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3114                                            /*IndexTypeQuals*/ 0);
3115       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3116                                  /*Pascal*/ false, ResTy, Loc);
3117     }
3118   }
3119 
3120   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3121 }
3122 
3123 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3124   PredefinedExpr::IdentType IT;
3125 
3126   switch (Kind) {
3127   default: llvm_unreachable("Unknown simple primary expr!");
3128   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3129   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3130   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3131   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3132   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3133   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3134   }
3135 
3136   return BuildPredefinedExpr(Loc, IT);
3137 }
3138 
3139 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3140   SmallString<16> CharBuffer;
3141   bool Invalid = false;
3142   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3143   if (Invalid)
3144     return ExprError();
3145 
3146   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3147                             PP, Tok.getKind());
3148   if (Literal.hadError())
3149     return ExprError();
3150 
3151   QualType Ty;
3152   if (Literal.isWide())
3153     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3154   else if (Literal.isUTF16())
3155     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3156   else if (Literal.isUTF32())
3157     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3158   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3159     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3160   else
3161     Ty = Context.CharTy;  // 'x' -> char in C++
3162 
3163   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3164   if (Literal.isWide())
3165     Kind = CharacterLiteral::Wide;
3166   else if (Literal.isUTF16())
3167     Kind = CharacterLiteral::UTF16;
3168   else if (Literal.isUTF32())
3169     Kind = CharacterLiteral::UTF32;
3170   else if (Literal.isUTF8())
3171     Kind = CharacterLiteral::UTF8;
3172 
3173   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3174                                              Tok.getLocation());
3175 
3176   if (Literal.getUDSuffix().empty())
3177     return Lit;
3178 
3179   // We're building a user-defined literal.
3180   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3181   SourceLocation UDSuffixLoc =
3182     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3183 
3184   // Make sure we're allowed user-defined literals here.
3185   if (!UDLScope)
3186     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3187 
3188   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3189   //   operator "" X (ch)
3190   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3191                                         Lit, Tok.getLocation());
3192 }
3193 
3194 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3195   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3196   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3197                                 Context.IntTy, Loc);
3198 }
3199 
3200 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3201                                   QualType Ty, SourceLocation Loc) {
3202   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3203 
3204   using llvm::APFloat;
3205   APFloat Val(Format);
3206 
3207   APFloat::opStatus result = Literal.GetFloatValue(Val);
3208 
3209   // Overflow is always an error, but underflow is only an error if
3210   // we underflowed to zero (APFloat reports denormals as underflow).
3211   if ((result & APFloat::opOverflow) ||
3212       ((result & APFloat::opUnderflow) && Val.isZero())) {
3213     unsigned diagnostic;
3214     SmallString<20> buffer;
3215     if (result & APFloat::opOverflow) {
3216       diagnostic = diag::warn_float_overflow;
3217       APFloat::getLargest(Format).toString(buffer);
3218     } else {
3219       diagnostic = diag::warn_float_underflow;
3220       APFloat::getSmallest(Format).toString(buffer);
3221     }
3222 
3223     S.Diag(Loc, diagnostic)
3224       << Ty
3225       << StringRef(buffer.data(), buffer.size());
3226   }
3227 
3228   bool isExact = (result == APFloat::opOK);
3229   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3230 }
3231 
3232 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3233   assert(E && "Invalid expression");
3234 
3235   if (E->isValueDependent())
3236     return false;
3237 
3238   QualType QT = E->getType();
3239   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3240     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3241     return true;
3242   }
3243 
3244   llvm::APSInt ValueAPS;
3245   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3246 
3247   if (R.isInvalid())
3248     return true;
3249 
3250   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3251   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3252     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3253         << ValueAPS.toString(10) << ValueIsPositive;
3254     return true;
3255   }
3256 
3257   return false;
3258 }
3259 
3260 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3261   // Fast path for a single digit (which is quite common).  A single digit
3262   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3263   if (Tok.getLength() == 1) {
3264     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3265     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3266   }
3267 
3268   SmallString<128> SpellingBuffer;
3269   // NumericLiteralParser wants to overread by one character.  Add padding to
3270   // the buffer in case the token is copied to the buffer.  If getSpelling()
3271   // returns a StringRef to the memory buffer, it should have a null char at
3272   // the EOF, so it is also safe.
3273   SpellingBuffer.resize(Tok.getLength() + 1);
3274 
3275   // Get the spelling of the token, which eliminates trigraphs, etc.
3276   bool Invalid = false;
3277   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3278   if (Invalid)
3279     return ExprError();
3280 
3281   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3282   if (Literal.hadError)
3283     return ExprError();
3284 
3285   if (Literal.hasUDSuffix()) {
3286     // We're building a user-defined literal.
3287     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3288     SourceLocation UDSuffixLoc =
3289       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3290 
3291     // Make sure we're allowed user-defined literals here.
3292     if (!UDLScope)
3293       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3294 
3295     QualType CookedTy;
3296     if (Literal.isFloatingLiteral()) {
3297       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3298       // long double, the literal is treated as a call of the form
3299       //   operator "" X (f L)
3300       CookedTy = Context.LongDoubleTy;
3301     } else {
3302       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3303       // unsigned long long, the literal is treated as a call of the form
3304       //   operator "" X (n ULL)
3305       CookedTy = Context.UnsignedLongLongTy;
3306     }
3307 
3308     DeclarationName OpName =
3309       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3310     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3311     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3312 
3313     SourceLocation TokLoc = Tok.getLocation();
3314 
3315     // Perform literal operator lookup to determine if we're building a raw
3316     // literal or a cooked one.
3317     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3318     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3319                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3320                                   /*AllowStringTemplate*/false)) {
3321     case LOLR_Error:
3322       return ExprError();
3323 
3324     case LOLR_Cooked: {
3325       Expr *Lit;
3326       if (Literal.isFloatingLiteral()) {
3327         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3328       } else {
3329         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3330         if (Literal.GetIntegerValue(ResultVal))
3331           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3332               << /* Unsigned */ 1;
3333         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3334                                      Tok.getLocation());
3335       }
3336       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3337     }
3338 
3339     case LOLR_Raw: {
3340       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3341       // literal is treated as a call of the form
3342       //   operator "" X ("n")
3343       unsigned Length = Literal.getUDSuffixOffset();
3344       QualType StrTy = Context.getConstantArrayType(
3345           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3346           ArrayType::Normal, 0);
3347       Expr *Lit = StringLiteral::Create(
3348           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3349           /*Pascal*/false, StrTy, &TokLoc, 1);
3350       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3351     }
3352 
3353     case LOLR_Template: {
3354       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3355       // template), L is treated as a call fo the form
3356       //   operator "" X <'c1', 'c2', ... 'ck'>()
3357       // where n is the source character sequence c1 c2 ... ck.
3358       TemplateArgumentListInfo ExplicitArgs;
3359       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3360       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3361       llvm::APSInt Value(CharBits, CharIsUnsigned);
3362       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3363         Value = TokSpelling[I];
3364         TemplateArgument Arg(Context, Value, Context.CharTy);
3365         TemplateArgumentLocInfo ArgInfo;
3366         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3367       }
3368       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3369                                       &ExplicitArgs);
3370     }
3371     case LOLR_StringTemplate:
3372       llvm_unreachable("unexpected literal operator lookup result");
3373     }
3374   }
3375 
3376   Expr *Res;
3377 
3378   if (Literal.isFloatingLiteral()) {
3379     QualType Ty;
3380     if (Literal.isHalf){
3381       if (getOpenCLOptions().cl_khr_fp16)
3382         Ty = Context.HalfTy;
3383       else {
3384         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3385         return ExprError();
3386       }
3387     } else if (Literal.isFloat)
3388       Ty = Context.FloatTy;
3389     else if (Literal.isLong)
3390       Ty = Context.LongDoubleTy;
3391     else if (Literal.isFloat128)
3392       Ty = Context.Float128Ty;
3393     else
3394       Ty = Context.DoubleTy;
3395 
3396     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3397 
3398     if (Ty == Context.DoubleTy) {
3399       if (getLangOpts().SinglePrecisionConstants) {
3400         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3401       } else if (getLangOpts().OpenCL &&
3402                  !((getLangOpts().OpenCLVersion >= 120) ||
3403                    getOpenCLOptions().cl_khr_fp64)) {
3404         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3405         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3406       }
3407     }
3408   } else if (!Literal.isIntegerLiteral()) {
3409     return ExprError();
3410   } else {
3411     QualType Ty;
3412 
3413     // 'long long' is a C99 or C++11 feature.
3414     if (!getLangOpts().C99 && Literal.isLongLong) {
3415       if (getLangOpts().CPlusPlus)
3416         Diag(Tok.getLocation(),
3417              getLangOpts().CPlusPlus11 ?
3418              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3419       else
3420         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3421     }
3422 
3423     // Get the value in the widest-possible width.
3424     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3425     llvm::APInt ResultVal(MaxWidth, 0);
3426 
3427     if (Literal.GetIntegerValue(ResultVal)) {
3428       // If this value didn't fit into uintmax_t, error and force to ull.
3429       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3430           << /* Unsigned */ 1;
3431       Ty = Context.UnsignedLongLongTy;
3432       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3433              "long long is not intmax_t?");
3434     } else {
3435       // If this value fits into a ULL, try to figure out what else it fits into
3436       // according to the rules of C99 6.4.4.1p5.
3437 
3438       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3439       // be an unsigned int.
3440       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3441 
3442       // Check from smallest to largest, picking the smallest type we can.
3443       unsigned Width = 0;
3444 
3445       // Microsoft specific integer suffixes are explicitly sized.
3446       if (Literal.MicrosoftInteger) {
3447         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3448           Width = 8;
3449           Ty = Context.CharTy;
3450         } else {
3451           Width = Literal.MicrosoftInteger;
3452           Ty = Context.getIntTypeForBitwidth(Width,
3453                                              /*Signed=*/!Literal.isUnsigned);
3454         }
3455       }
3456 
3457       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3458         // Are int/unsigned possibilities?
3459         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3460 
3461         // Does it fit in a unsigned int?
3462         if (ResultVal.isIntN(IntSize)) {
3463           // Does it fit in a signed int?
3464           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3465             Ty = Context.IntTy;
3466           else if (AllowUnsigned)
3467             Ty = Context.UnsignedIntTy;
3468           Width = IntSize;
3469         }
3470       }
3471 
3472       // Are long/unsigned long possibilities?
3473       if (Ty.isNull() && !Literal.isLongLong) {
3474         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3475 
3476         // Does it fit in a unsigned long?
3477         if (ResultVal.isIntN(LongSize)) {
3478           // Does it fit in a signed long?
3479           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3480             Ty = Context.LongTy;
3481           else if (AllowUnsigned)
3482             Ty = Context.UnsignedLongTy;
3483           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3484           // is compatible.
3485           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3486             const unsigned LongLongSize =
3487                 Context.getTargetInfo().getLongLongWidth();
3488             Diag(Tok.getLocation(),
3489                  getLangOpts().CPlusPlus
3490                      ? Literal.isLong
3491                            ? diag::warn_old_implicitly_unsigned_long_cxx
3492                            : /*C++98 UB*/ diag::
3493                                  ext_old_implicitly_unsigned_long_cxx
3494                      : diag::warn_old_implicitly_unsigned_long)
3495                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3496                                             : /*will be ill-formed*/ 1);
3497             Ty = Context.UnsignedLongTy;
3498           }
3499           Width = LongSize;
3500         }
3501       }
3502 
3503       // Check long long if needed.
3504       if (Ty.isNull()) {
3505         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3506 
3507         // Does it fit in a unsigned long long?
3508         if (ResultVal.isIntN(LongLongSize)) {
3509           // Does it fit in a signed long long?
3510           // To be compatible with MSVC, hex integer literals ending with the
3511           // LL or i64 suffix are always signed in Microsoft mode.
3512           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3513               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3514             Ty = Context.LongLongTy;
3515           else if (AllowUnsigned)
3516             Ty = Context.UnsignedLongLongTy;
3517           Width = LongLongSize;
3518         }
3519       }
3520 
3521       // If we still couldn't decide a type, we probably have something that
3522       // does not fit in a signed long long, but has no U suffix.
3523       if (Ty.isNull()) {
3524         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3525         Ty = Context.UnsignedLongLongTy;
3526         Width = Context.getTargetInfo().getLongLongWidth();
3527       }
3528 
3529       if (ResultVal.getBitWidth() != Width)
3530         ResultVal = ResultVal.trunc(Width);
3531     }
3532     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3533   }
3534 
3535   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3536   if (Literal.isImaginary)
3537     Res = new (Context) ImaginaryLiteral(Res,
3538                                         Context.getComplexType(Res->getType()));
3539 
3540   return Res;
3541 }
3542 
3543 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3544   assert(E && "ActOnParenExpr() missing expr");
3545   return new (Context) ParenExpr(L, R, E);
3546 }
3547 
3548 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3549                                          SourceLocation Loc,
3550                                          SourceRange ArgRange) {
3551   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3552   // scalar or vector data type argument..."
3553   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3554   // type (C99 6.2.5p18) or void.
3555   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3556     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3557       << T << ArgRange;
3558     return true;
3559   }
3560 
3561   assert((T->isVoidType() || !T->isIncompleteType()) &&
3562          "Scalar types should always be complete");
3563   return false;
3564 }
3565 
3566 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3567                                            SourceLocation Loc,
3568                                            SourceRange ArgRange,
3569                                            UnaryExprOrTypeTrait TraitKind) {
3570   // Invalid types must be hard errors for SFINAE in C++.
3571   if (S.LangOpts.CPlusPlus)
3572     return true;
3573 
3574   // C99 6.5.3.4p1:
3575   if (T->isFunctionType() &&
3576       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3577     // sizeof(function)/alignof(function) is allowed as an extension.
3578     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3579       << TraitKind << ArgRange;
3580     return false;
3581   }
3582 
3583   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3584   // this is an error (OpenCL v1.1 s6.3.k)
3585   if (T->isVoidType()) {
3586     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3587                                         : diag::ext_sizeof_alignof_void_type;
3588     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3589     return false;
3590   }
3591 
3592   return true;
3593 }
3594 
3595 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3596                                              SourceLocation Loc,
3597                                              SourceRange ArgRange,
3598                                              UnaryExprOrTypeTrait TraitKind) {
3599   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3600   // runtime doesn't allow it.
3601   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3602     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3603       << T << (TraitKind == UETT_SizeOf)
3604       << ArgRange;
3605     return true;
3606   }
3607 
3608   return false;
3609 }
3610 
3611 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3612 /// pointer type is equal to T) and emit a warning if it is.
3613 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3614                                      Expr *E) {
3615   // Don't warn if the operation changed the type.
3616   if (T != E->getType())
3617     return;
3618 
3619   // Now look for array decays.
3620   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3621   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3622     return;
3623 
3624   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3625                                              << ICE->getType()
3626                                              << ICE->getSubExpr()->getType();
3627 }
3628 
3629 /// \brief Check the constraints on expression operands to unary type expression
3630 /// and type traits.
3631 ///
3632 /// Completes any types necessary and validates the constraints on the operand
3633 /// expression. The logic mostly mirrors the type-based overload, but may modify
3634 /// the expression as it completes the type for that expression through template
3635 /// instantiation, etc.
3636 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3637                                             UnaryExprOrTypeTrait ExprKind) {
3638   QualType ExprTy = E->getType();
3639   assert(!ExprTy->isReferenceType());
3640 
3641   if (ExprKind == UETT_VecStep)
3642     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3643                                         E->getSourceRange());
3644 
3645   // Whitelist some types as extensions
3646   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3647                                       E->getSourceRange(), ExprKind))
3648     return false;
3649 
3650   // 'alignof' applied to an expression only requires the base element type of
3651   // the expression to be complete. 'sizeof' requires the expression's type to
3652   // be complete (and will attempt to complete it if it's an array of unknown
3653   // bound).
3654   if (ExprKind == UETT_AlignOf) {
3655     if (RequireCompleteType(E->getExprLoc(),
3656                             Context.getBaseElementType(E->getType()),
3657                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3658                             E->getSourceRange()))
3659       return true;
3660   } else {
3661     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3662                                 ExprKind, E->getSourceRange()))
3663       return true;
3664   }
3665 
3666   // Completing the expression's type may have changed it.
3667   ExprTy = E->getType();
3668   assert(!ExprTy->isReferenceType());
3669 
3670   if (ExprTy->isFunctionType()) {
3671     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3672       << ExprKind << E->getSourceRange();
3673     return true;
3674   }
3675 
3676   // The operand for sizeof and alignof is in an unevaluated expression context,
3677   // so side effects could result in unintended consequences.
3678   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3679       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3680     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3681 
3682   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3683                                        E->getSourceRange(), ExprKind))
3684     return true;
3685 
3686   if (ExprKind == UETT_SizeOf) {
3687     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3688       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3689         QualType OType = PVD->getOriginalType();
3690         QualType Type = PVD->getType();
3691         if (Type->isPointerType() && OType->isArrayType()) {
3692           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3693             << Type << OType;
3694           Diag(PVD->getLocation(), diag::note_declared_at);
3695         }
3696       }
3697     }
3698 
3699     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3700     // decays into a pointer and returns an unintended result. This is most
3701     // likely a typo for "sizeof(array) op x".
3702     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3703       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3704                                BO->getLHS());
3705       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3706                                BO->getRHS());
3707     }
3708   }
3709 
3710   return false;
3711 }
3712 
3713 /// \brief Check the constraints on operands to unary expression and type
3714 /// traits.
3715 ///
3716 /// This will complete any types necessary, and validate the various constraints
3717 /// on those operands.
3718 ///
3719 /// The UsualUnaryConversions() function is *not* called by this routine.
3720 /// C99 6.3.2.1p[2-4] all state:
3721 ///   Except when it is the operand of the sizeof operator ...
3722 ///
3723 /// C++ [expr.sizeof]p4
3724 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3725 ///   standard conversions are not applied to the operand of sizeof.
3726 ///
3727 /// This policy is followed for all of the unary trait expressions.
3728 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3729                                             SourceLocation OpLoc,
3730                                             SourceRange ExprRange,
3731                                             UnaryExprOrTypeTrait ExprKind) {
3732   if (ExprType->isDependentType())
3733     return false;
3734 
3735   // C++ [expr.sizeof]p2:
3736   //     When applied to a reference or a reference type, the result
3737   //     is the size of the referenced type.
3738   // C++11 [expr.alignof]p3:
3739   //     When alignof is applied to a reference type, the result
3740   //     shall be the alignment of the referenced type.
3741   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3742     ExprType = Ref->getPointeeType();
3743 
3744   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3745   //   When alignof or _Alignof is applied to an array type, the result
3746   //   is the alignment of the element type.
3747   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3748     ExprType = Context.getBaseElementType(ExprType);
3749 
3750   if (ExprKind == UETT_VecStep)
3751     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3752 
3753   // Whitelist some types as extensions
3754   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3755                                       ExprKind))
3756     return false;
3757 
3758   if (RequireCompleteType(OpLoc, ExprType,
3759                           diag::err_sizeof_alignof_incomplete_type,
3760                           ExprKind, ExprRange))
3761     return true;
3762 
3763   if (ExprType->isFunctionType()) {
3764     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3765       << ExprKind << ExprRange;
3766     return true;
3767   }
3768 
3769   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3770                                        ExprKind))
3771     return true;
3772 
3773   return false;
3774 }
3775 
3776 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3777   E = E->IgnoreParens();
3778 
3779   // Cannot know anything else if the expression is dependent.
3780   if (E->isTypeDependent())
3781     return false;
3782 
3783   if (E->getObjectKind() == OK_BitField) {
3784     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3785        << 1 << E->getSourceRange();
3786     return true;
3787   }
3788 
3789   ValueDecl *D = nullptr;
3790   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3791     D = DRE->getDecl();
3792   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3793     D = ME->getMemberDecl();
3794   }
3795 
3796   // If it's a field, require the containing struct to have a
3797   // complete definition so that we can compute the layout.
3798   //
3799   // This can happen in C++11 onwards, either by naming the member
3800   // in a way that is not transformed into a member access expression
3801   // (in an unevaluated operand, for instance), or by naming the member
3802   // in a trailing-return-type.
3803   //
3804   // For the record, since __alignof__ on expressions is a GCC
3805   // extension, GCC seems to permit this but always gives the
3806   // nonsensical answer 0.
3807   //
3808   // We don't really need the layout here --- we could instead just
3809   // directly check for all the appropriate alignment-lowing
3810   // attributes --- but that would require duplicating a lot of
3811   // logic that just isn't worth duplicating for such a marginal
3812   // use-case.
3813   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3814     // Fast path this check, since we at least know the record has a
3815     // definition if we can find a member of it.
3816     if (!FD->getParent()->isCompleteDefinition()) {
3817       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3818         << E->getSourceRange();
3819       return true;
3820     }
3821 
3822     // Otherwise, if it's a field, and the field doesn't have
3823     // reference type, then it must have a complete type (or be a
3824     // flexible array member, which we explicitly want to
3825     // white-list anyway), which makes the following checks trivial.
3826     if (!FD->getType()->isReferenceType())
3827       return false;
3828   }
3829 
3830   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3831 }
3832 
3833 bool Sema::CheckVecStepExpr(Expr *E) {
3834   E = E->IgnoreParens();
3835 
3836   // Cannot know anything else if the expression is dependent.
3837   if (E->isTypeDependent())
3838     return false;
3839 
3840   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3841 }
3842 
3843 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3844                                         CapturingScopeInfo *CSI) {
3845   assert(T->isVariablyModifiedType());
3846   assert(CSI != nullptr);
3847 
3848   // We're going to walk down into the type and look for VLA expressions.
3849   do {
3850     const Type *Ty = T.getTypePtr();
3851     switch (Ty->getTypeClass()) {
3852 #define TYPE(Class, Base)
3853 #define ABSTRACT_TYPE(Class, Base)
3854 #define NON_CANONICAL_TYPE(Class, Base)
3855 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3856 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3857 #include "clang/AST/TypeNodes.def"
3858       T = QualType();
3859       break;
3860     // These types are never variably-modified.
3861     case Type::Builtin:
3862     case Type::Complex:
3863     case Type::Vector:
3864     case Type::ExtVector:
3865     case Type::Record:
3866     case Type::Enum:
3867     case Type::Elaborated:
3868     case Type::TemplateSpecialization:
3869     case Type::ObjCObject:
3870     case Type::ObjCInterface:
3871     case Type::ObjCObjectPointer:
3872     case Type::ObjCTypeParam:
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     if (Inst.isAlreadyInstantiating()) {
4543       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4544       Param->setInvalidDecl();
4545       return ExprError();
4546     }
4547 
4548     ExprResult Result;
4549     {
4550       // C++ [dcl.fct.default]p5:
4551       //   The names in the [default argument] expression are bound, and
4552       //   the semantic constraints are checked, at the point where the
4553       //   default argument expression appears.
4554       ContextRAII SavedContext(*this, FD);
4555       LocalInstantiationScope Local(*this);
4556       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4557                                 /*DirectInit*/false);
4558     }
4559     if (Result.isInvalid())
4560       return ExprError();
4561 
4562     // Check the expression as an initializer for the parameter.
4563     InitializedEntity Entity
4564       = InitializedEntity::InitializeParameter(Context, Param);
4565     InitializationKind Kind
4566       = InitializationKind::CreateCopy(Param->getLocation(),
4567              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4568     Expr *ResultE = Result.getAs<Expr>();
4569 
4570     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4571     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4572     if (Result.isInvalid())
4573       return ExprError();
4574 
4575     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4576                                  Param->getOuterLocStart());
4577     if (Result.isInvalid())
4578       return ExprError();
4579 
4580     // Remember the instantiated default argument.
4581     Param->setDefaultArg(Result.getAs<Expr>());
4582     if (ASTMutationListener *L = getASTMutationListener()) {
4583       L->DefaultArgumentInstantiated(Param);
4584     }
4585   }
4586 
4587   // If the default argument expression is not set yet, we are building it now.
4588   if (!Param->hasInit()) {
4589     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4590     Param->setInvalidDecl();
4591     return ExprError();
4592   }
4593 
4594   // If the default expression creates temporaries, we need to
4595   // push them to the current stack of expression temporaries so they'll
4596   // be properly destroyed.
4597   // FIXME: We should really be rebuilding the default argument with new
4598   // bound temporaries; see the comment in PR5810.
4599   // We don't need to do that with block decls, though, because
4600   // blocks in default argument expression can never capture anything.
4601   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4602     // Set the "needs cleanups" bit regardless of whether there are
4603     // any explicit objects.
4604     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4605 
4606     // Append all the objects to the cleanup list.  Right now, this
4607     // should always be a no-op, because blocks in default argument
4608     // expressions should never be able to capture anything.
4609     assert(!Init->getNumObjects() &&
4610            "default argument expression has capturing blocks?");
4611   }
4612 
4613   // We already type-checked the argument, so we know it works.
4614   // Just mark all of the declarations in this potentially-evaluated expression
4615   // as being "referenced".
4616   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4617                                    /*SkipLocalVariables=*/true);
4618   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4619 }
4620 
4621 
4622 Sema::VariadicCallType
4623 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4624                           Expr *Fn) {
4625   if (Proto && Proto->isVariadic()) {
4626     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4627       return VariadicConstructor;
4628     else if (Fn && Fn->getType()->isBlockPointerType())
4629       return VariadicBlock;
4630     else if (FDecl) {
4631       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4632         if (Method->isInstance())
4633           return VariadicMethod;
4634     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4635       return VariadicMethod;
4636     return VariadicFunction;
4637   }
4638   return VariadicDoesNotApply;
4639 }
4640 
4641 namespace {
4642 class FunctionCallCCC : public FunctionCallFilterCCC {
4643 public:
4644   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4645                   unsigned NumArgs, MemberExpr *ME)
4646       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4647         FunctionName(FuncName) {}
4648 
4649   bool ValidateCandidate(const TypoCorrection &candidate) override {
4650     if (!candidate.getCorrectionSpecifier() ||
4651         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4652       return false;
4653     }
4654 
4655     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4656   }
4657 
4658 private:
4659   const IdentifierInfo *const FunctionName;
4660 };
4661 }
4662 
4663 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4664                                                FunctionDecl *FDecl,
4665                                                ArrayRef<Expr *> Args) {
4666   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4667   DeclarationName FuncName = FDecl->getDeclName();
4668   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4669 
4670   if (TypoCorrection Corrected = S.CorrectTypo(
4671           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4672           S.getScopeForContext(S.CurContext), nullptr,
4673           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4674                                              Args.size(), ME),
4675           Sema::CTK_ErrorRecovery)) {
4676     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4677       if (Corrected.isOverloaded()) {
4678         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4679         OverloadCandidateSet::iterator Best;
4680         for (NamedDecl *CD : Corrected) {
4681           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4682             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4683                                    OCS);
4684         }
4685         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4686         case OR_Success:
4687           ND = Best->FoundDecl;
4688           Corrected.setCorrectionDecl(ND);
4689           break;
4690         default:
4691           break;
4692         }
4693       }
4694       ND = ND->getUnderlyingDecl();
4695       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4696         return Corrected;
4697     }
4698   }
4699   return TypoCorrection();
4700 }
4701 
4702 /// ConvertArgumentsForCall - Converts the arguments specified in
4703 /// Args/NumArgs to the parameter types of the function FDecl with
4704 /// function prototype Proto. Call is the call expression itself, and
4705 /// Fn is the function expression. For a C++ member function, this
4706 /// routine does not attempt to convert the object argument. Returns
4707 /// true if the call is ill-formed.
4708 bool
4709 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4710                               FunctionDecl *FDecl,
4711                               const FunctionProtoType *Proto,
4712                               ArrayRef<Expr *> Args,
4713                               SourceLocation RParenLoc,
4714                               bool IsExecConfig) {
4715   // Bail out early if calling a builtin with custom typechecking.
4716   if (FDecl)
4717     if (unsigned ID = FDecl->getBuiltinID())
4718       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4719         return false;
4720 
4721   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4722   // assignment, to the types of the corresponding parameter, ...
4723   unsigned NumParams = Proto->getNumParams();
4724   bool Invalid = false;
4725   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4726   unsigned FnKind = Fn->getType()->isBlockPointerType()
4727                        ? 1 /* block */
4728                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4729                                        : 0 /* function */);
4730 
4731   // If too few arguments are available (and we don't have default
4732   // arguments for the remaining parameters), don't make the call.
4733   if (Args.size() < NumParams) {
4734     if (Args.size() < MinArgs) {
4735       TypoCorrection TC;
4736       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4737         unsigned diag_id =
4738             MinArgs == NumParams && !Proto->isVariadic()
4739                 ? diag::err_typecheck_call_too_few_args_suggest
4740                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4741         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4742                                         << static_cast<unsigned>(Args.size())
4743                                         << TC.getCorrectionRange());
4744       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4745         Diag(RParenLoc,
4746              MinArgs == NumParams && !Proto->isVariadic()
4747                  ? diag::err_typecheck_call_too_few_args_one
4748                  : diag::err_typecheck_call_too_few_args_at_least_one)
4749             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4750       else
4751         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4752                             ? diag::err_typecheck_call_too_few_args
4753                             : diag::err_typecheck_call_too_few_args_at_least)
4754             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4755             << Fn->getSourceRange();
4756 
4757       // Emit the location of the prototype.
4758       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4759         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4760           << FDecl;
4761 
4762       return true;
4763     }
4764     Call->setNumArgs(Context, NumParams);
4765   }
4766 
4767   // If too many are passed and not variadic, error on the extras and drop
4768   // them.
4769   if (Args.size() > NumParams) {
4770     if (!Proto->isVariadic()) {
4771       TypoCorrection TC;
4772       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4773         unsigned diag_id =
4774             MinArgs == NumParams && !Proto->isVariadic()
4775                 ? diag::err_typecheck_call_too_many_args_suggest
4776                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4777         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4778                                         << static_cast<unsigned>(Args.size())
4779                                         << TC.getCorrectionRange());
4780       } else if (NumParams == 1 && FDecl &&
4781                  FDecl->getParamDecl(0)->getDeclName())
4782         Diag(Args[NumParams]->getLocStart(),
4783              MinArgs == NumParams
4784                  ? diag::err_typecheck_call_too_many_args_one
4785                  : diag::err_typecheck_call_too_many_args_at_most_one)
4786             << FnKind << FDecl->getParamDecl(0)
4787             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4788             << SourceRange(Args[NumParams]->getLocStart(),
4789                            Args.back()->getLocEnd());
4790       else
4791         Diag(Args[NumParams]->getLocStart(),
4792              MinArgs == NumParams
4793                  ? diag::err_typecheck_call_too_many_args
4794                  : diag::err_typecheck_call_too_many_args_at_most)
4795             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4796             << Fn->getSourceRange()
4797             << SourceRange(Args[NumParams]->getLocStart(),
4798                            Args.back()->getLocEnd());
4799 
4800       // Emit the location of the prototype.
4801       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4802         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4803           << FDecl;
4804 
4805       // This deletes the extra arguments.
4806       Call->setNumArgs(Context, NumParams);
4807       return true;
4808     }
4809   }
4810   SmallVector<Expr *, 8> AllArgs;
4811   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4812 
4813   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4814                                    Proto, 0, Args, AllArgs, CallType);
4815   if (Invalid)
4816     return true;
4817   unsigned TotalNumArgs = AllArgs.size();
4818   for (unsigned i = 0; i < TotalNumArgs; ++i)
4819     Call->setArg(i, AllArgs[i]);
4820 
4821   return false;
4822 }
4823 
4824 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4825                                   const FunctionProtoType *Proto,
4826                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4827                                   SmallVectorImpl<Expr *> &AllArgs,
4828                                   VariadicCallType CallType, bool AllowExplicit,
4829                                   bool IsListInitialization) {
4830   unsigned NumParams = Proto->getNumParams();
4831   bool Invalid = false;
4832   size_t ArgIx = 0;
4833   // Continue to check argument types (even if we have too few/many args).
4834   for (unsigned i = FirstParam; i < NumParams; i++) {
4835     QualType ProtoArgType = Proto->getParamType(i);
4836 
4837     Expr *Arg;
4838     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4839     if (ArgIx < Args.size()) {
4840       Arg = Args[ArgIx++];
4841 
4842       if (RequireCompleteType(Arg->getLocStart(),
4843                               ProtoArgType,
4844                               diag::err_call_incomplete_argument, Arg))
4845         return true;
4846 
4847       // Strip the unbridged-cast placeholder expression off, if applicable.
4848       bool CFAudited = false;
4849       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4850           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4851           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4852         Arg = stripARCUnbridgedCast(Arg);
4853       else if (getLangOpts().ObjCAutoRefCount &&
4854                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4855                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4856         CFAudited = true;
4857 
4858       InitializedEntity Entity =
4859           Param ? InitializedEntity::InitializeParameter(Context, Param,
4860                                                          ProtoArgType)
4861                 : InitializedEntity::InitializeParameter(
4862                       Context, ProtoArgType, Proto->isParamConsumed(i));
4863 
4864       // Remember that parameter belongs to a CF audited API.
4865       if (CFAudited)
4866         Entity.setParameterCFAudited();
4867 
4868       ExprResult ArgE = PerformCopyInitialization(
4869           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4870       if (ArgE.isInvalid())
4871         return true;
4872 
4873       Arg = ArgE.getAs<Expr>();
4874     } else {
4875       assert(Param && "can't use default arguments without a known callee");
4876 
4877       ExprResult ArgExpr =
4878         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4879       if (ArgExpr.isInvalid())
4880         return true;
4881 
4882       Arg = ArgExpr.getAs<Expr>();
4883     }
4884 
4885     // Check for array bounds violations for each argument to the call. This
4886     // check only triggers warnings when the argument isn't a more complex Expr
4887     // with its own checking, such as a BinaryOperator.
4888     CheckArrayAccess(Arg);
4889 
4890     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4891     CheckStaticArrayArgument(CallLoc, Param, Arg);
4892 
4893     AllArgs.push_back(Arg);
4894   }
4895 
4896   // If this is a variadic call, handle args passed through "...".
4897   if (CallType != VariadicDoesNotApply) {
4898     // Assume that extern "C" functions with variadic arguments that
4899     // return __unknown_anytype aren't *really* variadic.
4900     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4901         FDecl->isExternC()) {
4902       for (Expr *A : Args.slice(ArgIx)) {
4903         QualType paramType; // ignored
4904         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4905         Invalid |= arg.isInvalid();
4906         AllArgs.push_back(arg.get());
4907       }
4908 
4909     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4910     } else {
4911       for (Expr *A : Args.slice(ArgIx)) {
4912         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4913         Invalid |= Arg.isInvalid();
4914         AllArgs.push_back(Arg.get());
4915       }
4916     }
4917 
4918     // Check for array bounds violations.
4919     for (Expr *A : Args.slice(ArgIx))
4920       CheckArrayAccess(A);
4921   }
4922   return Invalid;
4923 }
4924 
4925 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4926   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4927   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4928     TL = DTL.getOriginalLoc();
4929   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4930     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4931       << ATL.getLocalSourceRange();
4932 }
4933 
4934 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4935 /// array parameter, check that it is non-null, and that if it is formed by
4936 /// array-to-pointer decay, the underlying array is sufficiently large.
4937 ///
4938 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4939 /// array type derivation, then for each call to the function, the value of the
4940 /// corresponding actual argument shall provide access to the first element of
4941 /// an array with at least as many elements as specified by the size expression.
4942 void
4943 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4944                                ParmVarDecl *Param,
4945                                const Expr *ArgExpr) {
4946   // Static array parameters are not supported in C++.
4947   if (!Param || getLangOpts().CPlusPlus)
4948     return;
4949 
4950   QualType OrigTy = Param->getOriginalType();
4951 
4952   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4953   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4954     return;
4955 
4956   if (ArgExpr->isNullPointerConstant(Context,
4957                                      Expr::NPC_NeverValueDependent)) {
4958     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4959     DiagnoseCalleeStaticArrayParam(*this, Param);
4960     return;
4961   }
4962 
4963   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4964   if (!CAT)
4965     return;
4966 
4967   const ConstantArrayType *ArgCAT =
4968     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4969   if (!ArgCAT)
4970     return;
4971 
4972   if (ArgCAT->getSize().ult(CAT->getSize())) {
4973     Diag(CallLoc, diag::warn_static_array_too_small)
4974       << ArgExpr->getSourceRange()
4975       << (unsigned) ArgCAT->getSize().getZExtValue()
4976       << (unsigned) CAT->getSize().getZExtValue();
4977     DiagnoseCalleeStaticArrayParam(*this, Param);
4978   }
4979 }
4980 
4981 /// Given a function expression of unknown-any type, try to rebuild it
4982 /// to have a function type.
4983 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4984 
4985 /// Is the given type a placeholder that we need to lower out
4986 /// immediately during argument processing?
4987 static bool isPlaceholderToRemoveAsArg(QualType type) {
4988   // Placeholders are never sugared.
4989   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4990   if (!placeholder) return false;
4991 
4992   switch (placeholder->getKind()) {
4993   // Ignore all the non-placeholder types.
4994 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4995   case BuiltinType::Id:
4996 #include "clang/Basic/OpenCLImageTypes.def"
4997 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4998 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4999 #include "clang/AST/BuiltinTypes.def"
5000     return false;
5001 
5002   // We cannot lower out overload sets; they might validly be resolved
5003   // by the call machinery.
5004   case BuiltinType::Overload:
5005     return false;
5006 
5007   // Unbridged casts in ARC can be handled in some call positions and
5008   // should be left in place.
5009   case BuiltinType::ARCUnbridgedCast:
5010     return false;
5011 
5012   // Pseudo-objects should be converted as soon as possible.
5013   case BuiltinType::PseudoObject:
5014     return true;
5015 
5016   // The debugger mode could theoretically but currently does not try
5017   // to resolve unknown-typed arguments based on known parameter types.
5018   case BuiltinType::UnknownAny:
5019     return true;
5020 
5021   // These are always invalid as call arguments and should be reported.
5022   case BuiltinType::BoundMember:
5023   case BuiltinType::BuiltinFn:
5024   case BuiltinType::OMPArraySection:
5025     return true;
5026 
5027   }
5028   llvm_unreachable("bad builtin type kind");
5029 }
5030 
5031 /// Check an argument list for placeholders that we won't try to
5032 /// handle later.
5033 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5034   // Apply this processing to all the arguments at once instead of
5035   // dying at the first failure.
5036   bool hasInvalid = false;
5037   for (size_t i = 0, e = args.size(); i != e; i++) {
5038     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5039       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5040       if (result.isInvalid()) hasInvalid = true;
5041       else args[i] = result.get();
5042     } else if (hasInvalid) {
5043       (void)S.CorrectDelayedTyposInExpr(args[i]);
5044     }
5045   }
5046   return hasInvalid;
5047 }
5048 
5049 /// If a builtin function has a pointer argument with no explicit address
5050 /// space, then it should be able to accept a pointer to any address
5051 /// space as input.  In order to do this, we need to replace the
5052 /// standard builtin declaration with one that uses the same address space
5053 /// as the call.
5054 ///
5055 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5056 ///                  it does not contain any pointer arguments without
5057 ///                  an address space qualifer.  Otherwise the rewritten
5058 ///                  FunctionDecl is returned.
5059 /// TODO: Handle pointer return types.
5060 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5061                                                 const FunctionDecl *FDecl,
5062                                                 MultiExprArg ArgExprs) {
5063 
5064   QualType DeclType = FDecl->getType();
5065   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5066 
5067   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5068       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5069     return nullptr;
5070 
5071   bool NeedsNewDecl = false;
5072   unsigned i = 0;
5073   SmallVector<QualType, 8> OverloadParams;
5074 
5075   for (QualType ParamType : FT->param_types()) {
5076 
5077     // Convert array arguments to pointer to simplify type lookup.
5078     ExprResult ArgRes =
5079         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5080     if (ArgRes.isInvalid())
5081       return nullptr;
5082     Expr *Arg = ArgRes.get();
5083     QualType ArgType = Arg->getType();
5084     if (!ParamType->isPointerType() ||
5085         ParamType.getQualifiers().hasAddressSpace() ||
5086         !ArgType->isPointerType() ||
5087         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5088       OverloadParams.push_back(ParamType);
5089       continue;
5090     }
5091 
5092     NeedsNewDecl = true;
5093     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5094 
5095     QualType PointeeType = ParamType->getPointeeType();
5096     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5097     OverloadParams.push_back(Context.getPointerType(PointeeType));
5098   }
5099 
5100   if (!NeedsNewDecl)
5101     return nullptr;
5102 
5103   FunctionProtoType::ExtProtoInfo EPI;
5104   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5105                                                 OverloadParams, EPI);
5106   DeclContext *Parent = Context.getTranslationUnitDecl();
5107   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5108                                                     FDecl->getLocation(),
5109                                                     FDecl->getLocation(),
5110                                                     FDecl->getIdentifier(),
5111                                                     OverloadTy,
5112                                                     /*TInfo=*/nullptr,
5113                                                     SC_Extern, false,
5114                                                     /*hasPrototype=*/true);
5115   SmallVector<ParmVarDecl*, 16> Params;
5116   FT = cast<FunctionProtoType>(OverloadTy);
5117   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5118     QualType ParamType = FT->getParamType(i);
5119     ParmVarDecl *Parm =
5120         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5121                                 SourceLocation(), nullptr, ParamType,
5122                                 /*TInfo=*/nullptr, SC_None, nullptr);
5123     Parm->setScopeInfo(0, i);
5124     Params.push_back(Parm);
5125   }
5126   OverloadDecl->setParams(Params);
5127   return OverloadDecl;
5128 }
5129 
5130 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5131                                        std::size_t NumArgs) {
5132   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5133                          /*PartialOverloading=*/false))
5134     return Callee->isVariadic();
5135   return Callee->getMinRequiredArguments() <= NumArgs;
5136 }
5137 
5138 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5139 /// This provides the location of the left/right parens and a list of comma
5140 /// locations.
5141 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5142                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5143                                Expr *ExecConfig, bool IsExecConfig) {
5144   // Since this might be a postfix expression, get rid of ParenListExprs.
5145   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5146   if (Result.isInvalid()) return ExprError();
5147   Fn = Result.get();
5148 
5149   if (checkArgsForPlaceholders(*this, ArgExprs))
5150     return ExprError();
5151 
5152   if (getLangOpts().CPlusPlus) {
5153     // If this is a pseudo-destructor expression, build the call immediately.
5154     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5155       if (!ArgExprs.empty()) {
5156         // Pseudo-destructor calls should not have any arguments.
5157         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5158             << FixItHint::CreateRemoval(
5159                    SourceRange(ArgExprs.front()->getLocStart(),
5160                                ArgExprs.back()->getLocEnd()));
5161       }
5162 
5163       return new (Context)
5164           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5165     }
5166     if (Fn->getType() == Context.PseudoObjectTy) {
5167       ExprResult result = CheckPlaceholderExpr(Fn);
5168       if (result.isInvalid()) return ExprError();
5169       Fn = result.get();
5170     }
5171 
5172     // Determine whether this is a dependent call inside a C++ template,
5173     // in which case we won't do any semantic analysis now.
5174     bool Dependent = false;
5175     if (Fn->isTypeDependent())
5176       Dependent = true;
5177     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5178       Dependent = true;
5179 
5180     if (Dependent) {
5181       if (ExecConfig) {
5182         return new (Context) CUDAKernelCallExpr(
5183             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5184             Context.DependentTy, VK_RValue, RParenLoc);
5185       } else {
5186         return new (Context) CallExpr(
5187             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5188       }
5189     }
5190 
5191     // Determine whether this is a call to an object (C++ [over.call.object]).
5192     if (Fn->getType()->isRecordType())
5193       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5194                                           RParenLoc);
5195 
5196     if (Fn->getType() == Context.UnknownAnyTy) {
5197       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5198       if (result.isInvalid()) return ExprError();
5199       Fn = result.get();
5200     }
5201 
5202     if (Fn->getType() == Context.BoundMemberTy) {
5203       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5204                                        RParenLoc);
5205     }
5206   }
5207 
5208   // Check for overloaded calls.  This can happen even in C due to extensions.
5209   if (Fn->getType() == Context.OverloadTy) {
5210     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5211 
5212     // We aren't supposed to apply this logic for if there'Scope an '&'
5213     // involved.
5214     if (!find.HasFormOfMemberPointer) {
5215       OverloadExpr *ovl = find.Expression;
5216       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5217         return BuildOverloadedCallExpr(
5218             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5219             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5220       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5221                                        RParenLoc);
5222     }
5223   }
5224 
5225   // If we're directly calling a function, get the appropriate declaration.
5226   if (Fn->getType() == Context.UnknownAnyTy) {
5227     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5228     if (result.isInvalid()) return ExprError();
5229     Fn = result.get();
5230   }
5231 
5232   Expr *NakedFn = Fn->IgnoreParens();
5233 
5234   bool CallingNDeclIndirectly = false;
5235   NamedDecl *NDecl = nullptr;
5236   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5237     if (UnOp->getOpcode() == UO_AddrOf) {
5238       CallingNDeclIndirectly = true;
5239       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5240     }
5241   }
5242 
5243   if (isa<DeclRefExpr>(NakedFn)) {
5244     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5245 
5246     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5247     if (FDecl && FDecl->getBuiltinID()) {
5248       // Rewrite the function decl for this builtin by replacing parameters
5249       // with no explicit address space with the address space of the arguments
5250       // in ArgExprs.
5251       if ((FDecl =
5252                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5253         NDecl = FDecl;
5254         Fn = DeclRefExpr::Create(
5255             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5256             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5257       }
5258     }
5259   } else if (isa<MemberExpr>(NakedFn))
5260     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5261 
5262   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5263     if (CallingNDeclIndirectly &&
5264         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5265                                            Fn->getLocStart()))
5266       return ExprError();
5267 
5268     // CheckEnableIf assumes that the we're passing in a sane number of args for
5269     // FD, but that doesn't always hold true here. This is because, in some
5270     // cases, we'll emit a diag about an ill-formed function call, but then
5271     // we'll continue on as if the function call wasn't ill-formed. So, if the
5272     // number of args looks incorrect, don't do enable_if checks; we should've
5273     // already emitted an error about the bad call.
5274     if (FD->hasAttr<EnableIfAttr>() &&
5275         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5276       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5277         Diag(Fn->getLocStart(),
5278              isa<CXXMethodDecl>(FD)
5279                  ? diag::err_ovl_no_viable_member_function_in_call
5280                  : diag::err_ovl_no_viable_function_in_call)
5281             << FD << FD->getSourceRange();
5282         Diag(FD->getLocation(),
5283              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5284             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5285       }
5286     }
5287   }
5288 
5289   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5290                                ExecConfig, IsExecConfig);
5291 }
5292 
5293 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5294 ///
5295 /// __builtin_astype( value, dst type )
5296 ///
5297 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5298                                  SourceLocation BuiltinLoc,
5299                                  SourceLocation RParenLoc) {
5300   ExprValueKind VK = VK_RValue;
5301   ExprObjectKind OK = OK_Ordinary;
5302   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5303   QualType SrcTy = E->getType();
5304   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5305     return ExprError(Diag(BuiltinLoc,
5306                           diag::err_invalid_astype_of_different_size)
5307                      << DstTy
5308                      << SrcTy
5309                      << E->getSourceRange());
5310   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5311 }
5312 
5313 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5314 /// provided arguments.
5315 ///
5316 /// __builtin_convertvector( value, dst type )
5317 ///
5318 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5319                                         SourceLocation BuiltinLoc,
5320                                         SourceLocation RParenLoc) {
5321   TypeSourceInfo *TInfo;
5322   GetTypeFromParser(ParsedDestTy, &TInfo);
5323   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5324 }
5325 
5326 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5327 /// i.e. an expression not of \p OverloadTy.  The expression should
5328 /// unary-convert to an expression of function-pointer or
5329 /// block-pointer type.
5330 ///
5331 /// \param NDecl the declaration being called, if available
5332 ExprResult
5333 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5334                             SourceLocation LParenLoc,
5335                             ArrayRef<Expr *> Args,
5336                             SourceLocation RParenLoc,
5337                             Expr *Config, bool IsExecConfig) {
5338   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5339   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5340 
5341   // Functions with 'interrupt' attribute cannot be called directly.
5342   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5343     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5344     return ExprError();
5345   }
5346 
5347   // Promote the function operand.
5348   // We special-case function promotion here because we only allow promoting
5349   // builtin functions to function pointers in the callee of a call.
5350   ExprResult Result;
5351   if (BuiltinID &&
5352       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5353     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5354                                CK_BuiltinFnToFnPtr).get();
5355   } else {
5356     Result = CallExprUnaryConversions(Fn);
5357   }
5358   if (Result.isInvalid())
5359     return ExprError();
5360   Fn = Result.get();
5361 
5362   // Make the call expr early, before semantic checks.  This guarantees cleanup
5363   // of arguments and function on error.
5364   CallExpr *TheCall;
5365   if (Config)
5366     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5367                                                cast<CallExpr>(Config), Args,
5368                                                Context.BoolTy, VK_RValue,
5369                                                RParenLoc);
5370   else
5371     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5372                                      VK_RValue, RParenLoc);
5373 
5374   if (!getLangOpts().CPlusPlus) {
5375     // C cannot always handle TypoExpr nodes in builtin calls and direct
5376     // function calls as their argument checking don't necessarily handle
5377     // dependent types properly, so make sure any TypoExprs have been
5378     // dealt with.
5379     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5380     if (!Result.isUsable()) return ExprError();
5381     TheCall = dyn_cast<CallExpr>(Result.get());
5382     if (!TheCall) return Result;
5383     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5384   }
5385 
5386   // Bail out early if calling a builtin with custom typechecking.
5387   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5388     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5389 
5390  retry:
5391   const FunctionType *FuncT;
5392   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5393     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5394     // have type pointer to function".
5395     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5396     if (!FuncT)
5397       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5398                          << Fn->getType() << Fn->getSourceRange());
5399   } else if (const BlockPointerType *BPT =
5400                Fn->getType()->getAs<BlockPointerType>()) {
5401     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5402   } else {
5403     // Handle calls to expressions of unknown-any type.
5404     if (Fn->getType() == Context.UnknownAnyTy) {
5405       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5406       if (rewrite.isInvalid()) return ExprError();
5407       Fn = rewrite.get();
5408       TheCall->setCallee(Fn);
5409       goto retry;
5410     }
5411 
5412     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5413       << Fn->getType() << Fn->getSourceRange());
5414   }
5415 
5416   if (getLangOpts().CUDA) {
5417     if (Config) {
5418       // CUDA: Kernel calls must be to global functions
5419       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5420         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5421             << FDecl->getName() << Fn->getSourceRange());
5422 
5423       // CUDA: Kernel function must have 'void' return type
5424       if (!FuncT->getReturnType()->isVoidType())
5425         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5426             << Fn->getType() << Fn->getSourceRange());
5427     } else {
5428       // CUDA: Calls to global functions must be configured
5429       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5430         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5431             << FDecl->getName() << Fn->getSourceRange());
5432     }
5433   }
5434 
5435   // Check for a valid return type
5436   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5437                           FDecl))
5438     return ExprError();
5439 
5440   // We know the result type of the call, set it.
5441   TheCall->setType(FuncT->getCallResultType(Context));
5442   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5443 
5444   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5445   if (Proto) {
5446     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5447                                 IsExecConfig))
5448       return ExprError();
5449   } else {
5450     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5451 
5452     if (FDecl) {
5453       // Check if we have too few/too many template arguments, based
5454       // on our knowledge of the function definition.
5455       const FunctionDecl *Def = nullptr;
5456       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5457         Proto = Def->getType()->getAs<FunctionProtoType>();
5458        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5459           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5460           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5461       }
5462 
5463       // If the function we're calling isn't a function prototype, but we have
5464       // a function prototype from a prior declaratiom, use that prototype.
5465       if (!FDecl->hasPrototype())
5466         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5467     }
5468 
5469     // Promote the arguments (C99 6.5.2.2p6).
5470     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5471       Expr *Arg = Args[i];
5472 
5473       if (Proto && i < Proto->getNumParams()) {
5474         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5475             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5476         ExprResult ArgE =
5477             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5478         if (ArgE.isInvalid())
5479           return true;
5480 
5481         Arg = ArgE.getAs<Expr>();
5482 
5483       } else {
5484         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5485 
5486         if (ArgE.isInvalid())
5487           return true;
5488 
5489         Arg = ArgE.getAs<Expr>();
5490       }
5491 
5492       if (RequireCompleteType(Arg->getLocStart(),
5493                               Arg->getType(),
5494                               diag::err_call_incomplete_argument, Arg))
5495         return ExprError();
5496 
5497       TheCall->setArg(i, Arg);
5498     }
5499   }
5500 
5501   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5502     if (!Method->isStatic())
5503       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5504         << Fn->getSourceRange());
5505 
5506   // Check for sentinels
5507   if (NDecl)
5508     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5509 
5510   // Do special checking on direct calls to functions.
5511   if (FDecl) {
5512     if (CheckFunctionCall(FDecl, TheCall, Proto))
5513       return ExprError();
5514 
5515     if (BuiltinID)
5516       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5517   } else if (NDecl) {
5518     if (CheckPointerCall(NDecl, TheCall, Proto))
5519       return ExprError();
5520   } else {
5521     if (CheckOtherCall(TheCall, Proto))
5522       return ExprError();
5523   }
5524 
5525   return MaybeBindToTemporary(TheCall);
5526 }
5527 
5528 ExprResult
5529 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5530                            SourceLocation RParenLoc, Expr *InitExpr) {
5531   assert(Ty && "ActOnCompoundLiteral(): missing type");
5532   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5533 
5534   TypeSourceInfo *TInfo;
5535   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5536   if (!TInfo)
5537     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5538 
5539   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5540 }
5541 
5542 ExprResult
5543 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5544                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5545   QualType literalType = TInfo->getType();
5546 
5547   if (literalType->isArrayType()) {
5548     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5549           diag::err_illegal_decl_array_incomplete_type,
5550           SourceRange(LParenLoc,
5551                       LiteralExpr->getSourceRange().getEnd())))
5552       return ExprError();
5553     if (literalType->isVariableArrayType())
5554       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5555         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5556   } else if (!literalType->isDependentType() &&
5557              RequireCompleteType(LParenLoc, literalType,
5558                diag::err_typecheck_decl_incomplete_type,
5559                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5560     return ExprError();
5561 
5562   InitializedEntity Entity
5563     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5564   InitializationKind Kind
5565     = InitializationKind::CreateCStyleCast(LParenLoc,
5566                                            SourceRange(LParenLoc, RParenLoc),
5567                                            /*InitList=*/true);
5568   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5569   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5570                                       &literalType);
5571   if (Result.isInvalid())
5572     return ExprError();
5573   LiteralExpr = Result.get();
5574 
5575   bool isFileScope = !CurContext->isFunctionOrMethod();
5576   if (isFileScope &&
5577       !LiteralExpr->isTypeDependent() &&
5578       !LiteralExpr->isValueDependent() &&
5579       !literalType->isDependentType()) { // 6.5.2.5p3
5580     if (CheckForConstantInitializer(LiteralExpr, literalType))
5581       return ExprError();
5582   }
5583 
5584   // In C, compound literals are l-values for some reason.
5585   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5586 
5587   return MaybeBindToTemporary(
5588            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5589                                              VK, LiteralExpr, isFileScope));
5590 }
5591 
5592 ExprResult
5593 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5594                     SourceLocation RBraceLoc) {
5595   // Immediately handle non-overload placeholders.  Overloads can be
5596   // resolved contextually, but everything else here can't.
5597   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5598     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5599       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5600 
5601       // Ignore failures; dropping the entire initializer list because
5602       // of one failure would be terrible for indexing/etc.
5603       if (result.isInvalid()) continue;
5604 
5605       InitArgList[I] = result.get();
5606     }
5607   }
5608 
5609   // Semantic analysis for initializers is done by ActOnDeclarator() and
5610   // CheckInitializer() - it requires knowledge of the object being intialized.
5611 
5612   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5613                                                RBraceLoc);
5614   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5615   return E;
5616 }
5617 
5618 /// Do an explicit extend of the given block pointer if we're in ARC.
5619 void Sema::maybeExtendBlockObject(ExprResult &E) {
5620   assert(E.get()->getType()->isBlockPointerType());
5621   assert(E.get()->isRValue());
5622 
5623   // Only do this in an r-value context.
5624   if (!getLangOpts().ObjCAutoRefCount) return;
5625 
5626   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5627                                CK_ARCExtendBlockObject, E.get(),
5628                                /*base path*/ nullptr, VK_RValue);
5629   Cleanup.setExprNeedsCleanups(true);
5630 }
5631 
5632 /// Prepare a conversion of the given expression to an ObjC object
5633 /// pointer type.
5634 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5635   QualType type = E.get()->getType();
5636   if (type->isObjCObjectPointerType()) {
5637     return CK_BitCast;
5638   } else if (type->isBlockPointerType()) {
5639     maybeExtendBlockObject(E);
5640     return CK_BlockPointerToObjCPointerCast;
5641   } else {
5642     assert(type->isPointerType());
5643     return CK_CPointerToObjCPointerCast;
5644   }
5645 }
5646 
5647 /// Prepares for a scalar cast, performing all the necessary stages
5648 /// except the final cast and returning the kind required.
5649 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5650   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5651   // Also, callers should have filtered out the invalid cases with
5652   // pointers.  Everything else should be possible.
5653 
5654   QualType SrcTy = Src.get()->getType();
5655   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5656     return CK_NoOp;
5657 
5658   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5659   case Type::STK_MemberPointer:
5660     llvm_unreachable("member pointer type in C");
5661 
5662   case Type::STK_CPointer:
5663   case Type::STK_BlockPointer:
5664   case Type::STK_ObjCObjectPointer:
5665     switch (DestTy->getScalarTypeKind()) {
5666     case Type::STK_CPointer: {
5667       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5668       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5669       if (SrcAS != DestAS)
5670         return CK_AddressSpaceConversion;
5671       return CK_BitCast;
5672     }
5673     case Type::STK_BlockPointer:
5674       return (SrcKind == Type::STK_BlockPointer
5675                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5676     case Type::STK_ObjCObjectPointer:
5677       if (SrcKind == Type::STK_ObjCObjectPointer)
5678         return CK_BitCast;
5679       if (SrcKind == Type::STK_CPointer)
5680         return CK_CPointerToObjCPointerCast;
5681       maybeExtendBlockObject(Src);
5682       return CK_BlockPointerToObjCPointerCast;
5683     case Type::STK_Bool:
5684       return CK_PointerToBoolean;
5685     case Type::STK_Integral:
5686       return CK_PointerToIntegral;
5687     case Type::STK_Floating:
5688     case Type::STK_FloatingComplex:
5689     case Type::STK_IntegralComplex:
5690     case Type::STK_MemberPointer:
5691       llvm_unreachable("illegal cast from pointer");
5692     }
5693     llvm_unreachable("Should have returned before this");
5694 
5695   case Type::STK_Bool: // casting from bool is like casting from an integer
5696   case Type::STK_Integral:
5697     switch (DestTy->getScalarTypeKind()) {
5698     case Type::STK_CPointer:
5699     case Type::STK_ObjCObjectPointer:
5700     case Type::STK_BlockPointer:
5701       if (Src.get()->isNullPointerConstant(Context,
5702                                            Expr::NPC_ValueDependentIsNull))
5703         return CK_NullToPointer;
5704       return CK_IntegralToPointer;
5705     case Type::STK_Bool:
5706       return CK_IntegralToBoolean;
5707     case Type::STK_Integral:
5708       return CK_IntegralCast;
5709     case Type::STK_Floating:
5710       return CK_IntegralToFloating;
5711     case Type::STK_IntegralComplex:
5712       Src = ImpCastExprToType(Src.get(),
5713                       DestTy->castAs<ComplexType>()->getElementType(),
5714                       CK_IntegralCast);
5715       return CK_IntegralRealToComplex;
5716     case Type::STK_FloatingComplex:
5717       Src = ImpCastExprToType(Src.get(),
5718                       DestTy->castAs<ComplexType>()->getElementType(),
5719                       CK_IntegralToFloating);
5720       return CK_FloatingRealToComplex;
5721     case Type::STK_MemberPointer:
5722       llvm_unreachable("member pointer type in C");
5723     }
5724     llvm_unreachable("Should have returned before this");
5725 
5726   case Type::STK_Floating:
5727     switch (DestTy->getScalarTypeKind()) {
5728     case Type::STK_Floating:
5729       return CK_FloatingCast;
5730     case Type::STK_Bool:
5731       return CK_FloatingToBoolean;
5732     case Type::STK_Integral:
5733       return CK_FloatingToIntegral;
5734     case Type::STK_FloatingComplex:
5735       Src = ImpCastExprToType(Src.get(),
5736                               DestTy->castAs<ComplexType>()->getElementType(),
5737                               CK_FloatingCast);
5738       return CK_FloatingRealToComplex;
5739     case Type::STK_IntegralComplex:
5740       Src = ImpCastExprToType(Src.get(),
5741                               DestTy->castAs<ComplexType>()->getElementType(),
5742                               CK_FloatingToIntegral);
5743       return CK_IntegralRealToComplex;
5744     case Type::STK_CPointer:
5745     case Type::STK_ObjCObjectPointer:
5746     case Type::STK_BlockPointer:
5747       llvm_unreachable("valid float->pointer cast?");
5748     case Type::STK_MemberPointer:
5749       llvm_unreachable("member pointer type in C");
5750     }
5751     llvm_unreachable("Should have returned before this");
5752 
5753   case Type::STK_FloatingComplex:
5754     switch (DestTy->getScalarTypeKind()) {
5755     case Type::STK_FloatingComplex:
5756       return CK_FloatingComplexCast;
5757     case Type::STK_IntegralComplex:
5758       return CK_FloatingComplexToIntegralComplex;
5759     case Type::STK_Floating: {
5760       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5761       if (Context.hasSameType(ET, DestTy))
5762         return CK_FloatingComplexToReal;
5763       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5764       return CK_FloatingCast;
5765     }
5766     case Type::STK_Bool:
5767       return CK_FloatingComplexToBoolean;
5768     case Type::STK_Integral:
5769       Src = ImpCastExprToType(Src.get(),
5770                               SrcTy->castAs<ComplexType>()->getElementType(),
5771                               CK_FloatingComplexToReal);
5772       return CK_FloatingToIntegral;
5773     case Type::STK_CPointer:
5774     case Type::STK_ObjCObjectPointer:
5775     case Type::STK_BlockPointer:
5776       llvm_unreachable("valid complex float->pointer cast?");
5777     case Type::STK_MemberPointer:
5778       llvm_unreachable("member pointer type in C");
5779     }
5780     llvm_unreachable("Should have returned before this");
5781 
5782   case Type::STK_IntegralComplex:
5783     switch (DestTy->getScalarTypeKind()) {
5784     case Type::STK_FloatingComplex:
5785       return CK_IntegralComplexToFloatingComplex;
5786     case Type::STK_IntegralComplex:
5787       return CK_IntegralComplexCast;
5788     case Type::STK_Integral: {
5789       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5790       if (Context.hasSameType(ET, DestTy))
5791         return CK_IntegralComplexToReal;
5792       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5793       return CK_IntegralCast;
5794     }
5795     case Type::STK_Bool:
5796       return CK_IntegralComplexToBoolean;
5797     case Type::STK_Floating:
5798       Src = ImpCastExprToType(Src.get(),
5799                               SrcTy->castAs<ComplexType>()->getElementType(),
5800                               CK_IntegralComplexToReal);
5801       return CK_IntegralToFloating;
5802     case Type::STK_CPointer:
5803     case Type::STK_ObjCObjectPointer:
5804     case Type::STK_BlockPointer:
5805       llvm_unreachable("valid complex int->pointer cast?");
5806     case Type::STK_MemberPointer:
5807       llvm_unreachable("member pointer type in C");
5808     }
5809     llvm_unreachable("Should have returned before this");
5810   }
5811 
5812   llvm_unreachable("Unhandled scalar cast");
5813 }
5814 
5815 static bool breakDownVectorType(QualType type, uint64_t &len,
5816                                 QualType &eltType) {
5817   // Vectors are simple.
5818   if (const VectorType *vecType = type->getAs<VectorType>()) {
5819     len = vecType->getNumElements();
5820     eltType = vecType->getElementType();
5821     assert(eltType->isScalarType());
5822     return true;
5823   }
5824 
5825   // We allow lax conversion to and from non-vector types, but only if
5826   // they're real types (i.e. non-complex, non-pointer scalar types).
5827   if (!type->isRealType()) return false;
5828 
5829   len = 1;
5830   eltType = type;
5831   return true;
5832 }
5833 
5834 /// Are the two types lax-compatible vector types?  That is, given
5835 /// that one of them is a vector, do they have equal storage sizes,
5836 /// where the storage size is the number of elements times the element
5837 /// size?
5838 ///
5839 /// This will also return false if either of the types is neither a
5840 /// vector nor a real type.
5841 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5842   assert(destTy->isVectorType() || srcTy->isVectorType());
5843 
5844   // Disallow lax conversions between scalars and ExtVectors (these
5845   // conversions are allowed for other vector types because common headers
5846   // depend on them).  Most scalar OP ExtVector cases are handled by the
5847   // splat path anyway, which does what we want (convert, not bitcast).
5848   // What this rules out for ExtVectors is crazy things like char4*float.
5849   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5850   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5851 
5852   uint64_t srcLen, destLen;
5853   QualType srcEltTy, destEltTy;
5854   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5855   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5856 
5857   // ASTContext::getTypeSize will return the size rounded up to a
5858   // power of 2, so instead of using that, we need to use the raw
5859   // element size multiplied by the element count.
5860   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5861   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5862 
5863   return (srcLen * srcEltSize == destLen * destEltSize);
5864 }
5865 
5866 /// Is this a legal conversion between two types, one of which is
5867 /// known to be a vector type?
5868 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5869   assert(destTy->isVectorType() || srcTy->isVectorType());
5870 
5871   if (!Context.getLangOpts().LaxVectorConversions)
5872     return false;
5873   return areLaxCompatibleVectorTypes(srcTy, destTy);
5874 }
5875 
5876 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5877                            CastKind &Kind) {
5878   assert(VectorTy->isVectorType() && "Not a vector type!");
5879 
5880   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5881     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5882       return Diag(R.getBegin(),
5883                   Ty->isVectorType() ?
5884                   diag::err_invalid_conversion_between_vectors :
5885                   diag::err_invalid_conversion_between_vector_and_integer)
5886         << VectorTy << Ty << R;
5887   } else
5888     return Diag(R.getBegin(),
5889                 diag::err_invalid_conversion_between_vector_and_scalar)
5890       << VectorTy << Ty << R;
5891 
5892   Kind = CK_BitCast;
5893   return false;
5894 }
5895 
5896 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5897   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5898 
5899   if (DestElemTy == SplattedExpr->getType())
5900     return SplattedExpr;
5901 
5902   assert(DestElemTy->isFloatingType() ||
5903          DestElemTy->isIntegralOrEnumerationType());
5904 
5905   CastKind CK;
5906   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5907     // OpenCL requires that we convert `true` boolean expressions to -1, but
5908     // only when splatting vectors.
5909     if (DestElemTy->isFloatingType()) {
5910       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5911       // in two steps: boolean to signed integral, then to floating.
5912       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5913                                                  CK_BooleanToSignedIntegral);
5914       SplattedExpr = CastExprRes.get();
5915       CK = CK_IntegralToFloating;
5916     } else {
5917       CK = CK_BooleanToSignedIntegral;
5918     }
5919   } else {
5920     ExprResult CastExprRes = SplattedExpr;
5921     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5922     if (CastExprRes.isInvalid())
5923       return ExprError();
5924     SplattedExpr = CastExprRes.get();
5925   }
5926   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5927 }
5928 
5929 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5930                                     Expr *CastExpr, CastKind &Kind) {
5931   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5932 
5933   QualType SrcTy = CastExpr->getType();
5934 
5935   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5936   // an ExtVectorType.
5937   // In OpenCL, casts between vectors of different types are not allowed.
5938   // (See OpenCL 6.2).
5939   if (SrcTy->isVectorType()) {
5940     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5941         || (getLangOpts().OpenCL &&
5942             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5943       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5944         << DestTy << SrcTy << R;
5945       return ExprError();
5946     }
5947     Kind = CK_BitCast;
5948     return CastExpr;
5949   }
5950 
5951   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5952   // conversion will take place first from scalar to elt type, and then
5953   // splat from elt type to vector.
5954   if (SrcTy->isPointerType())
5955     return Diag(R.getBegin(),
5956                 diag::err_invalid_conversion_between_vector_and_scalar)
5957       << DestTy << SrcTy << R;
5958 
5959   Kind = CK_VectorSplat;
5960   return prepareVectorSplat(DestTy, CastExpr);
5961 }
5962 
5963 ExprResult
5964 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5965                     Declarator &D, ParsedType &Ty,
5966                     SourceLocation RParenLoc, Expr *CastExpr) {
5967   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5968          "ActOnCastExpr(): missing type or expr");
5969 
5970   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5971   if (D.isInvalidType())
5972     return ExprError();
5973 
5974   if (getLangOpts().CPlusPlus) {
5975     // Check that there are no default arguments (C++ only).
5976     CheckExtraCXXDefaultArguments(D);
5977   } else {
5978     // Make sure any TypoExprs have been dealt with.
5979     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5980     if (!Res.isUsable())
5981       return ExprError();
5982     CastExpr = Res.get();
5983   }
5984 
5985   checkUnusedDeclAttributes(D);
5986 
5987   QualType castType = castTInfo->getType();
5988   Ty = CreateParsedType(castType, castTInfo);
5989 
5990   bool isVectorLiteral = false;
5991 
5992   // Check for an altivec or OpenCL literal,
5993   // i.e. all the elements are integer constants.
5994   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5995   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5996   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5997        && castType->isVectorType() && (PE || PLE)) {
5998     if (PLE && PLE->getNumExprs() == 0) {
5999       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6000       return ExprError();
6001     }
6002     if (PE || PLE->getNumExprs() == 1) {
6003       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6004       if (!E->getType()->isVectorType())
6005         isVectorLiteral = true;
6006     }
6007     else
6008       isVectorLiteral = true;
6009   }
6010 
6011   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6012   // then handle it as such.
6013   if (isVectorLiteral)
6014     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6015 
6016   // If the Expr being casted is a ParenListExpr, handle it specially.
6017   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6018   // sequence of BinOp comma operators.
6019   if (isa<ParenListExpr>(CastExpr)) {
6020     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6021     if (Result.isInvalid()) return ExprError();
6022     CastExpr = Result.get();
6023   }
6024 
6025   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6026       !getSourceManager().isInSystemMacro(LParenLoc))
6027     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6028 
6029   CheckTollFreeBridgeCast(castType, CastExpr);
6030 
6031   CheckObjCBridgeRelatedCast(castType, CastExpr);
6032 
6033   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6034 
6035   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6036 }
6037 
6038 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6039                                     SourceLocation RParenLoc, Expr *E,
6040                                     TypeSourceInfo *TInfo) {
6041   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6042          "Expected paren or paren list expression");
6043 
6044   Expr **exprs;
6045   unsigned numExprs;
6046   Expr *subExpr;
6047   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6048   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6049     LiteralLParenLoc = PE->getLParenLoc();
6050     LiteralRParenLoc = PE->getRParenLoc();
6051     exprs = PE->getExprs();
6052     numExprs = PE->getNumExprs();
6053   } else { // isa<ParenExpr> by assertion at function entrance
6054     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6055     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6056     subExpr = cast<ParenExpr>(E)->getSubExpr();
6057     exprs = &subExpr;
6058     numExprs = 1;
6059   }
6060 
6061   QualType Ty = TInfo->getType();
6062   assert(Ty->isVectorType() && "Expected vector type");
6063 
6064   SmallVector<Expr *, 8> initExprs;
6065   const VectorType *VTy = Ty->getAs<VectorType>();
6066   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6067 
6068   // '(...)' form of vector initialization in AltiVec: the number of
6069   // initializers must be one or must match the size of the vector.
6070   // If a single value is specified in the initializer then it will be
6071   // replicated to all the components of the vector
6072   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6073     // The number of initializers must be one or must match the size of the
6074     // vector. If a single value is specified in the initializer then it will
6075     // be replicated to all the components of the vector
6076     if (numExprs == 1) {
6077       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6078       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6079       if (Literal.isInvalid())
6080         return ExprError();
6081       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6082                                   PrepareScalarCast(Literal, ElemTy));
6083       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6084     }
6085     else if (numExprs < numElems) {
6086       Diag(E->getExprLoc(),
6087            diag::err_incorrect_number_of_vector_initializers);
6088       return ExprError();
6089     }
6090     else
6091       initExprs.append(exprs, exprs + numExprs);
6092   }
6093   else {
6094     // For OpenCL, when the number of initializers is a single value,
6095     // it will be replicated to all components of the vector.
6096     if (getLangOpts().OpenCL &&
6097         VTy->getVectorKind() == VectorType::GenericVector &&
6098         numExprs == 1) {
6099         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6100         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6101         if (Literal.isInvalid())
6102           return ExprError();
6103         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6104                                     PrepareScalarCast(Literal, ElemTy));
6105         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6106     }
6107 
6108     initExprs.append(exprs, exprs + numExprs);
6109   }
6110   // FIXME: This means that pretty-printing the final AST will produce curly
6111   // braces instead of the original commas.
6112   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6113                                                    initExprs, LiteralRParenLoc);
6114   initE->setType(Ty);
6115   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6116 }
6117 
6118 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6119 /// the ParenListExpr into a sequence of comma binary operators.
6120 ExprResult
6121 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6122   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6123   if (!E)
6124     return OrigExpr;
6125 
6126   ExprResult Result(E->getExpr(0));
6127 
6128   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6129     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6130                         E->getExpr(i));
6131 
6132   if (Result.isInvalid()) return ExprError();
6133 
6134   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6135 }
6136 
6137 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6138                                     SourceLocation R,
6139                                     MultiExprArg Val) {
6140   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6141   return expr;
6142 }
6143 
6144 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6145 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6146 /// emitted.
6147 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6148                                       SourceLocation QuestionLoc) {
6149   Expr *NullExpr = LHSExpr;
6150   Expr *NonPointerExpr = RHSExpr;
6151   Expr::NullPointerConstantKind NullKind =
6152       NullExpr->isNullPointerConstant(Context,
6153                                       Expr::NPC_ValueDependentIsNotNull);
6154 
6155   if (NullKind == Expr::NPCK_NotNull) {
6156     NullExpr = RHSExpr;
6157     NonPointerExpr = LHSExpr;
6158     NullKind =
6159         NullExpr->isNullPointerConstant(Context,
6160                                         Expr::NPC_ValueDependentIsNotNull);
6161   }
6162 
6163   if (NullKind == Expr::NPCK_NotNull)
6164     return false;
6165 
6166   if (NullKind == Expr::NPCK_ZeroExpression)
6167     return false;
6168 
6169   if (NullKind == Expr::NPCK_ZeroLiteral) {
6170     // In this case, check to make sure that we got here from a "NULL"
6171     // string in the source code.
6172     NullExpr = NullExpr->IgnoreParenImpCasts();
6173     SourceLocation loc = NullExpr->getExprLoc();
6174     if (!findMacroSpelling(loc, "NULL"))
6175       return false;
6176   }
6177 
6178   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6179   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6180       << NonPointerExpr->getType() << DiagType
6181       << NonPointerExpr->getSourceRange();
6182   return true;
6183 }
6184 
6185 /// \brief Return false if the condition expression is valid, true otherwise.
6186 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6187   QualType CondTy = Cond->getType();
6188 
6189   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6190   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6191     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6192       << CondTy << Cond->getSourceRange();
6193     return true;
6194   }
6195 
6196   // C99 6.5.15p2
6197   if (CondTy->isScalarType()) return false;
6198 
6199   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6200     << CondTy << Cond->getSourceRange();
6201   return true;
6202 }
6203 
6204 /// \brief Handle when one or both operands are void type.
6205 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6206                                          ExprResult &RHS) {
6207     Expr *LHSExpr = LHS.get();
6208     Expr *RHSExpr = RHS.get();
6209 
6210     if (!LHSExpr->getType()->isVoidType())
6211       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6212         << RHSExpr->getSourceRange();
6213     if (!RHSExpr->getType()->isVoidType())
6214       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6215         << LHSExpr->getSourceRange();
6216     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6217     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6218     return S.Context.VoidTy;
6219 }
6220 
6221 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6222 /// true otherwise.
6223 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6224                                         QualType PointerTy) {
6225   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6226       !NullExpr.get()->isNullPointerConstant(S.Context,
6227                                             Expr::NPC_ValueDependentIsNull))
6228     return true;
6229 
6230   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6231   return false;
6232 }
6233 
6234 /// \brief Checks compatibility between two pointers and return the resulting
6235 /// type.
6236 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6237                                                      ExprResult &RHS,
6238                                                      SourceLocation Loc) {
6239   QualType LHSTy = LHS.get()->getType();
6240   QualType RHSTy = RHS.get()->getType();
6241 
6242   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6243     // Two identical pointers types are always compatible.
6244     return LHSTy;
6245   }
6246 
6247   QualType lhptee, rhptee;
6248 
6249   // Get the pointee types.
6250   bool IsBlockPointer = false;
6251   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6252     lhptee = LHSBTy->getPointeeType();
6253     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6254     IsBlockPointer = true;
6255   } else {
6256     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6257     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6258   }
6259 
6260   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6261   // differently qualified versions of compatible types, the result type is
6262   // a pointer to an appropriately qualified version of the composite
6263   // type.
6264 
6265   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6266   // clause doesn't make sense for our extensions. E.g. address space 2 should
6267   // be incompatible with address space 3: they may live on different devices or
6268   // anything.
6269   Qualifiers lhQual = lhptee.getQualifiers();
6270   Qualifiers rhQual = rhptee.getQualifiers();
6271 
6272   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6273   lhQual.removeCVRQualifiers();
6274   rhQual.removeCVRQualifiers();
6275 
6276   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6277   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6278 
6279   // For OpenCL:
6280   // 1. If LHS and RHS types match exactly and:
6281   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6282   //  (b) AS overlap => generate addrspacecast
6283   //  (c) AS don't overlap => give an error
6284   // 2. if LHS and RHS types don't match:
6285   //  (a) AS match => use standard C rules, generate bitcast
6286   //  (b) AS overlap => generate addrspacecast instead of bitcast
6287   //  (c) AS don't overlap => give an error
6288 
6289   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6290   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6291 
6292   // OpenCL cases 1c, 2a, 2b, and 2c.
6293   if (CompositeTy.isNull()) {
6294     // In this situation, we assume void* type. No especially good
6295     // reason, but this is what gcc does, and we do have to pick
6296     // to get a consistent AST.
6297     QualType incompatTy;
6298     if (S.getLangOpts().OpenCL) {
6299       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6300       // spaces is disallowed.
6301       unsigned ResultAddrSpace;
6302       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6303         // Cases 2a and 2b.
6304         ResultAddrSpace = lhQual.getAddressSpace();
6305       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6306         // Cases 2a and 2b.
6307         ResultAddrSpace = rhQual.getAddressSpace();
6308       } else {
6309         // Cases 1c and 2c.
6310         S.Diag(Loc,
6311                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6312             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6313             << RHS.get()->getSourceRange();
6314         return QualType();
6315       }
6316 
6317       // Continue handling cases 2a and 2b.
6318       incompatTy = S.Context.getPointerType(
6319           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6320       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6321                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6322                                     ? CK_AddressSpaceConversion /* 2b */
6323                                     : CK_BitCast /* 2a */);
6324       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6325                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6326                                     ? CK_AddressSpaceConversion /* 2b */
6327                                     : CK_BitCast /* 2a */);
6328     } else {
6329       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6330           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6331           << RHS.get()->getSourceRange();
6332       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6333       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6334       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6335     }
6336     return incompatTy;
6337   }
6338 
6339   // The pointer types are compatible.
6340   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6341   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6342   if (IsBlockPointer)
6343     ResultTy = S.Context.getBlockPointerType(ResultTy);
6344   else {
6345     // Cases 1a and 1b for OpenCL.
6346     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6347     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6348                       ? CK_BitCast /* 1a */
6349                       : CK_AddressSpaceConversion /* 1b */;
6350     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6351                       ? CK_BitCast /* 1a */
6352                       : CK_AddressSpaceConversion /* 1b */;
6353     ResultTy = S.Context.getPointerType(ResultTy);
6354   }
6355 
6356   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6357   // if the target type does not change.
6358   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6359   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6360   return ResultTy;
6361 }
6362 
6363 /// \brief Return the resulting type when the operands are both block pointers.
6364 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6365                                                           ExprResult &LHS,
6366                                                           ExprResult &RHS,
6367                                                           SourceLocation Loc) {
6368   QualType LHSTy = LHS.get()->getType();
6369   QualType RHSTy = RHS.get()->getType();
6370 
6371   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6372     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6373       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6374       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6375       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6376       return destType;
6377     }
6378     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6379       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6380       << RHS.get()->getSourceRange();
6381     return QualType();
6382   }
6383 
6384   // We have 2 block pointer types.
6385   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6386 }
6387 
6388 /// \brief Return the resulting type when the operands are both pointers.
6389 static QualType
6390 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6391                                             ExprResult &RHS,
6392                                             SourceLocation Loc) {
6393   // get the pointer types
6394   QualType LHSTy = LHS.get()->getType();
6395   QualType RHSTy = RHS.get()->getType();
6396 
6397   // get the "pointed to" types
6398   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6399   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6400 
6401   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6402   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6403     // Figure out necessary qualifiers (C99 6.5.15p6)
6404     QualType destPointee
6405       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6406     QualType destType = S.Context.getPointerType(destPointee);
6407     // Add qualifiers if necessary.
6408     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6409     // Promote to void*.
6410     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6411     return destType;
6412   }
6413   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6414     QualType destPointee
6415       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6416     QualType destType = S.Context.getPointerType(destPointee);
6417     // Add qualifiers if necessary.
6418     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6419     // Promote to void*.
6420     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6421     return destType;
6422   }
6423 
6424   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6425 }
6426 
6427 /// \brief Return false if the first expression is not an integer and the second
6428 /// expression is not a pointer, true otherwise.
6429 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6430                                         Expr* PointerExpr, SourceLocation Loc,
6431                                         bool IsIntFirstExpr) {
6432   if (!PointerExpr->getType()->isPointerType() ||
6433       !Int.get()->getType()->isIntegerType())
6434     return false;
6435 
6436   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6437   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6438 
6439   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6440     << Expr1->getType() << Expr2->getType()
6441     << Expr1->getSourceRange() << Expr2->getSourceRange();
6442   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6443                             CK_IntegralToPointer);
6444   return true;
6445 }
6446 
6447 /// \brief Simple conversion between integer and floating point types.
6448 ///
6449 /// Used when handling the OpenCL conditional operator where the
6450 /// condition is a vector while the other operands are scalar.
6451 ///
6452 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6453 /// types are either integer or floating type. Between the two
6454 /// operands, the type with the higher rank is defined as the "result
6455 /// type". The other operand needs to be promoted to the same type. No
6456 /// other type promotion is allowed. We cannot use
6457 /// UsualArithmeticConversions() for this purpose, since it always
6458 /// promotes promotable types.
6459 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6460                                             ExprResult &RHS,
6461                                             SourceLocation QuestionLoc) {
6462   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6463   if (LHS.isInvalid())
6464     return QualType();
6465   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6466   if (RHS.isInvalid())
6467     return QualType();
6468 
6469   // For conversion purposes, we ignore any qualifiers.
6470   // For example, "const float" and "float" are equivalent.
6471   QualType LHSType =
6472     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6473   QualType RHSType =
6474     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6475 
6476   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6477     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6478       << LHSType << LHS.get()->getSourceRange();
6479     return QualType();
6480   }
6481 
6482   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6483     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6484       << RHSType << RHS.get()->getSourceRange();
6485     return QualType();
6486   }
6487 
6488   // If both types are identical, no conversion is needed.
6489   if (LHSType == RHSType)
6490     return LHSType;
6491 
6492   // Now handle "real" floating types (i.e. float, double, long double).
6493   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6494     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6495                                  /*IsCompAssign = */ false);
6496 
6497   // Finally, we have two differing integer types.
6498   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6499   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6500 }
6501 
6502 /// \brief Convert scalar operands to a vector that matches the
6503 ///        condition in length.
6504 ///
6505 /// Used when handling the OpenCL conditional operator where the
6506 /// condition is a vector while the other operands are scalar.
6507 ///
6508 /// We first compute the "result type" for the scalar operands
6509 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6510 /// into a vector of that type where the length matches the condition
6511 /// vector type. s6.11.6 requires that the element types of the result
6512 /// and the condition must have the same number of bits.
6513 static QualType
6514 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6515                               QualType CondTy, SourceLocation QuestionLoc) {
6516   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6517   if (ResTy.isNull()) return QualType();
6518 
6519   const VectorType *CV = CondTy->getAs<VectorType>();
6520   assert(CV);
6521 
6522   // Determine the vector result type
6523   unsigned NumElements = CV->getNumElements();
6524   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6525 
6526   // Ensure that all types have the same number of bits
6527   if (S.Context.getTypeSize(CV->getElementType())
6528       != S.Context.getTypeSize(ResTy)) {
6529     // Since VectorTy is created internally, it does not pretty print
6530     // with an OpenCL name. Instead, we just print a description.
6531     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6532     SmallString<64> Str;
6533     llvm::raw_svector_ostream OS(Str);
6534     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6535     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6536       << CondTy << OS.str();
6537     return QualType();
6538   }
6539 
6540   // Convert operands to the vector result type
6541   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6542   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6543 
6544   return VectorTy;
6545 }
6546 
6547 /// \brief Return false if this is a valid OpenCL condition vector
6548 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6549                                        SourceLocation QuestionLoc) {
6550   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6551   // integral type.
6552   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6553   assert(CondTy);
6554   QualType EleTy = CondTy->getElementType();
6555   if (EleTy->isIntegerType()) return false;
6556 
6557   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6558     << Cond->getType() << Cond->getSourceRange();
6559   return true;
6560 }
6561 
6562 /// \brief Return false if the vector condition type and the vector
6563 ///        result type are compatible.
6564 ///
6565 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6566 /// number of elements, and their element types have the same number
6567 /// of bits.
6568 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6569                               SourceLocation QuestionLoc) {
6570   const VectorType *CV = CondTy->getAs<VectorType>();
6571   const VectorType *RV = VecResTy->getAs<VectorType>();
6572   assert(CV && RV);
6573 
6574   if (CV->getNumElements() != RV->getNumElements()) {
6575     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6576       << CondTy << VecResTy;
6577     return true;
6578   }
6579 
6580   QualType CVE = CV->getElementType();
6581   QualType RVE = RV->getElementType();
6582 
6583   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6584     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6585       << CondTy << VecResTy;
6586     return true;
6587   }
6588 
6589   return false;
6590 }
6591 
6592 /// \brief Return the resulting type for the conditional operator in
6593 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6594 ///        s6.3.i) when the condition is a vector type.
6595 static QualType
6596 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6597                              ExprResult &LHS, ExprResult &RHS,
6598                              SourceLocation QuestionLoc) {
6599   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6600   if (Cond.isInvalid())
6601     return QualType();
6602   QualType CondTy = Cond.get()->getType();
6603 
6604   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6605     return QualType();
6606 
6607   // If either operand is a vector then find the vector type of the
6608   // result as specified in OpenCL v1.1 s6.3.i.
6609   if (LHS.get()->getType()->isVectorType() ||
6610       RHS.get()->getType()->isVectorType()) {
6611     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6612                                               /*isCompAssign*/false,
6613                                               /*AllowBothBool*/true,
6614                                               /*AllowBoolConversions*/false);
6615     if (VecResTy.isNull()) return QualType();
6616     // The result type must match the condition type as specified in
6617     // OpenCL v1.1 s6.11.6.
6618     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6619       return QualType();
6620     return VecResTy;
6621   }
6622 
6623   // Both operands are scalar.
6624   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6625 }
6626 
6627 /// \brief Return true if the Expr is block type
6628 static bool checkBlockType(Sema &S, const Expr *E) {
6629   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6630     QualType Ty = CE->getCallee()->getType();
6631     if (Ty->isBlockPointerType()) {
6632       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6633       return true;
6634     }
6635   }
6636   return false;
6637 }
6638 
6639 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6640 /// In that case, LHS = cond.
6641 /// C99 6.5.15
6642 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6643                                         ExprResult &RHS, ExprValueKind &VK,
6644                                         ExprObjectKind &OK,
6645                                         SourceLocation QuestionLoc) {
6646 
6647   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6648   if (!LHSResult.isUsable()) return QualType();
6649   LHS = LHSResult;
6650 
6651   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6652   if (!RHSResult.isUsable()) return QualType();
6653   RHS = RHSResult;
6654 
6655   // C++ is sufficiently different to merit its own checker.
6656   if (getLangOpts().CPlusPlus)
6657     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6658 
6659   VK = VK_RValue;
6660   OK = OK_Ordinary;
6661 
6662   // The OpenCL operator with a vector condition is sufficiently
6663   // different to merit its own checker.
6664   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6665     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6666 
6667   // First, check the condition.
6668   Cond = UsualUnaryConversions(Cond.get());
6669   if (Cond.isInvalid())
6670     return QualType();
6671   if (checkCondition(*this, Cond.get(), QuestionLoc))
6672     return QualType();
6673 
6674   // Now check the two expressions.
6675   if (LHS.get()->getType()->isVectorType() ||
6676       RHS.get()->getType()->isVectorType())
6677     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6678                                /*AllowBothBool*/true,
6679                                /*AllowBoolConversions*/false);
6680 
6681   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6682   if (LHS.isInvalid() || RHS.isInvalid())
6683     return QualType();
6684 
6685   QualType LHSTy = LHS.get()->getType();
6686   QualType RHSTy = RHS.get()->getType();
6687 
6688   // Diagnose attempts to convert between __float128 and long double where
6689   // such conversions currently can't be handled.
6690   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6691     Diag(QuestionLoc,
6692          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6693       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6694     return QualType();
6695   }
6696 
6697   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6698   // selection operator (?:).
6699   if (getLangOpts().OpenCL &&
6700       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6701     return QualType();
6702   }
6703 
6704   // If both operands have arithmetic type, do the usual arithmetic conversions
6705   // to find a common type: C99 6.5.15p3,5.
6706   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6707     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6708     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6709 
6710     return ResTy;
6711   }
6712 
6713   // If both operands are the same structure or union type, the result is that
6714   // type.
6715   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6716     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6717       if (LHSRT->getDecl() == RHSRT->getDecl())
6718         // "If both the operands have structure or union type, the result has
6719         // that type."  This implies that CV qualifiers are dropped.
6720         return LHSTy.getUnqualifiedType();
6721     // FIXME: Type of conditional expression must be complete in C mode.
6722   }
6723 
6724   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6725   // The following || allows only one side to be void (a GCC-ism).
6726   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6727     return checkConditionalVoidType(*this, LHS, RHS);
6728   }
6729 
6730   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6731   // the type of the other operand."
6732   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6733   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6734 
6735   // All objective-c pointer type analysis is done here.
6736   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6737                                                         QuestionLoc);
6738   if (LHS.isInvalid() || RHS.isInvalid())
6739     return QualType();
6740   if (!compositeType.isNull())
6741     return compositeType;
6742 
6743 
6744   // Handle block pointer types.
6745   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6746     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6747                                                      QuestionLoc);
6748 
6749   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6750   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6751     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6752                                                        QuestionLoc);
6753 
6754   // GCC compatibility: soften pointer/integer mismatch.  Note that
6755   // null pointers have been filtered out by this point.
6756   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6757       /*isIntFirstExpr=*/true))
6758     return RHSTy;
6759   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6760       /*isIntFirstExpr=*/false))
6761     return LHSTy;
6762 
6763   // Emit a better diagnostic if one of the expressions is a null pointer
6764   // constant and the other is not a pointer type. In this case, the user most
6765   // likely forgot to take the address of the other expression.
6766   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6767     return QualType();
6768 
6769   // Otherwise, the operands are not compatible.
6770   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6771     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6772     << RHS.get()->getSourceRange();
6773   return QualType();
6774 }
6775 
6776 /// FindCompositeObjCPointerType - Helper method to find composite type of
6777 /// two objective-c pointer types of the two input expressions.
6778 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6779                                             SourceLocation QuestionLoc) {
6780   QualType LHSTy = LHS.get()->getType();
6781   QualType RHSTy = RHS.get()->getType();
6782 
6783   // Handle things like Class and struct objc_class*.  Here we case the result
6784   // to the pseudo-builtin, because that will be implicitly cast back to the
6785   // redefinition type if an attempt is made to access its fields.
6786   if (LHSTy->isObjCClassType() &&
6787       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6788     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6789     return LHSTy;
6790   }
6791   if (RHSTy->isObjCClassType() &&
6792       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6793     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6794     return RHSTy;
6795   }
6796   // And the same for struct objc_object* / id
6797   if (LHSTy->isObjCIdType() &&
6798       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6799     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6800     return LHSTy;
6801   }
6802   if (RHSTy->isObjCIdType() &&
6803       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6804     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6805     return RHSTy;
6806   }
6807   // And the same for struct objc_selector* / SEL
6808   if (Context.isObjCSelType(LHSTy) &&
6809       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6810     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6811     return LHSTy;
6812   }
6813   if (Context.isObjCSelType(RHSTy) &&
6814       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6815     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6816     return RHSTy;
6817   }
6818   // Check constraints for Objective-C object pointers types.
6819   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6820 
6821     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6822       // Two identical object pointer types are always compatible.
6823       return LHSTy;
6824     }
6825     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6826     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6827     QualType compositeType = LHSTy;
6828 
6829     // If both operands are interfaces and either operand can be
6830     // assigned to the other, use that type as the composite
6831     // type. This allows
6832     //   xxx ? (A*) a : (B*) b
6833     // where B is a subclass of A.
6834     //
6835     // Additionally, as for assignment, if either type is 'id'
6836     // allow silent coercion. Finally, if the types are
6837     // incompatible then make sure to use 'id' as the composite
6838     // type so the result is acceptable for sending messages to.
6839 
6840     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6841     // It could return the composite type.
6842     if (!(compositeType =
6843           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6844       // Nothing more to do.
6845     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6846       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6847     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6848       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6849     } else if ((LHSTy->isObjCQualifiedIdType() ||
6850                 RHSTy->isObjCQualifiedIdType()) &&
6851                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6852       // Need to handle "id<xx>" explicitly.
6853       // GCC allows qualified id and any Objective-C type to devolve to
6854       // id. Currently localizing to here until clear this should be
6855       // part of ObjCQualifiedIdTypesAreCompatible.
6856       compositeType = Context.getObjCIdType();
6857     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6858       compositeType = Context.getObjCIdType();
6859     } else {
6860       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6861       << LHSTy << RHSTy
6862       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6863       QualType incompatTy = Context.getObjCIdType();
6864       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6865       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6866       return incompatTy;
6867     }
6868     // The object pointer types are compatible.
6869     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6870     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6871     return compositeType;
6872   }
6873   // Check Objective-C object pointer types and 'void *'
6874   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6875     if (getLangOpts().ObjCAutoRefCount) {
6876       // ARC forbids the implicit conversion of object pointers to 'void *',
6877       // so these types are not compatible.
6878       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6879           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6880       LHS = RHS = true;
6881       return QualType();
6882     }
6883     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6884     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6885     QualType destPointee
6886     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6887     QualType destType = Context.getPointerType(destPointee);
6888     // Add qualifiers if necessary.
6889     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6890     // Promote to void*.
6891     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6892     return destType;
6893   }
6894   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6895     if (getLangOpts().ObjCAutoRefCount) {
6896       // ARC forbids the implicit conversion of object pointers to 'void *',
6897       // so these types are not compatible.
6898       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6899           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6900       LHS = RHS = true;
6901       return QualType();
6902     }
6903     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6904     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6905     QualType destPointee
6906     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6907     QualType destType = Context.getPointerType(destPointee);
6908     // Add qualifiers if necessary.
6909     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6910     // Promote to void*.
6911     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6912     return destType;
6913   }
6914   return QualType();
6915 }
6916 
6917 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6918 /// ParenRange in parentheses.
6919 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6920                                const PartialDiagnostic &Note,
6921                                SourceRange ParenRange) {
6922   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6923   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6924       EndLoc.isValid()) {
6925     Self.Diag(Loc, Note)
6926       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6927       << FixItHint::CreateInsertion(EndLoc, ")");
6928   } else {
6929     // We can't display the parentheses, so just show the bare note.
6930     Self.Diag(Loc, Note) << ParenRange;
6931   }
6932 }
6933 
6934 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6935   return BinaryOperator::isAdditiveOp(Opc) ||
6936          BinaryOperator::isMultiplicativeOp(Opc) ||
6937          BinaryOperator::isShiftOp(Opc);
6938 }
6939 
6940 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6941 /// expression, either using a built-in or overloaded operator,
6942 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6943 /// expression.
6944 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6945                                    Expr **RHSExprs) {
6946   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6947   E = E->IgnoreImpCasts();
6948   E = E->IgnoreConversionOperator();
6949   E = E->IgnoreImpCasts();
6950 
6951   // Built-in binary operator.
6952   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6953     if (IsArithmeticOp(OP->getOpcode())) {
6954       *Opcode = OP->getOpcode();
6955       *RHSExprs = OP->getRHS();
6956       return true;
6957     }
6958   }
6959 
6960   // Overloaded operator.
6961   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6962     if (Call->getNumArgs() != 2)
6963       return false;
6964 
6965     // Make sure this is really a binary operator that is safe to pass into
6966     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6967     OverloadedOperatorKind OO = Call->getOperator();
6968     if (OO < OO_Plus || OO > OO_Arrow ||
6969         OO == OO_PlusPlus || OO == OO_MinusMinus)
6970       return false;
6971 
6972     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6973     if (IsArithmeticOp(OpKind)) {
6974       *Opcode = OpKind;
6975       *RHSExprs = Call->getArg(1);
6976       return true;
6977     }
6978   }
6979 
6980   return false;
6981 }
6982 
6983 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6984 /// or is a logical expression such as (x==y) which has int type, but is
6985 /// commonly interpreted as boolean.
6986 static bool ExprLooksBoolean(Expr *E) {
6987   E = E->IgnoreParenImpCasts();
6988 
6989   if (E->getType()->isBooleanType())
6990     return true;
6991   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6992     return OP->isComparisonOp() || OP->isLogicalOp();
6993   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6994     return OP->getOpcode() == UO_LNot;
6995   if (E->getType()->isPointerType())
6996     return true;
6997 
6998   return false;
6999 }
7000 
7001 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7002 /// and binary operator are mixed in a way that suggests the programmer assumed
7003 /// the conditional operator has higher precedence, for example:
7004 /// "int x = a + someBinaryCondition ? 1 : 2".
7005 static void DiagnoseConditionalPrecedence(Sema &Self,
7006                                           SourceLocation OpLoc,
7007                                           Expr *Condition,
7008                                           Expr *LHSExpr,
7009                                           Expr *RHSExpr) {
7010   BinaryOperatorKind CondOpcode;
7011   Expr *CondRHS;
7012 
7013   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7014     return;
7015   if (!ExprLooksBoolean(CondRHS))
7016     return;
7017 
7018   // The condition is an arithmetic binary expression, with a right-
7019   // hand side that looks boolean, so warn.
7020 
7021   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7022       << Condition->getSourceRange()
7023       << BinaryOperator::getOpcodeStr(CondOpcode);
7024 
7025   SuggestParentheses(Self, OpLoc,
7026     Self.PDiag(diag::note_precedence_silence)
7027       << BinaryOperator::getOpcodeStr(CondOpcode),
7028     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7029 
7030   SuggestParentheses(Self, OpLoc,
7031     Self.PDiag(diag::note_precedence_conditional_first),
7032     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7033 }
7034 
7035 /// Compute the nullability of a conditional expression.
7036 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7037                                               QualType LHSTy, QualType RHSTy,
7038                                               ASTContext &Ctx) {
7039   if (!ResTy->isAnyPointerType())
7040     return ResTy;
7041 
7042   auto GetNullability = [&Ctx](QualType Ty) {
7043     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7044     if (Kind)
7045       return *Kind;
7046     return NullabilityKind::Unspecified;
7047   };
7048 
7049   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7050   NullabilityKind MergedKind;
7051 
7052   // Compute nullability of a binary conditional expression.
7053   if (IsBin) {
7054     if (LHSKind == NullabilityKind::NonNull)
7055       MergedKind = NullabilityKind::NonNull;
7056     else
7057       MergedKind = RHSKind;
7058   // Compute nullability of a normal conditional expression.
7059   } else {
7060     if (LHSKind == NullabilityKind::Nullable ||
7061         RHSKind == NullabilityKind::Nullable)
7062       MergedKind = NullabilityKind::Nullable;
7063     else if (LHSKind == NullabilityKind::NonNull)
7064       MergedKind = RHSKind;
7065     else if (RHSKind == NullabilityKind::NonNull)
7066       MergedKind = LHSKind;
7067     else
7068       MergedKind = NullabilityKind::Unspecified;
7069   }
7070 
7071   // Return if ResTy already has the correct nullability.
7072   if (GetNullability(ResTy) == MergedKind)
7073     return ResTy;
7074 
7075   // Strip all nullability from ResTy.
7076   while (ResTy->getNullability(Ctx))
7077     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7078 
7079   // Create a new AttributedType with the new nullability kind.
7080   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7081   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7082 }
7083 
7084 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7085 /// in the case of a the GNU conditional expr extension.
7086 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7087                                     SourceLocation ColonLoc,
7088                                     Expr *CondExpr, Expr *LHSExpr,
7089                                     Expr *RHSExpr) {
7090   if (!getLangOpts().CPlusPlus) {
7091     // C cannot handle TypoExpr nodes in the condition because it
7092     // doesn't handle dependent types properly, so make sure any TypoExprs have
7093     // been dealt with before checking the operands.
7094     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7095     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7096     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7097 
7098     if (!CondResult.isUsable())
7099       return ExprError();
7100 
7101     if (LHSExpr) {
7102       if (!LHSResult.isUsable())
7103         return ExprError();
7104     }
7105 
7106     if (!RHSResult.isUsable())
7107       return ExprError();
7108 
7109     CondExpr = CondResult.get();
7110     LHSExpr = LHSResult.get();
7111     RHSExpr = RHSResult.get();
7112   }
7113 
7114   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7115   // was the condition.
7116   OpaqueValueExpr *opaqueValue = nullptr;
7117   Expr *commonExpr = nullptr;
7118   if (!LHSExpr) {
7119     commonExpr = CondExpr;
7120     // Lower out placeholder types first.  This is important so that we don't
7121     // try to capture a placeholder. This happens in few cases in C++; such
7122     // as Objective-C++'s dictionary subscripting syntax.
7123     if (commonExpr->hasPlaceholderType()) {
7124       ExprResult result = CheckPlaceholderExpr(commonExpr);
7125       if (!result.isUsable()) return ExprError();
7126       commonExpr = result.get();
7127     }
7128     // We usually want to apply unary conversions *before* saving, except
7129     // in the special case of a C++ l-value conditional.
7130     if (!(getLangOpts().CPlusPlus
7131           && !commonExpr->isTypeDependent()
7132           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7133           && commonExpr->isGLValue()
7134           && commonExpr->isOrdinaryOrBitFieldObject()
7135           && RHSExpr->isOrdinaryOrBitFieldObject()
7136           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7137       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7138       if (commonRes.isInvalid())
7139         return ExprError();
7140       commonExpr = commonRes.get();
7141     }
7142 
7143     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7144                                                 commonExpr->getType(),
7145                                                 commonExpr->getValueKind(),
7146                                                 commonExpr->getObjectKind(),
7147                                                 commonExpr);
7148     LHSExpr = CondExpr = opaqueValue;
7149   }
7150 
7151   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7152   ExprValueKind VK = VK_RValue;
7153   ExprObjectKind OK = OK_Ordinary;
7154   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7155   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7156                                              VK, OK, QuestionLoc);
7157   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7158       RHS.isInvalid())
7159     return ExprError();
7160 
7161   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7162                                 RHS.get());
7163 
7164   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7165 
7166   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7167                                          Context);
7168 
7169   if (!commonExpr)
7170     return new (Context)
7171         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7172                             RHS.get(), result, VK, OK);
7173 
7174   return new (Context) BinaryConditionalOperator(
7175       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7176       ColonLoc, result, VK, OK);
7177 }
7178 
7179 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7180 // being closely modeled after the C99 spec:-). The odd characteristic of this
7181 // routine is it effectively iqnores the qualifiers on the top level pointee.
7182 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7183 // FIXME: add a couple examples in this comment.
7184 static Sema::AssignConvertType
7185 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7186   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7187   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7188 
7189   // get the "pointed to" type (ignoring qualifiers at the top level)
7190   const Type *lhptee, *rhptee;
7191   Qualifiers lhq, rhq;
7192   std::tie(lhptee, lhq) =
7193       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7194   std::tie(rhptee, rhq) =
7195       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7196 
7197   Sema::AssignConvertType ConvTy = Sema::Compatible;
7198 
7199   // C99 6.5.16.1p1: This following citation is common to constraints
7200   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7201   // qualifiers of the type *pointed to* by the right;
7202 
7203   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7204   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7205       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7206     // Ignore lifetime for further calculation.
7207     lhq.removeObjCLifetime();
7208     rhq.removeObjCLifetime();
7209   }
7210 
7211   if (!lhq.compatiblyIncludes(rhq)) {
7212     // Treat address-space mismatches as fatal.  TODO: address subspaces
7213     if (!lhq.isAddressSpaceSupersetOf(rhq))
7214       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7215 
7216     // It's okay to add or remove GC or lifetime qualifiers when converting to
7217     // and from void*.
7218     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7219                         .compatiblyIncludes(
7220                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7221              && (lhptee->isVoidType() || rhptee->isVoidType()))
7222       ; // keep old
7223 
7224     // Treat lifetime mismatches as fatal.
7225     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7226       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7227 
7228     // For GCC/MS compatibility, other qualifier mismatches are treated
7229     // as still compatible in C.
7230     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7231   }
7232 
7233   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7234   // incomplete type and the other is a pointer to a qualified or unqualified
7235   // version of void...
7236   if (lhptee->isVoidType()) {
7237     if (rhptee->isIncompleteOrObjectType())
7238       return ConvTy;
7239 
7240     // As an extension, we allow cast to/from void* to function pointer.
7241     assert(rhptee->isFunctionType());
7242     return Sema::FunctionVoidPointer;
7243   }
7244 
7245   if (rhptee->isVoidType()) {
7246     if (lhptee->isIncompleteOrObjectType())
7247       return ConvTy;
7248 
7249     // As an extension, we allow cast to/from void* to function pointer.
7250     assert(lhptee->isFunctionType());
7251     return Sema::FunctionVoidPointer;
7252   }
7253 
7254   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7255   // unqualified versions of compatible types, ...
7256   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7257   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7258     // Check if the pointee types are compatible ignoring the sign.
7259     // We explicitly check for char so that we catch "char" vs
7260     // "unsigned char" on systems where "char" is unsigned.
7261     if (lhptee->isCharType())
7262       ltrans = S.Context.UnsignedCharTy;
7263     else if (lhptee->hasSignedIntegerRepresentation())
7264       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7265 
7266     if (rhptee->isCharType())
7267       rtrans = S.Context.UnsignedCharTy;
7268     else if (rhptee->hasSignedIntegerRepresentation())
7269       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7270 
7271     if (ltrans == rtrans) {
7272       // Types are compatible ignoring the sign. Qualifier incompatibility
7273       // takes priority over sign incompatibility because the sign
7274       // warning can be disabled.
7275       if (ConvTy != Sema::Compatible)
7276         return ConvTy;
7277 
7278       return Sema::IncompatiblePointerSign;
7279     }
7280 
7281     // If we are a multi-level pointer, it's possible that our issue is simply
7282     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7283     // the eventual target type is the same and the pointers have the same
7284     // level of indirection, this must be the issue.
7285     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7286       do {
7287         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7288         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7289       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7290 
7291       if (lhptee == rhptee)
7292         return Sema::IncompatibleNestedPointerQualifiers;
7293     }
7294 
7295     // General pointer incompatibility takes priority over qualifiers.
7296     return Sema::IncompatiblePointer;
7297   }
7298   if (!S.getLangOpts().CPlusPlus &&
7299       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7300     return Sema::IncompatiblePointer;
7301   return ConvTy;
7302 }
7303 
7304 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7305 /// block pointer types are compatible or whether a block and normal pointer
7306 /// are compatible. It is more restrict than comparing two function pointer
7307 // types.
7308 static Sema::AssignConvertType
7309 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7310                                     QualType RHSType) {
7311   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7312   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7313 
7314   QualType lhptee, rhptee;
7315 
7316   // get the "pointed to" type (ignoring qualifiers at the top level)
7317   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7318   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7319 
7320   // In C++, the types have to match exactly.
7321   if (S.getLangOpts().CPlusPlus)
7322     return Sema::IncompatibleBlockPointer;
7323 
7324   Sema::AssignConvertType ConvTy = Sema::Compatible;
7325 
7326   // For blocks we enforce that qualifiers are identical.
7327   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7328     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7329 
7330   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7331     return Sema::IncompatibleBlockPointer;
7332 
7333   return ConvTy;
7334 }
7335 
7336 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7337 /// for assignment compatibility.
7338 static Sema::AssignConvertType
7339 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7340                                    QualType RHSType) {
7341   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7342   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7343 
7344   if (LHSType->isObjCBuiltinType()) {
7345     // Class is not compatible with ObjC object pointers.
7346     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7347         !RHSType->isObjCQualifiedClassType())
7348       return Sema::IncompatiblePointer;
7349     return Sema::Compatible;
7350   }
7351   if (RHSType->isObjCBuiltinType()) {
7352     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7353         !LHSType->isObjCQualifiedClassType())
7354       return Sema::IncompatiblePointer;
7355     return Sema::Compatible;
7356   }
7357   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7358   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7359 
7360   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7361       // make an exception for id<P>
7362       !LHSType->isObjCQualifiedIdType())
7363     return Sema::CompatiblePointerDiscardsQualifiers;
7364 
7365   if (S.Context.typesAreCompatible(LHSType, RHSType))
7366     return Sema::Compatible;
7367   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7368     return Sema::IncompatibleObjCQualifiedId;
7369   return Sema::IncompatiblePointer;
7370 }
7371 
7372 Sema::AssignConvertType
7373 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7374                                  QualType LHSType, QualType RHSType) {
7375   // Fake up an opaque expression.  We don't actually care about what
7376   // cast operations are required, so if CheckAssignmentConstraints
7377   // adds casts to this they'll be wasted, but fortunately that doesn't
7378   // usually happen on valid code.
7379   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7380   ExprResult RHSPtr = &RHSExpr;
7381   CastKind K = CK_Invalid;
7382 
7383   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7384 }
7385 
7386 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7387 /// has code to accommodate several GCC extensions when type checking
7388 /// pointers. Here are some objectionable examples that GCC considers warnings:
7389 ///
7390 ///  int a, *pint;
7391 ///  short *pshort;
7392 ///  struct foo *pfoo;
7393 ///
7394 ///  pint = pshort; // warning: assignment from incompatible pointer type
7395 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7396 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7397 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7398 ///
7399 /// As a result, the code for dealing with pointers is more complex than the
7400 /// C99 spec dictates.
7401 ///
7402 /// Sets 'Kind' for any result kind except Incompatible.
7403 Sema::AssignConvertType
7404 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7405                                  CastKind &Kind, bool ConvertRHS) {
7406   QualType RHSType = RHS.get()->getType();
7407   QualType OrigLHSType = LHSType;
7408 
7409   // Get canonical types.  We're not formatting these types, just comparing
7410   // them.
7411   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7412   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7413 
7414   // Common case: no conversion required.
7415   if (LHSType == RHSType) {
7416     Kind = CK_NoOp;
7417     return Compatible;
7418   }
7419 
7420   // If we have an atomic type, try a non-atomic assignment, then just add an
7421   // atomic qualification step.
7422   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7423     Sema::AssignConvertType result =
7424       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7425     if (result != Compatible)
7426       return result;
7427     if (Kind != CK_NoOp && ConvertRHS)
7428       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7429     Kind = CK_NonAtomicToAtomic;
7430     return Compatible;
7431   }
7432 
7433   // If the left-hand side is a reference type, then we are in a
7434   // (rare!) case where we've allowed the use of references in C,
7435   // e.g., as a parameter type in a built-in function. In this case,
7436   // just make sure that the type referenced is compatible with the
7437   // right-hand side type. The caller is responsible for adjusting
7438   // LHSType so that the resulting expression does not have reference
7439   // type.
7440   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7441     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7442       Kind = CK_LValueBitCast;
7443       return Compatible;
7444     }
7445     return Incompatible;
7446   }
7447 
7448   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7449   // to the same ExtVector type.
7450   if (LHSType->isExtVectorType()) {
7451     if (RHSType->isExtVectorType())
7452       return Incompatible;
7453     if (RHSType->isArithmeticType()) {
7454       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7455       if (ConvertRHS)
7456         RHS = prepareVectorSplat(LHSType, RHS.get());
7457       Kind = CK_VectorSplat;
7458       return Compatible;
7459     }
7460   }
7461 
7462   // Conversions to or from vector type.
7463   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7464     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7465       // Allow assignments of an AltiVec vector type to an equivalent GCC
7466       // vector type and vice versa
7467       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7468         Kind = CK_BitCast;
7469         return Compatible;
7470       }
7471 
7472       // If we are allowing lax vector conversions, and LHS and RHS are both
7473       // vectors, the total size only needs to be the same. This is a bitcast;
7474       // no bits are changed but the result type is different.
7475       if (isLaxVectorConversion(RHSType, LHSType)) {
7476         Kind = CK_BitCast;
7477         return IncompatibleVectors;
7478       }
7479     }
7480 
7481     // When the RHS comes from another lax conversion (e.g. binops between
7482     // scalars and vectors) the result is canonicalized as a vector. When the
7483     // LHS is also a vector, the lax is allowed by the condition above. Handle
7484     // the case where LHS is a scalar.
7485     if (LHSType->isScalarType()) {
7486       const VectorType *VecType = RHSType->getAs<VectorType>();
7487       if (VecType && VecType->getNumElements() == 1 &&
7488           isLaxVectorConversion(RHSType, LHSType)) {
7489         ExprResult *VecExpr = &RHS;
7490         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7491         Kind = CK_BitCast;
7492         return Compatible;
7493       }
7494     }
7495 
7496     return Incompatible;
7497   }
7498 
7499   // Diagnose attempts to convert between __float128 and long double where
7500   // such conversions currently can't be handled.
7501   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7502     return Incompatible;
7503 
7504   // Arithmetic conversions.
7505   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7506       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7507     if (ConvertRHS)
7508       Kind = PrepareScalarCast(RHS, LHSType);
7509     return Compatible;
7510   }
7511 
7512   // Conversions to normal pointers.
7513   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7514     // U* -> T*
7515     if (isa<PointerType>(RHSType)) {
7516       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7517       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7518       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7519       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7520     }
7521 
7522     // int -> T*
7523     if (RHSType->isIntegerType()) {
7524       Kind = CK_IntegralToPointer; // FIXME: null?
7525       return IntToPointer;
7526     }
7527 
7528     // C pointers are not compatible with ObjC object pointers,
7529     // with two exceptions:
7530     if (isa<ObjCObjectPointerType>(RHSType)) {
7531       //  - conversions to void*
7532       if (LHSPointer->getPointeeType()->isVoidType()) {
7533         Kind = CK_BitCast;
7534         return Compatible;
7535       }
7536 
7537       //  - conversions from 'Class' to the redefinition type
7538       if (RHSType->isObjCClassType() &&
7539           Context.hasSameType(LHSType,
7540                               Context.getObjCClassRedefinitionType())) {
7541         Kind = CK_BitCast;
7542         return Compatible;
7543       }
7544 
7545       Kind = CK_BitCast;
7546       return IncompatiblePointer;
7547     }
7548 
7549     // U^ -> void*
7550     if (RHSType->getAs<BlockPointerType>()) {
7551       if (LHSPointer->getPointeeType()->isVoidType()) {
7552         Kind = CK_BitCast;
7553         return Compatible;
7554       }
7555     }
7556 
7557     return Incompatible;
7558   }
7559 
7560   // Conversions to block pointers.
7561   if (isa<BlockPointerType>(LHSType)) {
7562     // U^ -> T^
7563     if (RHSType->isBlockPointerType()) {
7564       Kind = CK_BitCast;
7565       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7566     }
7567 
7568     // int or null -> T^
7569     if (RHSType->isIntegerType()) {
7570       Kind = CK_IntegralToPointer; // FIXME: null
7571       return IntToBlockPointer;
7572     }
7573 
7574     // id -> T^
7575     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7576       Kind = CK_AnyPointerToBlockPointerCast;
7577       return Compatible;
7578     }
7579 
7580     // void* -> T^
7581     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7582       if (RHSPT->getPointeeType()->isVoidType()) {
7583         Kind = CK_AnyPointerToBlockPointerCast;
7584         return Compatible;
7585       }
7586 
7587     return Incompatible;
7588   }
7589 
7590   // Conversions to Objective-C pointers.
7591   if (isa<ObjCObjectPointerType>(LHSType)) {
7592     // A* -> B*
7593     if (RHSType->isObjCObjectPointerType()) {
7594       Kind = CK_BitCast;
7595       Sema::AssignConvertType result =
7596         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7597       if (getLangOpts().ObjCAutoRefCount &&
7598           result == Compatible &&
7599           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7600         result = IncompatibleObjCWeakRef;
7601       return result;
7602     }
7603 
7604     // int or null -> A*
7605     if (RHSType->isIntegerType()) {
7606       Kind = CK_IntegralToPointer; // FIXME: null
7607       return IntToPointer;
7608     }
7609 
7610     // In general, C pointers are not compatible with ObjC object pointers,
7611     // with two exceptions:
7612     if (isa<PointerType>(RHSType)) {
7613       Kind = CK_CPointerToObjCPointerCast;
7614 
7615       //  - conversions from 'void*'
7616       if (RHSType->isVoidPointerType()) {
7617         return Compatible;
7618       }
7619 
7620       //  - conversions to 'Class' from its redefinition type
7621       if (LHSType->isObjCClassType() &&
7622           Context.hasSameType(RHSType,
7623                               Context.getObjCClassRedefinitionType())) {
7624         return Compatible;
7625       }
7626 
7627       return IncompatiblePointer;
7628     }
7629 
7630     // Only under strict condition T^ is compatible with an Objective-C pointer.
7631     if (RHSType->isBlockPointerType() &&
7632         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7633       if (ConvertRHS)
7634         maybeExtendBlockObject(RHS);
7635       Kind = CK_BlockPointerToObjCPointerCast;
7636       return Compatible;
7637     }
7638 
7639     return Incompatible;
7640   }
7641 
7642   // Conversions from pointers that are not covered by the above.
7643   if (isa<PointerType>(RHSType)) {
7644     // T* -> _Bool
7645     if (LHSType == Context.BoolTy) {
7646       Kind = CK_PointerToBoolean;
7647       return Compatible;
7648     }
7649 
7650     // T* -> int
7651     if (LHSType->isIntegerType()) {
7652       Kind = CK_PointerToIntegral;
7653       return PointerToInt;
7654     }
7655 
7656     return Incompatible;
7657   }
7658 
7659   // Conversions from Objective-C pointers that are not covered by the above.
7660   if (isa<ObjCObjectPointerType>(RHSType)) {
7661     // T* -> _Bool
7662     if (LHSType == Context.BoolTy) {
7663       Kind = CK_PointerToBoolean;
7664       return Compatible;
7665     }
7666 
7667     // T* -> int
7668     if (LHSType->isIntegerType()) {
7669       Kind = CK_PointerToIntegral;
7670       return PointerToInt;
7671     }
7672 
7673     return Incompatible;
7674   }
7675 
7676   // struct A -> struct B
7677   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7678     if (Context.typesAreCompatible(LHSType, RHSType)) {
7679       Kind = CK_NoOp;
7680       return Compatible;
7681     }
7682   }
7683 
7684   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7685     Kind = CK_IntToOCLSampler;
7686     return Compatible;
7687   }
7688 
7689   return Incompatible;
7690 }
7691 
7692 /// \brief Constructs a transparent union from an expression that is
7693 /// used to initialize the transparent union.
7694 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7695                                       ExprResult &EResult, QualType UnionType,
7696                                       FieldDecl *Field) {
7697   // Build an initializer list that designates the appropriate member
7698   // of the transparent union.
7699   Expr *E = EResult.get();
7700   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7701                                                    E, SourceLocation());
7702   Initializer->setType(UnionType);
7703   Initializer->setInitializedFieldInUnion(Field);
7704 
7705   // Build a compound literal constructing a value of the transparent
7706   // union type from this initializer list.
7707   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7708   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7709                                         VK_RValue, Initializer, false);
7710 }
7711 
7712 Sema::AssignConvertType
7713 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7714                                                ExprResult &RHS) {
7715   QualType RHSType = RHS.get()->getType();
7716 
7717   // If the ArgType is a Union type, we want to handle a potential
7718   // transparent_union GCC extension.
7719   const RecordType *UT = ArgType->getAsUnionType();
7720   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7721     return Incompatible;
7722 
7723   // The field to initialize within the transparent union.
7724   RecordDecl *UD = UT->getDecl();
7725   FieldDecl *InitField = nullptr;
7726   // It's compatible if the expression matches any of the fields.
7727   for (auto *it : UD->fields()) {
7728     if (it->getType()->isPointerType()) {
7729       // If the transparent union contains a pointer type, we allow:
7730       // 1) void pointer
7731       // 2) null pointer constant
7732       if (RHSType->isPointerType())
7733         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7734           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7735           InitField = it;
7736           break;
7737         }
7738 
7739       if (RHS.get()->isNullPointerConstant(Context,
7740                                            Expr::NPC_ValueDependentIsNull)) {
7741         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7742                                 CK_NullToPointer);
7743         InitField = it;
7744         break;
7745       }
7746     }
7747 
7748     CastKind Kind = CK_Invalid;
7749     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7750           == Compatible) {
7751       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7752       InitField = it;
7753       break;
7754     }
7755   }
7756 
7757   if (!InitField)
7758     return Incompatible;
7759 
7760   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7761   return Compatible;
7762 }
7763 
7764 Sema::AssignConvertType
7765 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7766                                        bool Diagnose,
7767                                        bool DiagnoseCFAudited,
7768                                        bool ConvertRHS) {
7769   // We need to be able to tell the caller whether we diagnosed a problem, if
7770   // they ask us to issue diagnostics.
7771   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7772 
7773   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7774   // we can't avoid *all* modifications at the moment, so we need some somewhere
7775   // to put the updated value.
7776   ExprResult LocalRHS = CallerRHS;
7777   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7778 
7779   if (getLangOpts().CPlusPlus) {
7780     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7781       // C++ 5.17p3: If the left operand is not of class type, the
7782       // expression is implicitly converted (C++ 4) to the
7783       // cv-unqualified type of the left operand.
7784       QualType RHSType = RHS.get()->getType();
7785       if (Diagnose) {
7786         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7787                                         AA_Assigning);
7788       } else {
7789         ImplicitConversionSequence ICS =
7790             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7791                                   /*SuppressUserConversions=*/false,
7792                                   /*AllowExplicit=*/false,
7793                                   /*InOverloadResolution=*/false,
7794                                   /*CStyle=*/false,
7795                                   /*AllowObjCWritebackConversion=*/false);
7796         if (ICS.isFailure())
7797           return Incompatible;
7798         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7799                                         ICS, AA_Assigning);
7800       }
7801       if (RHS.isInvalid())
7802         return Incompatible;
7803       Sema::AssignConvertType result = Compatible;
7804       if (getLangOpts().ObjCAutoRefCount &&
7805           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7806         result = IncompatibleObjCWeakRef;
7807       return result;
7808     }
7809 
7810     // FIXME: Currently, we fall through and treat C++ classes like C
7811     // structures.
7812     // FIXME: We also fall through for atomics; not sure what should
7813     // happen there, though.
7814   } else if (RHS.get()->getType() == Context.OverloadTy) {
7815     // As a set of extensions to C, we support overloading on functions. These
7816     // functions need to be resolved here.
7817     DeclAccessPair DAP;
7818     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7819             RHS.get(), LHSType, /*Complain=*/false, DAP))
7820       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7821     else
7822       return Incompatible;
7823   }
7824 
7825   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7826   // a null pointer constant.
7827   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7828        LHSType->isBlockPointerType()) &&
7829       RHS.get()->isNullPointerConstant(Context,
7830                                        Expr::NPC_ValueDependentIsNull)) {
7831     if (Diagnose || ConvertRHS) {
7832       CastKind Kind;
7833       CXXCastPath Path;
7834       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7835                              /*IgnoreBaseAccess=*/false, Diagnose);
7836       if (ConvertRHS)
7837         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7838     }
7839     return Compatible;
7840   }
7841 
7842   // This check seems unnatural, however it is necessary to ensure the proper
7843   // conversion of functions/arrays. If the conversion were done for all
7844   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7845   // expressions that suppress this implicit conversion (&, sizeof).
7846   //
7847   // Suppress this for references: C++ 8.5.3p5.
7848   if (!LHSType->isReferenceType()) {
7849     // FIXME: We potentially allocate here even if ConvertRHS is false.
7850     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7851     if (RHS.isInvalid())
7852       return Incompatible;
7853   }
7854 
7855   Expr *PRE = RHS.get()->IgnoreParenCasts();
7856   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7857     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7858     if (PDecl && !PDecl->hasDefinition()) {
7859       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7860       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7861     }
7862   }
7863 
7864   CastKind Kind = CK_Invalid;
7865   Sema::AssignConvertType result =
7866     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7867 
7868   // C99 6.5.16.1p2: The value of the right operand is converted to the
7869   // type of the assignment expression.
7870   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7871   // so that we can use references in built-in functions even in C.
7872   // The getNonReferenceType() call makes sure that the resulting expression
7873   // does not have reference type.
7874   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7875     QualType Ty = LHSType.getNonLValueExprType(Context);
7876     Expr *E = RHS.get();
7877 
7878     // Check for various Objective-C errors. If we are not reporting
7879     // diagnostics and just checking for errors, e.g., during overload
7880     // resolution, return Incompatible to indicate the failure.
7881     if (getLangOpts().ObjCAutoRefCount &&
7882         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7883                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7884       if (!Diagnose)
7885         return Incompatible;
7886     }
7887     if (getLangOpts().ObjC1 &&
7888         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7889                                            E->getType(), E, Diagnose) ||
7890          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7891       if (!Diagnose)
7892         return Incompatible;
7893       // Replace the expression with a corrected version and continue so we
7894       // can find further errors.
7895       RHS = E;
7896       return Compatible;
7897     }
7898 
7899     if (ConvertRHS)
7900       RHS = ImpCastExprToType(E, Ty, Kind);
7901   }
7902   return result;
7903 }
7904 
7905 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7906                                ExprResult &RHS) {
7907   Diag(Loc, diag::err_typecheck_invalid_operands)
7908     << LHS.get()->getType() << RHS.get()->getType()
7909     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7910   return QualType();
7911 }
7912 
7913 /// Try to convert a value of non-vector type to a vector type by converting
7914 /// the type to the element type of the vector and then performing a splat.
7915 /// If the language is OpenCL, we only use conversions that promote scalar
7916 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7917 /// for float->int.
7918 ///
7919 /// \param scalar - if non-null, actually perform the conversions
7920 /// \return true if the operation fails (but without diagnosing the failure)
7921 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7922                                      QualType scalarTy,
7923                                      QualType vectorEltTy,
7924                                      QualType vectorTy) {
7925   // The conversion to apply to the scalar before splatting it,
7926   // if necessary.
7927   CastKind scalarCast = CK_Invalid;
7928 
7929   if (vectorEltTy->isIntegralType(S.Context)) {
7930     if (!scalarTy->isIntegralType(S.Context))
7931       return true;
7932     if (S.getLangOpts().OpenCL &&
7933         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7934       return true;
7935     scalarCast = CK_IntegralCast;
7936   } else if (vectorEltTy->isRealFloatingType()) {
7937     if (scalarTy->isRealFloatingType()) {
7938       if (S.getLangOpts().OpenCL &&
7939           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7940         return true;
7941       scalarCast = CK_FloatingCast;
7942     }
7943     else if (scalarTy->isIntegralType(S.Context))
7944       scalarCast = CK_IntegralToFloating;
7945     else
7946       return true;
7947   } else {
7948     return true;
7949   }
7950 
7951   // Adjust scalar if desired.
7952   if (scalar) {
7953     if (scalarCast != CK_Invalid)
7954       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7955     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7956   }
7957   return false;
7958 }
7959 
7960 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7961                                    SourceLocation Loc, bool IsCompAssign,
7962                                    bool AllowBothBool,
7963                                    bool AllowBoolConversions) {
7964   if (!IsCompAssign) {
7965     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7966     if (LHS.isInvalid())
7967       return QualType();
7968   }
7969   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7970   if (RHS.isInvalid())
7971     return QualType();
7972 
7973   // For conversion purposes, we ignore any qualifiers.
7974   // For example, "const float" and "float" are equivalent.
7975   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7976   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7977 
7978   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7979   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7980   assert(LHSVecType || RHSVecType);
7981 
7982   // AltiVec-style "vector bool op vector bool" combinations are allowed
7983   // for some operators but not others.
7984   if (!AllowBothBool &&
7985       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7986       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7987     return InvalidOperands(Loc, LHS, RHS);
7988 
7989   // If the vector types are identical, return.
7990   if (Context.hasSameType(LHSType, RHSType))
7991     return LHSType;
7992 
7993   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7994   if (LHSVecType && RHSVecType &&
7995       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7996     if (isa<ExtVectorType>(LHSVecType)) {
7997       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7998       return LHSType;
7999     }
8000 
8001     if (!IsCompAssign)
8002       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8003     return RHSType;
8004   }
8005 
8006   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8007   // can be mixed, with the result being the non-bool type.  The non-bool
8008   // operand must have integer element type.
8009   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8010       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8011       (Context.getTypeSize(LHSVecType->getElementType()) ==
8012        Context.getTypeSize(RHSVecType->getElementType()))) {
8013     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8014         LHSVecType->getElementType()->isIntegerType() &&
8015         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8016       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8017       return LHSType;
8018     }
8019     if (!IsCompAssign &&
8020         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8021         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8022         RHSVecType->getElementType()->isIntegerType()) {
8023       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8024       return RHSType;
8025     }
8026   }
8027 
8028   // If there's an ext-vector type and a scalar, try to convert the scalar to
8029   // the vector element type and splat.
8030   // FIXME: this should also work for regular vector types as supported in GCC.
8031   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8032     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8033                                   LHSVecType->getElementType(), LHSType))
8034       return LHSType;
8035   }
8036   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8037     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8038                                   LHSType, RHSVecType->getElementType(),
8039                                   RHSType))
8040       return RHSType;
8041   }
8042 
8043   // FIXME: The code below also handles convertion between vectors and
8044   // non-scalars, we should break this down into fine grained specific checks
8045   // and emit proper diagnostics.
8046   QualType VecType = LHSVecType ? LHSType : RHSType;
8047   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8048   QualType OtherType = LHSVecType ? RHSType : LHSType;
8049   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8050   if (isLaxVectorConversion(OtherType, VecType)) {
8051     // If we're allowing lax vector conversions, only the total (data) size
8052     // needs to be the same. For non compound assignment, if one of the types is
8053     // scalar, the result is always the vector type.
8054     if (!IsCompAssign) {
8055       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8056       return VecType;
8057     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8058     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8059     // type. Note that this is already done by non-compound assignments in
8060     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8061     // <1 x T> -> T. The result is also a vector type.
8062     } else if (OtherType->isExtVectorType() ||
8063                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8064       ExprResult *RHSExpr = &RHS;
8065       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8066       return VecType;
8067     }
8068   }
8069 
8070   // Okay, the expression is invalid.
8071 
8072   // If there's a non-vector, non-real operand, diagnose that.
8073   if ((!RHSVecType && !RHSType->isRealType()) ||
8074       (!LHSVecType && !LHSType->isRealType())) {
8075     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8076       << LHSType << RHSType
8077       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8078     return QualType();
8079   }
8080 
8081   // OpenCL V1.1 6.2.6.p1:
8082   // If the operands are of more than one vector type, then an error shall
8083   // occur. Implicit conversions between vector types are not permitted, per
8084   // section 6.2.1.
8085   if (getLangOpts().OpenCL &&
8086       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8087       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8088     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8089                                                            << RHSType;
8090     return QualType();
8091   }
8092 
8093   // Otherwise, use the generic diagnostic.
8094   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8095     << LHSType << RHSType
8096     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8097   return QualType();
8098 }
8099 
8100 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8101 // expression.  These are mainly cases where the null pointer is used as an
8102 // integer instead of a pointer.
8103 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8104                                 SourceLocation Loc, bool IsCompare) {
8105   // The canonical way to check for a GNU null is with isNullPointerConstant,
8106   // but we use a bit of a hack here for speed; this is a relatively
8107   // hot path, and isNullPointerConstant is slow.
8108   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8109   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8110 
8111   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8112 
8113   // Avoid analyzing cases where the result will either be invalid (and
8114   // diagnosed as such) or entirely valid and not something to warn about.
8115   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8116       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8117     return;
8118 
8119   // Comparison operations would not make sense with a null pointer no matter
8120   // what the other expression is.
8121   if (!IsCompare) {
8122     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8123         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8124         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8125     return;
8126   }
8127 
8128   // The rest of the operations only make sense with a null pointer
8129   // if the other expression is a pointer.
8130   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8131       NonNullType->canDecayToPointerType())
8132     return;
8133 
8134   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8135       << LHSNull /* LHS is NULL */ << NonNullType
8136       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8137 }
8138 
8139 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8140                                                ExprResult &RHS,
8141                                                SourceLocation Loc, bool IsDiv) {
8142   // Check for division/remainder by zero.
8143   llvm::APSInt RHSValue;
8144   if (!RHS.get()->isValueDependent() &&
8145       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8146     S.DiagRuntimeBehavior(Loc, RHS.get(),
8147                           S.PDiag(diag::warn_remainder_division_by_zero)
8148                             << IsDiv << RHS.get()->getSourceRange());
8149 }
8150 
8151 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8152                                            SourceLocation Loc,
8153                                            bool IsCompAssign, bool IsDiv) {
8154   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8155 
8156   if (LHS.get()->getType()->isVectorType() ||
8157       RHS.get()->getType()->isVectorType())
8158     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8159                                /*AllowBothBool*/getLangOpts().AltiVec,
8160                                /*AllowBoolConversions*/false);
8161 
8162   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8163   if (LHS.isInvalid() || RHS.isInvalid())
8164     return QualType();
8165 
8166 
8167   if (compType.isNull() || !compType->isArithmeticType())
8168     return InvalidOperands(Loc, LHS, RHS);
8169   if (IsDiv)
8170     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8171   return compType;
8172 }
8173 
8174 QualType Sema::CheckRemainderOperands(
8175   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8176   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8177 
8178   if (LHS.get()->getType()->isVectorType() ||
8179       RHS.get()->getType()->isVectorType()) {
8180     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8181         RHS.get()->getType()->hasIntegerRepresentation())
8182       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8183                                  /*AllowBothBool*/getLangOpts().AltiVec,
8184                                  /*AllowBoolConversions*/false);
8185     return InvalidOperands(Loc, LHS, RHS);
8186   }
8187 
8188   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8189   if (LHS.isInvalid() || RHS.isInvalid())
8190     return QualType();
8191 
8192   if (compType.isNull() || !compType->isIntegerType())
8193     return InvalidOperands(Loc, LHS, RHS);
8194   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8195   return compType;
8196 }
8197 
8198 /// \brief Diagnose invalid arithmetic on two void pointers.
8199 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8200                                                 Expr *LHSExpr, Expr *RHSExpr) {
8201   S.Diag(Loc, S.getLangOpts().CPlusPlus
8202                 ? diag::err_typecheck_pointer_arith_void_type
8203                 : diag::ext_gnu_void_ptr)
8204     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8205                             << RHSExpr->getSourceRange();
8206 }
8207 
8208 /// \brief Diagnose invalid arithmetic on a void pointer.
8209 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8210                                             Expr *Pointer) {
8211   S.Diag(Loc, S.getLangOpts().CPlusPlus
8212                 ? diag::err_typecheck_pointer_arith_void_type
8213                 : diag::ext_gnu_void_ptr)
8214     << 0 /* one pointer */ << Pointer->getSourceRange();
8215 }
8216 
8217 /// \brief Diagnose invalid arithmetic on two function pointers.
8218 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8219                                                     Expr *LHS, Expr *RHS) {
8220   assert(LHS->getType()->isAnyPointerType());
8221   assert(RHS->getType()->isAnyPointerType());
8222   S.Diag(Loc, S.getLangOpts().CPlusPlus
8223                 ? diag::err_typecheck_pointer_arith_function_type
8224                 : diag::ext_gnu_ptr_func_arith)
8225     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8226     // We only show the second type if it differs from the first.
8227     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8228                                                    RHS->getType())
8229     << RHS->getType()->getPointeeType()
8230     << LHS->getSourceRange() << RHS->getSourceRange();
8231 }
8232 
8233 /// \brief Diagnose invalid arithmetic on a function pointer.
8234 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8235                                                 Expr *Pointer) {
8236   assert(Pointer->getType()->isAnyPointerType());
8237   S.Diag(Loc, S.getLangOpts().CPlusPlus
8238                 ? diag::err_typecheck_pointer_arith_function_type
8239                 : diag::ext_gnu_ptr_func_arith)
8240     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8241     << 0 /* one pointer, so only one type */
8242     << Pointer->getSourceRange();
8243 }
8244 
8245 /// \brief Emit error if Operand is incomplete pointer type
8246 ///
8247 /// \returns True if pointer has incomplete type
8248 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8249                                                  Expr *Operand) {
8250   QualType ResType = Operand->getType();
8251   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8252     ResType = ResAtomicType->getValueType();
8253 
8254   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8255   QualType PointeeTy = ResType->getPointeeType();
8256   return S.RequireCompleteType(Loc, PointeeTy,
8257                                diag::err_typecheck_arithmetic_incomplete_type,
8258                                PointeeTy, Operand->getSourceRange());
8259 }
8260 
8261 /// \brief Check the validity of an arithmetic pointer operand.
8262 ///
8263 /// If the operand has pointer type, this code will check for pointer types
8264 /// which are invalid in arithmetic operations. These will be diagnosed
8265 /// appropriately, including whether or not the use is supported as an
8266 /// extension.
8267 ///
8268 /// \returns True when the operand is valid to use (even if as an extension).
8269 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8270                                             Expr *Operand) {
8271   QualType ResType = Operand->getType();
8272   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8273     ResType = ResAtomicType->getValueType();
8274 
8275   if (!ResType->isAnyPointerType()) return true;
8276 
8277   QualType PointeeTy = ResType->getPointeeType();
8278   if (PointeeTy->isVoidType()) {
8279     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8280     return !S.getLangOpts().CPlusPlus;
8281   }
8282   if (PointeeTy->isFunctionType()) {
8283     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8284     return !S.getLangOpts().CPlusPlus;
8285   }
8286 
8287   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8288 
8289   return true;
8290 }
8291 
8292 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8293 /// operands.
8294 ///
8295 /// This routine will diagnose any invalid arithmetic on pointer operands much
8296 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8297 /// for emitting a single diagnostic even for operations where both LHS and RHS
8298 /// are (potentially problematic) pointers.
8299 ///
8300 /// \returns True when the operand is valid to use (even if as an extension).
8301 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8302                                                 Expr *LHSExpr, Expr *RHSExpr) {
8303   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8304   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8305   if (!isLHSPointer && !isRHSPointer) return true;
8306 
8307   QualType LHSPointeeTy, RHSPointeeTy;
8308   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8309   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8310 
8311   // if both are pointers check if operation is valid wrt address spaces
8312   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8313     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8314     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8315     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8316       S.Diag(Loc,
8317              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8318           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8319           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8320       return false;
8321     }
8322   }
8323 
8324   // Check for arithmetic on pointers to incomplete types.
8325   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8326   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8327   if (isLHSVoidPtr || isRHSVoidPtr) {
8328     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8329     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8330     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8331 
8332     return !S.getLangOpts().CPlusPlus;
8333   }
8334 
8335   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8336   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8337   if (isLHSFuncPtr || isRHSFuncPtr) {
8338     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8339     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8340                                                                 RHSExpr);
8341     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8342 
8343     return !S.getLangOpts().CPlusPlus;
8344   }
8345 
8346   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8347     return false;
8348   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8349     return false;
8350 
8351   return true;
8352 }
8353 
8354 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8355 /// literal.
8356 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8357                                   Expr *LHSExpr, Expr *RHSExpr) {
8358   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8359   Expr* IndexExpr = RHSExpr;
8360   if (!StrExpr) {
8361     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8362     IndexExpr = LHSExpr;
8363   }
8364 
8365   bool IsStringPlusInt = StrExpr &&
8366       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8367   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8368     return;
8369 
8370   llvm::APSInt index;
8371   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8372     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8373     if (index.isNonNegative() &&
8374         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8375                               index.isUnsigned()))
8376       return;
8377   }
8378 
8379   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8380   Self.Diag(OpLoc, diag::warn_string_plus_int)
8381       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8382 
8383   // Only print a fixit for "str" + int, not for int + "str".
8384   if (IndexExpr == RHSExpr) {
8385     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8386     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8387         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8388         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8389         << FixItHint::CreateInsertion(EndLoc, "]");
8390   } else
8391     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8392 }
8393 
8394 /// \brief Emit a warning when adding a char literal to a string.
8395 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8396                                    Expr *LHSExpr, Expr *RHSExpr) {
8397   const Expr *StringRefExpr = LHSExpr;
8398   const CharacterLiteral *CharExpr =
8399       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8400 
8401   if (!CharExpr) {
8402     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8403     StringRefExpr = RHSExpr;
8404   }
8405 
8406   if (!CharExpr || !StringRefExpr)
8407     return;
8408 
8409   const QualType StringType = StringRefExpr->getType();
8410 
8411   // Return if not a PointerType.
8412   if (!StringType->isAnyPointerType())
8413     return;
8414 
8415   // Return if not a CharacterType.
8416   if (!StringType->getPointeeType()->isAnyCharacterType())
8417     return;
8418 
8419   ASTContext &Ctx = Self.getASTContext();
8420   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8421 
8422   const QualType CharType = CharExpr->getType();
8423   if (!CharType->isAnyCharacterType() &&
8424       CharType->isIntegerType() &&
8425       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8426     Self.Diag(OpLoc, diag::warn_string_plus_char)
8427         << DiagRange << Ctx.CharTy;
8428   } else {
8429     Self.Diag(OpLoc, diag::warn_string_plus_char)
8430         << DiagRange << CharExpr->getType();
8431   }
8432 
8433   // Only print a fixit for str + char, not for char + str.
8434   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8435     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8436     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8437         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8438         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8439         << FixItHint::CreateInsertion(EndLoc, "]");
8440   } else {
8441     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8442   }
8443 }
8444 
8445 /// \brief Emit error when two pointers are incompatible.
8446 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8447                                            Expr *LHSExpr, Expr *RHSExpr) {
8448   assert(LHSExpr->getType()->isAnyPointerType());
8449   assert(RHSExpr->getType()->isAnyPointerType());
8450   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8451     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8452     << RHSExpr->getSourceRange();
8453 }
8454 
8455 // C99 6.5.6
8456 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8457                                      SourceLocation Loc, BinaryOperatorKind Opc,
8458                                      QualType* CompLHSTy) {
8459   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8460 
8461   if (LHS.get()->getType()->isVectorType() ||
8462       RHS.get()->getType()->isVectorType()) {
8463     QualType compType = CheckVectorOperands(
8464         LHS, RHS, Loc, CompLHSTy,
8465         /*AllowBothBool*/getLangOpts().AltiVec,
8466         /*AllowBoolConversions*/getLangOpts().ZVector);
8467     if (CompLHSTy) *CompLHSTy = compType;
8468     return compType;
8469   }
8470 
8471   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8472   if (LHS.isInvalid() || RHS.isInvalid())
8473     return QualType();
8474 
8475   // Diagnose "string literal" '+' int and string '+' "char literal".
8476   if (Opc == BO_Add) {
8477     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8478     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8479   }
8480 
8481   // handle the common case first (both operands are arithmetic).
8482   if (!compType.isNull() && compType->isArithmeticType()) {
8483     if (CompLHSTy) *CompLHSTy = compType;
8484     return compType;
8485   }
8486 
8487   // Type-checking.  Ultimately the pointer's going to be in PExp;
8488   // note that we bias towards the LHS being the pointer.
8489   Expr *PExp = LHS.get(), *IExp = RHS.get();
8490 
8491   bool isObjCPointer;
8492   if (PExp->getType()->isPointerType()) {
8493     isObjCPointer = false;
8494   } else if (PExp->getType()->isObjCObjectPointerType()) {
8495     isObjCPointer = true;
8496   } else {
8497     std::swap(PExp, IExp);
8498     if (PExp->getType()->isPointerType()) {
8499       isObjCPointer = false;
8500     } else if (PExp->getType()->isObjCObjectPointerType()) {
8501       isObjCPointer = true;
8502     } else {
8503       return InvalidOperands(Loc, LHS, RHS);
8504     }
8505   }
8506   assert(PExp->getType()->isAnyPointerType());
8507 
8508   if (!IExp->getType()->isIntegerType())
8509     return InvalidOperands(Loc, LHS, RHS);
8510 
8511   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8512     return QualType();
8513 
8514   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8515     return QualType();
8516 
8517   // Check array bounds for pointer arithemtic
8518   CheckArrayAccess(PExp, IExp);
8519 
8520   if (CompLHSTy) {
8521     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8522     if (LHSTy.isNull()) {
8523       LHSTy = LHS.get()->getType();
8524       if (LHSTy->isPromotableIntegerType())
8525         LHSTy = Context.getPromotedIntegerType(LHSTy);
8526     }
8527     *CompLHSTy = LHSTy;
8528   }
8529 
8530   return PExp->getType();
8531 }
8532 
8533 // C99 6.5.6
8534 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8535                                         SourceLocation Loc,
8536                                         QualType* CompLHSTy) {
8537   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8538 
8539   if (LHS.get()->getType()->isVectorType() ||
8540       RHS.get()->getType()->isVectorType()) {
8541     QualType compType = CheckVectorOperands(
8542         LHS, RHS, Loc, CompLHSTy,
8543         /*AllowBothBool*/getLangOpts().AltiVec,
8544         /*AllowBoolConversions*/getLangOpts().ZVector);
8545     if (CompLHSTy) *CompLHSTy = compType;
8546     return compType;
8547   }
8548 
8549   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8550   if (LHS.isInvalid() || RHS.isInvalid())
8551     return QualType();
8552 
8553   // Enforce type constraints: C99 6.5.6p3.
8554 
8555   // Handle the common case first (both operands are arithmetic).
8556   if (!compType.isNull() && compType->isArithmeticType()) {
8557     if (CompLHSTy) *CompLHSTy = compType;
8558     return compType;
8559   }
8560 
8561   // Either ptr - int   or   ptr - ptr.
8562   if (LHS.get()->getType()->isAnyPointerType()) {
8563     QualType lpointee = LHS.get()->getType()->getPointeeType();
8564 
8565     // Diagnose bad cases where we step over interface counts.
8566     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8567         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8568       return QualType();
8569 
8570     // The result type of a pointer-int computation is the pointer type.
8571     if (RHS.get()->getType()->isIntegerType()) {
8572       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8573         return QualType();
8574 
8575       // Check array bounds for pointer arithemtic
8576       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8577                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8578 
8579       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8580       return LHS.get()->getType();
8581     }
8582 
8583     // Handle pointer-pointer subtractions.
8584     if (const PointerType *RHSPTy
8585           = RHS.get()->getType()->getAs<PointerType>()) {
8586       QualType rpointee = RHSPTy->getPointeeType();
8587 
8588       if (getLangOpts().CPlusPlus) {
8589         // Pointee types must be the same: C++ [expr.add]
8590         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8591           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8592         }
8593       } else {
8594         // Pointee types must be compatible C99 6.5.6p3
8595         if (!Context.typesAreCompatible(
8596                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8597                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8598           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8599           return QualType();
8600         }
8601       }
8602 
8603       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8604                                                LHS.get(), RHS.get()))
8605         return QualType();
8606 
8607       // The pointee type may have zero size.  As an extension, a structure or
8608       // union may have zero size or an array may have zero length.  In this
8609       // case subtraction does not make sense.
8610       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8611         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8612         if (ElementSize.isZero()) {
8613           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8614             << rpointee.getUnqualifiedType()
8615             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8616         }
8617       }
8618 
8619       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8620       return Context.getPointerDiffType();
8621     }
8622   }
8623 
8624   return InvalidOperands(Loc, LHS, RHS);
8625 }
8626 
8627 static bool isScopedEnumerationType(QualType T) {
8628   if (const EnumType *ET = T->getAs<EnumType>())
8629     return ET->getDecl()->isScoped();
8630   return false;
8631 }
8632 
8633 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8634                                    SourceLocation Loc, BinaryOperatorKind Opc,
8635                                    QualType LHSType) {
8636   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8637   // so skip remaining warnings as we don't want to modify values within Sema.
8638   if (S.getLangOpts().OpenCL)
8639     return;
8640 
8641   llvm::APSInt Right;
8642   // Check right/shifter operand
8643   if (RHS.get()->isValueDependent() ||
8644       !RHS.get()->EvaluateAsInt(Right, S.Context))
8645     return;
8646 
8647   if (Right.isNegative()) {
8648     S.DiagRuntimeBehavior(Loc, RHS.get(),
8649                           S.PDiag(diag::warn_shift_negative)
8650                             << RHS.get()->getSourceRange());
8651     return;
8652   }
8653   llvm::APInt LeftBits(Right.getBitWidth(),
8654                        S.Context.getTypeSize(LHS.get()->getType()));
8655   if (Right.uge(LeftBits)) {
8656     S.DiagRuntimeBehavior(Loc, RHS.get(),
8657                           S.PDiag(diag::warn_shift_gt_typewidth)
8658                             << RHS.get()->getSourceRange());
8659     return;
8660   }
8661   if (Opc != BO_Shl)
8662     return;
8663 
8664   // When left shifting an ICE which is signed, we can check for overflow which
8665   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8666   // integers have defined behavior modulo one more than the maximum value
8667   // representable in the result type, so never warn for those.
8668   llvm::APSInt Left;
8669   if (LHS.get()->isValueDependent() ||
8670       LHSType->hasUnsignedIntegerRepresentation() ||
8671       !LHS.get()->EvaluateAsInt(Left, S.Context))
8672     return;
8673 
8674   // If LHS does not have a signed type and non-negative value
8675   // then, the behavior is undefined. Warn about it.
8676   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8677     S.DiagRuntimeBehavior(Loc, LHS.get(),
8678                           S.PDiag(diag::warn_shift_lhs_negative)
8679                             << LHS.get()->getSourceRange());
8680     return;
8681   }
8682 
8683   llvm::APInt ResultBits =
8684       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8685   if (LeftBits.uge(ResultBits))
8686     return;
8687   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8688   Result = Result.shl(Right);
8689 
8690   // Print the bit representation of the signed integer as an unsigned
8691   // hexadecimal number.
8692   SmallString<40> HexResult;
8693   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8694 
8695   // If we are only missing a sign bit, this is less likely to result in actual
8696   // bugs -- if the result is cast back to an unsigned type, it will have the
8697   // expected value. Thus we place this behind a different warning that can be
8698   // turned off separately if needed.
8699   if (LeftBits == ResultBits - 1) {
8700     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8701         << HexResult << LHSType
8702         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8703     return;
8704   }
8705 
8706   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8707     << HexResult.str() << Result.getMinSignedBits() << LHSType
8708     << Left.getBitWidth() << LHS.get()->getSourceRange()
8709     << RHS.get()->getSourceRange();
8710 }
8711 
8712 /// \brief Return the resulting type when a vector is shifted
8713 ///        by a scalar or vector shift amount.
8714 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8715                                  SourceLocation Loc, bool IsCompAssign) {
8716   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8717   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8718       !LHS.get()->getType()->isVectorType()) {
8719     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8720       << RHS.get()->getType() << LHS.get()->getType()
8721       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8722     return QualType();
8723   }
8724 
8725   if (!IsCompAssign) {
8726     LHS = S.UsualUnaryConversions(LHS.get());
8727     if (LHS.isInvalid()) return QualType();
8728   }
8729 
8730   RHS = S.UsualUnaryConversions(RHS.get());
8731   if (RHS.isInvalid()) return QualType();
8732 
8733   QualType LHSType = LHS.get()->getType();
8734   // Note that LHS might be a scalar because the routine calls not only in
8735   // OpenCL case.
8736   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8737   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8738 
8739   // Note that RHS might not be a vector.
8740   QualType RHSType = RHS.get()->getType();
8741   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8742   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8743 
8744   // The operands need to be integers.
8745   if (!LHSEleType->isIntegerType()) {
8746     S.Diag(Loc, diag::err_typecheck_expect_int)
8747       << LHS.get()->getType() << LHS.get()->getSourceRange();
8748     return QualType();
8749   }
8750 
8751   if (!RHSEleType->isIntegerType()) {
8752     S.Diag(Loc, diag::err_typecheck_expect_int)
8753       << RHS.get()->getType() << RHS.get()->getSourceRange();
8754     return QualType();
8755   }
8756 
8757   if (!LHSVecTy) {
8758     assert(RHSVecTy);
8759     if (IsCompAssign)
8760       return RHSType;
8761     if (LHSEleType != RHSEleType) {
8762       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8763       LHSEleType = RHSEleType;
8764     }
8765     QualType VecTy =
8766         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8767     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8768     LHSType = VecTy;
8769   } else if (RHSVecTy) {
8770     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8771     // are applied component-wise. So if RHS is a vector, then ensure
8772     // that the number of elements is the same as LHS...
8773     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8774       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8775         << LHS.get()->getType() << RHS.get()->getType()
8776         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8777       return QualType();
8778     }
8779     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8780       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8781       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8782       if (LHSBT != RHSBT &&
8783           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8784         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8785             << LHS.get()->getType() << RHS.get()->getType()
8786             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8787       }
8788     }
8789   } else {
8790     // ...else expand RHS to match the number of elements in LHS.
8791     QualType VecTy =
8792       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8793     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8794   }
8795 
8796   return LHSType;
8797 }
8798 
8799 // C99 6.5.7
8800 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8801                                   SourceLocation Loc, BinaryOperatorKind Opc,
8802                                   bool IsCompAssign) {
8803   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8804 
8805   // Vector shifts promote their scalar inputs to vector type.
8806   if (LHS.get()->getType()->isVectorType() ||
8807       RHS.get()->getType()->isVectorType()) {
8808     if (LangOpts.ZVector) {
8809       // The shift operators for the z vector extensions work basically
8810       // like general shifts, except that neither the LHS nor the RHS is
8811       // allowed to be a "vector bool".
8812       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8813         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8814           return InvalidOperands(Loc, LHS, RHS);
8815       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8816         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8817           return InvalidOperands(Loc, LHS, RHS);
8818     }
8819     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8820   }
8821 
8822   // Shifts don't perform usual arithmetic conversions, they just do integer
8823   // promotions on each operand. C99 6.5.7p3
8824 
8825   // For the LHS, do usual unary conversions, but then reset them away
8826   // if this is a compound assignment.
8827   ExprResult OldLHS = LHS;
8828   LHS = UsualUnaryConversions(LHS.get());
8829   if (LHS.isInvalid())
8830     return QualType();
8831   QualType LHSType = LHS.get()->getType();
8832   if (IsCompAssign) LHS = OldLHS;
8833 
8834   // The RHS is simpler.
8835   RHS = UsualUnaryConversions(RHS.get());
8836   if (RHS.isInvalid())
8837     return QualType();
8838   QualType RHSType = RHS.get()->getType();
8839 
8840   // C99 6.5.7p2: Each of the operands shall have integer type.
8841   if (!LHSType->hasIntegerRepresentation() ||
8842       !RHSType->hasIntegerRepresentation())
8843     return InvalidOperands(Loc, LHS, RHS);
8844 
8845   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8846   // hasIntegerRepresentation() above instead of this.
8847   if (isScopedEnumerationType(LHSType) ||
8848       isScopedEnumerationType(RHSType)) {
8849     return InvalidOperands(Loc, LHS, RHS);
8850   }
8851   // Sanity-check shift operands
8852   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8853 
8854   // "The type of the result is that of the promoted left operand."
8855   return LHSType;
8856 }
8857 
8858 static bool IsWithinTemplateSpecialization(Decl *D) {
8859   if (DeclContext *DC = D->getDeclContext()) {
8860     if (isa<ClassTemplateSpecializationDecl>(DC))
8861       return true;
8862     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8863       return FD->isFunctionTemplateSpecialization();
8864   }
8865   return false;
8866 }
8867 
8868 /// If two different enums are compared, raise a warning.
8869 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8870                                 Expr *RHS) {
8871   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8872   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8873 
8874   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8875   if (!LHSEnumType)
8876     return;
8877   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8878   if (!RHSEnumType)
8879     return;
8880 
8881   // Ignore anonymous enums.
8882   if (!LHSEnumType->getDecl()->getIdentifier())
8883     return;
8884   if (!RHSEnumType->getDecl()->getIdentifier())
8885     return;
8886 
8887   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8888     return;
8889 
8890   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8891       << LHSStrippedType << RHSStrippedType
8892       << LHS->getSourceRange() << RHS->getSourceRange();
8893 }
8894 
8895 /// \brief Diagnose bad pointer comparisons.
8896 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8897                                               ExprResult &LHS, ExprResult &RHS,
8898                                               bool IsError) {
8899   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8900                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8901     << LHS.get()->getType() << RHS.get()->getType()
8902     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8903 }
8904 
8905 /// \brief Returns false if the pointers are converted to a composite type,
8906 /// true otherwise.
8907 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8908                                            ExprResult &LHS, ExprResult &RHS) {
8909   // C++ [expr.rel]p2:
8910   //   [...] Pointer conversions (4.10) and qualification
8911   //   conversions (4.4) are performed on pointer operands (or on
8912   //   a pointer operand and a null pointer constant) to bring
8913   //   them to their composite pointer type. [...]
8914   //
8915   // C++ [expr.eq]p1 uses the same notion for (in)equality
8916   // comparisons of pointers.
8917 
8918   QualType LHSType = LHS.get()->getType();
8919   QualType RHSType = RHS.get()->getType();
8920   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8921          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
8922 
8923   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
8924   if (T.isNull()) {
8925     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8926         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8927       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8928     else
8929       S.InvalidOperands(Loc, LHS, RHS);
8930     return true;
8931   }
8932 
8933   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8934   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8935   return false;
8936 }
8937 
8938 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8939                                                     ExprResult &LHS,
8940                                                     ExprResult &RHS,
8941                                                     bool IsError) {
8942   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8943                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8944     << LHS.get()->getType() << RHS.get()->getType()
8945     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8946 }
8947 
8948 static bool isObjCObjectLiteral(ExprResult &E) {
8949   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8950   case Stmt::ObjCArrayLiteralClass:
8951   case Stmt::ObjCDictionaryLiteralClass:
8952   case Stmt::ObjCStringLiteralClass:
8953   case Stmt::ObjCBoxedExprClass:
8954     return true;
8955   default:
8956     // Note that ObjCBoolLiteral is NOT an object literal!
8957     return false;
8958   }
8959 }
8960 
8961 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8962   const ObjCObjectPointerType *Type =
8963     LHS->getType()->getAs<ObjCObjectPointerType>();
8964 
8965   // If this is not actually an Objective-C object, bail out.
8966   if (!Type)
8967     return false;
8968 
8969   // Get the LHS object's interface type.
8970   QualType InterfaceType = Type->getPointeeType();
8971 
8972   // If the RHS isn't an Objective-C object, bail out.
8973   if (!RHS->getType()->isObjCObjectPointerType())
8974     return false;
8975 
8976   // Try to find the -isEqual: method.
8977   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8978   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8979                                                       InterfaceType,
8980                                                       /*instance=*/true);
8981   if (!Method) {
8982     if (Type->isObjCIdType()) {
8983       // For 'id', just check the global pool.
8984       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8985                                                   /*receiverId=*/true);
8986     } else {
8987       // Check protocols.
8988       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8989                                              /*instance=*/true);
8990     }
8991   }
8992 
8993   if (!Method)
8994     return false;
8995 
8996   QualType T = Method->parameters()[0]->getType();
8997   if (!T->isObjCObjectPointerType())
8998     return false;
8999 
9000   QualType R = Method->getReturnType();
9001   if (!R->isScalarType())
9002     return false;
9003 
9004   return true;
9005 }
9006 
9007 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9008   FromE = FromE->IgnoreParenImpCasts();
9009   switch (FromE->getStmtClass()) {
9010     default:
9011       break;
9012     case Stmt::ObjCStringLiteralClass:
9013       // "string literal"
9014       return LK_String;
9015     case Stmt::ObjCArrayLiteralClass:
9016       // "array literal"
9017       return LK_Array;
9018     case Stmt::ObjCDictionaryLiteralClass:
9019       // "dictionary literal"
9020       return LK_Dictionary;
9021     case Stmt::BlockExprClass:
9022       return LK_Block;
9023     case Stmt::ObjCBoxedExprClass: {
9024       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9025       switch (Inner->getStmtClass()) {
9026         case Stmt::IntegerLiteralClass:
9027         case Stmt::FloatingLiteralClass:
9028         case Stmt::CharacterLiteralClass:
9029         case Stmt::ObjCBoolLiteralExprClass:
9030         case Stmt::CXXBoolLiteralExprClass:
9031           // "numeric literal"
9032           return LK_Numeric;
9033         case Stmt::ImplicitCastExprClass: {
9034           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9035           // Boolean literals can be represented by implicit casts.
9036           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9037             return LK_Numeric;
9038           break;
9039         }
9040         default:
9041           break;
9042       }
9043       return LK_Boxed;
9044     }
9045   }
9046   return LK_None;
9047 }
9048 
9049 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9050                                           ExprResult &LHS, ExprResult &RHS,
9051                                           BinaryOperator::Opcode Opc){
9052   Expr *Literal;
9053   Expr *Other;
9054   if (isObjCObjectLiteral(LHS)) {
9055     Literal = LHS.get();
9056     Other = RHS.get();
9057   } else {
9058     Literal = RHS.get();
9059     Other = LHS.get();
9060   }
9061 
9062   // Don't warn on comparisons against nil.
9063   Other = Other->IgnoreParenCasts();
9064   if (Other->isNullPointerConstant(S.getASTContext(),
9065                                    Expr::NPC_ValueDependentIsNotNull))
9066     return;
9067 
9068   // This should be kept in sync with warn_objc_literal_comparison.
9069   // LK_String should always be after the other literals, since it has its own
9070   // warning flag.
9071   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9072   assert(LiteralKind != Sema::LK_Block);
9073   if (LiteralKind == Sema::LK_None) {
9074     llvm_unreachable("Unknown Objective-C object literal kind");
9075   }
9076 
9077   if (LiteralKind == Sema::LK_String)
9078     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9079       << Literal->getSourceRange();
9080   else
9081     S.Diag(Loc, diag::warn_objc_literal_comparison)
9082       << LiteralKind << Literal->getSourceRange();
9083 
9084   if (BinaryOperator::isEqualityOp(Opc) &&
9085       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9086     SourceLocation Start = LHS.get()->getLocStart();
9087     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9088     CharSourceRange OpRange =
9089       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9090 
9091     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9092       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9093       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9094       << FixItHint::CreateInsertion(End, "]");
9095   }
9096 }
9097 
9098 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9099 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9100                                            ExprResult &RHS, SourceLocation Loc,
9101                                            BinaryOperatorKind Opc) {
9102   // Check that left hand side is !something.
9103   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9104   if (!UO || UO->getOpcode() != UO_LNot) return;
9105 
9106   // Only check if the right hand side is non-bool arithmetic type.
9107   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9108 
9109   // Make sure that the something in !something is not bool.
9110   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9111   if (SubExpr->isKnownToHaveBooleanValue()) return;
9112 
9113   // Emit warning.
9114   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9115   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9116       << Loc << IsBitwiseOp;
9117 
9118   // First note suggest !(x < y)
9119   SourceLocation FirstOpen = SubExpr->getLocStart();
9120   SourceLocation FirstClose = RHS.get()->getLocEnd();
9121   FirstClose = S.getLocForEndOfToken(FirstClose);
9122   if (FirstClose.isInvalid())
9123     FirstOpen = SourceLocation();
9124   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9125       << IsBitwiseOp
9126       << FixItHint::CreateInsertion(FirstOpen, "(")
9127       << FixItHint::CreateInsertion(FirstClose, ")");
9128 
9129   // Second note suggests (!x) < y
9130   SourceLocation SecondOpen = LHS.get()->getLocStart();
9131   SourceLocation SecondClose = LHS.get()->getLocEnd();
9132   SecondClose = S.getLocForEndOfToken(SecondClose);
9133   if (SecondClose.isInvalid())
9134     SecondOpen = SourceLocation();
9135   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9136       << FixItHint::CreateInsertion(SecondOpen, "(")
9137       << FixItHint::CreateInsertion(SecondClose, ")");
9138 }
9139 
9140 // Get the decl for a simple expression: a reference to a variable,
9141 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9142 static ValueDecl *getCompareDecl(Expr *E) {
9143   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9144     return DR->getDecl();
9145   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9146     if (Ivar->isFreeIvar())
9147       return Ivar->getDecl();
9148   }
9149   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9150     if (Mem->isImplicitAccess())
9151       return Mem->getMemberDecl();
9152   }
9153   return nullptr;
9154 }
9155 
9156 // C99 6.5.8, C++ [expr.rel]
9157 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9158                                     SourceLocation Loc, BinaryOperatorKind Opc,
9159                                     bool IsRelational) {
9160   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9161 
9162   // Handle vector comparisons separately.
9163   if (LHS.get()->getType()->isVectorType() ||
9164       RHS.get()->getType()->isVectorType())
9165     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9166 
9167   QualType LHSType = LHS.get()->getType();
9168   QualType RHSType = RHS.get()->getType();
9169 
9170   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9171   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9172 
9173   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9174   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9175 
9176   if (!LHSType->hasFloatingRepresentation() &&
9177       !(LHSType->isBlockPointerType() && IsRelational) &&
9178       !LHS.get()->getLocStart().isMacroID() &&
9179       !RHS.get()->getLocStart().isMacroID() &&
9180       ActiveTemplateInstantiations.empty()) {
9181     // For non-floating point types, check for self-comparisons of the form
9182     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9183     // often indicate logic errors in the program.
9184     //
9185     // NOTE: Don't warn about comparison expressions resulting from macro
9186     // expansion. Also don't warn about comparisons which are only self
9187     // comparisons within a template specialization. The warnings should catch
9188     // obvious cases in the definition of the template anyways. The idea is to
9189     // warn when the typed comparison operator will always evaluate to the same
9190     // result.
9191     ValueDecl *DL = getCompareDecl(LHSStripped);
9192     ValueDecl *DR = getCompareDecl(RHSStripped);
9193     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9194       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9195                           << 0 // self-
9196                           << (Opc == BO_EQ
9197                               || Opc == BO_LE
9198                               || Opc == BO_GE));
9199     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9200                !DL->getType()->isReferenceType() &&
9201                !DR->getType()->isReferenceType()) {
9202         // what is it always going to eval to?
9203         char always_evals_to;
9204         switch(Opc) {
9205         case BO_EQ: // e.g. array1 == array2
9206           always_evals_to = 0; // false
9207           break;
9208         case BO_NE: // e.g. array1 != array2
9209           always_evals_to = 1; // true
9210           break;
9211         default:
9212           // best we can say is 'a constant'
9213           always_evals_to = 2; // e.g. array1 <= array2
9214           break;
9215         }
9216         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9217                             << 1 // array
9218                             << always_evals_to);
9219     }
9220 
9221     if (isa<CastExpr>(LHSStripped))
9222       LHSStripped = LHSStripped->IgnoreParenCasts();
9223     if (isa<CastExpr>(RHSStripped))
9224       RHSStripped = RHSStripped->IgnoreParenCasts();
9225 
9226     // Warn about comparisons against a string constant (unless the other
9227     // operand is null), the user probably wants strcmp.
9228     Expr *literalString = nullptr;
9229     Expr *literalStringStripped = nullptr;
9230     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9231         !RHSStripped->isNullPointerConstant(Context,
9232                                             Expr::NPC_ValueDependentIsNull)) {
9233       literalString = LHS.get();
9234       literalStringStripped = LHSStripped;
9235     } else if ((isa<StringLiteral>(RHSStripped) ||
9236                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9237                !LHSStripped->isNullPointerConstant(Context,
9238                                             Expr::NPC_ValueDependentIsNull)) {
9239       literalString = RHS.get();
9240       literalStringStripped = RHSStripped;
9241     }
9242 
9243     if (literalString) {
9244       DiagRuntimeBehavior(Loc, nullptr,
9245         PDiag(diag::warn_stringcompare)
9246           << isa<ObjCEncodeExpr>(literalStringStripped)
9247           << literalString->getSourceRange());
9248     }
9249   }
9250 
9251   // C99 6.5.8p3 / C99 6.5.9p4
9252   UsualArithmeticConversions(LHS, RHS);
9253   if (LHS.isInvalid() || RHS.isInvalid())
9254     return QualType();
9255 
9256   LHSType = LHS.get()->getType();
9257   RHSType = RHS.get()->getType();
9258 
9259   // The result of comparisons is 'bool' in C++, 'int' in C.
9260   QualType ResultTy = Context.getLogicalOperationType();
9261 
9262   if (IsRelational) {
9263     if (LHSType->isRealType() && RHSType->isRealType())
9264       return ResultTy;
9265   } else {
9266     // Check for comparisons of floating point operands using != and ==.
9267     if (LHSType->hasFloatingRepresentation())
9268       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9269 
9270     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9271       return ResultTy;
9272   }
9273 
9274   const Expr::NullPointerConstantKind LHSNullKind =
9275       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9276   const Expr::NullPointerConstantKind RHSNullKind =
9277       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9278   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9279   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9280 
9281   if (!IsRelational && LHSIsNull != RHSIsNull) {
9282     bool IsEquality = Opc == BO_EQ;
9283     if (RHSIsNull)
9284       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9285                                    RHS.get()->getSourceRange());
9286     else
9287       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9288                                    LHS.get()->getSourceRange());
9289   }
9290 
9291   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9292       (RHSType->isIntegerType() && !RHSIsNull)) {
9293     // Skip normal pointer conversion checks in this case; we have better
9294     // diagnostics for this below.
9295   } else if (getLangOpts().CPlusPlus) {
9296     // Equality comparison of a function pointer to a void pointer is invalid,
9297     // but we allow it as an extension.
9298     // FIXME: If we really want to allow this, should it be part of composite
9299     // pointer type computation so it works in conditionals too?
9300     if (!IsRelational &&
9301         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9302          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9303       // This is a gcc extension compatibility comparison.
9304       // In a SFINAE context, we treat this as a hard error to maintain
9305       // conformance with the C++ standard.
9306       diagnoseFunctionPointerToVoidComparison(
9307           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9308 
9309       if (isSFINAEContext())
9310         return QualType();
9311 
9312       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9313       return ResultTy;
9314     }
9315 
9316     // C++ [expr.eq]p2:
9317     //   If at least one operand is a pointer [...] bring them to their
9318     //   composite pointer type.
9319     // C++ [expr.rel]p2:
9320     //   If both operands are pointers, [...] bring them to their composite
9321     //   pointer type.
9322     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9323         (IsRelational ? 2 : 1)) {
9324       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9325         return QualType();
9326       else
9327         return ResultTy;
9328     }
9329   } else if (LHSType->isPointerType() &&
9330              RHSType->isPointerType()) { // C99 6.5.8p2
9331     // All of the following pointer-related warnings are GCC extensions, except
9332     // when handling null pointer constants.
9333     QualType LCanPointeeTy =
9334       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9335     QualType RCanPointeeTy =
9336       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9337 
9338     // C99 6.5.9p2 and C99 6.5.8p2
9339     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9340                                    RCanPointeeTy.getUnqualifiedType())) {
9341       // Valid unless a relational comparison of function pointers
9342       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9343         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9344           << LHSType << RHSType << LHS.get()->getSourceRange()
9345           << RHS.get()->getSourceRange();
9346       }
9347     } else if (!IsRelational &&
9348                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9349       // Valid unless comparison between non-null pointer and function pointer
9350       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9351           && !LHSIsNull && !RHSIsNull)
9352         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9353                                                 /*isError*/false);
9354     } else {
9355       // Invalid
9356       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9357     }
9358     if (LCanPointeeTy != RCanPointeeTy) {
9359       // Treat NULL constant as a special case in OpenCL.
9360       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9361         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9362         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9363           Diag(Loc,
9364                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9365               << LHSType << RHSType << 0 /* comparison */
9366               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9367         }
9368       }
9369       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9370       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9371       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9372                                                : CK_BitCast;
9373       if (LHSIsNull && !RHSIsNull)
9374         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9375       else
9376         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9377     }
9378     return ResultTy;
9379   }
9380 
9381   if (getLangOpts().CPlusPlus) {
9382     // C++ [expr.eq]p4:
9383     //   Two operands of type std::nullptr_t or one operand of type
9384     //   std::nullptr_t and the other a null pointer constant compare equal.
9385     if (!IsRelational && LHSIsNull && RHSIsNull) {
9386       if (LHSType->isNullPtrType()) {
9387         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9388         return ResultTy;
9389       }
9390       if (RHSType->isNullPtrType()) {
9391         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9392         return ResultTy;
9393       }
9394     }
9395 
9396     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9397     // These aren't covered by the composite pointer type rules.
9398     if (!IsRelational && RHSType->isNullPtrType() &&
9399         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9400       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9401       return ResultTy;
9402     }
9403     if (!IsRelational && LHSType->isNullPtrType() &&
9404         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9405       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9406       return ResultTy;
9407     }
9408 
9409     if (IsRelational &&
9410         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9411          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9412       // HACK: Relational comparison of nullptr_t against a pointer type is
9413       // invalid per DR583, but we allow it within std::less<> and friends,
9414       // since otherwise common uses of it break.
9415       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9416       // friends to have std::nullptr_t overload candidates.
9417       DeclContext *DC = CurContext;
9418       if (isa<FunctionDecl>(DC))
9419         DC = DC->getParent();
9420       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9421         if (CTSD->isInStdNamespace() &&
9422             llvm::StringSwitch<bool>(CTSD->getName())
9423                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9424                 .Default(false)) {
9425           if (RHSType->isNullPtrType())
9426             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9427           else
9428             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9429           return ResultTy;
9430         }
9431       }
9432     }
9433 
9434     // C++ [expr.eq]p2:
9435     //   If at least one operand is a pointer to member, [...] bring them to
9436     //   their composite pointer type.
9437     if (!IsRelational &&
9438         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9439       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9440         return QualType();
9441       else
9442         return ResultTy;
9443     }
9444 
9445     // Handle scoped enumeration types specifically, since they don't promote
9446     // to integers.
9447     if (LHS.get()->getType()->isEnumeralType() &&
9448         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9449                                        RHS.get()->getType()))
9450       return ResultTy;
9451   }
9452 
9453   // Handle block pointer types.
9454   if (!IsRelational && LHSType->isBlockPointerType() &&
9455       RHSType->isBlockPointerType()) {
9456     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9457     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9458 
9459     if (!LHSIsNull && !RHSIsNull &&
9460         !Context.typesAreCompatible(lpointee, rpointee)) {
9461       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9462         << LHSType << RHSType << LHS.get()->getSourceRange()
9463         << RHS.get()->getSourceRange();
9464     }
9465     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9466     return ResultTy;
9467   }
9468 
9469   // Allow block pointers to be compared with null pointer constants.
9470   if (!IsRelational
9471       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9472           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9473     if (!LHSIsNull && !RHSIsNull) {
9474       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9475              ->getPointeeType()->isVoidType())
9476             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9477                 ->getPointeeType()->isVoidType())))
9478         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9479           << LHSType << RHSType << LHS.get()->getSourceRange()
9480           << RHS.get()->getSourceRange();
9481     }
9482     if (LHSIsNull && !RHSIsNull)
9483       LHS = ImpCastExprToType(LHS.get(), RHSType,
9484                               RHSType->isPointerType() ? CK_BitCast
9485                                 : CK_AnyPointerToBlockPointerCast);
9486     else
9487       RHS = ImpCastExprToType(RHS.get(), LHSType,
9488                               LHSType->isPointerType() ? CK_BitCast
9489                                 : CK_AnyPointerToBlockPointerCast);
9490     return ResultTy;
9491   }
9492 
9493   if (LHSType->isObjCObjectPointerType() ||
9494       RHSType->isObjCObjectPointerType()) {
9495     const PointerType *LPT = LHSType->getAs<PointerType>();
9496     const PointerType *RPT = RHSType->getAs<PointerType>();
9497     if (LPT || RPT) {
9498       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9499       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9500 
9501       if (!LPtrToVoid && !RPtrToVoid &&
9502           !Context.typesAreCompatible(LHSType, RHSType)) {
9503         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9504                                           /*isError*/false);
9505       }
9506       if (LHSIsNull && !RHSIsNull) {
9507         Expr *E = LHS.get();
9508         if (getLangOpts().ObjCAutoRefCount)
9509           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9510         LHS = ImpCastExprToType(E, RHSType,
9511                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9512       }
9513       else {
9514         Expr *E = RHS.get();
9515         if (getLangOpts().ObjCAutoRefCount)
9516           CheckObjCARCConversion(SourceRange(), LHSType, E,
9517                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9518                                  /*DiagnoseCFAudited=*/false, Opc);
9519         RHS = ImpCastExprToType(E, LHSType,
9520                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9521       }
9522       return ResultTy;
9523     }
9524     if (LHSType->isObjCObjectPointerType() &&
9525         RHSType->isObjCObjectPointerType()) {
9526       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9527         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9528                                           /*isError*/false);
9529       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9530         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9531 
9532       if (LHSIsNull && !RHSIsNull)
9533         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9534       else
9535         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9536       return ResultTy;
9537     }
9538   }
9539   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9540       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9541     unsigned DiagID = 0;
9542     bool isError = false;
9543     if (LangOpts.DebuggerSupport) {
9544       // Under a debugger, allow the comparison of pointers to integers,
9545       // since users tend to want to compare addresses.
9546     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9547                (RHSIsNull && RHSType->isIntegerType())) {
9548       if (IsRelational) {
9549         isError = getLangOpts().CPlusPlus;
9550         DiagID =
9551           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9552                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9553       }
9554     } else if (getLangOpts().CPlusPlus) {
9555       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9556       isError = true;
9557     } else if (IsRelational)
9558       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9559     else
9560       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9561 
9562     if (DiagID) {
9563       Diag(Loc, DiagID)
9564         << LHSType << RHSType << LHS.get()->getSourceRange()
9565         << RHS.get()->getSourceRange();
9566       if (isError)
9567         return QualType();
9568     }
9569 
9570     if (LHSType->isIntegerType())
9571       LHS = ImpCastExprToType(LHS.get(), RHSType,
9572                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9573     else
9574       RHS = ImpCastExprToType(RHS.get(), LHSType,
9575                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9576     return ResultTy;
9577   }
9578 
9579   // Handle block pointers.
9580   if (!IsRelational && RHSIsNull
9581       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9582     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9583     return ResultTy;
9584   }
9585   if (!IsRelational && LHSIsNull
9586       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9587     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9588     return ResultTy;
9589   }
9590 
9591   return InvalidOperands(Loc, LHS, RHS);
9592 }
9593 
9594 
9595 // Return a signed type that is of identical size and number of elements.
9596 // For floating point vectors, return an integer type of identical size
9597 // and number of elements.
9598 QualType Sema::GetSignedVectorType(QualType V) {
9599   const VectorType *VTy = V->getAs<VectorType>();
9600   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9601   if (TypeSize == Context.getTypeSize(Context.CharTy))
9602     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9603   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9604     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9605   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9606     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9607   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9608     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9609   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9610          "Unhandled vector element size in vector compare");
9611   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9612 }
9613 
9614 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9615 /// operates on extended vector types.  Instead of producing an IntTy result,
9616 /// like a scalar comparison, a vector comparison produces a vector of integer
9617 /// types.
9618 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9619                                           SourceLocation Loc,
9620                                           bool IsRelational) {
9621   // Check to make sure we're operating on vectors of the same type and width,
9622   // Allowing one side to be a scalar of element type.
9623   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9624                               /*AllowBothBool*/true,
9625                               /*AllowBoolConversions*/getLangOpts().ZVector);
9626   if (vType.isNull())
9627     return vType;
9628 
9629   QualType LHSType = LHS.get()->getType();
9630 
9631   // If AltiVec, the comparison results in a numeric type, i.e.
9632   // bool for C++, int for C
9633   if (getLangOpts().AltiVec &&
9634       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9635     return Context.getLogicalOperationType();
9636 
9637   // For non-floating point types, check for self-comparisons of the form
9638   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9639   // often indicate logic errors in the program.
9640   if (!LHSType->hasFloatingRepresentation() &&
9641       ActiveTemplateInstantiations.empty()) {
9642     if (DeclRefExpr* DRL
9643           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9644       if (DeclRefExpr* DRR
9645             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9646         if (DRL->getDecl() == DRR->getDecl())
9647           DiagRuntimeBehavior(Loc, nullptr,
9648                               PDiag(diag::warn_comparison_always)
9649                                 << 0 // self-
9650                                 << 2 // "a constant"
9651                               );
9652   }
9653 
9654   // Check for comparisons of floating point operands using != and ==.
9655   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9656     assert (RHS.get()->getType()->hasFloatingRepresentation());
9657     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9658   }
9659 
9660   // Return a signed type for the vector.
9661   return GetSignedVectorType(vType);
9662 }
9663 
9664 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9665                                           SourceLocation Loc) {
9666   // Ensure that either both operands are of the same vector type, or
9667   // one operand is of a vector type and the other is of its element type.
9668   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9669                                        /*AllowBothBool*/true,
9670                                        /*AllowBoolConversions*/false);
9671   if (vType.isNull())
9672     return InvalidOperands(Loc, LHS, RHS);
9673   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9674       vType->hasFloatingRepresentation())
9675     return InvalidOperands(Loc, LHS, RHS);
9676 
9677   return GetSignedVectorType(LHS.get()->getType());
9678 }
9679 
9680 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9681                                            SourceLocation Loc,
9682                                            BinaryOperatorKind Opc) {
9683   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9684 
9685   bool IsCompAssign =
9686       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9687 
9688   if (LHS.get()->getType()->isVectorType() ||
9689       RHS.get()->getType()->isVectorType()) {
9690     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9691         RHS.get()->getType()->hasIntegerRepresentation())
9692       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9693                         /*AllowBothBool*/true,
9694                         /*AllowBoolConversions*/getLangOpts().ZVector);
9695     return InvalidOperands(Loc, LHS, RHS);
9696   }
9697 
9698   if (Opc == BO_And)
9699     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9700 
9701   ExprResult LHSResult = LHS, RHSResult = RHS;
9702   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9703                                                  IsCompAssign);
9704   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9705     return QualType();
9706   LHS = LHSResult.get();
9707   RHS = RHSResult.get();
9708 
9709   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9710     return compType;
9711   return InvalidOperands(Loc, LHS, RHS);
9712 }
9713 
9714 // C99 6.5.[13,14]
9715 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9716                                            SourceLocation Loc,
9717                                            BinaryOperatorKind Opc) {
9718   // Check vector operands differently.
9719   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9720     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9721 
9722   // Diagnose cases where the user write a logical and/or but probably meant a
9723   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9724   // is a constant.
9725   if (LHS.get()->getType()->isIntegerType() &&
9726       !LHS.get()->getType()->isBooleanType() &&
9727       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9728       // Don't warn in macros or template instantiations.
9729       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9730     // If the RHS can be constant folded, and if it constant folds to something
9731     // that isn't 0 or 1 (which indicate a potential logical operation that
9732     // happened to fold to true/false) then warn.
9733     // Parens on the RHS are ignored.
9734     llvm::APSInt Result;
9735     if (RHS.get()->EvaluateAsInt(Result, Context))
9736       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9737            !RHS.get()->getExprLoc().isMacroID()) ||
9738           (Result != 0 && Result != 1)) {
9739         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9740           << RHS.get()->getSourceRange()
9741           << (Opc == BO_LAnd ? "&&" : "||");
9742         // Suggest replacing the logical operator with the bitwise version
9743         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9744             << (Opc == BO_LAnd ? "&" : "|")
9745             << FixItHint::CreateReplacement(SourceRange(
9746                                                  Loc, getLocForEndOfToken(Loc)),
9747                                             Opc == BO_LAnd ? "&" : "|");
9748         if (Opc == BO_LAnd)
9749           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9750           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9751               << FixItHint::CreateRemoval(
9752                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9753                               RHS.get()->getLocEnd()));
9754       }
9755   }
9756 
9757   if (!Context.getLangOpts().CPlusPlus) {
9758     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9759     // not operate on the built-in scalar and vector float types.
9760     if (Context.getLangOpts().OpenCL &&
9761         Context.getLangOpts().OpenCLVersion < 120) {
9762       if (LHS.get()->getType()->isFloatingType() ||
9763           RHS.get()->getType()->isFloatingType())
9764         return InvalidOperands(Loc, LHS, RHS);
9765     }
9766 
9767     LHS = UsualUnaryConversions(LHS.get());
9768     if (LHS.isInvalid())
9769       return QualType();
9770 
9771     RHS = UsualUnaryConversions(RHS.get());
9772     if (RHS.isInvalid())
9773       return QualType();
9774 
9775     if (!LHS.get()->getType()->isScalarType() ||
9776         !RHS.get()->getType()->isScalarType())
9777       return InvalidOperands(Loc, LHS, RHS);
9778 
9779     return Context.IntTy;
9780   }
9781 
9782   // The following is safe because we only use this method for
9783   // non-overloadable operands.
9784 
9785   // C++ [expr.log.and]p1
9786   // C++ [expr.log.or]p1
9787   // The operands are both contextually converted to type bool.
9788   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9789   if (LHSRes.isInvalid())
9790     return InvalidOperands(Loc, LHS, RHS);
9791   LHS = LHSRes;
9792 
9793   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9794   if (RHSRes.isInvalid())
9795     return InvalidOperands(Loc, LHS, RHS);
9796   RHS = RHSRes;
9797 
9798   // C++ [expr.log.and]p2
9799   // C++ [expr.log.or]p2
9800   // The result is a bool.
9801   return Context.BoolTy;
9802 }
9803 
9804 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9805   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9806   if (!ME) return false;
9807   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9808   ObjCMessageExpr *Base =
9809     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9810   if (!Base) return false;
9811   return Base->getMethodDecl() != nullptr;
9812 }
9813 
9814 /// Is the given expression (which must be 'const') a reference to a
9815 /// variable which was originally non-const, but which has become
9816 /// 'const' due to being captured within a block?
9817 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9818 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9819   assert(E->isLValue() && E->getType().isConstQualified());
9820   E = E->IgnoreParens();
9821 
9822   // Must be a reference to a declaration from an enclosing scope.
9823   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9824   if (!DRE) return NCCK_None;
9825   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9826 
9827   // The declaration must be a variable which is not declared 'const'.
9828   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9829   if (!var) return NCCK_None;
9830   if (var->getType().isConstQualified()) return NCCK_None;
9831   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9832 
9833   // Decide whether the first capture was for a block or a lambda.
9834   DeclContext *DC = S.CurContext, *Prev = nullptr;
9835   // Decide whether the first capture was for a block or a lambda.
9836   while (DC) {
9837     // For init-capture, it is possible that the variable belongs to the
9838     // template pattern of the current context.
9839     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9840       if (var->isInitCapture() &&
9841           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9842         break;
9843     if (DC == var->getDeclContext())
9844       break;
9845     Prev = DC;
9846     DC = DC->getParent();
9847   }
9848   // Unless we have an init-capture, we've gone one step too far.
9849   if (!var->isInitCapture())
9850     DC = Prev;
9851   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9852 }
9853 
9854 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9855   Ty = Ty.getNonReferenceType();
9856   if (IsDereference && Ty->isPointerType())
9857     Ty = Ty->getPointeeType();
9858   return !Ty.isConstQualified();
9859 }
9860 
9861 /// Emit the "read-only variable not assignable" error and print notes to give
9862 /// more information about why the variable is not assignable, such as pointing
9863 /// to the declaration of a const variable, showing that a method is const, or
9864 /// that the function is returning a const reference.
9865 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9866                                     SourceLocation Loc) {
9867   // Update err_typecheck_assign_const and note_typecheck_assign_const
9868   // when this enum is changed.
9869   enum {
9870     ConstFunction,
9871     ConstVariable,
9872     ConstMember,
9873     ConstMethod,
9874     ConstUnknown,  // Keep as last element
9875   };
9876 
9877   SourceRange ExprRange = E->getSourceRange();
9878 
9879   // Only emit one error on the first const found.  All other consts will emit
9880   // a note to the error.
9881   bool DiagnosticEmitted = false;
9882 
9883   // Track if the current expression is the result of a dereference, and if the
9884   // next checked expression is the result of a dereference.
9885   bool IsDereference = false;
9886   bool NextIsDereference = false;
9887 
9888   // Loop to process MemberExpr chains.
9889   while (true) {
9890     IsDereference = NextIsDereference;
9891 
9892     E = E->IgnoreParenImpCasts();
9893     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9894       NextIsDereference = ME->isArrow();
9895       const ValueDecl *VD = ME->getMemberDecl();
9896       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9897         // Mutable fields can be modified even if the class is const.
9898         if (Field->isMutable()) {
9899           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9900           break;
9901         }
9902 
9903         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9904           if (!DiagnosticEmitted) {
9905             S.Diag(Loc, diag::err_typecheck_assign_const)
9906                 << ExprRange << ConstMember << false /*static*/ << Field
9907                 << Field->getType();
9908             DiagnosticEmitted = true;
9909           }
9910           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9911               << ConstMember << false /*static*/ << Field << Field->getType()
9912               << Field->getSourceRange();
9913         }
9914         E = ME->getBase();
9915         continue;
9916       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9917         if (VDecl->getType().isConstQualified()) {
9918           if (!DiagnosticEmitted) {
9919             S.Diag(Loc, diag::err_typecheck_assign_const)
9920                 << ExprRange << ConstMember << true /*static*/ << VDecl
9921                 << VDecl->getType();
9922             DiagnosticEmitted = true;
9923           }
9924           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9925               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9926               << VDecl->getSourceRange();
9927         }
9928         // Static fields do not inherit constness from parents.
9929         break;
9930       }
9931       break;
9932     } // End MemberExpr
9933     break;
9934   }
9935 
9936   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9937     // Function calls
9938     const FunctionDecl *FD = CE->getDirectCallee();
9939     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9940       if (!DiagnosticEmitted) {
9941         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9942                                                       << ConstFunction << FD;
9943         DiagnosticEmitted = true;
9944       }
9945       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9946              diag::note_typecheck_assign_const)
9947           << ConstFunction << FD << FD->getReturnType()
9948           << FD->getReturnTypeSourceRange();
9949     }
9950   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9951     // Point to variable declaration.
9952     if (const ValueDecl *VD = DRE->getDecl()) {
9953       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9954         if (!DiagnosticEmitted) {
9955           S.Diag(Loc, diag::err_typecheck_assign_const)
9956               << ExprRange << ConstVariable << VD << VD->getType();
9957           DiagnosticEmitted = true;
9958         }
9959         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9960             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9961       }
9962     }
9963   } else if (isa<CXXThisExpr>(E)) {
9964     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9965       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9966         if (MD->isConst()) {
9967           if (!DiagnosticEmitted) {
9968             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9969                                                           << ConstMethod << MD;
9970             DiagnosticEmitted = true;
9971           }
9972           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9973               << ConstMethod << MD << MD->getSourceRange();
9974         }
9975       }
9976     }
9977   }
9978 
9979   if (DiagnosticEmitted)
9980     return;
9981 
9982   // Can't determine a more specific message, so display the generic error.
9983   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9984 }
9985 
9986 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9987 /// emit an error and return true.  If so, return false.
9988 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9989   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9990 
9991   S.CheckShadowingDeclModification(E, Loc);
9992 
9993   SourceLocation OrigLoc = Loc;
9994   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9995                                                               &Loc);
9996   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9997     IsLV = Expr::MLV_InvalidMessageExpression;
9998   if (IsLV == Expr::MLV_Valid)
9999     return false;
10000 
10001   unsigned DiagID = 0;
10002   bool NeedType = false;
10003   switch (IsLV) { // C99 6.5.16p2
10004   case Expr::MLV_ConstQualified:
10005     // Use a specialized diagnostic when we're assigning to an object
10006     // from an enclosing function or block.
10007     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10008       if (NCCK == NCCK_Block)
10009         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10010       else
10011         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10012       break;
10013     }
10014 
10015     // In ARC, use some specialized diagnostics for occasions where we
10016     // infer 'const'.  These are always pseudo-strong variables.
10017     if (S.getLangOpts().ObjCAutoRefCount) {
10018       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10019       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10020         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10021 
10022         // Use the normal diagnostic if it's pseudo-__strong but the
10023         // user actually wrote 'const'.
10024         if (var->isARCPseudoStrong() &&
10025             (!var->getTypeSourceInfo() ||
10026              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10027           // There are two pseudo-strong cases:
10028           //  - self
10029           ObjCMethodDecl *method = S.getCurMethodDecl();
10030           if (method && var == method->getSelfDecl())
10031             DiagID = method->isClassMethod()
10032               ? diag::err_typecheck_arc_assign_self_class_method
10033               : diag::err_typecheck_arc_assign_self;
10034 
10035           //  - fast enumeration variables
10036           else
10037             DiagID = diag::err_typecheck_arr_assign_enumeration;
10038 
10039           SourceRange Assign;
10040           if (Loc != OrigLoc)
10041             Assign = SourceRange(OrigLoc, OrigLoc);
10042           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10043           // We need to preserve the AST regardless, so migration tool
10044           // can do its job.
10045           return false;
10046         }
10047       }
10048     }
10049 
10050     // If none of the special cases above are triggered, then this is a
10051     // simple const assignment.
10052     if (DiagID == 0) {
10053       DiagnoseConstAssignment(S, E, Loc);
10054       return true;
10055     }
10056 
10057     break;
10058   case Expr::MLV_ConstAddrSpace:
10059     DiagnoseConstAssignment(S, E, Loc);
10060     return true;
10061   case Expr::MLV_ArrayType:
10062   case Expr::MLV_ArrayTemporary:
10063     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10064     NeedType = true;
10065     break;
10066   case Expr::MLV_NotObjectType:
10067     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10068     NeedType = true;
10069     break;
10070   case Expr::MLV_LValueCast:
10071     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10072     break;
10073   case Expr::MLV_Valid:
10074     llvm_unreachable("did not take early return for MLV_Valid");
10075   case Expr::MLV_InvalidExpression:
10076   case Expr::MLV_MemberFunction:
10077   case Expr::MLV_ClassTemporary:
10078     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10079     break;
10080   case Expr::MLV_IncompleteType:
10081   case Expr::MLV_IncompleteVoidType:
10082     return S.RequireCompleteType(Loc, E->getType(),
10083              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10084   case Expr::MLV_DuplicateVectorComponents:
10085     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10086     break;
10087   case Expr::MLV_NoSetterProperty:
10088     llvm_unreachable("readonly properties should be processed differently");
10089   case Expr::MLV_InvalidMessageExpression:
10090     DiagID = diag::error_readonly_message_assignment;
10091     break;
10092   case Expr::MLV_SubObjCPropertySetting:
10093     DiagID = diag::error_no_subobject_property_setting;
10094     break;
10095   }
10096 
10097   SourceRange Assign;
10098   if (Loc != OrigLoc)
10099     Assign = SourceRange(OrigLoc, OrigLoc);
10100   if (NeedType)
10101     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10102   else
10103     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10104   return true;
10105 }
10106 
10107 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10108                                          SourceLocation Loc,
10109                                          Sema &Sema) {
10110   // C / C++ fields
10111   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10112   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10113   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10114     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10115       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10116   }
10117 
10118   // Objective-C instance variables
10119   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10120   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10121   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10122     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10123     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10124     if (RL && RR && RL->getDecl() == RR->getDecl())
10125       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10126   }
10127 }
10128 
10129 // C99 6.5.16.1
10130 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10131                                        SourceLocation Loc,
10132                                        QualType CompoundType) {
10133   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10134 
10135   // Verify that LHS is a modifiable lvalue, and emit error if not.
10136   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10137     return QualType();
10138 
10139   QualType LHSType = LHSExpr->getType();
10140   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10141                                              CompoundType;
10142   // OpenCL v1.2 s6.1.1.1 p2:
10143   // The half data type can only be used to declare a pointer to a buffer that
10144   // contains half values
10145   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
10146     LHSType->isHalfType()) {
10147     Diag(Loc, diag::err_opencl_half_load_store) << 1
10148         << LHSType.getUnqualifiedType();
10149     return QualType();
10150   }
10151 
10152   AssignConvertType ConvTy;
10153   if (CompoundType.isNull()) {
10154     Expr *RHSCheck = RHS.get();
10155 
10156     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10157 
10158     QualType LHSTy(LHSType);
10159     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10160     if (RHS.isInvalid())
10161       return QualType();
10162     // Special case of NSObject attributes on c-style pointer types.
10163     if (ConvTy == IncompatiblePointer &&
10164         ((Context.isObjCNSObjectType(LHSType) &&
10165           RHSType->isObjCObjectPointerType()) ||
10166          (Context.isObjCNSObjectType(RHSType) &&
10167           LHSType->isObjCObjectPointerType())))
10168       ConvTy = Compatible;
10169 
10170     if (ConvTy == Compatible &&
10171         LHSType->isObjCObjectType())
10172         Diag(Loc, diag::err_objc_object_assignment)
10173           << LHSType;
10174 
10175     // If the RHS is a unary plus or minus, check to see if they = and + are
10176     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10177     // instead of "x += 4".
10178     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10179       RHSCheck = ICE->getSubExpr();
10180     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10181       if ((UO->getOpcode() == UO_Plus ||
10182            UO->getOpcode() == UO_Minus) &&
10183           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10184           // Only if the two operators are exactly adjacent.
10185           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10186           // And there is a space or other character before the subexpr of the
10187           // unary +/-.  We don't want to warn on "x=-1".
10188           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10189           UO->getSubExpr()->getLocStart().isFileID()) {
10190         Diag(Loc, diag::warn_not_compound_assign)
10191           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10192           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10193       }
10194     }
10195 
10196     if (ConvTy == Compatible) {
10197       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10198         // Warn about retain cycles where a block captures the LHS, but
10199         // not if the LHS is a simple variable into which the block is
10200         // being stored...unless that variable can be captured by reference!
10201         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10202         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10203         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10204           checkRetainCycles(LHSExpr, RHS.get());
10205 
10206         // It is safe to assign a weak reference into a strong variable.
10207         // Although this code can still have problems:
10208         //   id x = self.weakProp;
10209         //   id y = self.weakProp;
10210         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10211         // paths through the function. This should be revisited if
10212         // -Wrepeated-use-of-weak is made flow-sensitive.
10213         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10214                              RHS.get()->getLocStart()))
10215           getCurFunction()->markSafeWeakUse(RHS.get());
10216 
10217       } else if (getLangOpts().ObjCAutoRefCount) {
10218         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10219       }
10220     }
10221   } else {
10222     // Compound assignment "x += y"
10223     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10224   }
10225 
10226   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10227                                RHS.get(), AA_Assigning))
10228     return QualType();
10229 
10230   CheckForNullPointerDereference(*this, LHSExpr);
10231 
10232   // C99 6.5.16p3: The type of an assignment expression is the type of the
10233   // left operand unless the left operand has qualified type, in which case
10234   // it is the unqualified version of the type of the left operand.
10235   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10236   // is converted to the type of the assignment expression (above).
10237   // C++ 5.17p1: the type of the assignment expression is that of its left
10238   // operand.
10239   return (getLangOpts().CPlusPlus
10240           ? LHSType : LHSType.getUnqualifiedType());
10241 }
10242 
10243 // Only ignore explicit casts to void.
10244 static bool IgnoreCommaOperand(const Expr *E) {
10245   E = E->IgnoreParens();
10246 
10247   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10248     if (CE->getCastKind() == CK_ToVoid) {
10249       return true;
10250     }
10251   }
10252 
10253   return false;
10254 }
10255 
10256 // Look for instances where it is likely the comma operator is confused with
10257 // another operator.  There is a whitelist of acceptable expressions for the
10258 // left hand side of the comma operator, otherwise emit a warning.
10259 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10260   // No warnings in macros
10261   if (Loc.isMacroID())
10262     return;
10263 
10264   // Don't warn in template instantiations.
10265   if (!ActiveTemplateInstantiations.empty())
10266     return;
10267 
10268   // Scope isn't fine-grained enough to whitelist the specific cases, so
10269   // instead, skip more than needed, then call back into here with the
10270   // CommaVisitor in SemaStmt.cpp.
10271   // The whitelisted locations are the initialization and increment portions
10272   // of a for loop.  The additional checks are on the condition of
10273   // if statements, do/while loops, and for loops.
10274   const unsigned ForIncrementFlags =
10275       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10276   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10277   const unsigned ScopeFlags = getCurScope()->getFlags();
10278   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10279       (ScopeFlags & ForInitFlags) == ForInitFlags)
10280     return;
10281 
10282   // If there are multiple comma operators used together, get the RHS of the
10283   // of the comma operator as the LHS.
10284   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10285     if (BO->getOpcode() != BO_Comma)
10286       break;
10287     LHS = BO->getRHS();
10288   }
10289 
10290   // Only allow some expressions on LHS to not warn.
10291   if (IgnoreCommaOperand(LHS))
10292     return;
10293 
10294   Diag(Loc, diag::warn_comma_operator);
10295   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10296       << LHS->getSourceRange()
10297       << FixItHint::CreateInsertion(LHS->getLocStart(),
10298                                     LangOpts.CPlusPlus ? "static_cast<void>("
10299                                                        : "(void)(")
10300       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10301                                     ")");
10302 }
10303 
10304 // C99 6.5.17
10305 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10306                                    SourceLocation Loc) {
10307   LHS = S.CheckPlaceholderExpr(LHS.get());
10308   RHS = S.CheckPlaceholderExpr(RHS.get());
10309   if (LHS.isInvalid() || RHS.isInvalid())
10310     return QualType();
10311 
10312   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10313   // operands, but not unary promotions.
10314   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10315 
10316   // So we treat the LHS as a ignored value, and in C++ we allow the
10317   // containing site to determine what should be done with the RHS.
10318   LHS = S.IgnoredValueConversions(LHS.get());
10319   if (LHS.isInvalid())
10320     return QualType();
10321 
10322   S.DiagnoseUnusedExprResult(LHS.get());
10323 
10324   if (!S.getLangOpts().CPlusPlus) {
10325     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10326     if (RHS.isInvalid())
10327       return QualType();
10328     if (!RHS.get()->getType()->isVoidType())
10329       S.RequireCompleteType(Loc, RHS.get()->getType(),
10330                             diag::err_incomplete_type);
10331   }
10332 
10333   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10334     S.DiagnoseCommaOperator(LHS.get(), Loc);
10335 
10336   return RHS.get()->getType();
10337 }
10338 
10339 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10340 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10341 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10342                                                ExprValueKind &VK,
10343                                                ExprObjectKind &OK,
10344                                                SourceLocation OpLoc,
10345                                                bool IsInc, bool IsPrefix) {
10346   if (Op->isTypeDependent())
10347     return S.Context.DependentTy;
10348 
10349   QualType ResType = Op->getType();
10350   // Atomic types can be used for increment / decrement where the non-atomic
10351   // versions can, so ignore the _Atomic() specifier for the purpose of
10352   // checking.
10353   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10354     ResType = ResAtomicType->getValueType();
10355 
10356   assert(!ResType.isNull() && "no type for increment/decrement expression");
10357 
10358   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10359     // Decrement of bool is not allowed.
10360     if (!IsInc) {
10361       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10362       return QualType();
10363     }
10364     // Increment of bool sets it to true, but is deprecated.
10365     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10366                                               : diag::warn_increment_bool)
10367       << Op->getSourceRange();
10368   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10369     // Error on enum increments and decrements in C++ mode
10370     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10371     return QualType();
10372   } else if (ResType->isRealType()) {
10373     // OK!
10374   } else if (ResType->isPointerType()) {
10375     // C99 6.5.2.4p2, 6.5.6p2
10376     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10377       return QualType();
10378   } else if (ResType->isObjCObjectPointerType()) {
10379     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10380     // Otherwise, we just need a complete type.
10381     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10382         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10383       return QualType();
10384   } else if (ResType->isAnyComplexType()) {
10385     // C99 does not support ++/-- on complex types, we allow as an extension.
10386     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10387       << ResType << Op->getSourceRange();
10388   } else if (ResType->isPlaceholderType()) {
10389     ExprResult PR = S.CheckPlaceholderExpr(Op);
10390     if (PR.isInvalid()) return QualType();
10391     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10392                                           IsInc, IsPrefix);
10393   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10394     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10395   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10396              (ResType->getAs<VectorType>()->getVectorKind() !=
10397               VectorType::AltiVecBool)) {
10398     // The z vector extensions allow ++ and -- for non-bool vectors.
10399   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10400             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10401     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10402   } else {
10403     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10404       << ResType << int(IsInc) << Op->getSourceRange();
10405     return QualType();
10406   }
10407   // At this point, we know we have a real, complex or pointer type.
10408   // Now make sure the operand is a modifiable lvalue.
10409   if (CheckForModifiableLvalue(Op, OpLoc, S))
10410     return QualType();
10411   // In C++, a prefix increment is the same type as the operand. Otherwise
10412   // (in C or with postfix), the increment is the unqualified type of the
10413   // operand.
10414   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10415     VK = VK_LValue;
10416     OK = Op->getObjectKind();
10417     return ResType;
10418   } else {
10419     VK = VK_RValue;
10420     return ResType.getUnqualifiedType();
10421   }
10422 }
10423 
10424 
10425 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10426 /// This routine allows us to typecheck complex/recursive expressions
10427 /// where the declaration is needed for type checking. We only need to
10428 /// handle cases when the expression references a function designator
10429 /// or is an lvalue. Here are some examples:
10430 ///  - &(x) => x
10431 ///  - &*****f => f for f a function designator.
10432 ///  - &s.xx => s
10433 ///  - &s.zz[1].yy -> s, if zz is an array
10434 ///  - *(x + 1) -> x, if x is an array
10435 ///  - &"123"[2] -> 0
10436 ///  - & __real__ x -> x
10437 static ValueDecl *getPrimaryDecl(Expr *E) {
10438   switch (E->getStmtClass()) {
10439   case Stmt::DeclRefExprClass:
10440     return cast<DeclRefExpr>(E)->getDecl();
10441   case Stmt::MemberExprClass:
10442     // If this is an arrow operator, the address is an offset from
10443     // the base's value, so the object the base refers to is
10444     // irrelevant.
10445     if (cast<MemberExpr>(E)->isArrow())
10446       return nullptr;
10447     // Otherwise, the expression refers to a part of the base
10448     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10449   case Stmt::ArraySubscriptExprClass: {
10450     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10451     // promotion of register arrays earlier.
10452     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10453     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10454       if (ICE->getSubExpr()->getType()->isArrayType())
10455         return getPrimaryDecl(ICE->getSubExpr());
10456     }
10457     return nullptr;
10458   }
10459   case Stmt::UnaryOperatorClass: {
10460     UnaryOperator *UO = cast<UnaryOperator>(E);
10461 
10462     switch(UO->getOpcode()) {
10463     case UO_Real:
10464     case UO_Imag:
10465     case UO_Extension:
10466       return getPrimaryDecl(UO->getSubExpr());
10467     default:
10468       return nullptr;
10469     }
10470   }
10471   case Stmt::ParenExprClass:
10472     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10473   case Stmt::ImplicitCastExprClass:
10474     // If the result of an implicit cast is an l-value, we care about
10475     // the sub-expression; otherwise, the result here doesn't matter.
10476     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10477   default:
10478     return nullptr;
10479   }
10480 }
10481 
10482 namespace {
10483   enum {
10484     AO_Bit_Field = 0,
10485     AO_Vector_Element = 1,
10486     AO_Property_Expansion = 2,
10487     AO_Register_Variable = 3,
10488     AO_No_Error = 4
10489   };
10490 }
10491 /// \brief Diagnose invalid operand for address of operations.
10492 ///
10493 /// \param Type The type of operand which cannot have its address taken.
10494 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10495                                          Expr *E, unsigned Type) {
10496   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10497 }
10498 
10499 /// CheckAddressOfOperand - The operand of & must be either a function
10500 /// designator or an lvalue designating an object. If it is an lvalue, the
10501 /// object cannot be declared with storage class register or be a bit field.
10502 /// Note: The usual conversions are *not* applied to the operand of the &
10503 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10504 /// In C++, the operand might be an overloaded function name, in which case
10505 /// we allow the '&' but retain the overloaded-function type.
10506 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10507   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10508     if (PTy->getKind() == BuiltinType::Overload) {
10509       Expr *E = OrigOp.get()->IgnoreParens();
10510       if (!isa<OverloadExpr>(E)) {
10511         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10512         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10513           << OrigOp.get()->getSourceRange();
10514         return QualType();
10515       }
10516 
10517       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10518       if (isa<UnresolvedMemberExpr>(Ovl))
10519         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10520           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10521             << OrigOp.get()->getSourceRange();
10522           return QualType();
10523         }
10524 
10525       return Context.OverloadTy;
10526     }
10527 
10528     if (PTy->getKind() == BuiltinType::UnknownAny)
10529       return Context.UnknownAnyTy;
10530 
10531     if (PTy->getKind() == BuiltinType::BoundMember) {
10532       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10533         << OrigOp.get()->getSourceRange();
10534       return QualType();
10535     }
10536 
10537     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10538     if (OrigOp.isInvalid()) return QualType();
10539   }
10540 
10541   if (OrigOp.get()->isTypeDependent())
10542     return Context.DependentTy;
10543 
10544   assert(!OrigOp.get()->getType()->isPlaceholderType());
10545 
10546   // Make sure to ignore parentheses in subsequent checks
10547   Expr *op = OrigOp.get()->IgnoreParens();
10548 
10549   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10550   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10551     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10552     return QualType();
10553   }
10554 
10555   if (getLangOpts().C99) {
10556     // Implement C99-only parts of addressof rules.
10557     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10558       if (uOp->getOpcode() == UO_Deref)
10559         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10560         // (assuming the deref expression is valid).
10561         return uOp->getSubExpr()->getType();
10562     }
10563     // Technically, there should be a check for array subscript
10564     // expressions here, but the result of one is always an lvalue anyway.
10565   }
10566   ValueDecl *dcl = getPrimaryDecl(op);
10567 
10568   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10569     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10570                                            op->getLocStart()))
10571       return QualType();
10572 
10573   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10574   unsigned AddressOfError = AO_No_Error;
10575 
10576   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10577     bool sfinae = (bool)isSFINAEContext();
10578     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10579                                   : diag::ext_typecheck_addrof_temporary)
10580       << op->getType() << op->getSourceRange();
10581     if (sfinae)
10582       return QualType();
10583     // Materialize the temporary as an lvalue so that we can take its address.
10584     OrigOp = op =
10585         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10586   } else if (isa<ObjCSelectorExpr>(op)) {
10587     return Context.getPointerType(op->getType());
10588   } else if (lval == Expr::LV_MemberFunction) {
10589     // If it's an instance method, make a member pointer.
10590     // The expression must have exactly the form &A::foo.
10591 
10592     // If the underlying expression isn't a decl ref, give up.
10593     if (!isa<DeclRefExpr>(op)) {
10594       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10595         << OrigOp.get()->getSourceRange();
10596       return QualType();
10597     }
10598     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10599     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10600 
10601     // The id-expression was parenthesized.
10602     if (OrigOp.get() != DRE) {
10603       Diag(OpLoc, diag::err_parens_pointer_member_function)
10604         << OrigOp.get()->getSourceRange();
10605 
10606     // The method was named without a qualifier.
10607     } else if (!DRE->getQualifier()) {
10608       if (MD->getParent()->getName().empty())
10609         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10610           << op->getSourceRange();
10611       else {
10612         SmallString<32> Str;
10613         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10614         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10615           << op->getSourceRange()
10616           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10617       }
10618     }
10619 
10620     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10621     if (isa<CXXDestructorDecl>(MD))
10622       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10623 
10624     QualType MPTy = Context.getMemberPointerType(
10625         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10626     // Under the MS ABI, lock down the inheritance model now.
10627     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10628       (void)isCompleteType(OpLoc, MPTy);
10629     return MPTy;
10630   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10631     // C99 6.5.3.2p1
10632     // The operand must be either an l-value or a function designator
10633     if (!op->getType()->isFunctionType()) {
10634       // Use a special diagnostic for loads from property references.
10635       if (isa<PseudoObjectExpr>(op)) {
10636         AddressOfError = AO_Property_Expansion;
10637       } else {
10638         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10639           << op->getType() << op->getSourceRange();
10640         return QualType();
10641       }
10642     }
10643   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10644     // The operand cannot be a bit-field
10645     AddressOfError = AO_Bit_Field;
10646   } else if (op->getObjectKind() == OK_VectorComponent) {
10647     // The operand cannot be an element of a vector
10648     AddressOfError = AO_Vector_Element;
10649   } else if (dcl) { // C99 6.5.3.2p1
10650     // We have an lvalue with a decl. Make sure the decl is not declared
10651     // with the register storage-class specifier.
10652     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10653       // in C++ it is not error to take address of a register
10654       // variable (c++03 7.1.1P3)
10655       if (vd->getStorageClass() == SC_Register &&
10656           !getLangOpts().CPlusPlus) {
10657         AddressOfError = AO_Register_Variable;
10658       }
10659     } else if (isa<MSPropertyDecl>(dcl)) {
10660       AddressOfError = AO_Property_Expansion;
10661     } else if (isa<FunctionTemplateDecl>(dcl)) {
10662       return Context.OverloadTy;
10663     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10664       // Okay: we can take the address of a field.
10665       // Could be a pointer to member, though, if there is an explicit
10666       // scope qualifier for the class.
10667       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10668         DeclContext *Ctx = dcl->getDeclContext();
10669         if (Ctx && Ctx->isRecord()) {
10670           if (dcl->getType()->isReferenceType()) {
10671             Diag(OpLoc,
10672                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10673               << dcl->getDeclName() << dcl->getType();
10674             return QualType();
10675           }
10676 
10677           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10678             Ctx = Ctx->getParent();
10679 
10680           QualType MPTy = Context.getMemberPointerType(
10681               op->getType(),
10682               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10683           // Under the MS ABI, lock down the inheritance model now.
10684           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10685             (void)isCompleteType(OpLoc, MPTy);
10686           return MPTy;
10687         }
10688       }
10689     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10690                !isa<BindingDecl>(dcl))
10691       llvm_unreachable("Unknown/unexpected decl type");
10692   }
10693 
10694   if (AddressOfError != AO_No_Error) {
10695     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10696     return QualType();
10697   }
10698 
10699   if (lval == Expr::LV_IncompleteVoidType) {
10700     // Taking the address of a void variable is technically illegal, but we
10701     // allow it in cases which are otherwise valid.
10702     // Example: "extern void x; void* y = &x;".
10703     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10704   }
10705 
10706   // If the operand has type "type", the result has type "pointer to type".
10707   if (op->getType()->isObjCObjectType())
10708     return Context.getObjCObjectPointerType(op->getType());
10709 
10710   CheckAddressOfPackedMember(op);
10711 
10712   return Context.getPointerType(op->getType());
10713 }
10714 
10715 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10716   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10717   if (!DRE)
10718     return;
10719   const Decl *D = DRE->getDecl();
10720   if (!D)
10721     return;
10722   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10723   if (!Param)
10724     return;
10725   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10726     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10727       return;
10728   if (FunctionScopeInfo *FD = S.getCurFunction())
10729     if (!FD->ModifiedNonNullParams.count(Param))
10730       FD->ModifiedNonNullParams.insert(Param);
10731 }
10732 
10733 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10734 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10735                                         SourceLocation OpLoc) {
10736   if (Op->isTypeDependent())
10737     return S.Context.DependentTy;
10738 
10739   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10740   if (ConvResult.isInvalid())
10741     return QualType();
10742   Op = ConvResult.get();
10743   QualType OpTy = Op->getType();
10744   QualType Result;
10745 
10746   if (isa<CXXReinterpretCastExpr>(Op)) {
10747     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10748     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10749                                      Op->getSourceRange());
10750   }
10751 
10752   if (const PointerType *PT = OpTy->getAs<PointerType>())
10753   {
10754     Result = PT->getPointeeType();
10755   }
10756   else if (const ObjCObjectPointerType *OPT =
10757              OpTy->getAs<ObjCObjectPointerType>())
10758     Result = OPT->getPointeeType();
10759   else {
10760     ExprResult PR = S.CheckPlaceholderExpr(Op);
10761     if (PR.isInvalid()) return QualType();
10762     if (PR.get() != Op)
10763       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10764   }
10765 
10766   if (Result.isNull()) {
10767     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10768       << OpTy << Op->getSourceRange();
10769     return QualType();
10770   }
10771 
10772   // Note that per both C89 and C99, indirection is always legal, even if Result
10773   // is an incomplete type or void.  It would be possible to warn about
10774   // dereferencing a void pointer, but it's completely well-defined, and such a
10775   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10776   // for pointers to 'void' but is fine for any other pointer type:
10777   //
10778   // C++ [expr.unary.op]p1:
10779   //   [...] the expression to which [the unary * operator] is applied shall
10780   //   be a pointer to an object type, or a pointer to a function type
10781   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10782     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10783       << OpTy << Op->getSourceRange();
10784 
10785   // Dereferences are usually l-values...
10786   VK = VK_LValue;
10787 
10788   // ...except that certain expressions are never l-values in C.
10789   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10790     VK = VK_RValue;
10791 
10792   return Result;
10793 }
10794 
10795 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10796   BinaryOperatorKind Opc;
10797   switch (Kind) {
10798   default: llvm_unreachable("Unknown binop!");
10799   case tok::periodstar:           Opc = BO_PtrMemD; break;
10800   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10801   case tok::star:                 Opc = BO_Mul; break;
10802   case tok::slash:                Opc = BO_Div; break;
10803   case tok::percent:              Opc = BO_Rem; break;
10804   case tok::plus:                 Opc = BO_Add; break;
10805   case tok::minus:                Opc = BO_Sub; break;
10806   case tok::lessless:             Opc = BO_Shl; break;
10807   case tok::greatergreater:       Opc = BO_Shr; break;
10808   case tok::lessequal:            Opc = BO_LE; break;
10809   case tok::less:                 Opc = BO_LT; break;
10810   case tok::greaterequal:         Opc = BO_GE; break;
10811   case tok::greater:              Opc = BO_GT; break;
10812   case tok::exclaimequal:         Opc = BO_NE; break;
10813   case tok::equalequal:           Opc = BO_EQ; break;
10814   case tok::amp:                  Opc = BO_And; break;
10815   case tok::caret:                Opc = BO_Xor; break;
10816   case tok::pipe:                 Opc = BO_Or; break;
10817   case tok::ampamp:               Opc = BO_LAnd; break;
10818   case tok::pipepipe:             Opc = BO_LOr; break;
10819   case tok::equal:                Opc = BO_Assign; break;
10820   case tok::starequal:            Opc = BO_MulAssign; break;
10821   case tok::slashequal:           Opc = BO_DivAssign; break;
10822   case tok::percentequal:         Opc = BO_RemAssign; break;
10823   case tok::plusequal:            Opc = BO_AddAssign; break;
10824   case tok::minusequal:           Opc = BO_SubAssign; break;
10825   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10826   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10827   case tok::ampequal:             Opc = BO_AndAssign; break;
10828   case tok::caretequal:           Opc = BO_XorAssign; break;
10829   case tok::pipeequal:            Opc = BO_OrAssign; break;
10830   case tok::comma:                Opc = BO_Comma; break;
10831   }
10832   return Opc;
10833 }
10834 
10835 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10836   tok::TokenKind Kind) {
10837   UnaryOperatorKind Opc;
10838   switch (Kind) {
10839   default: llvm_unreachable("Unknown unary op!");
10840   case tok::plusplus:     Opc = UO_PreInc; break;
10841   case tok::minusminus:   Opc = UO_PreDec; break;
10842   case tok::amp:          Opc = UO_AddrOf; break;
10843   case tok::star:         Opc = UO_Deref; break;
10844   case tok::plus:         Opc = UO_Plus; break;
10845   case tok::minus:        Opc = UO_Minus; break;
10846   case tok::tilde:        Opc = UO_Not; break;
10847   case tok::exclaim:      Opc = UO_LNot; break;
10848   case tok::kw___real:    Opc = UO_Real; break;
10849   case tok::kw___imag:    Opc = UO_Imag; break;
10850   case tok::kw___extension__: Opc = UO_Extension; break;
10851   }
10852   return Opc;
10853 }
10854 
10855 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10856 /// This warning is only emitted for builtin assignment operations. It is also
10857 /// suppressed in the event of macro expansions.
10858 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10859                                    SourceLocation OpLoc) {
10860   if (!S.ActiveTemplateInstantiations.empty())
10861     return;
10862   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10863     return;
10864   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10865   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10866   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10867   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10868   if (!LHSDeclRef || !RHSDeclRef ||
10869       LHSDeclRef->getLocation().isMacroID() ||
10870       RHSDeclRef->getLocation().isMacroID())
10871     return;
10872   const ValueDecl *LHSDecl =
10873     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10874   const ValueDecl *RHSDecl =
10875     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10876   if (LHSDecl != RHSDecl)
10877     return;
10878   if (LHSDecl->getType().isVolatileQualified())
10879     return;
10880   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10881     if (RefTy->getPointeeType().isVolatileQualified())
10882       return;
10883 
10884   S.Diag(OpLoc, diag::warn_self_assignment)
10885       << LHSDeclRef->getType()
10886       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10887 }
10888 
10889 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10890 /// is usually indicative of introspection within the Objective-C pointer.
10891 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10892                                           SourceLocation OpLoc) {
10893   if (!S.getLangOpts().ObjC1)
10894     return;
10895 
10896   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10897   const Expr *LHS = L.get();
10898   const Expr *RHS = R.get();
10899 
10900   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10901     ObjCPointerExpr = LHS;
10902     OtherExpr = RHS;
10903   }
10904   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10905     ObjCPointerExpr = RHS;
10906     OtherExpr = LHS;
10907   }
10908 
10909   // This warning is deliberately made very specific to reduce false
10910   // positives with logic that uses '&' for hashing.  This logic mainly
10911   // looks for code trying to introspect into tagged pointers, which
10912   // code should generally never do.
10913   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10914     unsigned Diag = diag::warn_objc_pointer_masking;
10915     // Determine if we are introspecting the result of performSelectorXXX.
10916     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10917     // Special case messages to -performSelector and friends, which
10918     // can return non-pointer values boxed in a pointer value.
10919     // Some clients may wish to silence warnings in this subcase.
10920     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10921       Selector S = ME->getSelector();
10922       StringRef SelArg0 = S.getNameForSlot(0);
10923       if (SelArg0.startswith("performSelector"))
10924         Diag = diag::warn_objc_pointer_masking_performSelector;
10925     }
10926 
10927     S.Diag(OpLoc, Diag)
10928       << ObjCPointerExpr->getSourceRange();
10929   }
10930 }
10931 
10932 static NamedDecl *getDeclFromExpr(Expr *E) {
10933   if (!E)
10934     return nullptr;
10935   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10936     return DRE->getDecl();
10937   if (auto *ME = dyn_cast<MemberExpr>(E))
10938     return ME->getMemberDecl();
10939   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10940     return IRE->getDecl();
10941   return nullptr;
10942 }
10943 
10944 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10945 /// operator @p Opc at location @c TokLoc. This routine only supports
10946 /// built-in operations; ActOnBinOp handles overloaded operators.
10947 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10948                                     BinaryOperatorKind Opc,
10949                                     Expr *LHSExpr, Expr *RHSExpr) {
10950   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10951     // The syntax only allows initializer lists on the RHS of assignment,
10952     // so we don't need to worry about accepting invalid code for
10953     // non-assignment operators.
10954     // C++11 5.17p9:
10955     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10956     //   of x = {} is x = T().
10957     InitializationKind Kind =
10958         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10959     InitializedEntity Entity =
10960         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10961     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10962     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10963     if (Init.isInvalid())
10964       return Init;
10965     RHSExpr = Init.get();
10966   }
10967 
10968   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10969   QualType ResultTy;     // Result type of the binary operator.
10970   // The following two variables are used for compound assignment operators
10971   QualType CompLHSTy;    // Type of LHS after promotions for computation
10972   QualType CompResultTy; // Type of computation result
10973   ExprValueKind VK = VK_RValue;
10974   ExprObjectKind OK = OK_Ordinary;
10975 
10976   if (!getLangOpts().CPlusPlus) {
10977     // C cannot handle TypoExpr nodes on either side of a binop because it
10978     // doesn't handle dependent types properly, so make sure any TypoExprs have
10979     // been dealt with before checking the operands.
10980     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10981     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10982       if (Opc != BO_Assign)
10983         return ExprResult(E);
10984       // Avoid correcting the RHS to the same Expr as the LHS.
10985       Decl *D = getDeclFromExpr(E);
10986       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10987     });
10988     if (!LHS.isUsable() || !RHS.isUsable())
10989       return ExprError();
10990   }
10991 
10992   if (getLangOpts().OpenCL) {
10993     QualType LHSTy = LHSExpr->getType();
10994     QualType RHSTy = RHSExpr->getType();
10995     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10996     // the ATOMIC_VAR_INIT macro.
10997     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10998       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10999       if (BO_Assign == Opc)
11000         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11001       else
11002         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11003       return ExprError();
11004     }
11005 
11006     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11007     // only with a builtin functions and therefore should be disallowed here.
11008     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11009         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11010         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11011         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11012       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11013       return ExprError();
11014     }
11015   }
11016 
11017   switch (Opc) {
11018   case BO_Assign:
11019     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11020     if (getLangOpts().CPlusPlus &&
11021         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11022       VK = LHS.get()->getValueKind();
11023       OK = LHS.get()->getObjectKind();
11024     }
11025     if (!ResultTy.isNull()) {
11026       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11027       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11028     }
11029     RecordModifiableNonNullParam(*this, LHS.get());
11030     break;
11031   case BO_PtrMemD:
11032   case BO_PtrMemI:
11033     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11034                                             Opc == BO_PtrMemI);
11035     break;
11036   case BO_Mul:
11037   case BO_Div:
11038     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11039                                            Opc == BO_Div);
11040     break;
11041   case BO_Rem:
11042     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11043     break;
11044   case BO_Add:
11045     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11046     break;
11047   case BO_Sub:
11048     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11049     break;
11050   case BO_Shl:
11051   case BO_Shr:
11052     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11053     break;
11054   case BO_LE:
11055   case BO_LT:
11056   case BO_GE:
11057   case BO_GT:
11058     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11059     break;
11060   case BO_EQ:
11061   case BO_NE:
11062     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11063     break;
11064   case BO_And:
11065     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11066   case BO_Xor:
11067   case BO_Or:
11068     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11069     break;
11070   case BO_LAnd:
11071   case BO_LOr:
11072     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11073     break;
11074   case BO_MulAssign:
11075   case BO_DivAssign:
11076     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11077                                                Opc == BO_DivAssign);
11078     CompLHSTy = CompResultTy;
11079     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11080       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11081     break;
11082   case BO_RemAssign:
11083     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11084     CompLHSTy = CompResultTy;
11085     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11086       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11087     break;
11088   case BO_AddAssign:
11089     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11090     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11091       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11092     break;
11093   case BO_SubAssign:
11094     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11095     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11096       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11097     break;
11098   case BO_ShlAssign:
11099   case BO_ShrAssign:
11100     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11101     CompLHSTy = CompResultTy;
11102     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11103       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11104     break;
11105   case BO_AndAssign:
11106   case BO_OrAssign: // fallthrough
11107     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11108   case BO_XorAssign:
11109     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11110     CompLHSTy = CompResultTy;
11111     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11112       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11113     break;
11114   case BO_Comma:
11115     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11116     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11117       VK = RHS.get()->getValueKind();
11118       OK = RHS.get()->getObjectKind();
11119     }
11120     break;
11121   }
11122   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11123     return ExprError();
11124 
11125   // Check for array bounds violations for both sides of the BinaryOperator
11126   CheckArrayAccess(LHS.get());
11127   CheckArrayAccess(RHS.get());
11128 
11129   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11130     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11131                                                  &Context.Idents.get("object_setClass"),
11132                                                  SourceLocation(), LookupOrdinaryName);
11133     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11134       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11135       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11136       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11137       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11138       FixItHint::CreateInsertion(RHSLocEnd, ")");
11139     }
11140     else
11141       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11142   }
11143   else if (const ObjCIvarRefExpr *OIRE =
11144            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11145     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11146 
11147   if (CompResultTy.isNull())
11148     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11149                                         OK, OpLoc, FPFeatures.fp_contract);
11150   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11151       OK_ObjCProperty) {
11152     VK = VK_LValue;
11153     OK = LHS.get()->getObjectKind();
11154   }
11155   return new (Context) CompoundAssignOperator(
11156       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11157       OpLoc, FPFeatures.fp_contract);
11158 }
11159 
11160 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11161 /// operators are mixed in a way that suggests that the programmer forgot that
11162 /// comparison operators have higher precedence. The most typical example of
11163 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11164 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11165                                       SourceLocation OpLoc, Expr *LHSExpr,
11166                                       Expr *RHSExpr) {
11167   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11168   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11169 
11170   // Check that one of the sides is a comparison operator and the other isn't.
11171   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11172   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11173   if (isLeftComp == isRightComp)
11174     return;
11175 
11176   // Bitwise operations are sometimes used as eager logical ops.
11177   // Don't diagnose this.
11178   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11179   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11180   if (isLeftBitwise || isRightBitwise)
11181     return;
11182 
11183   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11184                                                    OpLoc)
11185                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11186   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11187   SourceRange ParensRange = isLeftComp ?
11188       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11189     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11190 
11191   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11192     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11193   SuggestParentheses(Self, OpLoc,
11194     Self.PDiag(diag::note_precedence_silence) << OpStr,
11195     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11196   SuggestParentheses(Self, OpLoc,
11197     Self.PDiag(diag::note_precedence_bitwise_first)
11198       << BinaryOperator::getOpcodeStr(Opc),
11199     ParensRange);
11200 }
11201 
11202 /// \brief It accepts a '&&' expr that is inside a '||' one.
11203 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11204 /// in parentheses.
11205 static void
11206 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11207                                        BinaryOperator *Bop) {
11208   assert(Bop->getOpcode() == BO_LAnd);
11209   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11210       << Bop->getSourceRange() << OpLoc;
11211   SuggestParentheses(Self, Bop->getOperatorLoc(),
11212     Self.PDiag(diag::note_precedence_silence)
11213       << Bop->getOpcodeStr(),
11214     Bop->getSourceRange());
11215 }
11216 
11217 /// \brief Returns true if the given expression can be evaluated as a constant
11218 /// 'true'.
11219 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11220   bool Res;
11221   return !E->isValueDependent() &&
11222          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11223 }
11224 
11225 /// \brief Returns true if the given expression can be evaluated as a constant
11226 /// 'false'.
11227 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11228   bool Res;
11229   return !E->isValueDependent() &&
11230          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11231 }
11232 
11233 /// \brief Look for '&&' in the left hand of a '||' expr.
11234 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11235                                              Expr *LHSExpr, Expr *RHSExpr) {
11236   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11237     if (Bop->getOpcode() == BO_LAnd) {
11238       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11239       if (EvaluatesAsFalse(S, RHSExpr))
11240         return;
11241       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11242       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11243         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11244     } else if (Bop->getOpcode() == BO_LOr) {
11245       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11246         // If it's "a || b && 1 || c" we didn't warn earlier for
11247         // "a || b && 1", but warn now.
11248         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11249           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11250       }
11251     }
11252   }
11253 }
11254 
11255 /// \brief Look for '&&' in the right hand of a '||' expr.
11256 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11257                                              Expr *LHSExpr, Expr *RHSExpr) {
11258   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11259     if (Bop->getOpcode() == BO_LAnd) {
11260       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11261       if (EvaluatesAsFalse(S, LHSExpr))
11262         return;
11263       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11264       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11265         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11266     }
11267   }
11268 }
11269 
11270 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11271 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11272 /// the '&' expression in parentheses.
11273 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11274                                          SourceLocation OpLoc, Expr *SubExpr) {
11275   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11276     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11277       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11278         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11279         << Bop->getSourceRange() << OpLoc;
11280       SuggestParentheses(S, Bop->getOperatorLoc(),
11281         S.PDiag(diag::note_precedence_silence)
11282           << Bop->getOpcodeStr(),
11283         Bop->getSourceRange());
11284     }
11285   }
11286 }
11287 
11288 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11289                                     Expr *SubExpr, StringRef Shift) {
11290   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11291     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11292       StringRef Op = Bop->getOpcodeStr();
11293       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11294           << Bop->getSourceRange() << OpLoc << Shift << Op;
11295       SuggestParentheses(S, Bop->getOperatorLoc(),
11296           S.PDiag(diag::note_precedence_silence) << Op,
11297           Bop->getSourceRange());
11298     }
11299   }
11300 }
11301 
11302 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11303                                  Expr *LHSExpr, Expr *RHSExpr) {
11304   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11305   if (!OCE)
11306     return;
11307 
11308   FunctionDecl *FD = OCE->getDirectCallee();
11309   if (!FD || !FD->isOverloadedOperator())
11310     return;
11311 
11312   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11313   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11314     return;
11315 
11316   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11317       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11318       << (Kind == OO_LessLess);
11319   SuggestParentheses(S, OCE->getOperatorLoc(),
11320                      S.PDiag(diag::note_precedence_silence)
11321                          << (Kind == OO_LessLess ? "<<" : ">>"),
11322                      OCE->getSourceRange());
11323   SuggestParentheses(S, OpLoc,
11324                      S.PDiag(diag::note_evaluate_comparison_first),
11325                      SourceRange(OCE->getArg(1)->getLocStart(),
11326                                  RHSExpr->getLocEnd()));
11327 }
11328 
11329 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11330 /// precedence.
11331 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11332                                     SourceLocation OpLoc, Expr *LHSExpr,
11333                                     Expr *RHSExpr){
11334   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11335   if (BinaryOperator::isBitwiseOp(Opc))
11336     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11337 
11338   // Diagnose "arg1 & arg2 | arg3"
11339   if ((Opc == BO_Or || Opc == BO_Xor) &&
11340       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11341     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11342     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11343   }
11344 
11345   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11346   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11347   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11348     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11349     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11350   }
11351 
11352   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11353       || Opc == BO_Shr) {
11354     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11355     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11356     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11357   }
11358 
11359   // Warn on overloaded shift operators and comparisons, such as:
11360   // cout << 5 == 4;
11361   if (BinaryOperator::isComparisonOp(Opc))
11362     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11363 }
11364 
11365 // Binary Operators.  'Tok' is the token for the operator.
11366 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11367                             tok::TokenKind Kind,
11368                             Expr *LHSExpr, Expr *RHSExpr) {
11369   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11370   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11371   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11372 
11373   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11374   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11375 
11376   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11377 }
11378 
11379 /// Build an overloaded binary operator expression in the given scope.
11380 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11381                                        BinaryOperatorKind Opc,
11382                                        Expr *LHS, Expr *RHS) {
11383   // Find all of the overloaded operators visible from this
11384   // point. We perform both an operator-name lookup from the local
11385   // scope and an argument-dependent lookup based on the types of
11386   // the arguments.
11387   UnresolvedSet<16> Functions;
11388   OverloadedOperatorKind OverOp
11389     = BinaryOperator::getOverloadedOperator(Opc);
11390   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11391     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11392                                    RHS->getType(), Functions);
11393 
11394   // Build the (potentially-overloaded, potentially-dependent)
11395   // binary operation.
11396   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11397 }
11398 
11399 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11400                             BinaryOperatorKind Opc,
11401                             Expr *LHSExpr, Expr *RHSExpr) {
11402   // We want to end up calling one of checkPseudoObjectAssignment
11403   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11404   // both expressions are overloadable or either is type-dependent),
11405   // or CreateBuiltinBinOp (in any other case).  We also want to get
11406   // any placeholder types out of the way.
11407 
11408   // Handle pseudo-objects in the LHS.
11409   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11410     // Assignments with a pseudo-object l-value need special analysis.
11411     if (pty->getKind() == BuiltinType::PseudoObject &&
11412         BinaryOperator::isAssignmentOp(Opc))
11413       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11414 
11415     // Don't resolve overloads if the other type is overloadable.
11416     if (pty->getKind() == BuiltinType::Overload) {
11417       // We can't actually test that if we still have a placeholder,
11418       // though.  Fortunately, none of the exceptions we see in that
11419       // code below are valid when the LHS is an overload set.  Note
11420       // that an overload set can be dependently-typed, but it never
11421       // instantiates to having an overloadable type.
11422       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11423       if (resolvedRHS.isInvalid()) return ExprError();
11424       RHSExpr = resolvedRHS.get();
11425 
11426       if (RHSExpr->isTypeDependent() ||
11427           RHSExpr->getType()->isOverloadableType())
11428         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11429     }
11430 
11431     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11432     if (LHS.isInvalid()) return ExprError();
11433     LHSExpr = LHS.get();
11434   }
11435 
11436   // Handle pseudo-objects in the RHS.
11437   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11438     // An overload in the RHS can potentially be resolved by the type
11439     // being assigned to.
11440     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11441       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11442         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11443 
11444       if (LHSExpr->getType()->isOverloadableType())
11445         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11446 
11447       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11448     }
11449 
11450     // Don't resolve overloads if the other type is overloadable.
11451     if (pty->getKind() == BuiltinType::Overload &&
11452         LHSExpr->getType()->isOverloadableType())
11453       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11454 
11455     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11456     if (!resolvedRHS.isUsable()) return ExprError();
11457     RHSExpr = resolvedRHS.get();
11458   }
11459 
11460   if (getLangOpts().CPlusPlus) {
11461     // If either expression is type-dependent, always build an
11462     // overloaded op.
11463     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11464       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11465 
11466     // Otherwise, build an overloaded op if either expression has an
11467     // overloadable type.
11468     if (LHSExpr->getType()->isOverloadableType() ||
11469         RHSExpr->getType()->isOverloadableType())
11470       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11471   }
11472 
11473   // Build a built-in binary operation.
11474   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11475 }
11476 
11477 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11478                                       UnaryOperatorKind Opc,
11479                                       Expr *InputExpr) {
11480   ExprResult Input = InputExpr;
11481   ExprValueKind VK = VK_RValue;
11482   ExprObjectKind OK = OK_Ordinary;
11483   QualType resultType;
11484   if (getLangOpts().OpenCL) {
11485     QualType Ty = InputExpr->getType();
11486     // The only legal unary operation for atomics is '&'.
11487     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11488     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11489     // only with a builtin functions and therefore should be disallowed here.
11490         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11491         || Ty->isBlockPointerType())) {
11492       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11493                        << InputExpr->getType()
11494                        << Input.get()->getSourceRange());
11495     }
11496   }
11497   switch (Opc) {
11498   case UO_PreInc:
11499   case UO_PreDec:
11500   case UO_PostInc:
11501   case UO_PostDec:
11502     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11503                                                 OpLoc,
11504                                                 Opc == UO_PreInc ||
11505                                                 Opc == UO_PostInc,
11506                                                 Opc == UO_PreInc ||
11507                                                 Opc == UO_PreDec);
11508     break;
11509   case UO_AddrOf:
11510     resultType = CheckAddressOfOperand(Input, OpLoc);
11511     RecordModifiableNonNullParam(*this, InputExpr);
11512     break;
11513   case UO_Deref: {
11514     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11515     if (Input.isInvalid()) return ExprError();
11516     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11517     break;
11518   }
11519   case UO_Plus:
11520   case UO_Minus:
11521     Input = UsualUnaryConversions(Input.get());
11522     if (Input.isInvalid()) return ExprError();
11523     resultType = Input.get()->getType();
11524     if (resultType->isDependentType())
11525       break;
11526     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11527       break;
11528     else if (resultType->isVectorType() &&
11529              // The z vector extensions don't allow + or - with bool vectors.
11530              (!Context.getLangOpts().ZVector ||
11531               resultType->getAs<VectorType>()->getVectorKind() !=
11532               VectorType::AltiVecBool))
11533       break;
11534     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11535              Opc == UO_Plus &&
11536              resultType->isPointerType())
11537       break;
11538 
11539     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11540       << resultType << Input.get()->getSourceRange());
11541 
11542   case UO_Not: // bitwise complement
11543     Input = UsualUnaryConversions(Input.get());
11544     if (Input.isInvalid())
11545       return ExprError();
11546     resultType = Input.get()->getType();
11547     if (resultType->isDependentType())
11548       break;
11549     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11550     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11551       // C99 does not support '~' for complex conjugation.
11552       Diag(OpLoc, diag::ext_integer_complement_complex)
11553           << resultType << Input.get()->getSourceRange();
11554     else if (resultType->hasIntegerRepresentation())
11555       break;
11556     else if (resultType->isExtVectorType()) {
11557       if (Context.getLangOpts().OpenCL) {
11558         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11559         // on vector float types.
11560         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11561         if (!T->isIntegerType())
11562           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11563                            << resultType << Input.get()->getSourceRange());
11564       }
11565       break;
11566     } else {
11567       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11568                        << resultType << Input.get()->getSourceRange());
11569     }
11570     break;
11571 
11572   case UO_LNot: // logical negation
11573     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11574     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11575     if (Input.isInvalid()) return ExprError();
11576     resultType = Input.get()->getType();
11577 
11578     // Though we still have to promote half FP to float...
11579     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11580       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11581       resultType = Context.FloatTy;
11582     }
11583 
11584     if (resultType->isDependentType())
11585       break;
11586     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11587       // C99 6.5.3.3p1: ok, fallthrough;
11588       if (Context.getLangOpts().CPlusPlus) {
11589         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11590         // operand contextually converted to bool.
11591         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11592                                   ScalarTypeToBooleanCastKind(resultType));
11593       } else if (Context.getLangOpts().OpenCL &&
11594                  Context.getLangOpts().OpenCLVersion < 120) {
11595         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11596         // operate on scalar float types.
11597         if (!resultType->isIntegerType())
11598           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11599                            << resultType << Input.get()->getSourceRange());
11600       }
11601     } else if (resultType->isExtVectorType()) {
11602       if (Context.getLangOpts().OpenCL &&
11603           Context.getLangOpts().OpenCLVersion < 120) {
11604         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11605         // operate on vector float types.
11606         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11607         if (!T->isIntegerType())
11608           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11609                            << resultType << Input.get()->getSourceRange());
11610       }
11611       // Vector logical not returns the signed variant of the operand type.
11612       resultType = GetSignedVectorType(resultType);
11613       break;
11614     } else {
11615       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11616         << resultType << Input.get()->getSourceRange());
11617     }
11618 
11619     // LNot always has type int. C99 6.5.3.3p5.
11620     // In C++, it's bool. C++ 5.3.1p8
11621     resultType = Context.getLogicalOperationType();
11622     break;
11623   case UO_Real:
11624   case UO_Imag:
11625     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11626     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11627     // complex l-values to ordinary l-values and all other values to r-values.
11628     if (Input.isInvalid()) return ExprError();
11629     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11630       if (Input.get()->getValueKind() != VK_RValue &&
11631           Input.get()->getObjectKind() == OK_Ordinary)
11632         VK = Input.get()->getValueKind();
11633     } else if (!getLangOpts().CPlusPlus) {
11634       // In C, a volatile scalar is read by __imag. In C++, it is not.
11635       Input = DefaultLvalueConversion(Input.get());
11636     }
11637     break;
11638   case UO_Extension:
11639   case UO_Coawait:
11640     resultType = Input.get()->getType();
11641     VK = Input.get()->getValueKind();
11642     OK = Input.get()->getObjectKind();
11643     break;
11644   }
11645   if (resultType.isNull() || Input.isInvalid())
11646     return ExprError();
11647 
11648   // Check for array bounds violations in the operand of the UnaryOperator,
11649   // except for the '*' and '&' operators that have to be handled specially
11650   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11651   // that are explicitly defined as valid by the standard).
11652   if (Opc != UO_AddrOf && Opc != UO_Deref)
11653     CheckArrayAccess(Input.get());
11654 
11655   return new (Context)
11656       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11657 }
11658 
11659 /// \brief Determine whether the given expression is a qualified member
11660 /// access expression, of a form that could be turned into a pointer to member
11661 /// with the address-of operator.
11662 static bool isQualifiedMemberAccess(Expr *E) {
11663   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11664     if (!DRE->getQualifier())
11665       return false;
11666 
11667     ValueDecl *VD = DRE->getDecl();
11668     if (!VD->isCXXClassMember())
11669       return false;
11670 
11671     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11672       return true;
11673     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11674       return Method->isInstance();
11675 
11676     return false;
11677   }
11678 
11679   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11680     if (!ULE->getQualifier())
11681       return false;
11682 
11683     for (NamedDecl *D : ULE->decls()) {
11684       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11685         if (Method->isInstance())
11686           return true;
11687       } else {
11688         // Overload set does not contain methods.
11689         break;
11690       }
11691     }
11692 
11693     return false;
11694   }
11695 
11696   return false;
11697 }
11698 
11699 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11700                               UnaryOperatorKind Opc, Expr *Input) {
11701   // First things first: handle placeholders so that the
11702   // overloaded-operator check considers the right type.
11703   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11704     // Increment and decrement of pseudo-object references.
11705     if (pty->getKind() == BuiltinType::PseudoObject &&
11706         UnaryOperator::isIncrementDecrementOp(Opc))
11707       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11708 
11709     // extension is always a builtin operator.
11710     if (Opc == UO_Extension)
11711       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11712 
11713     // & gets special logic for several kinds of placeholder.
11714     // The builtin code knows what to do.
11715     if (Opc == UO_AddrOf &&
11716         (pty->getKind() == BuiltinType::Overload ||
11717          pty->getKind() == BuiltinType::UnknownAny ||
11718          pty->getKind() == BuiltinType::BoundMember))
11719       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11720 
11721     // Anything else needs to be handled now.
11722     ExprResult Result = CheckPlaceholderExpr(Input);
11723     if (Result.isInvalid()) return ExprError();
11724     Input = Result.get();
11725   }
11726 
11727   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11728       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11729       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11730     // Find all of the overloaded operators visible from this
11731     // point. We perform both an operator-name lookup from the local
11732     // scope and an argument-dependent lookup based on the types of
11733     // the arguments.
11734     UnresolvedSet<16> Functions;
11735     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11736     if (S && OverOp != OO_None)
11737       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11738                                    Functions);
11739 
11740     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11741   }
11742 
11743   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11744 }
11745 
11746 // Unary Operators.  'Tok' is the token for the operator.
11747 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11748                               tok::TokenKind Op, Expr *Input) {
11749   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11750 }
11751 
11752 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11753 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11754                                 LabelDecl *TheDecl) {
11755   TheDecl->markUsed(Context);
11756   // Create the AST node.  The address of a label always has type 'void*'.
11757   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11758                                      Context.getPointerType(Context.VoidTy));
11759 }
11760 
11761 /// Given the last statement in a statement-expression, check whether
11762 /// the result is a producing expression (like a call to an
11763 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11764 /// release out of the full-expression.  Otherwise, return null.
11765 /// Cannot fail.
11766 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11767   // Should always be wrapped with one of these.
11768   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11769   if (!cleanups) return nullptr;
11770 
11771   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11772   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11773     return nullptr;
11774 
11775   // Splice out the cast.  This shouldn't modify any interesting
11776   // features of the statement.
11777   Expr *producer = cast->getSubExpr();
11778   assert(producer->getType() == cast->getType());
11779   assert(producer->getValueKind() == cast->getValueKind());
11780   cleanups->setSubExpr(producer);
11781   return cleanups;
11782 }
11783 
11784 void Sema::ActOnStartStmtExpr() {
11785   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11786 }
11787 
11788 void Sema::ActOnStmtExprError() {
11789   // Note that function is also called by TreeTransform when leaving a
11790   // StmtExpr scope without rebuilding anything.
11791 
11792   DiscardCleanupsInEvaluationContext();
11793   PopExpressionEvaluationContext();
11794 }
11795 
11796 ExprResult
11797 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11798                     SourceLocation RPLoc) { // "({..})"
11799   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11800   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11801 
11802   if (hasAnyUnrecoverableErrorsInThisFunction())
11803     DiscardCleanupsInEvaluationContext();
11804   assert(!Cleanup.exprNeedsCleanups() &&
11805          "cleanups within StmtExpr not correctly bound!");
11806   PopExpressionEvaluationContext();
11807 
11808   // FIXME: there are a variety of strange constraints to enforce here, for
11809   // example, it is not possible to goto into a stmt expression apparently.
11810   // More semantic analysis is needed.
11811 
11812   // If there are sub-stmts in the compound stmt, take the type of the last one
11813   // as the type of the stmtexpr.
11814   QualType Ty = Context.VoidTy;
11815   bool StmtExprMayBindToTemp = false;
11816   if (!Compound->body_empty()) {
11817     Stmt *LastStmt = Compound->body_back();
11818     LabelStmt *LastLabelStmt = nullptr;
11819     // If LastStmt is a label, skip down through into the body.
11820     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11821       LastLabelStmt = Label;
11822       LastStmt = Label->getSubStmt();
11823     }
11824 
11825     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11826       // Do function/array conversion on the last expression, but not
11827       // lvalue-to-rvalue.  However, initialize an unqualified type.
11828       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11829       if (LastExpr.isInvalid())
11830         return ExprError();
11831       Ty = LastExpr.get()->getType().getUnqualifiedType();
11832 
11833       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11834         // In ARC, if the final expression ends in a consume, splice
11835         // the consume out and bind it later.  In the alternate case
11836         // (when dealing with a retainable type), the result
11837         // initialization will create a produce.  In both cases the
11838         // result will be +1, and we'll need to balance that out with
11839         // a bind.
11840         if (Expr *rebuiltLastStmt
11841               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11842           LastExpr = rebuiltLastStmt;
11843         } else {
11844           LastExpr = PerformCopyInitialization(
11845                             InitializedEntity::InitializeResult(LPLoc,
11846                                                                 Ty,
11847                                                                 false),
11848                                                    SourceLocation(),
11849                                                LastExpr);
11850         }
11851 
11852         if (LastExpr.isInvalid())
11853           return ExprError();
11854         if (LastExpr.get() != nullptr) {
11855           if (!LastLabelStmt)
11856             Compound->setLastStmt(LastExpr.get());
11857           else
11858             LastLabelStmt->setSubStmt(LastExpr.get());
11859           StmtExprMayBindToTemp = true;
11860         }
11861       }
11862     }
11863   }
11864 
11865   // FIXME: Check that expression type is complete/non-abstract; statement
11866   // expressions are not lvalues.
11867   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11868   if (StmtExprMayBindToTemp)
11869     return MaybeBindToTemporary(ResStmtExpr);
11870   return ResStmtExpr;
11871 }
11872 
11873 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11874                                       TypeSourceInfo *TInfo,
11875                                       ArrayRef<OffsetOfComponent> Components,
11876                                       SourceLocation RParenLoc) {
11877   QualType ArgTy = TInfo->getType();
11878   bool Dependent = ArgTy->isDependentType();
11879   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11880 
11881   // We must have at least one component that refers to the type, and the first
11882   // one is known to be a field designator.  Verify that the ArgTy represents
11883   // a struct/union/class.
11884   if (!Dependent && !ArgTy->isRecordType())
11885     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11886                        << ArgTy << TypeRange);
11887 
11888   // Type must be complete per C99 7.17p3 because a declaring a variable
11889   // with an incomplete type would be ill-formed.
11890   if (!Dependent
11891       && RequireCompleteType(BuiltinLoc, ArgTy,
11892                              diag::err_offsetof_incomplete_type, TypeRange))
11893     return ExprError();
11894 
11895   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11896   // GCC extension, diagnose them.
11897   // FIXME: This diagnostic isn't actually visible because the location is in
11898   // a system header!
11899   if (Components.size() != 1)
11900     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11901       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11902 
11903   bool DidWarnAboutNonPOD = false;
11904   QualType CurrentType = ArgTy;
11905   SmallVector<OffsetOfNode, 4> Comps;
11906   SmallVector<Expr*, 4> Exprs;
11907   for (const OffsetOfComponent &OC : Components) {
11908     if (OC.isBrackets) {
11909       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11910       if (!CurrentType->isDependentType()) {
11911         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11912         if(!AT)
11913           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11914                            << CurrentType);
11915         CurrentType = AT->getElementType();
11916       } else
11917         CurrentType = Context.DependentTy;
11918 
11919       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11920       if (IdxRval.isInvalid())
11921         return ExprError();
11922       Expr *Idx = IdxRval.get();
11923 
11924       // The expression must be an integral expression.
11925       // FIXME: An integral constant expression?
11926       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11927           !Idx->getType()->isIntegerType())
11928         return ExprError(Diag(Idx->getLocStart(),
11929                               diag::err_typecheck_subscript_not_integer)
11930                          << Idx->getSourceRange());
11931 
11932       // Record this array index.
11933       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11934       Exprs.push_back(Idx);
11935       continue;
11936     }
11937 
11938     // Offset of a field.
11939     if (CurrentType->isDependentType()) {
11940       // We have the offset of a field, but we can't look into the dependent
11941       // type. Just record the identifier of the field.
11942       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11943       CurrentType = Context.DependentTy;
11944       continue;
11945     }
11946 
11947     // We need to have a complete type to look into.
11948     if (RequireCompleteType(OC.LocStart, CurrentType,
11949                             diag::err_offsetof_incomplete_type))
11950       return ExprError();
11951 
11952     // Look for the designated field.
11953     const RecordType *RC = CurrentType->getAs<RecordType>();
11954     if (!RC)
11955       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11956                        << CurrentType);
11957     RecordDecl *RD = RC->getDecl();
11958 
11959     // C++ [lib.support.types]p5:
11960     //   The macro offsetof accepts a restricted set of type arguments in this
11961     //   International Standard. type shall be a POD structure or a POD union
11962     //   (clause 9).
11963     // C++11 [support.types]p4:
11964     //   If type is not a standard-layout class (Clause 9), the results are
11965     //   undefined.
11966     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11967       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11968       unsigned DiagID =
11969         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11970                             : diag::ext_offsetof_non_pod_type;
11971 
11972       if (!IsSafe && !DidWarnAboutNonPOD &&
11973           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11974                               PDiag(DiagID)
11975                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11976                               << CurrentType))
11977         DidWarnAboutNonPOD = true;
11978     }
11979 
11980     // Look for the field.
11981     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11982     LookupQualifiedName(R, RD);
11983     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11984     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11985     if (!MemberDecl) {
11986       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11987         MemberDecl = IndirectMemberDecl->getAnonField();
11988     }
11989 
11990     if (!MemberDecl)
11991       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11992                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11993                                                               OC.LocEnd));
11994 
11995     // C99 7.17p3:
11996     //   (If the specified member is a bit-field, the behavior is undefined.)
11997     //
11998     // We diagnose this as an error.
11999     if (MemberDecl->isBitField()) {
12000       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12001         << MemberDecl->getDeclName()
12002         << SourceRange(BuiltinLoc, RParenLoc);
12003       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12004       return ExprError();
12005     }
12006 
12007     RecordDecl *Parent = MemberDecl->getParent();
12008     if (IndirectMemberDecl)
12009       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12010 
12011     // If the member was found in a base class, introduce OffsetOfNodes for
12012     // the base class indirections.
12013     CXXBasePaths Paths;
12014     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12015                       Paths)) {
12016       if (Paths.getDetectedVirtual()) {
12017         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12018           << MemberDecl->getDeclName()
12019           << SourceRange(BuiltinLoc, RParenLoc);
12020         return ExprError();
12021       }
12022 
12023       CXXBasePath &Path = Paths.front();
12024       for (const CXXBasePathElement &B : Path)
12025         Comps.push_back(OffsetOfNode(B.Base));
12026     }
12027 
12028     if (IndirectMemberDecl) {
12029       for (auto *FI : IndirectMemberDecl->chain()) {
12030         assert(isa<FieldDecl>(FI));
12031         Comps.push_back(OffsetOfNode(OC.LocStart,
12032                                      cast<FieldDecl>(FI), OC.LocEnd));
12033       }
12034     } else
12035       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12036 
12037     CurrentType = MemberDecl->getType().getNonReferenceType();
12038   }
12039 
12040   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12041                               Comps, Exprs, RParenLoc);
12042 }
12043 
12044 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12045                                       SourceLocation BuiltinLoc,
12046                                       SourceLocation TypeLoc,
12047                                       ParsedType ParsedArgTy,
12048                                       ArrayRef<OffsetOfComponent> Components,
12049                                       SourceLocation RParenLoc) {
12050 
12051   TypeSourceInfo *ArgTInfo;
12052   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12053   if (ArgTy.isNull())
12054     return ExprError();
12055 
12056   if (!ArgTInfo)
12057     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12058 
12059   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12060 }
12061 
12062 
12063 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12064                                  Expr *CondExpr,
12065                                  Expr *LHSExpr, Expr *RHSExpr,
12066                                  SourceLocation RPLoc) {
12067   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12068 
12069   ExprValueKind VK = VK_RValue;
12070   ExprObjectKind OK = OK_Ordinary;
12071   QualType resType;
12072   bool ValueDependent = false;
12073   bool CondIsTrue = false;
12074   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12075     resType = Context.DependentTy;
12076     ValueDependent = true;
12077   } else {
12078     // The conditional expression is required to be a constant expression.
12079     llvm::APSInt condEval(32);
12080     ExprResult CondICE
12081       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12082           diag::err_typecheck_choose_expr_requires_constant, false);
12083     if (CondICE.isInvalid())
12084       return ExprError();
12085     CondExpr = CondICE.get();
12086     CondIsTrue = condEval.getZExtValue();
12087 
12088     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12089     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12090 
12091     resType = ActiveExpr->getType();
12092     ValueDependent = ActiveExpr->isValueDependent();
12093     VK = ActiveExpr->getValueKind();
12094     OK = ActiveExpr->getObjectKind();
12095   }
12096 
12097   return new (Context)
12098       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12099                  CondIsTrue, resType->isDependentType(), ValueDependent);
12100 }
12101 
12102 //===----------------------------------------------------------------------===//
12103 // Clang Extensions.
12104 //===----------------------------------------------------------------------===//
12105 
12106 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12107 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12108   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12109 
12110   if (LangOpts.CPlusPlus) {
12111     Decl *ManglingContextDecl;
12112     if (MangleNumberingContext *MCtx =
12113             getCurrentMangleNumberContext(Block->getDeclContext(),
12114                                           ManglingContextDecl)) {
12115       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12116       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12117     }
12118   }
12119 
12120   PushBlockScope(CurScope, Block);
12121   CurContext->addDecl(Block);
12122   if (CurScope)
12123     PushDeclContext(CurScope, Block);
12124   else
12125     CurContext = Block;
12126 
12127   getCurBlock()->HasImplicitReturnType = true;
12128 
12129   // Enter a new evaluation context to insulate the block from any
12130   // cleanups from the enclosing full-expression.
12131   PushExpressionEvaluationContext(PotentiallyEvaluated);
12132 }
12133 
12134 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12135                                Scope *CurScope) {
12136   assert(ParamInfo.getIdentifier() == nullptr &&
12137          "block-id should have no identifier!");
12138   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12139   BlockScopeInfo *CurBlock = getCurBlock();
12140 
12141   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12142   QualType T = Sig->getType();
12143 
12144   // FIXME: We should allow unexpanded parameter packs here, but that would,
12145   // in turn, make the block expression contain unexpanded parameter packs.
12146   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12147     // Drop the parameters.
12148     FunctionProtoType::ExtProtoInfo EPI;
12149     EPI.HasTrailingReturn = false;
12150     EPI.TypeQuals |= DeclSpec::TQ_const;
12151     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12152     Sig = Context.getTrivialTypeSourceInfo(T);
12153   }
12154 
12155   // GetTypeForDeclarator always produces a function type for a block
12156   // literal signature.  Furthermore, it is always a FunctionProtoType
12157   // unless the function was written with a typedef.
12158   assert(T->isFunctionType() &&
12159          "GetTypeForDeclarator made a non-function block signature");
12160 
12161   // Look for an explicit signature in that function type.
12162   FunctionProtoTypeLoc ExplicitSignature;
12163 
12164   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12165   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12166 
12167     // Check whether that explicit signature was synthesized by
12168     // GetTypeForDeclarator.  If so, don't save that as part of the
12169     // written signature.
12170     if (ExplicitSignature.getLocalRangeBegin() ==
12171         ExplicitSignature.getLocalRangeEnd()) {
12172       // This would be much cheaper if we stored TypeLocs instead of
12173       // TypeSourceInfos.
12174       TypeLoc Result = ExplicitSignature.getReturnLoc();
12175       unsigned Size = Result.getFullDataSize();
12176       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12177       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12178 
12179       ExplicitSignature = FunctionProtoTypeLoc();
12180     }
12181   }
12182 
12183   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12184   CurBlock->FunctionType = T;
12185 
12186   const FunctionType *Fn = T->getAs<FunctionType>();
12187   QualType RetTy = Fn->getReturnType();
12188   bool isVariadic =
12189     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12190 
12191   CurBlock->TheDecl->setIsVariadic(isVariadic);
12192 
12193   // Context.DependentTy is used as a placeholder for a missing block
12194   // return type.  TODO:  what should we do with declarators like:
12195   //   ^ * { ... }
12196   // If the answer is "apply template argument deduction"....
12197   if (RetTy != Context.DependentTy) {
12198     CurBlock->ReturnType = RetTy;
12199     CurBlock->TheDecl->setBlockMissingReturnType(false);
12200     CurBlock->HasImplicitReturnType = false;
12201   }
12202 
12203   // Push block parameters from the declarator if we had them.
12204   SmallVector<ParmVarDecl*, 8> Params;
12205   if (ExplicitSignature) {
12206     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12207       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12208       if (Param->getIdentifier() == nullptr &&
12209           !Param->isImplicit() &&
12210           !Param->isInvalidDecl() &&
12211           !getLangOpts().CPlusPlus)
12212         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12213       Params.push_back(Param);
12214     }
12215 
12216   // Fake up parameter variables if we have a typedef, like
12217   //   ^ fntype { ... }
12218   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12219     for (const auto &I : Fn->param_types()) {
12220       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12221           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12222       Params.push_back(Param);
12223     }
12224   }
12225 
12226   // Set the parameters on the block decl.
12227   if (!Params.empty()) {
12228     CurBlock->TheDecl->setParams(Params);
12229     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12230                              /*CheckParameterNames=*/false);
12231   }
12232 
12233   // Finally we can process decl attributes.
12234   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12235 
12236   // Put the parameter variables in scope.
12237   for (auto AI : CurBlock->TheDecl->parameters()) {
12238     AI->setOwningFunction(CurBlock->TheDecl);
12239 
12240     // If this has an identifier, add it to the scope stack.
12241     if (AI->getIdentifier()) {
12242       CheckShadow(CurBlock->TheScope, AI);
12243 
12244       PushOnScopeChains(AI, CurBlock->TheScope);
12245     }
12246   }
12247 }
12248 
12249 /// ActOnBlockError - If there is an error parsing a block, this callback
12250 /// is invoked to pop the information about the block from the action impl.
12251 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12252   // Leave the expression-evaluation context.
12253   DiscardCleanupsInEvaluationContext();
12254   PopExpressionEvaluationContext();
12255 
12256   // Pop off CurBlock, handle nested blocks.
12257   PopDeclContext();
12258   PopFunctionScopeInfo();
12259 }
12260 
12261 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12262 /// literal was successfully completed.  ^(int x){...}
12263 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12264                                     Stmt *Body, Scope *CurScope) {
12265   // If blocks are disabled, emit an error.
12266   if (!LangOpts.Blocks)
12267     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12268 
12269   // Leave the expression-evaluation context.
12270   if (hasAnyUnrecoverableErrorsInThisFunction())
12271     DiscardCleanupsInEvaluationContext();
12272   assert(!Cleanup.exprNeedsCleanups() &&
12273          "cleanups within block not correctly bound!");
12274   PopExpressionEvaluationContext();
12275 
12276   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12277 
12278   if (BSI->HasImplicitReturnType)
12279     deduceClosureReturnType(*BSI);
12280 
12281   PopDeclContext();
12282 
12283   QualType RetTy = Context.VoidTy;
12284   if (!BSI->ReturnType.isNull())
12285     RetTy = BSI->ReturnType;
12286 
12287   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12288   QualType BlockTy;
12289 
12290   // Set the captured variables on the block.
12291   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12292   SmallVector<BlockDecl::Capture, 4> Captures;
12293   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12294     if (Cap.isThisCapture())
12295       continue;
12296     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12297                               Cap.isNested(), Cap.getInitExpr());
12298     Captures.push_back(NewCap);
12299   }
12300   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12301 
12302   // If the user wrote a function type in some form, try to use that.
12303   if (!BSI->FunctionType.isNull()) {
12304     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12305 
12306     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12307     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12308 
12309     // Turn protoless block types into nullary block types.
12310     if (isa<FunctionNoProtoType>(FTy)) {
12311       FunctionProtoType::ExtProtoInfo EPI;
12312       EPI.ExtInfo = Ext;
12313       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12314 
12315     // Otherwise, if we don't need to change anything about the function type,
12316     // preserve its sugar structure.
12317     } else if (FTy->getReturnType() == RetTy &&
12318                (!NoReturn || FTy->getNoReturnAttr())) {
12319       BlockTy = BSI->FunctionType;
12320 
12321     // Otherwise, make the minimal modifications to the function type.
12322     } else {
12323       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12324       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12325       EPI.TypeQuals = 0; // FIXME: silently?
12326       EPI.ExtInfo = Ext;
12327       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12328     }
12329 
12330   // If we don't have a function type, just build one from nothing.
12331   } else {
12332     FunctionProtoType::ExtProtoInfo EPI;
12333     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12334     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12335   }
12336 
12337   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12338   BlockTy = Context.getBlockPointerType(BlockTy);
12339 
12340   // If needed, diagnose invalid gotos and switches in the block.
12341   if (getCurFunction()->NeedsScopeChecking() &&
12342       !PP.isCodeCompletionEnabled())
12343     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12344 
12345   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12346 
12347   // Try to apply the named return value optimization. We have to check again
12348   // if we can do this, though, because blocks keep return statements around
12349   // to deduce an implicit return type.
12350   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12351       !BSI->TheDecl->isDependentContext())
12352     computeNRVO(Body, BSI);
12353 
12354   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12355   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12356   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12357 
12358   // If the block isn't obviously global, i.e. it captures anything at
12359   // all, then we need to do a few things in the surrounding context:
12360   if (Result->getBlockDecl()->hasCaptures()) {
12361     // First, this expression has a new cleanup object.
12362     ExprCleanupObjects.push_back(Result->getBlockDecl());
12363     Cleanup.setExprNeedsCleanups(true);
12364 
12365     // It also gets a branch-protected scope if any of the captured
12366     // variables needs destruction.
12367     for (const auto &CI : Result->getBlockDecl()->captures()) {
12368       const VarDecl *var = CI.getVariable();
12369       if (var->getType().isDestructedType() != QualType::DK_none) {
12370         getCurFunction()->setHasBranchProtectedScope();
12371         break;
12372       }
12373     }
12374   }
12375 
12376   return Result;
12377 }
12378 
12379 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12380                             SourceLocation RPLoc) {
12381   TypeSourceInfo *TInfo;
12382   GetTypeFromParser(Ty, &TInfo);
12383   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12384 }
12385 
12386 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12387                                 Expr *E, TypeSourceInfo *TInfo,
12388                                 SourceLocation RPLoc) {
12389   Expr *OrigExpr = E;
12390   bool IsMS = false;
12391 
12392   // CUDA device code does not support varargs.
12393   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12394     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12395       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12396       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12397         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12398     }
12399   }
12400 
12401   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12402   // as Microsoft ABI on an actual Microsoft platform, where
12403   // __builtin_ms_va_list and __builtin_va_list are the same.)
12404   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12405       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12406     QualType MSVaListType = Context.getBuiltinMSVaListType();
12407     if (Context.hasSameType(MSVaListType, E->getType())) {
12408       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12409         return ExprError();
12410       IsMS = true;
12411     }
12412   }
12413 
12414   // Get the va_list type
12415   QualType VaListType = Context.getBuiltinVaListType();
12416   if (!IsMS) {
12417     if (VaListType->isArrayType()) {
12418       // Deal with implicit array decay; for example, on x86-64,
12419       // va_list is an array, but it's supposed to decay to
12420       // a pointer for va_arg.
12421       VaListType = Context.getArrayDecayedType(VaListType);
12422       // Make sure the input expression also decays appropriately.
12423       ExprResult Result = UsualUnaryConversions(E);
12424       if (Result.isInvalid())
12425         return ExprError();
12426       E = Result.get();
12427     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12428       // If va_list is a record type and we are compiling in C++ mode,
12429       // check the argument using reference binding.
12430       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12431           Context, Context.getLValueReferenceType(VaListType), false);
12432       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12433       if (Init.isInvalid())
12434         return ExprError();
12435       E = Init.getAs<Expr>();
12436     } else {
12437       // Otherwise, the va_list argument must be an l-value because
12438       // it is modified by va_arg.
12439       if (!E->isTypeDependent() &&
12440           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12441         return ExprError();
12442     }
12443   }
12444 
12445   if (!IsMS && !E->isTypeDependent() &&
12446       !Context.hasSameType(VaListType, E->getType()))
12447     return ExprError(Diag(E->getLocStart(),
12448                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12449       << OrigExpr->getType() << E->getSourceRange());
12450 
12451   if (!TInfo->getType()->isDependentType()) {
12452     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12453                             diag::err_second_parameter_to_va_arg_incomplete,
12454                             TInfo->getTypeLoc()))
12455       return ExprError();
12456 
12457     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12458                                TInfo->getType(),
12459                                diag::err_second_parameter_to_va_arg_abstract,
12460                                TInfo->getTypeLoc()))
12461       return ExprError();
12462 
12463     if (!TInfo->getType().isPODType(Context)) {
12464       Diag(TInfo->getTypeLoc().getBeginLoc(),
12465            TInfo->getType()->isObjCLifetimeType()
12466              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12467              : diag::warn_second_parameter_to_va_arg_not_pod)
12468         << TInfo->getType()
12469         << TInfo->getTypeLoc().getSourceRange();
12470     }
12471 
12472     // Check for va_arg where arguments of the given type will be promoted
12473     // (i.e. this va_arg is guaranteed to have undefined behavior).
12474     QualType PromoteType;
12475     if (TInfo->getType()->isPromotableIntegerType()) {
12476       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12477       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12478         PromoteType = QualType();
12479     }
12480     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12481       PromoteType = Context.DoubleTy;
12482     if (!PromoteType.isNull())
12483       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12484                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12485                           << TInfo->getType()
12486                           << PromoteType
12487                           << TInfo->getTypeLoc().getSourceRange());
12488   }
12489 
12490   QualType T = TInfo->getType().getNonLValueExprType(Context);
12491   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12492 }
12493 
12494 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12495   // The type of __null will be int or long, depending on the size of
12496   // pointers on the target.
12497   QualType Ty;
12498   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12499   if (pw == Context.getTargetInfo().getIntWidth())
12500     Ty = Context.IntTy;
12501   else if (pw == Context.getTargetInfo().getLongWidth())
12502     Ty = Context.LongTy;
12503   else if (pw == Context.getTargetInfo().getLongLongWidth())
12504     Ty = Context.LongLongTy;
12505   else {
12506     llvm_unreachable("I don't know size of pointer!");
12507   }
12508 
12509   return new (Context) GNUNullExpr(Ty, TokenLoc);
12510 }
12511 
12512 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12513                                               bool Diagnose) {
12514   if (!getLangOpts().ObjC1)
12515     return false;
12516 
12517   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12518   if (!PT)
12519     return false;
12520 
12521   if (!PT->isObjCIdType()) {
12522     // Check if the destination is the 'NSString' interface.
12523     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12524     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12525       return false;
12526   }
12527 
12528   // Ignore any parens, implicit casts (should only be
12529   // array-to-pointer decays), and not-so-opaque values.  The last is
12530   // important for making this trigger for property assignments.
12531   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12532   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12533     if (OV->getSourceExpr())
12534       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12535 
12536   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12537   if (!SL || !SL->isAscii())
12538     return false;
12539   if (Diagnose) {
12540     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12541       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12542     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12543   }
12544   return true;
12545 }
12546 
12547 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12548                                               const Expr *SrcExpr) {
12549   if (!DstType->isFunctionPointerType() ||
12550       !SrcExpr->getType()->isFunctionType())
12551     return false;
12552 
12553   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12554   if (!DRE)
12555     return false;
12556 
12557   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12558   if (!FD)
12559     return false;
12560 
12561   return !S.checkAddressOfFunctionIsAvailable(FD,
12562                                               /*Complain=*/true,
12563                                               SrcExpr->getLocStart());
12564 }
12565 
12566 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12567                                     SourceLocation Loc,
12568                                     QualType DstType, QualType SrcType,
12569                                     Expr *SrcExpr, AssignmentAction Action,
12570                                     bool *Complained) {
12571   if (Complained)
12572     *Complained = false;
12573 
12574   // Decode the result (notice that AST's are still created for extensions).
12575   bool CheckInferredResultType = false;
12576   bool isInvalid = false;
12577   unsigned DiagKind = 0;
12578   FixItHint Hint;
12579   ConversionFixItGenerator ConvHints;
12580   bool MayHaveConvFixit = false;
12581   bool MayHaveFunctionDiff = false;
12582   const ObjCInterfaceDecl *IFace = nullptr;
12583   const ObjCProtocolDecl *PDecl = nullptr;
12584 
12585   switch (ConvTy) {
12586   case Compatible:
12587       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12588       return false;
12589 
12590   case PointerToInt:
12591     DiagKind = diag::ext_typecheck_convert_pointer_int;
12592     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12593     MayHaveConvFixit = true;
12594     break;
12595   case IntToPointer:
12596     DiagKind = diag::ext_typecheck_convert_int_pointer;
12597     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12598     MayHaveConvFixit = true;
12599     break;
12600   case IncompatiblePointer:
12601     if (Action == AA_Passing_CFAudited)
12602       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12603     else if (SrcType->isFunctionPointerType() &&
12604              DstType->isFunctionPointerType())
12605       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12606     else
12607       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12608 
12609     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12610       SrcType->isObjCObjectPointerType();
12611     if (Hint.isNull() && !CheckInferredResultType) {
12612       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12613     }
12614     else if (CheckInferredResultType) {
12615       SrcType = SrcType.getUnqualifiedType();
12616       DstType = DstType.getUnqualifiedType();
12617     }
12618     MayHaveConvFixit = true;
12619     break;
12620   case IncompatiblePointerSign:
12621     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12622     break;
12623   case FunctionVoidPointer:
12624     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12625     break;
12626   case IncompatiblePointerDiscardsQualifiers: {
12627     // Perform array-to-pointer decay if necessary.
12628     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12629 
12630     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12631     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12632     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12633       DiagKind = diag::err_typecheck_incompatible_address_space;
12634       break;
12635 
12636 
12637     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12638       DiagKind = diag::err_typecheck_incompatible_ownership;
12639       break;
12640     }
12641 
12642     llvm_unreachable("unknown error case for discarding qualifiers!");
12643     // fallthrough
12644   }
12645   case CompatiblePointerDiscardsQualifiers:
12646     // If the qualifiers lost were because we were applying the
12647     // (deprecated) C++ conversion from a string literal to a char*
12648     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12649     // Ideally, this check would be performed in
12650     // checkPointerTypesForAssignment. However, that would require a
12651     // bit of refactoring (so that the second argument is an
12652     // expression, rather than a type), which should be done as part
12653     // of a larger effort to fix checkPointerTypesForAssignment for
12654     // C++ semantics.
12655     if (getLangOpts().CPlusPlus &&
12656         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12657       return false;
12658     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12659     break;
12660   case IncompatibleNestedPointerQualifiers:
12661     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12662     break;
12663   case IntToBlockPointer:
12664     DiagKind = diag::err_int_to_block_pointer;
12665     break;
12666   case IncompatibleBlockPointer:
12667     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12668     break;
12669   case IncompatibleObjCQualifiedId: {
12670     if (SrcType->isObjCQualifiedIdType()) {
12671       const ObjCObjectPointerType *srcOPT =
12672                 SrcType->getAs<ObjCObjectPointerType>();
12673       for (auto *srcProto : srcOPT->quals()) {
12674         PDecl = srcProto;
12675         break;
12676       }
12677       if (const ObjCInterfaceType *IFaceT =
12678             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12679         IFace = IFaceT->getDecl();
12680     }
12681     else if (DstType->isObjCQualifiedIdType()) {
12682       const ObjCObjectPointerType *dstOPT =
12683         DstType->getAs<ObjCObjectPointerType>();
12684       for (auto *dstProto : dstOPT->quals()) {
12685         PDecl = dstProto;
12686         break;
12687       }
12688       if (const ObjCInterfaceType *IFaceT =
12689             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12690         IFace = IFaceT->getDecl();
12691     }
12692     DiagKind = diag::warn_incompatible_qualified_id;
12693     break;
12694   }
12695   case IncompatibleVectors:
12696     DiagKind = diag::warn_incompatible_vectors;
12697     break;
12698   case IncompatibleObjCWeakRef:
12699     DiagKind = diag::err_arc_weak_unavailable_assign;
12700     break;
12701   case Incompatible:
12702     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12703       if (Complained)
12704         *Complained = true;
12705       return true;
12706     }
12707 
12708     DiagKind = diag::err_typecheck_convert_incompatible;
12709     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12710     MayHaveConvFixit = true;
12711     isInvalid = true;
12712     MayHaveFunctionDiff = true;
12713     break;
12714   }
12715 
12716   QualType FirstType, SecondType;
12717   switch (Action) {
12718   case AA_Assigning:
12719   case AA_Initializing:
12720     // The destination type comes first.
12721     FirstType = DstType;
12722     SecondType = SrcType;
12723     break;
12724 
12725   case AA_Returning:
12726   case AA_Passing:
12727   case AA_Passing_CFAudited:
12728   case AA_Converting:
12729   case AA_Sending:
12730   case AA_Casting:
12731     // The source type comes first.
12732     FirstType = SrcType;
12733     SecondType = DstType;
12734     break;
12735   }
12736 
12737   PartialDiagnostic FDiag = PDiag(DiagKind);
12738   if (Action == AA_Passing_CFAudited)
12739     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12740   else
12741     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12742 
12743   // If we can fix the conversion, suggest the FixIts.
12744   assert(ConvHints.isNull() || Hint.isNull());
12745   if (!ConvHints.isNull()) {
12746     for (FixItHint &H : ConvHints.Hints)
12747       FDiag << H;
12748   } else {
12749     FDiag << Hint;
12750   }
12751   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12752 
12753   if (MayHaveFunctionDiff)
12754     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12755 
12756   Diag(Loc, FDiag);
12757   if (DiagKind == diag::warn_incompatible_qualified_id &&
12758       PDecl && IFace && !IFace->hasDefinition())
12759       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12760         << IFace->getName() << PDecl->getName();
12761 
12762   if (SecondType == Context.OverloadTy)
12763     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12764                               FirstType, /*TakingAddress=*/true);
12765 
12766   if (CheckInferredResultType)
12767     EmitRelatedResultTypeNote(SrcExpr);
12768 
12769   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12770     EmitRelatedResultTypeNoteForReturn(DstType);
12771 
12772   if (Complained)
12773     *Complained = true;
12774   return isInvalid;
12775 }
12776 
12777 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12778                                                  llvm::APSInt *Result) {
12779   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12780   public:
12781     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12782       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12783     }
12784   } Diagnoser;
12785 
12786   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12787 }
12788 
12789 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12790                                                  llvm::APSInt *Result,
12791                                                  unsigned DiagID,
12792                                                  bool AllowFold) {
12793   class IDDiagnoser : public VerifyICEDiagnoser {
12794     unsigned DiagID;
12795 
12796   public:
12797     IDDiagnoser(unsigned DiagID)
12798       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12799 
12800     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12801       S.Diag(Loc, DiagID) << SR;
12802     }
12803   } Diagnoser(DiagID);
12804 
12805   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12806 }
12807 
12808 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12809                                             SourceRange SR) {
12810   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12811 }
12812 
12813 ExprResult
12814 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12815                                       VerifyICEDiagnoser &Diagnoser,
12816                                       bool AllowFold) {
12817   SourceLocation DiagLoc = E->getLocStart();
12818 
12819   if (getLangOpts().CPlusPlus11) {
12820     // C++11 [expr.const]p5:
12821     //   If an expression of literal class type is used in a context where an
12822     //   integral constant expression is required, then that class type shall
12823     //   have a single non-explicit conversion function to an integral or
12824     //   unscoped enumeration type
12825     ExprResult Converted;
12826     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12827     public:
12828       CXX11ConvertDiagnoser(bool Silent)
12829           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12830                                 Silent, true) {}
12831 
12832       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12833                                            QualType T) override {
12834         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12835       }
12836 
12837       SemaDiagnosticBuilder diagnoseIncomplete(
12838           Sema &S, SourceLocation Loc, QualType T) override {
12839         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12840       }
12841 
12842       SemaDiagnosticBuilder diagnoseExplicitConv(
12843           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12844         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12845       }
12846 
12847       SemaDiagnosticBuilder noteExplicitConv(
12848           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12849         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12850                  << ConvTy->isEnumeralType() << ConvTy;
12851       }
12852 
12853       SemaDiagnosticBuilder diagnoseAmbiguous(
12854           Sema &S, SourceLocation Loc, QualType T) override {
12855         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12856       }
12857 
12858       SemaDiagnosticBuilder noteAmbiguous(
12859           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12860         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12861                  << ConvTy->isEnumeralType() << ConvTy;
12862       }
12863 
12864       SemaDiagnosticBuilder diagnoseConversion(
12865           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12866         llvm_unreachable("conversion functions are permitted");
12867       }
12868     } ConvertDiagnoser(Diagnoser.Suppress);
12869 
12870     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12871                                                     ConvertDiagnoser);
12872     if (Converted.isInvalid())
12873       return Converted;
12874     E = Converted.get();
12875     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12876       return ExprError();
12877   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12878     // An ICE must be of integral or unscoped enumeration type.
12879     if (!Diagnoser.Suppress)
12880       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12881     return ExprError();
12882   }
12883 
12884   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12885   // in the non-ICE case.
12886   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12887     if (Result)
12888       *Result = E->EvaluateKnownConstInt(Context);
12889     return E;
12890   }
12891 
12892   Expr::EvalResult EvalResult;
12893   SmallVector<PartialDiagnosticAt, 8> Notes;
12894   EvalResult.Diag = &Notes;
12895 
12896   // Try to evaluate the expression, and produce diagnostics explaining why it's
12897   // not a constant expression as a side-effect.
12898   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12899                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12900 
12901   // In C++11, we can rely on diagnostics being produced for any expression
12902   // which is not a constant expression. If no diagnostics were produced, then
12903   // this is a constant expression.
12904   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12905     if (Result)
12906       *Result = EvalResult.Val.getInt();
12907     return E;
12908   }
12909 
12910   // If our only note is the usual "invalid subexpression" note, just point
12911   // the caret at its location rather than producing an essentially
12912   // redundant note.
12913   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12914         diag::note_invalid_subexpr_in_const_expr) {
12915     DiagLoc = Notes[0].first;
12916     Notes.clear();
12917   }
12918 
12919   if (!Folded || !AllowFold) {
12920     if (!Diagnoser.Suppress) {
12921       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12922       for (const PartialDiagnosticAt &Note : Notes)
12923         Diag(Note.first, Note.second);
12924     }
12925 
12926     return ExprError();
12927   }
12928 
12929   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12930   for (const PartialDiagnosticAt &Note : Notes)
12931     Diag(Note.first, Note.second);
12932 
12933   if (Result)
12934     *Result = EvalResult.Val.getInt();
12935   return E;
12936 }
12937 
12938 namespace {
12939   // Handle the case where we conclude a expression which we speculatively
12940   // considered to be unevaluated is actually evaluated.
12941   class TransformToPE : public TreeTransform<TransformToPE> {
12942     typedef TreeTransform<TransformToPE> BaseTransform;
12943 
12944   public:
12945     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12946 
12947     // Make sure we redo semantic analysis
12948     bool AlwaysRebuild() { return true; }
12949 
12950     // Make sure we handle LabelStmts correctly.
12951     // FIXME: This does the right thing, but maybe we need a more general
12952     // fix to TreeTransform?
12953     StmtResult TransformLabelStmt(LabelStmt *S) {
12954       S->getDecl()->setStmt(nullptr);
12955       return BaseTransform::TransformLabelStmt(S);
12956     }
12957 
12958     // We need to special-case DeclRefExprs referring to FieldDecls which
12959     // are not part of a member pointer formation; normal TreeTransforming
12960     // doesn't catch this case because of the way we represent them in the AST.
12961     // FIXME: This is a bit ugly; is it really the best way to handle this
12962     // case?
12963     //
12964     // Error on DeclRefExprs referring to FieldDecls.
12965     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12966       if (isa<FieldDecl>(E->getDecl()) &&
12967           !SemaRef.isUnevaluatedContext())
12968         return SemaRef.Diag(E->getLocation(),
12969                             diag::err_invalid_non_static_member_use)
12970             << E->getDecl() << E->getSourceRange();
12971 
12972       return BaseTransform::TransformDeclRefExpr(E);
12973     }
12974 
12975     // Exception: filter out member pointer formation
12976     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12977       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12978         return E;
12979 
12980       return BaseTransform::TransformUnaryOperator(E);
12981     }
12982 
12983     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12984       // Lambdas never need to be transformed.
12985       return E;
12986     }
12987   };
12988 }
12989 
12990 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12991   assert(isUnevaluatedContext() &&
12992          "Should only transform unevaluated expressions");
12993   ExprEvalContexts.back().Context =
12994       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12995   if (isUnevaluatedContext())
12996     return E;
12997   return TransformToPE(*this).TransformExpr(E);
12998 }
12999 
13000 void
13001 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13002                                       Decl *LambdaContextDecl,
13003                                       bool IsDecltype) {
13004   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13005                                 LambdaContextDecl, IsDecltype);
13006   Cleanup.reset();
13007   if (!MaybeODRUseExprs.empty())
13008     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13009 }
13010 
13011 void
13012 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13013                                       ReuseLambdaContextDecl_t,
13014                                       bool IsDecltype) {
13015   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13016   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13017 }
13018 
13019 void Sema::PopExpressionEvaluationContext() {
13020   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13021   unsigned NumTypos = Rec.NumTypos;
13022 
13023   if (!Rec.Lambdas.empty()) {
13024     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13025       unsigned D;
13026       if (Rec.isUnevaluated()) {
13027         // C++11 [expr.prim.lambda]p2:
13028         //   A lambda-expression shall not appear in an unevaluated operand
13029         //   (Clause 5).
13030         D = diag::err_lambda_unevaluated_operand;
13031       } else {
13032         // C++1y [expr.const]p2:
13033         //   A conditional-expression e is a core constant expression unless the
13034         //   evaluation of e, following the rules of the abstract machine, would
13035         //   evaluate [...] a lambda-expression.
13036         D = diag::err_lambda_in_constant_expression;
13037       }
13038       for (const auto *L : Rec.Lambdas)
13039         Diag(L->getLocStart(), D);
13040     } else {
13041       // Mark the capture expressions odr-used. This was deferred
13042       // during lambda expression creation.
13043       for (auto *Lambda : Rec.Lambdas) {
13044         for (auto *C : Lambda->capture_inits())
13045           MarkDeclarationsReferencedInExpr(C);
13046       }
13047     }
13048   }
13049 
13050   // When are coming out of an unevaluated context, clear out any
13051   // temporaries that we may have created as part of the evaluation of
13052   // the expression in that context: they aren't relevant because they
13053   // will never be constructed.
13054   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13055     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13056                              ExprCleanupObjects.end());
13057     Cleanup = Rec.ParentCleanup;
13058     CleanupVarDeclMarking();
13059     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13060   // Otherwise, merge the contexts together.
13061   } else {
13062     Cleanup.mergeFrom(Rec.ParentCleanup);
13063     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13064                             Rec.SavedMaybeODRUseExprs.end());
13065   }
13066 
13067   // Pop the current expression evaluation context off the stack.
13068   ExprEvalContexts.pop_back();
13069 
13070   if (!ExprEvalContexts.empty())
13071     ExprEvalContexts.back().NumTypos += NumTypos;
13072   else
13073     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13074                             "last ExpressionEvaluationContextRecord");
13075 }
13076 
13077 void Sema::DiscardCleanupsInEvaluationContext() {
13078   ExprCleanupObjects.erase(
13079          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13080          ExprCleanupObjects.end());
13081   Cleanup.reset();
13082   MaybeODRUseExprs.clear();
13083 }
13084 
13085 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13086   if (!E->getType()->isVariablyModifiedType())
13087     return E;
13088   return TransformToPotentiallyEvaluated(E);
13089 }
13090 
13091 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
13092   // Do not mark anything as "used" within a dependent context; wait for
13093   // an instantiation.
13094   if (SemaRef.CurContext->isDependentContext())
13095     return false;
13096 
13097   switch (SemaRef.ExprEvalContexts.back().Context) {
13098     case Sema::Unevaluated:
13099     case Sema::UnevaluatedAbstract:
13100       // We are in an expression that is not potentially evaluated; do nothing.
13101       // (Depending on how you read the standard, we actually do need to do
13102       // something here for null pointer constants, but the standard's
13103       // definition of a null pointer constant is completely crazy.)
13104       return false;
13105 
13106     case Sema::DiscardedStatement:
13107       // These are technically a potentially evaluated but they have the effect
13108       // of suppressing use marking.
13109       return false;
13110 
13111     case Sema::ConstantEvaluated:
13112     case Sema::PotentiallyEvaluated:
13113       // We are in a potentially evaluated expression (or a constant-expression
13114       // in C++03); we need to do implicit template instantiation, implicitly
13115       // define class members, and mark most declarations as used.
13116       return true;
13117 
13118     case Sema::PotentiallyEvaluatedIfUsed:
13119       // Referenced declarations will only be used if the construct in the
13120       // containing expression is used.
13121       return false;
13122   }
13123   llvm_unreachable("Invalid context");
13124 }
13125 
13126 /// \brief Mark a function referenced, and check whether it is odr-used
13127 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13128 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13129                                   bool MightBeOdrUse) {
13130   assert(Func && "No function?");
13131 
13132   Func->setReferenced();
13133 
13134   // C++11 [basic.def.odr]p3:
13135   //   A function whose name appears as a potentially-evaluated expression is
13136   //   odr-used if it is the unique lookup result or the selected member of a
13137   //   set of overloaded functions [...].
13138   //
13139   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13140   // can just check that here.
13141   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13142 
13143   // Determine whether we require a function definition to exist, per
13144   // C++11 [temp.inst]p3:
13145   //   Unless a function template specialization has been explicitly
13146   //   instantiated or explicitly specialized, the function template
13147   //   specialization is implicitly instantiated when the specialization is
13148   //   referenced in a context that requires a function definition to exist.
13149   //
13150   // We consider constexpr function templates to be referenced in a context
13151   // that requires a definition to exist whenever they are referenced.
13152   //
13153   // FIXME: This instantiates constexpr functions too frequently. If this is
13154   // really an unevaluated context (and we're not just in the definition of a
13155   // function template or overload resolution or other cases which we
13156   // incorrectly consider to be unevaluated contexts), and we're not in a
13157   // subexpression which we actually need to evaluate (for instance, a
13158   // template argument, array bound or an expression in a braced-init-list),
13159   // we are not permitted to instantiate this constexpr function definition.
13160   //
13161   // FIXME: This also implicitly defines special members too frequently. They
13162   // are only supposed to be implicitly defined if they are odr-used, but they
13163   // are not odr-used from constant expressions in unevaluated contexts.
13164   // However, they cannot be referenced if they are deleted, and they are
13165   // deleted whenever the implicit definition of the special member would
13166   // fail (with very few exceptions).
13167   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13168   bool NeedDefinition =
13169       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13170                                          (MD && !MD->isUserProvided())));
13171 
13172   // C++14 [temp.expl.spec]p6:
13173   //   If a template [...] is explicitly specialized then that specialization
13174   //   shall be declared before the first use of that specialization that would
13175   //   cause an implicit instantiation to take place, in every translation unit
13176   //   in which such a use occurs
13177   if (NeedDefinition &&
13178       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13179        Func->getMemberSpecializationInfo()))
13180     checkSpecializationVisibility(Loc, Func);
13181 
13182   // C++14 [except.spec]p17:
13183   //   An exception-specification is considered to be needed when:
13184   //   - the function is odr-used or, if it appears in an unevaluated operand,
13185   //     would be odr-used if the expression were potentially-evaluated;
13186   //
13187   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13188   // function is a pure virtual function we're calling, and in that case the
13189   // function was selected by overload resolution and we need to resolve its
13190   // exception specification for a different reason.
13191   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13192   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13193     ResolveExceptionSpec(Loc, FPT);
13194 
13195   // If we don't need to mark the function as used, and we don't need to
13196   // try to provide a definition, there's nothing more to do.
13197   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13198       (!NeedDefinition || Func->getBody()))
13199     return;
13200 
13201   // Note that this declaration has been used.
13202   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13203     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13204     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13205       if (Constructor->isDefaultConstructor()) {
13206         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13207           return;
13208         DefineImplicitDefaultConstructor(Loc, Constructor);
13209       } else if (Constructor->isCopyConstructor()) {
13210         DefineImplicitCopyConstructor(Loc, Constructor);
13211       } else if (Constructor->isMoveConstructor()) {
13212         DefineImplicitMoveConstructor(Loc, Constructor);
13213       }
13214     } else if (Constructor->getInheritedConstructor()) {
13215       DefineInheritingConstructor(Loc, Constructor);
13216     }
13217   } else if (CXXDestructorDecl *Destructor =
13218                  dyn_cast<CXXDestructorDecl>(Func)) {
13219     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13220     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13221       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13222         return;
13223       DefineImplicitDestructor(Loc, Destructor);
13224     }
13225     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13226       MarkVTableUsed(Loc, Destructor->getParent());
13227   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13228     if (MethodDecl->isOverloadedOperator() &&
13229         MethodDecl->getOverloadedOperator() == OO_Equal) {
13230       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13231       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13232         if (MethodDecl->isCopyAssignmentOperator())
13233           DefineImplicitCopyAssignment(Loc, MethodDecl);
13234         else if (MethodDecl->isMoveAssignmentOperator())
13235           DefineImplicitMoveAssignment(Loc, MethodDecl);
13236       }
13237     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13238                MethodDecl->getParent()->isLambda()) {
13239       CXXConversionDecl *Conversion =
13240           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13241       if (Conversion->isLambdaToBlockPointerConversion())
13242         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13243       else
13244         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13245     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13246       MarkVTableUsed(Loc, MethodDecl->getParent());
13247   }
13248 
13249   // Recursive functions should be marked when used from another function.
13250   // FIXME: Is this really right?
13251   if (CurContext == Func) return;
13252 
13253   // Implicit instantiation of function templates and member functions of
13254   // class templates.
13255   if (Func->isImplicitlyInstantiable()) {
13256     bool AlreadyInstantiated = false;
13257     SourceLocation PointOfInstantiation = Loc;
13258     if (FunctionTemplateSpecializationInfo *SpecInfo
13259                               = Func->getTemplateSpecializationInfo()) {
13260       if (SpecInfo->getPointOfInstantiation().isInvalid())
13261         SpecInfo->setPointOfInstantiation(Loc);
13262       else if (SpecInfo->getTemplateSpecializationKind()
13263                  == TSK_ImplicitInstantiation) {
13264         AlreadyInstantiated = true;
13265         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13266       }
13267     } else if (MemberSpecializationInfo *MSInfo
13268                                 = Func->getMemberSpecializationInfo()) {
13269       if (MSInfo->getPointOfInstantiation().isInvalid())
13270         MSInfo->setPointOfInstantiation(Loc);
13271       else if (MSInfo->getTemplateSpecializationKind()
13272                  == TSK_ImplicitInstantiation) {
13273         AlreadyInstantiated = true;
13274         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13275       }
13276     }
13277 
13278     if (!AlreadyInstantiated || Func->isConstexpr()) {
13279       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13280           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13281           ActiveTemplateInstantiations.size())
13282         PendingLocalImplicitInstantiations.push_back(
13283             std::make_pair(Func, PointOfInstantiation));
13284       else if (Func->isConstexpr())
13285         // Do not defer instantiations of constexpr functions, to avoid the
13286         // expression evaluator needing to call back into Sema if it sees a
13287         // call to such a function.
13288         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13289       else {
13290         PendingInstantiations.push_back(std::make_pair(Func,
13291                                                        PointOfInstantiation));
13292         // Notify the consumer that a function was implicitly instantiated.
13293         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13294       }
13295     }
13296   } else {
13297     // Walk redefinitions, as some of them may be instantiable.
13298     for (auto i : Func->redecls()) {
13299       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13300         MarkFunctionReferenced(Loc, i, OdrUse);
13301     }
13302   }
13303 
13304   if (!OdrUse) return;
13305 
13306   // Keep track of used but undefined functions.
13307   if (!Func->isDefined()) {
13308     if (mightHaveNonExternalLinkage(Func))
13309       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13310     else if (Func->getMostRecentDecl()->isInlined() &&
13311              !LangOpts.GNUInline &&
13312              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13313       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13314   }
13315 
13316   Func->markUsed(Context);
13317 }
13318 
13319 static void
13320 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13321                                    ValueDecl *var, DeclContext *DC) {
13322   DeclContext *VarDC = var->getDeclContext();
13323 
13324   //  If the parameter still belongs to the translation unit, then
13325   //  we're actually just using one parameter in the declaration of
13326   //  the next.
13327   if (isa<ParmVarDecl>(var) &&
13328       isa<TranslationUnitDecl>(VarDC))
13329     return;
13330 
13331   // For C code, don't diagnose about capture if we're not actually in code
13332   // right now; it's impossible to write a non-constant expression outside of
13333   // function context, so we'll get other (more useful) diagnostics later.
13334   //
13335   // For C++, things get a bit more nasty... it would be nice to suppress this
13336   // diagnostic for certain cases like using a local variable in an array bound
13337   // for a member of a local class, but the correct predicate is not obvious.
13338   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13339     return;
13340 
13341   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13342   unsigned ContextKind = 3; // unknown
13343   if (isa<CXXMethodDecl>(VarDC) &&
13344       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13345     ContextKind = 2;
13346   } else if (isa<FunctionDecl>(VarDC)) {
13347     ContextKind = 0;
13348   } else if (isa<BlockDecl>(VarDC)) {
13349     ContextKind = 1;
13350   }
13351 
13352   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13353     << var << ValueKind << ContextKind << VarDC;
13354   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13355       << var;
13356 
13357   // FIXME: Add additional diagnostic info about class etc. which prevents
13358   // capture.
13359 }
13360 
13361 
13362 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13363                                       bool &SubCapturesAreNested,
13364                                       QualType &CaptureType,
13365                                       QualType &DeclRefType) {
13366    // Check whether we've already captured it.
13367   if (CSI->CaptureMap.count(Var)) {
13368     // If we found a capture, any subcaptures are nested.
13369     SubCapturesAreNested = true;
13370 
13371     // Retrieve the capture type for this variable.
13372     CaptureType = CSI->getCapture(Var).getCaptureType();
13373 
13374     // Compute the type of an expression that refers to this variable.
13375     DeclRefType = CaptureType.getNonReferenceType();
13376 
13377     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13378     // are mutable in the sense that user can change their value - they are
13379     // private instances of the captured declarations.
13380     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13381     if (Cap.isCopyCapture() &&
13382         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13383         !(isa<CapturedRegionScopeInfo>(CSI) &&
13384           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13385       DeclRefType.addConst();
13386     return true;
13387   }
13388   return false;
13389 }
13390 
13391 // Only block literals, captured statements, and lambda expressions can
13392 // capture; other scopes don't work.
13393 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13394                                  SourceLocation Loc,
13395                                  const bool Diagnose, Sema &S) {
13396   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13397     return getLambdaAwareParentOfDeclContext(DC);
13398   else if (Var->hasLocalStorage()) {
13399     if (Diagnose)
13400        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13401   }
13402   return nullptr;
13403 }
13404 
13405 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13406 // certain types of variables (unnamed, variably modified types etc.)
13407 // so check for eligibility.
13408 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13409                                  SourceLocation Loc,
13410                                  const bool Diagnose, Sema &S) {
13411 
13412   bool IsBlock = isa<BlockScopeInfo>(CSI);
13413   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13414 
13415   // Lambdas are not allowed to capture unnamed variables
13416   // (e.g. anonymous unions).
13417   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13418   // assuming that's the intent.
13419   if (IsLambda && !Var->getDeclName()) {
13420     if (Diagnose) {
13421       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13422       S.Diag(Var->getLocation(), diag::note_declared_at);
13423     }
13424     return false;
13425   }
13426 
13427   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13428   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13429     if (Diagnose) {
13430       S.Diag(Loc, diag::err_ref_vm_type);
13431       S.Diag(Var->getLocation(), diag::note_previous_decl)
13432         << Var->getDeclName();
13433     }
13434     return false;
13435   }
13436   // Prohibit structs with flexible array members too.
13437   // We cannot capture what is in the tail end of the struct.
13438   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13439     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13440       if (Diagnose) {
13441         if (IsBlock)
13442           S.Diag(Loc, diag::err_ref_flexarray_type);
13443         else
13444           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13445             << Var->getDeclName();
13446         S.Diag(Var->getLocation(), diag::note_previous_decl)
13447           << Var->getDeclName();
13448       }
13449       return false;
13450     }
13451   }
13452   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13453   // Lambdas and captured statements are not allowed to capture __block
13454   // variables; they don't support the expected semantics.
13455   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13456     if (Diagnose) {
13457       S.Diag(Loc, diag::err_capture_block_variable)
13458         << Var->getDeclName() << !IsLambda;
13459       S.Diag(Var->getLocation(), diag::note_previous_decl)
13460         << Var->getDeclName();
13461     }
13462     return false;
13463   }
13464 
13465   return true;
13466 }
13467 
13468 // Returns true if the capture by block was successful.
13469 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13470                                  SourceLocation Loc,
13471                                  const bool BuildAndDiagnose,
13472                                  QualType &CaptureType,
13473                                  QualType &DeclRefType,
13474                                  const bool Nested,
13475                                  Sema &S) {
13476   Expr *CopyExpr = nullptr;
13477   bool ByRef = false;
13478 
13479   // Blocks are not allowed to capture arrays.
13480   if (CaptureType->isArrayType()) {
13481     if (BuildAndDiagnose) {
13482       S.Diag(Loc, diag::err_ref_array_type);
13483       S.Diag(Var->getLocation(), diag::note_previous_decl)
13484       << Var->getDeclName();
13485     }
13486     return false;
13487   }
13488 
13489   // Forbid the block-capture of autoreleasing variables.
13490   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13491     if (BuildAndDiagnose) {
13492       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13493         << /*block*/ 0;
13494       S.Diag(Var->getLocation(), diag::note_previous_decl)
13495         << Var->getDeclName();
13496     }
13497     return false;
13498   }
13499 
13500   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13501   if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13502     QualType PointeeTy = PT->getPointeeType();
13503     if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13504         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13505         !isa<AttributedType>(PointeeTy)) {
13506       if (BuildAndDiagnose) {
13507         SourceLocation VarLoc = Var->getLocation();
13508         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13509         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13510             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13511         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13512       }
13513     }
13514   }
13515 
13516   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13517   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13518       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13519     // Block capture by reference does not change the capture or
13520     // declaration reference types.
13521     ByRef = true;
13522   } else {
13523     // Block capture by copy introduces 'const'.
13524     CaptureType = CaptureType.getNonReferenceType().withConst();
13525     DeclRefType = CaptureType;
13526 
13527     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13528       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13529         // The capture logic needs the destructor, so make sure we mark it.
13530         // Usually this is unnecessary because most local variables have
13531         // their destructors marked at declaration time, but parameters are
13532         // an exception because it's technically only the call site that
13533         // actually requires the destructor.
13534         if (isa<ParmVarDecl>(Var))
13535           S.FinalizeVarWithDestructor(Var, Record);
13536 
13537         // Enter a new evaluation context to insulate the copy
13538         // full-expression.
13539         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13540 
13541         // According to the blocks spec, the capture of a variable from
13542         // the stack requires a const copy constructor.  This is not true
13543         // of the copy/move done to move a __block variable to the heap.
13544         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13545                                                   DeclRefType.withConst(),
13546                                                   VK_LValue, Loc);
13547 
13548         ExprResult Result
13549           = S.PerformCopyInitialization(
13550               InitializedEntity::InitializeBlock(Var->getLocation(),
13551                                                   CaptureType, false),
13552               Loc, DeclRef);
13553 
13554         // Build a full-expression copy expression if initialization
13555         // succeeded and used a non-trivial constructor.  Recover from
13556         // errors by pretending that the copy isn't necessary.
13557         if (!Result.isInvalid() &&
13558             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13559                 ->isTrivial()) {
13560           Result = S.MaybeCreateExprWithCleanups(Result);
13561           CopyExpr = Result.get();
13562         }
13563       }
13564     }
13565   }
13566 
13567   // Actually capture the variable.
13568   if (BuildAndDiagnose)
13569     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13570                     SourceLocation(), CaptureType, CopyExpr);
13571 
13572   return true;
13573 
13574 }
13575 
13576 
13577 /// \brief Capture the given variable in the captured region.
13578 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13579                                     VarDecl *Var,
13580                                     SourceLocation Loc,
13581                                     const bool BuildAndDiagnose,
13582                                     QualType &CaptureType,
13583                                     QualType &DeclRefType,
13584                                     const bool RefersToCapturedVariable,
13585                                     Sema &S) {
13586   // By default, capture variables by reference.
13587   bool ByRef = true;
13588   // Using an LValue reference type is consistent with Lambdas (see below).
13589   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13590     if (S.IsOpenMPCapturedDecl(Var))
13591       DeclRefType = DeclRefType.getUnqualifiedType();
13592     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13593   }
13594 
13595   if (ByRef)
13596     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13597   else
13598     CaptureType = DeclRefType;
13599 
13600   Expr *CopyExpr = nullptr;
13601   if (BuildAndDiagnose) {
13602     // The current implementation assumes that all variables are captured
13603     // by references. Since there is no capture by copy, no expression
13604     // evaluation will be needed.
13605     RecordDecl *RD = RSI->TheRecordDecl;
13606 
13607     FieldDecl *Field
13608       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13609                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13610                           nullptr, false, ICIS_NoInit);
13611     Field->setImplicit(true);
13612     Field->setAccess(AS_private);
13613     RD->addDecl(Field);
13614 
13615     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13616                                             DeclRefType, VK_LValue, Loc);
13617     Var->setReferenced(true);
13618     Var->markUsed(S.Context);
13619   }
13620 
13621   // Actually capture the variable.
13622   if (BuildAndDiagnose)
13623     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13624                     SourceLocation(), CaptureType, CopyExpr);
13625 
13626 
13627   return true;
13628 }
13629 
13630 /// \brief Create a field within the lambda class for the variable
13631 /// being captured.
13632 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13633                                     QualType FieldType, QualType DeclRefType,
13634                                     SourceLocation Loc,
13635                                     bool RefersToCapturedVariable) {
13636   CXXRecordDecl *Lambda = LSI->Lambda;
13637 
13638   // Build the non-static data member.
13639   FieldDecl *Field
13640     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13641                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13642                         nullptr, false, ICIS_NoInit);
13643   Field->setImplicit(true);
13644   Field->setAccess(AS_private);
13645   Lambda->addDecl(Field);
13646 }
13647 
13648 /// \brief Capture the given variable in the lambda.
13649 static bool captureInLambda(LambdaScopeInfo *LSI,
13650                             VarDecl *Var,
13651                             SourceLocation Loc,
13652                             const bool BuildAndDiagnose,
13653                             QualType &CaptureType,
13654                             QualType &DeclRefType,
13655                             const bool RefersToCapturedVariable,
13656                             const Sema::TryCaptureKind Kind,
13657                             SourceLocation EllipsisLoc,
13658                             const bool IsTopScope,
13659                             Sema &S) {
13660 
13661   // Determine whether we are capturing by reference or by value.
13662   bool ByRef = false;
13663   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13664     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13665   } else {
13666     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13667   }
13668 
13669   // Compute the type of the field that will capture this variable.
13670   if (ByRef) {
13671     // C++11 [expr.prim.lambda]p15:
13672     //   An entity is captured by reference if it is implicitly or
13673     //   explicitly captured but not captured by copy. It is
13674     //   unspecified whether additional unnamed non-static data
13675     //   members are declared in the closure type for entities
13676     //   captured by reference.
13677     //
13678     // FIXME: It is not clear whether we want to build an lvalue reference
13679     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13680     // to do the former, while EDG does the latter. Core issue 1249 will
13681     // clarify, but for now we follow GCC because it's a more permissive and
13682     // easily defensible position.
13683     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13684   } else {
13685     // C++11 [expr.prim.lambda]p14:
13686     //   For each entity captured by copy, an unnamed non-static
13687     //   data member is declared in the closure type. The
13688     //   declaration order of these members is unspecified. The type
13689     //   of such a data member is the type of the corresponding
13690     //   captured entity if the entity is not a reference to an
13691     //   object, or the referenced type otherwise. [Note: If the
13692     //   captured entity is a reference to a function, the
13693     //   corresponding data member is also a reference to a
13694     //   function. - end note ]
13695     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13696       if (!RefType->getPointeeType()->isFunctionType())
13697         CaptureType = RefType->getPointeeType();
13698     }
13699 
13700     // Forbid the lambda copy-capture of autoreleasing variables.
13701     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13702       if (BuildAndDiagnose) {
13703         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13704         S.Diag(Var->getLocation(), diag::note_previous_decl)
13705           << Var->getDeclName();
13706       }
13707       return false;
13708     }
13709 
13710     // Make sure that by-copy captures are of a complete and non-abstract type.
13711     if (BuildAndDiagnose) {
13712       if (!CaptureType->isDependentType() &&
13713           S.RequireCompleteType(Loc, CaptureType,
13714                                 diag::err_capture_of_incomplete_type,
13715                                 Var->getDeclName()))
13716         return false;
13717 
13718       if (S.RequireNonAbstractType(Loc, CaptureType,
13719                                    diag::err_capture_of_abstract_type))
13720         return false;
13721     }
13722   }
13723 
13724   // Capture this variable in the lambda.
13725   if (BuildAndDiagnose)
13726     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13727                             RefersToCapturedVariable);
13728 
13729   // Compute the type of a reference to this captured variable.
13730   if (ByRef)
13731     DeclRefType = CaptureType.getNonReferenceType();
13732   else {
13733     // C++ [expr.prim.lambda]p5:
13734     //   The closure type for a lambda-expression has a public inline
13735     //   function call operator [...]. This function call operator is
13736     //   declared const (9.3.1) if and only if the lambda-expression's
13737     //   parameter-declaration-clause is not followed by mutable.
13738     DeclRefType = CaptureType.getNonReferenceType();
13739     if (!LSI->Mutable && !CaptureType->isReferenceType())
13740       DeclRefType.addConst();
13741   }
13742 
13743   // Add the capture.
13744   if (BuildAndDiagnose)
13745     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13746                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13747 
13748   return true;
13749 }
13750 
13751 bool Sema::tryCaptureVariable(
13752     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13753     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13754     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13755   // An init-capture is notionally from the context surrounding its
13756   // declaration, but its parent DC is the lambda class.
13757   DeclContext *VarDC = Var->getDeclContext();
13758   if (Var->isInitCapture())
13759     VarDC = VarDC->getParent();
13760 
13761   DeclContext *DC = CurContext;
13762   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13763       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13764   // We need to sync up the Declaration Context with the
13765   // FunctionScopeIndexToStopAt
13766   if (FunctionScopeIndexToStopAt) {
13767     unsigned FSIndex = FunctionScopes.size() - 1;
13768     while (FSIndex != MaxFunctionScopesIndex) {
13769       DC = getLambdaAwareParentOfDeclContext(DC);
13770       --FSIndex;
13771     }
13772   }
13773 
13774 
13775   // If the variable is declared in the current context, there is no need to
13776   // capture it.
13777   if (VarDC == DC) return true;
13778 
13779   // Capture global variables if it is required to use private copy of this
13780   // variable.
13781   bool IsGlobal = !Var->hasLocalStorage();
13782   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13783     return true;
13784 
13785   // Walk up the stack to determine whether we can capture the variable,
13786   // performing the "simple" checks that don't depend on type. We stop when
13787   // we've either hit the declared scope of the variable or find an existing
13788   // capture of that variable.  We start from the innermost capturing-entity
13789   // (the DC) and ensure that all intervening capturing-entities
13790   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13791   // declcontext can either capture the variable or have already captured
13792   // the variable.
13793   CaptureType = Var->getType();
13794   DeclRefType = CaptureType.getNonReferenceType();
13795   bool Nested = false;
13796   bool Explicit = (Kind != TryCapture_Implicit);
13797   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13798   do {
13799     // Only block literals, captured statements, and lambda expressions can
13800     // capture; other scopes don't work.
13801     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13802                                                               ExprLoc,
13803                                                               BuildAndDiagnose,
13804                                                               *this);
13805     // We need to check for the parent *first* because, if we *have*
13806     // private-captured a global variable, we need to recursively capture it in
13807     // intermediate blocks, lambdas, etc.
13808     if (!ParentDC) {
13809       if (IsGlobal) {
13810         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13811         break;
13812       }
13813       return true;
13814     }
13815 
13816     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13817     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13818 
13819 
13820     // Check whether we've already captured it.
13821     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13822                                              DeclRefType))
13823       break;
13824     // If we are instantiating a generic lambda call operator body,
13825     // we do not want to capture new variables.  What was captured
13826     // during either a lambdas transformation or initial parsing
13827     // should be used.
13828     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13829       if (BuildAndDiagnose) {
13830         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13831         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13832           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13833           Diag(Var->getLocation(), diag::note_previous_decl)
13834              << Var->getDeclName();
13835           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13836         } else
13837           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13838       }
13839       return true;
13840     }
13841     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13842     // certain types of variables (unnamed, variably modified types etc.)
13843     // so check for eligibility.
13844     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13845        return true;
13846 
13847     // Try to capture variable-length arrays types.
13848     if (Var->getType()->isVariablyModifiedType()) {
13849       // We're going to walk down into the type and look for VLA
13850       // expressions.
13851       QualType QTy = Var->getType();
13852       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13853         QTy = PVD->getOriginalType();
13854       captureVariablyModifiedType(Context, QTy, CSI);
13855     }
13856 
13857     if (getLangOpts().OpenMP) {
13858       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13859         // OpenMP private variables should not be captured in outer scope, so
13860         // just break here. Similarly, global variables that are captured in a
13861         // target region should not be captured outside the scope of the region.
13862         if (RSI->CapRegionKind == CR_OpenMP) {
13863           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13864           // When we detect target captures we are looking from inside the
13865           // target region, therefore we need to propagate the capture from the
13866           // enclosing region. Therefore, the capture is not initially nested.
13867           if (IsTargetCap)
13868             FunctionScopesIndex--;
13869 
13870           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13871             Nested = !IsTargetCap;
13872             DeclRefType = DeclRefType.getUnqualifiedType();
13873             CaptureType = Context.getLValueReferenceType(DeclRefType);
13874             break;
13875           }
13876         }
13877       }
13878     }
13879     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13880       // No capture-default, and this is not an explicit capture
13881       // so cannot capture this variable.
13882       if (BuildAndDiagnose) {
13883         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13884         Diag(Var->getLocation(), diag::note_previous_decl)
13885           << Var->getDeclName();
13886         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13887           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13888                diag::note_lambda_decl);
13889         // FIXME: If we error out because an outer lambda can not implicitly
13890         // capture a variable that an inner lambda explicitly captures, we
13891         // should have the inner lambda do the explicit capture - because
13892         // it makes for cleaner diagnostics later.  This would purely be done
13893         // so that the diagnostic does not misleadingly claim that a variable
13894         // can not be captured by a lambda implicitly even though it is captured
13895         // explicitly.  Suggestion:
13896         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13897         //    at the function head
13898         //  - cache the StartingDeclContext - this must be a lambda
13899         //  - captureInLambda in the innermost lambda the variable.
13900       }
13901       return true;
13902     }
13903 
13904     FunctionScopesIndex--;
13905     DC = ParentDC;
13906     Explicit = false;
13907   } while (!VarDC->Equals(DC));
13908 
13909   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13910   // computing the type of the capture at each step, checking type-specific
13911   // requirements, and adding captures if requested.
13912   // If the variable had already been captured previously, we start capturing
13913   // at the lambda nested within that one.
13914   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13915        ++I) {
13916     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13917 
13918     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13919       if (!captureInBlock(BSI, Var, ExprLoc,
13920                           BuildAndDiagnose, CaptureType,
13921                           DeclRefType, Nested, *this))
13922         return true;
13923       Nested = true;
13924     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13925       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13926                                    BuildAndDiagnose, CaptureType,
13927                                    DeclRefType, Nested, *this))
13928         return true;
13929       Nested = true;
13930     } else {
13931       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13932       if (!captureInLambda(LSI, Var, ExprLoc,
13933                            BuildAndDiagnose, CaptureType,
13934                            DeclRefType, Nested, Kind, EllipsisLoc,
13935                             /*IsTopScope*/I == N - 1, *this))
13936         return true;
13937       Nested = true;
13938     }
13939   }
13940   return false;
13941 }
13942 
13943 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13944                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13945   QualType CaptureType;
13946   QualType DeclRefType;
13947   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13948                             /*BuildAndDiagnose=*/true, CaptureType,
13949                             DeclRefType, nullptr);
13950 }
13951 
13952 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13953   QualType CaptureType;
13954   QualType DeclRefType;
13955   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13956                              /*BuildAndDiagnose=*/false, CaptureType,
13957                              DeclRefType, nullptr);
13958 }
13959 
13960 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13961   QualType CaptureType;
13962   QualType DeclRefType;
13963 
13964   // Determine whether we can capture this variable.
13965   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13966                          /*BuildAndDiagnose=*/false, CaptureType,
13967                          DeclRefType, nullptr))
13968     return QualType();
13969 
13970   return DeclRefType;
13971 }
13972 
13973 
13974 
13975 // If either the type of the variable or the initializer is dependent,
13976 // return false. Otherwise, determine whether the variable is a constant
13977 // expression. Use this if you need to know if a variable that might or
13978 // might not be dependent is truly a constant expression.
13979 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13980     ASTContext &Context) {
13981 
13982   if (Var->getType()->isDependentType())
13983     return false;
13984   const VarDecl *DefVD = nullptr;
13985   Var->getAnyInitializer(DefVD);
13986   if (!DefVD)
13987     return false;
13988   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13989   Expr *Init = cast<Expr>(Eval->Value);
13990   if (Init->isValueDependent())
13991     return false;
13992   return IsVariableAConstantExpression(Var, Context);
13993 }
13994 
13995 
13996 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13997   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13998   // an object that satisfies the requirements for appearing in a
13999   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14000   // is immediately applied."  This function handles the lvalue-to-rvalue
14001   // conversion part.
14002   MaybeODRUseExprs.erase(E->IgnoreParens());
14003 
14004   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14005   // to a variable that is a constant expression, and if so, identify it as
14006   // a reference to a variable that does not involve an odr-use of that
14007   // variable.
14008   if (LambdaScopeInfo *LSI = getCurLambda()) {
14009     Expr *SansParensExpr = E->IgnoreParens();
14010     VarDecl *Var = nullptr;
14011     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14012       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14013     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14014       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14015 
14016     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14017       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14018   }
14019 }
14020 
14021 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14022   Res = CorrectDelayedTyposInExpr(Res);
14023 
14024   if (!Res.isUsable())
14025     return Res;
14026 
14027   // If a constant-expression is a reference to a variable where we delay
14028   // deciding whether it is an odr-use, just assume we will apply the
14029   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14030   // (a non-type template argument), we have special handling anyway.
14031   UpdateMarkingForLValueToRValue(Res.get());
14032   return Res;
14033 }
14034 
14035 void Sema::CleanupVarDeclMarking() {
14036   for (Expr *E : MaybeODRUseExprs) {
14037     VarDecl *Var;
14038     SourceLocation Loc;
14039     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14040       Var = cast<VarDecl>(DRE->getDecl());
14041       Loc = DRE->getLocation();
14042     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14043       Var = cast<VarDecl>(ME->getMemberDecl());
14044       Loc = ME->getMemberLoc();
14045     } else {
14046       llvm_unreachable("Unexpected expression");
14047     }
14048 
14049     MarkVarDeclODRUsed(Var, Loc, *this,
14050                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14051   }
14052 
14053   MaybeODRUseExprs.clear();
14054 }
14055 
14056 
14057 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14058                                     VarDecl *Var, Expr *E) {
14059   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14060          "Invalid Expr argument to DoMarkVarDeclReferenced");
14061   Var->setReferenced();
14062 
14063   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14064   bool MarkODRUsed = true;
14065 
14066   // If the context is not potentially evaluated, this is not an odr-use and
14067   // does not trigger instantiation.
14068   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
14069     if (SemaRef.isUnevaluatedContext())
14070       return;
14071 
14072     // If we don't yet know whether this context is going to end up being an
14073     // evaluated context, and we're referencing a variable from an enclosing
14074     // scope, add a potential capture.
14075     //
14076     // FIXME: Is this necessary? These contexts are only used for default
14077     // arguments, where local variables can't be used.
14078     const bool RefersToEnclosingScope =
14079         (SemaRef.CurContext != Var->getDeclContext() &&
14080          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14081     if (RefersToEnclosingScope) {
14082       if (LambdaScopeInfo *const LSI =
14083               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14084         // If a variable could potentially be odr-used, defer marking it so
14085         // until we finish analyzing the full expression for any
14086         // lvalue-to-rvalue
14087         // or discarded value conversions that would obviate odr-use.
14088         // Add it to the list of potential captures that will be analyzed
14089         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14090         // unless the variable is a reference that was initialized by a constant
14091         // expression (this will never need to be captured or odr-used).
14092         assert(E && "Capture variable should be used in an expression.");
14093         if (!Var->getType()->isReferenceType() ||
14094             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14095           LSI->addPotentialCapture(E->IgnoreParens());
14096       }
14097     }
14098 
14099     if (!isTemplateInstantiation(TSK))
14100       return;
14101 
14102     // Instantiate, but do not mark as odr-used, variable templates.
14103     MarkODRUsed = false;
14104   }
14105 
14106   VarTemplateSpecializationDecl *VarSpec =
14107       dyn_cast<VarTemplateSpecializationDecl>(Var);
14108   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14109          "Can't instantiate a partial template specialization.");
14110 
14111   // If this might be a member specialization of a static data member, check
14112   // the specialization is visible. We already did the checks for variable
14113   // template specializations when we created them.
14114   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14115     SemaRef.checkSpecializationVisibility(Loc, Var);
14116 
14117   // Perform implicit instantiation of static data members, static data member
14118   // templates of class templates, and variable template specializations. Delay
14119   // instantiations of variable templates, except for those that could be used
14120   // in a constant expression.
14121   if (isTemplateInstantiation(TSK)) {
14122     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14123 
14124     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14125       if (Var->getPointOfInstantiation().isInvalid()) {
14126         // This is a modification of an existing AST node. Notify listeners.
14127         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14128           L->StaticDataMemberInstantiated(Var);
14129       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14130         // Don't bother trying to instantiate it again, unless we might need
14131         // its initializer before we get to the end of the TU.
14132         TryInstantiating = false;
14133     }
14134 
14135     if (Var->getPointOfInstantiation().isInvalid())
14136       Var->setTemplateSpecializationKind(TSK, Loc);
14137 
14138     if (TryInstantiating) {
14139       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14140       bool InstantiationDependent = false;
14141       bool IsNonDependent =
14142           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14143                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14144                   : true;
14145 
14146       // Do not instantiate specializations that are still type-dependent.
14147       if (IsNonDependent) {
14148         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14149           // Do not defer instantiations of variables which could be used in a
14150           // constant expression.
14151           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14152         } else {
14153           SemaRef.PendingInstantiations
14154               .push_back(std::make_pair(Var, PointOfInstantiation));
14155         }
14156       }
14157     }
14158   }
14159 
14160   if (!MarkODRUsed)
14161     return;
14162 
14163   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14164   // the requirements for appearing in a constant expression (5.19) and, if
14165   // it is an object, the lvalue-to-rvalue conversion (4.1)
14166   // is immediately applied."  We check the first part here, and
14167   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14168   // Note that we use the C++11 definition everywhere because nothing in
14169   // C++03 depends on whether we get the C++03 version correct. The second
14170   // part does not apply to references, since they are not objects.
14171   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14172     // A reference initialized by a constant expression can never be
14173     // odr-used, so simply ignore it.
14174     if (!Var->getType()->isReferenceType())
14175       SemaRef.MaybeODRUseExprs.insert(E);
14176   } else
14177     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14178                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14179 }
14180 
14181 /// \brief Mark a variable referenced, and check whether it is odr-used
14182 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14183 /// used directly for normal expressions referring to VarDecl.
14184 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14185   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14186 }
14187 
14188 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14189                                Decl *D, Expr *E, bool MightBeOdrUse) {
14190   if (SemaRef.isInOpenMPDeclareTargetContext())
14191     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14192 
14193   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14194     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14195     return;
14196   }
14197 
14198   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14199 
14200   // If this is a call to a method via a cast, also mark the method in the
14201   // derived class used in case codegen can devirtualize the call.
14202   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14203   if (!ME)
14204     return;
14205   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14206   if (!MD)
14207     return;
14208   // Only attempt to devirtualize if this is truly a virtual call.
14209   bool IsVirtualCall = MD->isVirtual() &&
14210                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14211   if (!IsVirtualCall)
14212     return;
14213   const Expr *Base = ME->getBase();
14214   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14215   if (!MostDerivedClassDecl)
14216     return;
14217   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14218   if (!DM || DM->isPure())
14219     return;
14220   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14221 }
14222 
14223 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14224 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14225   // TODO: update this with DR# once a defect report is filed.
14226   // C++11 defect. The address of a pure member should not be an ODR use, even
14227   // if it's a qualified reference.
14228   bool OdrUse = true;
14229   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14230     if (Method->isVirtual())
14231       OdrUse = false;
14232   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14233 }
14234 
14235 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14236 void Sema::MarkMemberReferenced(MemberExpr *E) {
14237   // C++11 [basic.def.odr]p2:
14238   //   A non-overloaded function whose name appears as a potentially-evaluated
14239   //   expression or a member of a set of candidate functions, if selected by
14240   //   overload resolution when referred to from a potentially-evaluated
14241   //   expression, is odr-used, unless it is a pure virtual function and its
14242   //   name is not explicitly qualified.
14243   bool MightBeOdrUse = true;
14244   if (E->performsVirtualDispatch(getLangOpts())) {
14245     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14246       if (Method->isPure())
14247         MightBeOdrUse = false;
14248   }
14249   SourceLocation Loc = E->getMemberLoc().isValid() ?
14250                             E->getMemberLoc() : E->getLocStart();
14251   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14252 }
14253 
14254 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14255 /// marks the declaration referenced, and performs odr-use checking for
14256 /// functions and variables. This method should not be used when building a
14257 /// normal expression which refers to a variable.
14258 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14259                                  bool MightBeOdrUse) {
14260   if (MightBeOdrUse) {
14261     if (auto *VD = dyn_cast<VarDecl>(D)) {
14262       MarkVariableReferenced(Loc, VD);
14263       return;
14264     }
14265   }
14266   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14267     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14268     return;
14269   }
14270   D->setReferenced();
14271 }
14272 
14273 namespace {
14274   // Mark all of the declarations referenced
14275   // FIXME: Not fully implemented yet! We need to have a better understanding
14276   // of when we're entering
14277   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14278     Sema &S;
14279     SourceLocation Loc;
14280 
14281   public:
14282     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14283 
14284     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14285 
14286     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14287     bool TraverseRecordType(RecordType *T);
14288   };
14289 }
14290 
14291 bool MarkReferencedDecls::TraverseTemplateArgument(
14292     const TemplateArgument &Arg) {
14293   if (Arg.getKind() == TemplateArgument::Declaration) {
14294     if (Decl *D = Arg.getAsDecl())
14295       S.MarkAnyDeclReferenced(Loc, D, true);
14296   }
14297 
14298   return Inherited::TraverseTemplateArgument(Arg);
14299 }
14300 
14301 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14302   if (ClassTemplateSpecializationDecl *Spec
14303                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14304     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14305     return TraverseTemplateArguments(Args.data(), Args.size());
14306   }
14307 
14308   return true;
14309 }
14310 
14311 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14312   MarkReferencedDecls Marker(*this, Loc);
14313   Marker.TraverseType(Context.getCanonicalType(T));
14314 }
14315 
14316 namespace {
14317   /// \brief Helper class that marks all of the declarations referenced by
14318   /// potentially-evaluated subexpressions as "referenced".
14319   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14320     Sema &S;
14321     bool SkipLocalVariables;
14322 
14323   public:
14324     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14325 
14326     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14327       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14328 
14329     void VisitDeclRefExpr(DeclRefExpr *E) {
14330       // If we were asked not to visit local variables, don't.
14331       if (SkipLocalVariables) {
14332         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14333           if (VD->hasLocalStorage())
14334             return;
14335       }
14336 
14337       S.MarkDeclRefReferenced(E);
14338     }
14339 
14340     void VisitMemberExpr(MemberExpr *E) {
14341       S.MarkMemberReferenced(E);
14342       Inherited::VisitMemberExpr(E);
14343     }
14344 
14345     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14346       S.MarkFunctionReferenced(E->getLocStart(),
14347             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14348       Visit(E->getSubExpr());
14349     }
14350 
14351     void VisitCXXNewExpr(CXXNewExpr *E) {
14352       if (E->getOperatorNew())
14353         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14354       if (E->getOperatorDelete())
14355         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14356       Inherited::VisitCXXNewExpr(E);
14357     }
14358 
14359     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14360       if (E->getOperatorDelete())
14361         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14362       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14363       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14364         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14365         S.MarkFunctionReferenced(E->getLocStart(),
14366                                     S.LookupDestructor(Record));
14367       }
14368 
14369       Inherited::VisitCXXDeleteExpr(E);
14370     }
14371 
14372     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14373       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14374       Inherited::VisitCXXConstructExpr(E);
14375     }
14376 
14377     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14378       Visit(E->getExpr());
14379     }
14380 
14381     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14382       Inherited::VisitImplicitCastExpr(E);
14383 
14384       if (E->getCastKind() == CK_LValueToRValue)
14385         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14386     }
14387   };
14388 }
14389 
14390 /// \brief Mark any declarations that appear within this expression or any
14391 /// potentially-evaluated subexpressions as "referenced".
14392 ///
14393 /// \param SkipLocalVariables If true, don't mark local variables as
14394 /// 'referenced'.
14395 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14396                                             bool SkipLocalVariables) {
14397   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14398 }
14399 
14400 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14401 /// of the program being compiled.
14402 ///
14403 /// This routine emits the given diagnostic when the code currently being
14404 /// type-checked is "potentially evaluated", meaning that there is a
14405 /// possibility that the code will actually be executable. Code in sizeof()
14406 /// expressions, code used only during overload resolution, etc., are not
14407 /// potentially evaluated. This routine will suppress such diagnostics or,
14408 /// in the absolutely nutty case of potentially potentially evaluated
14409 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14410 /// later.
14411 ///
14412 /// This routine should be used for all diagnostics that describe the run-time
14413 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14414 /// Failure to do so will likely result in spurious diagnostics or failures
14415 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14416 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14417                                const PartialDiagnostic &PD) {
14418   switch (ExprEvalContexts.back().Context) {
14419   case Unevaluated:
14420   case UnevaluatedAbstract:
14421   case DiscardedStatement:
14422     // The argument will never be evaluated, so don't complain.
14423     break;
14424 
14425   case ConstantEvaluated:
14426     // Relevant diagnostics should be produced by constant evaluation.
14427     break;
14428 
14429   case PotentiallyEvaluated:
14430   case PotentiallyEvaluatedIfUsed:
14431     if (Statement && getCurFunctionOrMethodDecl()) {
14432       FunctionScopes.back()->PossiblyUnreachableDiags.
14433         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14434     }
14435     else
14436       Diag(Loc, PD);
14437 
14438     return true;
14439   }
14440 
14441   return false;
14442 }
14443 
14444 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14445                                CallExpr *CE, FunctionDecl *FD) {
14446   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14447     return false;
14448 
14449   // If we're inside a decltype's expression, don't check for a valid return
14450   // type or construct temporaries until we know whether this is the last call.
14451   if (ExprEvalContexts.back().IsDecltype) {
14452     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14453     return false;
14454   }
14455 
14456   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14457     FunctionDecl *FD;
14458     CallExpr *CE;
14459 
14460   public:
14461     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14462       : FD(FD), CE(CE) { }
14463 
14464     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14465       if (!FD) {
14466         S.Diag(Loc, diag::err_call_incomplete_return)
14467           << T << CE->getSourceRange();
14468         return;
14469       }
14470 
14471       S.Diag(Loc, diag::err_call_function_incomplete_return)
14472         << CE->getSourceRange() << FD->getDeclName() << T;
14473       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14474           << FD->getDeclName();
14475     }
14476   } Diagnoser(FD, CE);
14477 
14478   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14479     return true;
14480 
14481   return false;
14482 }
14483 
14484 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14485 // will prevent this condition from triggering, which is what we want.
14486 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14487   SourceLocation Loc;
14488 
14489   unsigned diagnostic = diag::warn_condition_is_assignment;
14490   bool IsOrAssign = false;
14491 
14492   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14493     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14494       return;
14495 
14496     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14497 
14498     // Greylist some idioms by putting them into a warning subcategory.
14499     if (ObjCMessageExpr *ME
14500           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14501       Selector Sel = ME->getSelector();
14502 
14503       // self = [<foo> init...]
14504       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14505         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14506 
14507       // <foo> = [<bar> nextObject]
14508       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14509         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14510     }
14511 
14512     Loc = Op->getOperatorLoc();
14513   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14514     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14515       return;
14516 
14517     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14518     Loc = Op->getOperatorLoc();
14519   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14520     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14521   else {
14522     // Not an assignment.
14523     return;
14524   }
14525 
14526   Diag(Loc, diagnostic) << E->getSourceRange();
14527 
14528   SourceLocation Open = E->getLocStart();
14529   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14530   Diag(Loc, diag::note_condition_assign_silence)
14531         << FixItHint::CreateInsertion(Open, "(")
14532         << FixItHint::CreateInsertion(Close, ")");
14533 
14534   if (IsOrAssign)
14535     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14536       << FixItHint::CreateReplacement(Loc, "!=");
14537   else
14538     Diag(Loc, diag::note_condition_assign_to_comparison)
14539       << FixItHint::CreateReplacement(Loc, "==");
14540 }
14541 
14542 /// \brief Redundant parentheses over an equality comparison can indicate
14543 /// that the user intended an assignment used as condition.
14544 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14545   // Don't warn if the parens came from a macro.
14546   SourceLocation parenLoc = ParenE->getLocStart();
14547   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14548     return;
14549   // Don't warn for dependent expressions.
14550   if (ParenE->isTypeDependent())
14551     return;
14552 
14553   Expr *E = ParenE->IgnoreParens();
14554 
14555   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14556     if (opE->getOpcode() == BO_EQ &&
14557         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14558                                                            == Expr::MLV_Valid) {
14559       SourceLocation Loc = opE->getOperatorLoc();
14560 
14561       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14562       SourceRange ParenERange = ParenE->getSourceRange();
14563       Diag(Loc, diag::note_equality_comparison_silence)
14564         << FixItHint::CreateRemoval(ParenERange.getBegin())
14565         << FixItHint::CreateRemoval(ParenERange.getEnd());
14566       Diag(Loc, diag::note_equality_comparison_to_assign)
14567         << FixItHint::CreateReplacement(Loc, "=");
14568     }
14569 }
14570 
14571 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14572                                        bool IsConstexpr) {
14573   DiagnoseAssignmentAsCondition(E);
14574   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14575     DiagnoseEqualityWithExtraParens(parenE);
14576 
14577   ExprResult result = CheckPlaceholderExpr(E);
14578   if (result.isInvalid()) return ExprError();
14579   E = result.get();
14580 
14581   if (!E->isTypeDependent()) {
14582     if (getLangOpts().CPlusPlus)
14583       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14584 
14585     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14586     if (ERes.isInvalid())
14587       return ExprError();
14588     E = ERes.get();
14589 
14590     QualType T = E->getType();
14591     if (!T->isScalarType()) { // C99 6.8.4.1p1
14592       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14593         << T << E->getSourceRange();
14594       return ExprError();
14595     }
14596     CheckBoolLikeConversion(E, Loc);
14597   }
14598 
14599   return E;
14600 }
14601 
14602 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14603                                            Expr *SubExpr, ConditionKind CK) {
14604   // Empty conditions are valid in for-statements.
14605   if (!SubExpr)
14606     return ConditionResult();
14607 
14608   ExprResult Cond;
14609   switch (CK) {
14610   case ConditionKind::Boolean:
14611     Cond = CheckBooleanCondition(Loc, SubExpr);
14612     break;
14613 
14614   case ConditionKind::ConstexprIf:
14615     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14616     break;
14617 
14618   case ConditionKind::Switch:
14619     Cond = CheckSwitchCondition(Loc, SubExpr);
14620     break;
14621   }
14622   if (Cond.isInvalid())
14623     return ConditionError();
14624 
14625   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14626   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14627   if (!FullExpr.get())
14628     return ConditionError();
14629 
14630   return ConditionResult(*this, nullptr, FullExpr,
14631                          CK == ConditionKind::ConstexprIf);
14632 }
14633 
14634 namespace {
14635   /// A visitor for rebuilding a call to an __unknown_any expression
14636   /// to have an appropriate type.
14637   struct RebuildUnknownAnyFunction
14638     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14639 
14640     Sema &S;
14641 
14642     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14643 
14644     ExprResult VisitStmt(Stmt *S) {
14645       llvm_unreachable("unexpected statement!");
14646     }
14647 
14648     ExprResult VisitExpr(Expr *E) {
14649       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14650         << E->getSourceRange();
14651       return ExprError();
14652     }
14653 
14654     /// Rebuild an expression which simply semantically wraps another
14655     /// expression which it shares the type and value kind of.
14656     template <class T> ExprResult rebuildSugarExpr(T *E) {
14657       ExprResult SubResult = Visit(E->getSubExpr());
14658       if (SubResult.isInvalid()) return ExprError();
14659 
14660       Expr *SubExpr = SubResult.get();
14661       E->setSubExpr(SubExpr);
14662       E->setType(SubExpr->getType());
14663       E->setValueKind(SubExpr->getValueKind());
14664       assert(E->getObjectKind() == OK_Ordinary);
14665       return E;
14666     }
14667 
14668     ExprResult VisitParenExpr(ParenExpr *E) {
14669       return rebuildSugarExpr(E);
14670     }
14671 
14672     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14673       return rebuildSugarExpr(E);
14674     }
14675 
14676     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14677       ExprResult SubResult = Visit(E->getSubExpr());
14678       if (SubResult.isInvalid()) return ExprError();
14679 
14680       Expr *SubExpr = SubResult.get();
14681       E->setSubExpr(SubExpr);
14682       E->setType(S.Context.getPointerType(SubExpr->getType()));
14683       assert(E->getValueKind() == VK_RValue);
14684       assert(E->getObjectKind() == OK_Ordinary);
14685       return E;
14686     }
14687 
14688     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14689       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14690 
14691       E->setType(VD->getType());
14692 
14693       assert(E->getValueKind() == VK_RValue);
14694       if (S.getLangOpts().CPlusPlus &&
14695           !(isa<CXXMethodDecl>(VD) &&
14696             cast<CXXMethodDecl>(VD)->isInstance()))
14697         E->setValueKind(VK_LValue);
14698 
14699       return E;
14700     }
14701 
14702     ExprResult VisitMemberExpr(MemberExpr *E) {
14703       return resolveDecl(E, E->getMemberDecl());
14704     }
14705 
14706     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14707       return resolveDecl(E, E->getDecl());
14708     }
14709   };
14710 }
14711 
14712 /// Given a function expression of unknown-any type, try to rebuild it
14713 /// to have a function type.
14714 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14715   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14716   if (Result.isInvalid()) return ExprError();
14717   return S.DefaultFunctionArrayConversion(Result.get());
14718 }
14719 
14720 namespace {
14721   /// A visitor for rebuilding an expression of type __unknown_anytype
14722   /// into one which resolves the type directly on the referring
14723   /// expression.  Strict preservation of the original source
14724   /// structure is not a goal.
14725   struct RebuildUnknownAnyExpr
14726     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14727 
14728     Sema &S;
14729 
14730     /// The current destination type.
14731     QualType DestType;
14732 
14733     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14734       : S(S), DestType(CastType) {}
14735 
14736     ExprResult VisitStmt(Stmt *S) {
14737       llvm_unreachable("unexpected statement!");
14738     }
14739 
14740     ExprResult VisitExpr(Expr *E) {
14741       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14742         << E->getSourceRange();
14743       return ExprError();
14744     }
14745 
14746     ExprResult VisitCallExpr(CallExpr *E);
14747     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14748 
14749     /// Rebuild an expression which simply semantically wraps another
14750     /// expression which it shares the type and value kind of.
14751     template <class T> ExprResult rebuildSugarExpr(T *E) {
14752       ExprResult SubResult = Visit(E->getSubExpr());
14753       if (SubResult.isInvalid()) return ExprError();
14754       Expr *SubExpr = SubResult.get();
14755       E->setSubExpr(SubExpr);
14756       E->setType(SubExpr->getType());
14757       E->setValueKind(SubExpr->getValueKind());
14758       assert(E->getObjectKind() == OK_Ordinary);
14759       return E;
14760     }
14761 
14762     ExprResult VisitParenExpr(ParenExpr *E) {
14763       return rebuildSugarExpr(E);
14764     }
14765 
14766     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14767       return rebuildSugarExpr(E);
14768     }
14769 
14770     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14771       const PointerType *Ptr = DestType->getAs<PointerType>();
14772       if (!Ptr) {
14773         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14774           << E->getSourceRange();
14775         return ExprError();
14776       }
14777       assert(E->getValueKind() == VK_RValue);
14778       assert(E->getObjectKind() == OK_Ordinary);
14779       E->setType(DestType);
14780 
14781       // Build the sub-expression as if it were an object of the pointee type.
14782       DestType = Ptr->getPointeeType();
14783       ExprResult SubResult = Visit(E->getSubExpr());
14784       if (SubResult.isInvalid()) return ExprError();
14785       E->setSubExpr(SubResult.get());
14786       return E;
14787     }
14788 
14789     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14790 
14791     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14792 
14793     ExprResult VisitMemberExpr(MemberExpr *E) {
14794       return resolveDecl(E, E->getMemberDecl());
14795     }
14796 
14797     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14798       return resolveDecl(E, E->getDecl());
14799     }
14800   };
14801 }
14802 
14803 /// Rebuilds a call expression which yielded __unknown_anytype.
14804 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14805   Expr *CalleeExpr = E->getCallee();
14806 
14807   enum FnKind {
14808     FK_MemberFunction,
14809     FK_FunctionPointer,
14810     FK_BlockPointer
14811   };
14812 
14813   FnKind Kind;
14814   QualType CalleeType = CalleeExpr->getType();
14815   if (CalleeType == S.Context.BoundMemberTy) {
14816     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14817     Kind = FK_MemberFunction;
14818     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14819   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14820     CalleeType = Ptr->getPointeeType();
14821     Kind = FK_FunctionPointer;
14822   } else {
14823     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14824     Kind = FK_BlockPointer;
14825   }
14826   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14827 
14828   // Verify that this is a legal result type of a function.
14829   if (DestType->isArrayType() || DestType->isFunctionType()) {
14830     unsigned diagID = diag::err_func_returning_array_function;
14831     if (Kind == FK_BlockPointer)
14832       diagID = diag::err_block_returning_array_function;
14833 
14834     S.Diag(E->getExprLoc(), diagID)
14835       << DestType->isFunctionType() << DestType;
14836     return ExprError();
14837   }
14838 
14839   // Otherwise, go ahead and set DestType as the call's result.
14840   E->setType(DestType.getNonLValueExprType(S.Context));
14841   E->setValueKind(Expr::getValueKindForType(DestType));
14842   assert(E->getObjectKind() == OK_Ordinary);
14843 
14844   // Rebuild the function type, replacing the result type with DestType.
14845   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14846   if (Proto) {
14847     // __unknown_anytype(...) is a special case used by the debugger when
14848     // it has no idea what a function's signature is.
14849     //
14850     // We want to build this call essentially under the K&R
14851     // unprototyped rules, but making a FunctionNoProtoType in C++
14852     // would foul up all sorts of assumptions.  However, we cannot
14853     // simply pass all arguments as variadic arguments, nor can we
14854     // portably just call the function under a non-variadic type; see
14855     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14856     // However, it turns out that in practice it is generally safe to
14857     // call a function declared as "A foo(B,C,D);" under the prototype
14858     // "A foo(B,C,D,...);".  The only known exception is with the
14859     // Windows ABI, where any variadic function is implicitly cdecl
14860     // regardless of its normal CC.  Therefore we change the parameter
14861     // types to match the types of the arguments.
14862     //
14863     // This is a hack, but it is far superior to moving the
14864     // corresponding target-specific code from IR-gen to Sema/AST.
14865 
14866     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14867     SmallVector<QualType, 8> ArgTypes;
14868     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14869       ArgTypes.reserve(E->getNumArgs());
14870       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14871         Expr *Arg = E->getArg(i);
14872         QualType ArgType = Arg->getType();
14873         if (E->isLValue()) {
14874           ArgType = S.Context.getLValueReferenceType(ArgType);
14875         } else if (E->isXValue()) {
14876           ArgType = S.Context.getRValueReferenceType(ArgType);
14877         }
14878         ArgTypes.push_back(ArgType);
14879       }
14880       ParamTypes = ArgTypes;
14881     }
14882     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14883                                          Proto->getExtProtoInfo());
14884   } else {
14885     DestType = S.Context.getFunctionNoProtoType(DestType,
14886                                                 FnType->getExtInfo());
14887   }
14888 
14889   // Rebuild the appropriate pointer-to-function type.
14890   switch (Kind) {
14891   case FK_MemberFunction:
14892     // Nothing to do.
14893     break;
14894 
14895   case FK_FunctionPointer:
14896     DestType = S.Context.getPointerType(DestType);
14897     break;
14898 
14899   case FK_BlockPointer:
14900     DestType = S.Context.getBlockPointerType(DestType);
14901     break;
14902   }
14903 
14904   // Finally, we can recurse.
14905   ExprResult CalleeResult = Visit(CalleeExpr);
14906   if (!CalleeResult.isUsable()) return ExprError();
14907   E->setCallee(CalleeResult.get());
14908 
14909   // Bind a temporary if necessary.
14910   return S.MaybeBindToTemporary(E);
14911 }
14912 
14913 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14914   // Verify that this is a legal result type of a call.
14915   if (DestType->isArrayType() || DestType->isFunctionType()) {
14916     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14917       << DestType->isFunctionType() << DestType;
14918     return ExprError();
14919   }
14920 
14921   // Rewrite the method result type if available.
14922   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14923     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14924     Method->setReturnType(DestType);
14925   }
14926 
14927   // Change the type of the message.
14928   E->setType(DestType.getNonReferenceType());
14929   E->setValueKind(Expr::getValueKindForType(DestType));
14930 
14931   return S.MaybeBindToTemporary(E);
14932 }
14933 
14934 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14935   // The only case we should ever see here is a function-to-pointer decay.
14936   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14937     assert(E->getValueKind() == VK_RValue);
14938     assert(E->getObjectKind() == OK_Ordinary);
14939 
14940     E->setType(DestType);
14941 
14942     // Rebuild the sub-expression as the pointee (function) type.
14943     DestType = DestType->castAs<PointerType>()->getPointeeType();
14944 
14945     ExprResult Result = Visit(E->getSubExpr());
14946     if (!Result.isUsable()) return ExprError();
14947 
14948     E->setSubExpr(Result.get());
14949     return E;
14950   } else if (E->getCastKind() == CK_LValueToRValue) {
14951     assert(E->getValueKind() == VK_RValue);
14952     assert(E->getObjectKind() == OK_Ordinary);
14953 
14954     assert(isa<BlockPointerType>(E->getType()));
14955 
14956     E->setType(DestType);
14957 
14958     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14959     DestType = S.Context.getLValueReferenceType(DestType);
14960 
14961     ExprResult Result = Visit(E->getSubExpr());
14962     if (!Result.isUsable()) return ExprError();
14963 
14964     E->setSubExpr(Result.get());
14965     return E;
14966   } else {
14967     llvm_unreachable("Unhandled cast type!");
14968   }
14969 }
14970 
14971 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14972   ExprValueKind ValueKind = VK_LValue;
14973   QualType Type = DestType;
14974 
14975   // We know how to make this work for certain kinds of decls:
14976 
14977   //  - functions
14978   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14979     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14980       DestType = Ptr->getPointeeType();
14981       ExprResult Result = resolveDecl(E, VD);
14982       if (Result.isInvalid()) return ExprError();
14983       return S.ImpCastExprToType(Result.get(), Type,
14984                                  CK_FunctionToPointerDecay, VK_RValue);
14985     }
14986 
14987     if (!Type->isFunctionType()) {
14988       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14989         << VD << E->getSourceRange();
14990       return ExprError();
14991     }
14992     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14993       // We must match the FunctionDecl's type to the hack introduced in
14994       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14995       // type. See the lengthy commentary in that routine.
14996       QualType FDT = FD->getType();
14997       const FunctionType *FnType = FDT->castAs<FunctionType>();
14998       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14999       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15000       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15001         SourceLocation Loc = FD->getLocation();
15002         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15003                                       FD->getDeclContext(),
15004                                       Loc, Loc, FD->getNameInfo().getName(),
15005                                       DestType, FD->getTypeSourceInfo(),
15006                                       SC_None, false/*isInlineSpecified*/,
15007                                       FD->hasPrototype(),
15008                                       false/*isConstexprSpecified*/);
15009 
15010         if (FD->getQualifier())
15011           NewFD->setQualifierInfo(FD->getQualifierLoc());
15012 
15013         SmallVector<ParmVarDecl*, 16> Params;
15014         for (const auto &AI : FT->param_types()) {
15015           ParmVarDecl *Param =
15016             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15017           Param->setScopeInfo(0, Params.size());
15018           Params.push_back(Param);
15019         }
15020         NewFD->setParams(Params);
15021         DRE->setDecl(NewFD);
15022         VD = DRE->getDecl();
15023       }
15024     }
15025 
15026     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15027       if (MD->isInstance()) {
15028         ValueKind = VK_RValue;
15029         Type = S.Context.BoundMemberTy;
15030       }
15031 
15032     // Function references aren't l-values in C.
15033     if (!S.getLangOpts().CPlusPlus)
15034       ValueKind = VK_RValue;
15035 
15036   //  - variables
15037   } else if (isa<VarDecl>(VD)) {
15038     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15039       Type = RefTy->getPointeeType();
15040     } else if (Type->isFunctionType()) {
15041       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15042         << VD << E->getSourceRange();
15043       return ExprError();
15044     }
15045 
15046   //  - nothing else
15047   } else {
15048     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15049       << VD << E->getSourceRange();
15050     return ExprError();
15051   }
15052 
15053   // Modifying the declaration like this is friendly to IR-gen but
15054   // also really dangerous.
15055   VD->setType(DestType);
15056   E->setType(Type);
15057   E->setValueKind(ValueKind);
15058   return E;
15059 }
15060 
15061 /// Check a cast of an unknown-any type.  We intentionally only
15062 /// trigger this for C-style casts.
15063 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15064                                      Expr *CastExpr, CastKind &CastKind,
15065                                      ExprValueKind &VK, CXXCastPath &Path) {
15066   // The type we're casting to must be either void or complete.
15067   if (!CastType->isVoidType() &&
15068       RequireCompleteType(TypeRange.getBegin(), CastType,
15069                           diag::err_typecheck_cast_to_incomplete))
15070     return ExprError();
15071 
15072   // Rewrite the casted expression from scratch.
15073   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15074   if (!result.isUsable()) return ExprError();
15075 
15076   CastExpr = result.get();
15077   VK = CastExpr->getValueKind();
15078   CastKind = CK_NoOp;
15079 
15080   return CastExpr;
15081 }
15082 
15083 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15084   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15085 }
15086 
15087 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15088                                     Expr *arg, QualType &paramType) {
15089   // If the syntactic form of the argument is not an explicit cast of
15090   // any sort, just do default argument promotion.
15091   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15092   if (!castArg) {
15093     ExprResult result = DefaultArgumentPromotion(arg);
15094     if (result.isInvalid()) return ExprError();
15095     paramType = result.get()->getType();
15096     return result;
15097   }
15098 
15099   // Otherwise, use the type that was written in the explicit cast.
15100   assert(!arg->hasPlaceholderType());
15101   paramType = castArg->getTypeAsWritten();
15102 
15103   // Copy-initialize a parameter of that type.
15104   InitializedEntity entity =
15105     InitializedEntity::InitializeParameter(Context, paramType,
15106                                            /*consumed*/ false);
15107   return PerformCopyInitialization(entity, callLoc, arg);
15108 }
15109 
15110 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15111   Expr *orig = E;
15112   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15113   while (true) {
15114     E = E->IgnoreParenImpCasts();
15115     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15116       E = call->getCallee();
15117       diagID = diag::err_uncasted_call_of_unknown_any;
15118     } else {
15119       break;
15120     }
15121   }
15122 
15123   SourceLocation loc;
15124   NamedDecl *d;
15125   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15126     loc = ref->getLocation();
15127     d = ref->getDecl();
15128   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15129     loc = mem->getMemberLoc();
15130     d = mem->getMemberDecl();
15131   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15132     diagID = diag::err_uncasted_call_of_unknown_any;
15133     loc = msg->getSelectorStartLoc();
15134     d = msg->getMethodDecl();
15135     if (!d) {
15136       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15137         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15138         << orig->getSourceRange();
15139       return ExprError();
15140     }
15141   } else {
15142     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15143       << E->getSourceRange();
15144     return ExprError();
15145   }
15146 
15147   S.Diag(loc, diagID) << d << orig->getSourceRange();
15148 
15149   // Never recoverable.
15150   return ExprError();
15151 }
15152 
15153 /// Check for operands with placeholder types and complain if found.
15154 /// Returns true if there was an error and no recovery was possible.
15155 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15156   if (!getLangOpts().CPlusPlus) {
15157     // C cannot handle TypoExpr nodes on either side of a binop because it
15158     // doesn't handle dependent types properly, so make sure any TypoExprs have
15159     // been dealt with before checking the operands.
15160     ExprResult Result = CorrectDelayedTyposInExpr(E);
15161     if (!Result.isUsable()) return ExprError();
15162     E = Result.get();
15163   }
15164 
15165   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15166   if (!placeholderType) return E;
15167 
15168   switch (placeholderType->getKind()) {
15169 
15170   // Overloaded expressions.
15171   case BuiltinType::Overload: {
15172     // Try to resolve a single function template specialization.
15173     // This is obligatory.
15174     ExprResult Result = E;
15175     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15176       return Result;
15177 
15178     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15179     // leaves Result unchanged on failure.
15180     Result = E;
15181     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15182       return Result;
15183 
15184     // If that failed, try to recover with a call.
15185     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15186                          /*complain*/ true);
15187     return Result;
15188   }
15189 
15190   // Bound member functions.
15191   case BuiltinType::BoundMember: {
15192     ExprResult result = E;
15193     const Expr *BME = E->IgnoreParens();
15194     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15195     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15196     if (isa<CXXPseudoDestructorExpr>(BME)) {
15197       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15198     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15199       if (ME->getMemberNameInfo().getName().getNameKind() ==
15200           DeclarationName::CXXDestructorName)
15201         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15202     }
15203     tryToRecoverWithCall(result, PD,
15204                          /*complain*/ true);
15205     return result;
15206   }
15207 
15208   // ARC unbridged casts.
15209   case BuiltinType::ARCUnbridgedCast: {
15210     Expr *realCast = stripARCUnbridgedCast(E);
15211     diagnoseARCUnbridgedCast(realCast);
15212     return realCast;
15213   }
15214 
15215   // Expressions of unknown type.
15216   case BuiltinType::UnknownAny:
15217     return diagnoseUnknownAnyExpr(*this, E);
15218 
15219   // Pseudo-objects.
15220   case BuiltinType::PseudoObject:
15221     return checkPseudoObjectRValue(E);
15222 
15223   case BuiltinType::BuiltinFn: {
15224     // Accept __noop without parens by implicitly converting it to a call expr.
15225     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15226     if (DRE) {
15227       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15228       if (FD->getBuiltinID() == Builtin::BI__noop) {
15229         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15230                               CK_BuiltinFnToFnPtr).get();
15231         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15232                                       VK_RValue, SourceLocation());
15233       }
15234     }
15235 
15236     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15237     return ExprError();
15238   }
15239 
15240   // Expressions of unknown type.
15241   case BuiltinType::OMPArraySection:
15242     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15243     return ExprError();
15244 
15245   // Everything else should be impossible.
15246 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15247   case BuiltinType::Id:
15248 #include "clang/Basic/OpenCLImageTypes.def"
15249 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15250 #define PLACEHOLDER_TYPE(Id, SingletonId)
15251 #include "clang/AST/BuiltinTypes.def"
15252     break;
15253   }
15254 
15255   llvm_unreachable("invalid placeholder type!");
15256 }
15257 
15258 bool Sema::CheckCaseExpression(Expr *E) {
15259   if (E->isTypeDependent())
15260     return true;
15261   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15262     return E->getType()->isIntegralOrEnumerationType();
15263   return false;
15264 }
15265 
15266 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15267 ExprResult
15268 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15269   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15270          "Unknown Objective-C Boolean value!");
15271   QualType BoolT = Context.ObjCBuiltinBoolTy;
15272   if (!Context.getBOOLDecl()) {
15273     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15274                         Sema::LookupOrdinaryName);
15275     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15276       NamedDecl *ND = Result.getFoundDecl();
15277       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15278         Context.setBOOLDecl(TD);
15279     }
15280   }
15281   if (Context.getBOOLDecl())
15282     BoolT = Context.getBOOLType();
15283   return new (Context)
15284       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15285 }
15286 
15287 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15288     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15289     SourceLocation RParen) {
15290 
15291   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15292 
15293   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15294                            [&](const AvailabilitySpec &Spec) {
15295                              return Spec.getPlatform() == Platform;
15296                            });
15297 
15298   VersionTuple Version;
15299   if (Spec != AvailSpecs.end())
15300     Version = Spec->getVersion();
15301 
15302   return new (Context)
15303       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15304 }
15305