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 "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.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 static AvailabilityResult
107 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
108                            const ObjCInterfaceDecl *UnknownObjCClass,
109                            bool ObjCPropertyAccess) {
110   // See if this declaration is unavailable or deprecated.
111   std::string Message;
112   AvailabilityResult Result = D->getAvailability(&Message);
113 
114   // For typedefs, if the typedef declaration appears available look
115   // to the underlying type to see if it is more restrictive.
116   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
117     if (Result == AR_Available) {
118       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
119         D = TT->getDecl();
120         Result = D->getAvailability(&Message);
121         continue;
122       }
123     }
124     break;
125   }
126 
127   // Forward class declarations get their attributes from their definition.
128   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
129     if (IDecl->getDefinition()) {
130       D = IDecl->getDefinition();
131       Result = D->getAvailability(&Message);
132     }
133   }
134 
135   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
136     if (Result == AR_Available) {
137       const DeclContext *DC = ECD->getDeclContext();
138       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
139         Result = TheEnumDecl->getAvailability(&Message);
140     }
141 
142   const ObjCPropertyDecl *ObjCPDecl = nullptr;
143   if (Result == AR_Deprecated || Result == AR_Unavailable ||
144       Result == AR_NotYetIntroduced) {
145     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
146       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
147         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
148         if (PDeclResult == Result)
149           ObjCPDecl = PD;
150       }
151     }
152   }
153 
154   switch (Result) {
155     case AR_Available:
156       break;
157 
158     case AR_Deprecated:
159       if (S.getCurContextAvailability() != AR_Deprecated)
160         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
161                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
162                                   ObjCPropertyAccess);
163       break;
164 
165     case AR_NotYetIntroduced: {
166       // Don't do this for enums, they can't be redeclared.
167       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
168         break;
169 
170       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
171       // Objective-C method declarations in categories are not modelled as
172       // redeclarations, so manually look for a redeclaration in a category
173       // if necessary.
174       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
175         Warn = false;
176       // In general, D will point to the most recent redeclaration. However,
177       // for `@class A;` decls, this isn't true -- manually go through the
178       // redecl chain in that case.
179       if (Warn && isa<ObjCInterfaceDecl>(D))
180         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
181              Redecl = Redecl->getPreviousDecl())
182           if (!Redecl->hasAttr<AvailabilityAttr>() ||
183               Redecl->getAttr<AvailabilityAttr>()->isInherited())
184             Warn = false;
185 
186       if (Warn)
187         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
188                                   UnknownObjCClass, ObjCPDecl,
189                                   ObjCPropertyAccess);
190       break;
191     }
192 
193     case AR_Unavailable:
194       if (S.getCurContextAvailability() != AR_Unavailable)
195         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
196                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
197                                   ObjCPropertyAccess);
198       break;
199 
200     }
201     return Result;
202 }
203 
204 /// \brief Emit a note explaining that this function is deleted.
205 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
206   assert(Decl->isDeleted());
207 
208   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
209 
210   if (Method && Method->isDeleted() && Method->isDefaulted()) {
211     // If the method was explicitly defaulted, point at that declaration.
212     if (!Method->isImplicit())
213       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
214 
215     // Try to diagnose why this special member function was implicitly
216     // deleted. This might fail, if that reason no longer applies.
217     CXXSpecialMember CSM = getSpecialMember(Method);
218     if (CSM != CXXInvalid)
219       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
220 
221     return;
222   }
223 
224   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
225     if (CXXConstructorDecl *BaseCD =
226             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
227       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
228       if (BaseCD->isDeleted()) {
229         NoteDeletedFunction(BaseCD);
230       } else {
231         // FIXME: An explanation of why exactly it can't be inherited
232         // would be nice.
233         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
234       }
235       return;
236     }
237   }
238 
239   Diag(Decl->getLocation(), diag::note_availability_specified_here)
240     << Decl << true;
241 }
242 
243 /// \brief Determine whether a FunctionDecl was ever declared with an
244 /// explicit storage class.
245 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
246   for (auto I : D->redecls()) {
247     if (I->getStorageClass() != SC_None)
248       return true;
249   }
250   return false;
251 }
252 
253 /// \brief Check whether we're in an extern inline function and referring to a
254 /// variable or function with internal linkage (C11 6.7.4p3).
255 ///
256 /// This is only a warning because we used to silently accept this code, but
257 /// in many cases it will not behave correctly. This is not enabled in C++ mode
258 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
259 /// and so while there may still be user mistakes, most of the time we can't
260 /// prove that there are errors.
261 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
262                                                       const NamedDecl *D,
263                                                       SourceLocation Loc) {
264   // This is disabled under C++; there are too many ways for this to fire in
265   // contexts where the warning is a false positive, or where it is technically
266   // correct but benign.
267   if (S.getLangOpts().CPlusPlus)
268     return;
269 
270   // Check if this is an inlined function or method.
271   FunctionDecl *Current = S.getCurFunctionDecl();
272   if (!Current)
273     return;
274   if (!Current->isInlined())
275     return;
276   if (!Current->isExternallyVisible())
277     return;
278 
279   // Check if the decl has internal linkage.
280   if (D->getFormalLinkage() != InternalLinkage)
281     return;
282 
283   // Downgrade from ExtWarn to Extension if
284   //  (1) the supposedly external inline function is in the main file,
285   //      and probably won't be included anywhere else.
286   //  (2) the thing we're referencing is a pure function.
287   //  (3) the thing we're referencing is another inline function.
288   // This last can give us false negatives, but it's better than warning on
289   // wrappers for simple C library functions.
290   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
291   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
292   if (!DowngradeWarning && UsedFn)
293     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
294 
295   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
296                                : diag::ext_internal_in_extern_inline)
297     << /*IsVar=*/!UsedFn << D;
298 
299   S.MaybeSuggestAddingStaticToDecl(Current);
300 
301   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
302       << D;
303 }
304 
305 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
306   const FunctionDecl *First = Cur->getFirstDecl();
307 
308   // Suggest "static" on the function, if possible.
309   if (!hasAnyExplicitStorageClass(First)) {
310     SourceLocation DeclBegin = First->getSourceRange().getBegin();
311     Diag(DeclBegin, diag::note_convert_inline_to_static)
312       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
313   }
314 }
315 
316 /// \brief Determine whether the use of this declaration is valid, and
317 /// emit any corresponding diagnostics.
318 ///
319 /// This routine diagnoses various problems with referencing
320 /// declarations that can occur when using a declaration. For example,
321 /// it might warn if a deprecated or unavailable declaration is being
322 /// used, or produce an error (and return true) if a C++0x deleted
323 /// function is being used.
324 ///
325 /// \returns true if there was an error (this declaration cannot be
326 /// referenced), false otherwise.
327 ///
328 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
329                              const ObjCInterfaceDecl *UnknownObjCClass,
330                              bool ObjCPropertyAccess) {
331   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
332     // If there were any diagnostics suppressed by template argument deduction,
333     // emit them now.
334     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
335     if (Pos != SuppressedDiagnostics.end()) {
336       for (const PartialDiagnosticAt &Suppressed : Pos->second)
337         Diag(Suppressed.first, Suppressed.second);
338 
339       // Clear out the list of suppressed diagnostics, so that we don't emit
340       // them again for this specialization. However, we don't obsolete this
341       // entry from the table, because we want to avoid ever emitting these
342       // diagnostics again.
343       Pos->second.clear();
344     }
345 
346     // C++ [basic.start.main]p3:
347     //   The function 'main' shall not be used within a program.
348     if (cast<FunctionDecl>(D)->isMain())
349       Diag(Loc, diag::ext_main_used);
350   }
351 
352   // See if this is an auto-typed variable whose initializer we are parsing.
353   if (ParsingInitForAutoVars.count(D)) {
354     const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
355 
356     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
357       << D->getDeclName() << (unsigned)AT->getKeyword();
358     return true;
359   }
360 
361   // See if this is a deleted function.
362   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
363     if (FD->isDeleted()) {
364       Diag(Loc, diag::err_deleted_function_use);
365       NoteDeletedFunction(FD);
366       return true;
367     }
368 
369     // If the function has a deduced return type, and we can't deduce it,
370     // then we can't use it either.
371     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
372         DeduceReturnType(FD, Loc))
373       return true;
374   }
375 
376   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
377   // Only the variables omp_in and omp_out are allowed in the combiner.
378   // Only the variables omp_priv and omp_orig are allowed in the
379   // initializer-clause.
380   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
381   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
382       isa<VarDecl>(D)) {
383     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
384         << getCurFunction()->HasOMPDeclareReductionCombiner;
385     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
386     return true;
387   }
388   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
389                              ObjCPropertyAccess);
390 
391   DiagnoseUnusedOfDecl(*this, D, Loc);
392 
393   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
394 
395   return false;
396 }
397 
398 /// \brief Retrieve the message suffix that should be added to a
399 /// diagnostic complaining about the given function being deleted or
400 /// unavailable.
401 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
402   std::string Message;
403   if (FD->getAvailability(&Message))
404     return ": " + Message;
405 
406   return std::string();
407 }
408 
409 /// DiagnoseSentinelCalls - This routine checks whether a call or
410 /// message-send is to a declaration with the sentinel attribute, and
411 /// if so, it checks that the requirements of the sentinel are
412 /// satisfied.
413 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
414                                  ArrayRef<Expr *> Args) {
415   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
416   if (!attr)
417     return;
418 
419   // The number of formal parameters of the declaration.
420   unsigned numFormalParams;
421 
422   // The kind of declaration.  This is also an index into a %select in
423   // the diagnostic.
424   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
425 
426   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
427     numFormalParams = MD->param_size();
428     calleeType = CT_Method;
429   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
430     numFormalParams = FD->param_size();
431     calleeType = CT_Function;
432   } else if (isa<VarDecl>(D)) {
433     QualType type = cast<ValueDecl>(D)->getType();
434     const FunctionType *fn = nullptr;
435     if (const PointerType *ptr = type->getAs<PointerType>()) {
436       fn = ptr->getPointeeType()->getAs<FunctionType>();
437       if (!fn) return;
438       calleeType = CT_Function;
439     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
440       fn = ptr->getPointeeType()->castAs<FunctionType>();
441       calleeType = CT_Block;
442     } else {
443       return;
444     }
445 
446     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
447       numFormalParams = proto->getNumParams();
448     } else {
449       numFormalParams = 0;
450     }
451   } else {
452     return;
453   }
454 
455   // "nullPos" is the number of formal parameters at the end which
456   // effectively count as part of the variadic arguments.  This is
457   // useful if you would prefer to not have *any* formal parameters,
458   // but the language forces you to have at least one.
459   unsigned nullPos = attr->getNullPos();
460   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
461   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
462 
463   // The number of arguments which should follow the sentinel.
464   unsigned numArgsAfterSentinel = attr->getSentinel();
465 
466   // If there aren't enough arguments for all the formal parameters,
467   // the sentinel, and the args after the sentinel, complain.
468   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
469     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
470     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
471     return;
472   }
473 
474   // Otherwise, find the sentinel expression.
475   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
476   if (!sentinelExpr) return;
477   if (sentinelExpr->isValueDependent()) return;
478   if (Context.isSentinelNullExpr(sentinelExpr)) return;
479 
480   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
481   // or 'NULL' if those are actually defined in the context.  Only use
482   // 'nil' for ObjC methods, where it's much more likely that the
483   // variadic arguments form a list of object pointers.
484   SourceLocation MissingNilLoc
485     = getLocForEndOfToken(sentinelExpr->getLocEnd());
486   std::string NullValue;
487   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
488     NullValue = "nil";
489   else if (getLangOpts().CPlusPlus11)
490     NullValue = "nullptr";
491   else if (PP.isMacroDefined("NULL"))
492     NullValue = "NULL";
493   else
494     NullValue = "(void*) 0";
495 
496   if (MissingNilLoc.isInvalid())
497     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
498   else
499     Diag(MissingNilLoc, diag::warn_missing_sentinel)
500       << int(calleeType)
501       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
502   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
503 }
504 
505 SourceRange Sema::getExprRange(Expr *E) const {
506   return E ? E->getSourceRange() : SourceRange();
507 }
508 
509 //===----------------------------------------------------------------------===//
510 //  Standard Promotions and Conversions
511 //===----------------------------------------------------------------------===//
512 
513 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
514 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
515   // Handle any placeholder expressions which made it here.
516   if (E->getType()->isPlaceholderType()) {
517     ExprResult result = CheckPlaceholderExpr(E);
518     if (result.isInvalid()) return ExprError();
519     E = result.get();
520   }
521 
522   QualType Ty = E->getType();
523   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
524 
525   if (Ty->isFunctionType()) {
526     // If we are here, we are not calling a function but taking
527     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
528     if (getLangOpts().OpenCL) {
529       if (Diagnose)
530         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
531       return ExprError();
532     }
533 
534     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
535       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
536         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
537           return ExprError();
538 
539     E = ImpCastExprToType(E, Context.getPointerType(Ty),
540                           CK_FunctionToPointerDecay).get();
541   } else if (Ty->isArrayType()) {
542     // In C90 mode, arrays only promote to pointers if the array expression is
543     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
544     // type 'array of type' is converted to an expression that has type 'pointer
545     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
546     // that has type 'array of type' ...".  The relevant change is "an lvalue"
547     // (C90) to "an expression" (C99).
548     //
549     // C++ 4.2p1:
550     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
551     // T" can be converted to an rvalue of type "pointer to T".
552     //
553     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
554       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
555                             CK_ArrayToPointerDecay).get();
556   }
557   return E;
558 }
559 
560 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
561   // Check to see if we are dereferencing a null pointer.  If so,
562   // and if not volatile-qualified, this is undefined behavior that the
563   // optimizer will delete, so warn about it.  People sometimes try to use this
564   // to get a deterministic trap and are surprised by clang's behavior.  This
565   // only handles the pattern "*null", which is a very syntactic check.
566   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
567     if (UO->getOpcode() == UO_Deref &&
568         UO->getSubExpr()->IgnoreParenCasts()->
569           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
570         !UO->getType().isVolatileQualified()) {
571     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
572                           S.PDiag(diag::warn_indirection_through_null)
573                             << UO->getSubExpr()->getSourceRange());
574     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575                         S.PDiag(diag::note_indirection_through_null));
576   }
577 }
578 
579 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
580                                     SourceLocation AssignLoc,
581                                     const Expr* RHS) {
582   const ObjCIvarDecl *IV = OIRE->getDecl();
583   if (!IV)
584     return;
585 
586   DeclarationName MemberName = IV->getDeclName();
587   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
588   if (!Member || !Member->isStr("isa"))
589     return;
590 
591   const Expr *Base = OIRE->getBase();
592   QualType BaseType = Base->getType();
593   if (OIRE->isArrow())
594     BaseType = BaseType->getPointeeType();
595   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
596     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
597       ObjCInterfaceDecl *ClassDeclared = nullptr;
598       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
599       if (!ClassDeclared->getSuperClass()
600           && (*ClassDeclared->ivar_begin()) == IV) {
601         if (RHS) {
602           NamedDecl *ObjectSetClass =
603             S.LookupSingleName(S.TUScope,
604                                &S.Context.Idents.get("object_setClass"),
605                                SourceLocation(), S.LookupOrdinaryName);
606           if (ObjectSetClass) {
607             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
608             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
609             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
610             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
611                                                      AssignLoc), ",") <<
612             FixItHint::CreateInsertion(RHSLocEnd, ")");
613           }
614           else
615             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
616         } else {
617           NamedDecl *ObjectGetClass =
618             S.LookupSingleName(S.TUScope,
619                                &S.Context.Idents.get("object_getClass"),
620                                SourceLocation(), S.LookupOrdinaryName);
621           if (ObjectGetClass)
622             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
623             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
624             FixItHint::CreateReplacement(
625                                          SourceRange(OIRE->getOpLoc(),
626                                                      OIRE->getLocEnd()), ")");
627           else
628             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
629         }
630         S.Diag(IV->getLocation(), diag::note_ivar_decl);
631       }
632     }
633 }
634 
635 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
636   // Handle any placeholder expressions which made it here.
637   if (E->getType()->isPlaceholderType()) {
638     ExprResult result = CheckPlaceholderExpr(E);
639     if (result.isInvalid()) return ExprError();
640     E = result.get();
641   }
642 
643   // C++ [conv.lval]p1:
644   //   A glvalue of a non-function, non-array type T can be
645   //   converted to a prvalue.
646   if (!E->isGLValue()) return E;
647 
648   QualType T = E->getType();
649   assert(!T.isNull() && "r-value conversion on typeless expression?");
650 
651   // We don't want to throw lvalue-to-rvalue casts on top of
652   // expressions of certain types in C++.
653   if (getLangOpts().CPlusPlus &&
654       (E->getType() == Context.OverloadTy ||
655        T->isDependentType() ||
656        T->isRecordType()))
657     return E;
658 
659   // The C standard is actually really unclear on this point, and
660   // DR106 tells us what the result should be but not why.  It's
661   // generally best to say that void types just doesn't undergo
662   // lvalue-to-rvalue at all.  Note that expressions of unqualified
663   // 'void' type are never l-values, but qualified void can be.
664   if (T->isVoidType())
665     return E;
666 
667   // OpenCL usually rejects direct accesses to values of 'half' type.
668   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
669       T->isHalfType()) {
670     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
671       << 0 << T;
672     return ExprError();
673   }
674 
675   CheckForNullPointerDereference(*this, E);
676   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
677     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
678                                      &Context.Idents.get("object_getClass"),
679                                      SourceLocation(), LookupOrdinaryName);
680     if (ObjectGetClass)
681       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
682         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
683         FixItHint::CreateReplacement(
684                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
685     else
686       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
687   }
688   else if (const ObjCIvarRefExpr *OIRE =
689             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
690     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
691 
692   // C++ [conv.lval]p1:
693   //   [...] If T is a non-class type, the type of the prvalue is the
694   //   cv-unqualified version of T. Otherwise, the type of the
695   //   rvalue is T.
696   //
697   // C99 6.3.2.1p2:
698   //   If the lvalue has qualified type, the value has the unqualified
699   //   version of the type of the lvalue; otherwise, the value has the
700   //   type of the lvalue.
701   if (T.hasQualifiers())
702     T = T.getUnqualifiedType();
703 
704   // Under the MS ABI, lock down the inheritance model now.
705   if (T->isMemberPointerType() &&
706       Context.getTargetInfo().getCXXABI().isMicrosoft())
707     (void)isCompleteType(E->getExprLoc(), T);
708 
709   UpdateMarkingForLValueToRValue(E);
710 
711   // Loading a __weak object implicitly retains the value, so we need a cleanup to
712   // balance that.
713   if (getLangOpts().ObjCAutoRefCount &&
714       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
715     ExprNeedsCleanups = true;
716 
717   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
718                                             nullptr, VK_RValue);
719 
720   // C11 6.3.2.1p2:
721   //   ... if the lvalue has atomic type, the value has the non-atomic version
722   //   of the type of the lvalue ...
723   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724     T = Atomic->getValueType().getUnqualifiedType();
725     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726                                    nullptr, VK_RValue);
727   }
728 
729   return Res;
730 }
731 
732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734   if (Res.isInvalid())
735     return ExprError();
736   Res = DefaultLvalueConversion(Res.get());
737   if (Res.isInvalid())
738     return ExprError();
739   return Res;
740 }
741 
742 /// CallExprUnaryConversions - a special case of an unary conversion
743 /// performed on a function designator of a call expression.
744 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745   QualType Ty = E->getType();
746   ExprResult Res = E;
747   // Only do implicit cast for a function type, but not for a pointer
748   // to function type.
749   if (Ty->isFunctionType()) {
750     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751                             CK_FunctionToPointerDecay).get();
752     if (Res.isInvalid())
753       return ExprError();
754   }
755   Res = DefaultLvalueConversion(Res.get());
756   if (Res.isInvalid())
757     return ExprError();
758   return Res.get();
759 }
760 
761 /// UsualUnaryConversions - Performs various conversions that are common to most
762 /// operators (C99 6.3). The conversions of array and function types are
763 /// sometimes suppressed. For example, the array->pointer conversion doesn't
764 /// apply if the array is an argument to the sizeof or address (&) operators.
765 /// In these instances, this routine should *not* be called.
766 ExprResult Sema::UsualUnaryConversions(Expr *E) {
767   // First, convert to an r-value.
768   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769   if (Res.isInvalid())
770     return ExprError();
771   E = Res.get();
772 
773   QualType Ty = E->getType();
774   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
775 
776   // Half FP have to be promoted to float unless it is natively supported
777   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
778     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
779 
780   // Try to perform integral promotions if the object has a theoretically
781   // promotable type.
782   if (Ty->isIntegralOrUnscopedEnumerationType()) {
783     // C99 6.3.1.1p2:
784     //
785     //   The following may be used in an expression wherever an int or
786     //   unsigned int may be used:
787     //     - an object or expression with an integer type whose integer
788     //       conversion rank is less than or equal to the rank of int
789     //       and unsigned int.
790     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
791     //
792     //   If an int can represent all values of the original type, the
793     //   value is converted to an int; otherwise, it is converted to an
794     //   unsigned int. These are called the integer promotions. All
795     //   other types are unchanged by the integer promotions.
796 
797     QualType PTy = Context.isPromotableBitField(E);
798     if (!PTy.isNull()) {
799       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
800       return E;
801     }
802     if (Ty->isPromotableIntegerType()) {
803       QualType PT = Context.getPromotedIntegerType(Ty);
804       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
805       return E;
806     }
807   }
808   return E;
809 }
810 
811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
812 /// do not have a prototype. Arguments that have type float or __fp16
813 /// are promoted to double. All other argument types are converted by
814 /// UsualUnaryConversions().
815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
816   QualType Ty = E->getType();
817   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
818 
819   ExprResult Res = UsualUnaryConversions(E);
820   if (Res.isInvalid())
821     return ExprError();
822   E = Res.get();
823 
824   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
825   // double.
826   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
827   if (BTy && (BTy->getKind() == BuiltinType::Half ||
828               BTy->getKind() == BuiltinType::Float))
829     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
830 
831   // C++ performs lvalue-to-rvalue conversion as a default argument
832   // promotion, even on class types, but note:
833   //   C++11 [conv.lval]p2:
834   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
835   //     operand or a subexpression thereof the value contained in the
836   //     referenced object is not accessed. Otherwise, if the glvalue
837   //     has a class type, the conversion copy-initializes a temporary
838   //     of type T from the glvalue and the result of the conversion
839   //     is a prvalue for the temporary.
840   // FIXME: add some way to gate this entire thing for correctness in
841   // potentially potentially evaluated contexts.
842   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
843     ExprResult Temp = PerformCopyInitialization(
844                        InitializedEntity::InitializeTemporary(E->getType()),
845                                                 E->getExprLoc(), E);
846     if (Temp.isInvalid())
847       return ExprError();
848     E = Temp.get();
849   }
850 
851   return E;
852 }
853 
854 /// Determine the degree of POD-ness for an expression.
855 /// Incomplete types are considered POD, since this check can be performed
856 /// when we're in an unevaluated context.
857 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
858   if (Ty->isIncompleteType()) {
859     // C++11 [expr.call]p7:
860     //   After these conversions, if the argument does not have arithmetic,
861     //   enumeration, pointer, pointer to member, or class type, the program
862     //   is ill-formed.
863     //
864     // Since we've already performed array-to-pointer and function-to-pointer
865     // decay, the only such type in C++ is cv void. This also handles
866     // initializer lists as variadic arguments.
867     if (Ty->isVoidType())
868       return VAK_Invalid;
869 
870     if (Ty->isObjCObjectType())
871       return VAK_Invalid;
872     return VAK_Valid;
873   }
874 
875   if (Ty.isCXX98PODType(Context))
876     return VAK_Valid;
877 
878   // C++11 [expr.call]p7:
879   //   Passing a potentially-evaluated argument of class type (Clause 9)
880   //   having a non-trivial copy constructor, a non-trivial move constructor,
881   //   or a non-trivial destructor, with no corresponding parameter,
882   //   is conditionally-supported with implementation-defined semantics.
883   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
884     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
885       if (!Record->hasNonTrivialCopyConstructor() &&
886           !Record->hasNonTrivialMoveConstructor() &&
887           !Record->hasNonTrivialDestructor())
888         return VAK_ValidInCXX11;
889 
890   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
891     return VAK_Valid;
892 
893   if (Ty->isObjCObjectType())
894     return VAK_Invalid;
895 
896   if (getLangOpts().MSVCCompat)
897     return VAK_MSVCUndefined;
898 
899   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
900   // permitted to reject them. We should consider doing so.
901   return VAK_Undefined;
902 }
903 
904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
905   // Don't allow one to pass an Objective-C interface to a vararg.
906   const QualType &Ty = E->getType();
907   VarArgKind VAK = isValidVarArgType(Ty);
908 
909   // Complain about passing non-POD types through varargs.
910   switch (VAK) {
911   case VAK_ValidInCXX11:
912     DiagRuntimeBehavior(
913         E->getLocStart(), nullptr,
914         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
915           << Ty << CT);
916     // Fall through.
917   case VAK_Valid:
918     if (Ty->isRecordType()) {
919       // This is unlikely to be what the user intended. If the class has a
920       // 'c_str' member function, the user probably meant to call that.
921       DiagRuntimeBehavior(E->getLocStart(), nullptr,
922                           PDiag(diag::warn_pass_class_arg_to_vararg)
923                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
924     }
925     break;
926 
927   case VAK_Undefined:
928   case VAK_MSVCUndefined:
929     DiagRuntimeBehavior(
930         E->getLocStart(), nullptr,
931         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
932           << getLangOpts().CPlusPlus11 << Ty << CT);
933     break;
934 
935   case VAK_Invalid:
936     if (Ty->isObjCObjectType())
937       DiagRuntimeBehavior(
938           E->getLocStart(), nullptr,
939           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
940             << Ty << CT);
941     else
942       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
943         << isa<InitListExpr>(E) << Ty << CT;
944     break;
945   }
946 }
947 
948 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
949 /// will create a trap if the resulting type is not a POD type.
950 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
951                                                   FunctionDecl *FDecl) {
952   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
953     // Strip the unbridged-cast placeholder expression off, if applicable.
954     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
955         (CT == VariadicMethod ||
956          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
957       E = stripARCUnbridgedCast(E);
958 
959     // Otherwise, do normal placeholder checking.
960     } else {
961       ExprResult ExprRes = CheckPlaceholderExpr(E);
962       if (ExprRes.isInvalid())
963         return ExprError();
964       E = ExprRes.get();
965     }
966   }
967 
968   ExprResult ExprRes = DefaultArgumentPromotion(E);
969   if (ExprRes.isInvalid())
970     return ExprError();
971   E = ExprRes.get();
972 
973   // Diagnostics regarding non-POD argument types are
974   // emitted along with format string checking in Sema::CheckFunctionCall().
975   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
976     // Turn this into a trap.
977     CXXScopeSpec SS;
978     SourceLocation TemplateKWLoc;
979     UnqualifiedId Name;
980     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
981                        E->getLocStart());
982     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
983                                           Name, true, false);
984     if (TrapFn.isInvalid())
985       return ExprError();
986 
987     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
988                                     E->getLocStart(), None,
989                                     E->getLocEnd());
990     if (Call.isInvalid())
991       return ExprError();
992 
993     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
994                                   Call.get(), E);
995     if (Comma.isInvalid())
996       return ExprError();
997     return Comma.get();
998   }
999 
1000   if (!getLangOpts().CPlusPlus &&
1001       RequireCompleteType(E->getExprLoc(), E->getType(),
1002                           diag::err_call_incomplete_argument))
1003     return ExprError();
1004 
1005   return E;
1006 }
1007 
1008 /// \brief Converts an integer to complex float type.  Helper function of
1009 /// UsualArithmeticConversions()
1010 ///
1011 /// \return false if the integer expression is an integer type and is
1012 /// successfully converted to the complex type.
1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1014                                                   ExprResult &ComplexExpr,
1015                                                   QualType IntTy,
1016                                                   QualType ComplexTy,
1017                                                   bool SkipCast) {
1018   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1019   if (SkipCast) return false;
1020   if (IntTy->isIntegerType()) {
1021     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1024                                   CK_FloatingRealToComplex);
1025   } else {
1026     assert(IntTy->isComplexIntegerType());
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_IntegralComplexToFloatingComplex);
1029   }
1030   return false;
1031 }
1032 
1033 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1034 /// UsualArithmeticConversions()
1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1036                                              ExprResult &RHS, QualType LHSType,
1037                                              QualType RHSType,
1038                                              bool IsCompAssign) {
1039   // if we have an integer operand, the result is the complex type.
1040   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1041                                              /*skipCast*/false))
1042     return LHSType;
1043   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1044                                              /*skipCast*/IsCompAssign))
1045     return RHSType;
1046 
1047   // This handles complex/complex, complex/float, or float/complex.
1048   // When both operands are complex, the shorter operand is converted to the
1049   // type of the longer, and that is the type of the result. This corresponds
1050   // to what is done when combining two real floating-point operands.
1051   // The fun begins when size promotion occur across type domains.
1052   // From H&S 6.3.4: When one operand is complex and the other is a real
1053   // floating-point type, the less precise type is converted, within it's
1054   // real or complex domain, to the precision of the other type. For example,
1055   // when combining a "long double" with a "double _Complex", the
1056   // "double _Complex" is promoted to "long double _Complex".
1057 
1058   // Compute the rank of the two types, regardless of whether they are complex.
1059   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1060 
1061   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1062   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1063   QualType LHSElementType =
1064       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1065   QualType RHSElementType =
1066       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1067 
1068   QualType ResultType = S.Context.getComplexType(LHSElementType);
1069   if (Order < 0) {
1070     // Promote the precision of the LHS if not an assignment.
1071     ResultType = S.Context.getComplexType(RHSElementType);
1072     if (!IsCompAssign) {
1073       if (LHSComplexType)
1074         LHS =
1075             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1076       else
1077         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1078     }
1079   } else if (Order > 0) {
1080     // Promote the precision of the RHS.
1081     if (RHSComplexType)
1082       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1083     else
1084       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1085   }
1086   return ResultType;
1087 }
1088 
1089 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1090 /// of UsualArithmeticConversions()
1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1092                                            ExprResult &IntExpr,
1093                                            QualType FloatTy, QualType IntTy,
1094                                            bool ConvertFloat, bool ConvertInt) {
1095   if (IntTy->isIntegerType()) {
1096     if (ConvertInt)
1097       // Convert intExpr to the lhs floating point type.
1098       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1099                                     CK_IntegralToFloating);
1100     return FloatTy;
1101   }
1102 
1103   // Convert both sides to the appropriate complex float.
1104   assert(IntTy->isComplexIntegerType());
1105   QualType result = S.Context.getComplexType(FloatTy);
1106 
1107   // _Complex int -> _Complex float
1108   if (ConvertInt)
1109     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1110                                   CK_IntegralComplexToFloatingComplex);
1111 
1112   // float -> _Complex float
1113   if (ConvertFloat)
1114     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1115                                     CK_FloatingRealToComplex);
1116 
1117   return result;
1118 }
1119 
1120 /// \brief Handle arithmethic conversion with floating point types.  Helper
1121 /// function of UsualArithmeticConversions()
1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1123                                       ExprResult &RHS, QualType LHSType,
1124                                       QualType RHSType, bool IsCompAssign) {
1125   bool LHSFloat = LHSType->isRealFloatingType();
1126   bool RHSFloat = RHSType->isRealFloatingType();
1127 
1128   // If we have two real floating types, convert the smaller operand
1129   // to the bigger result.
1130   if (LHSFloat && RHSFloat) {
1131     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1132     if (order > 0) {
1133       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1134       return LHSType;
1135     }
1136 
1137     assert(order < 0 && "illegal float comparison");
1138     if (!IsCompAssign)
1139       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1140     return RHSType;
1141   }
1142 
1143   if (LHSFloat) {
1144     // Half FP has to be promoted to float unless it is natively supported
1145     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1146       LHSType = S.Context.FloatTy;
1147 
1148     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1149                                       /*convertFloat=*/!IsCompAssign,
1150                                       /*convertInt=*/ true);
1151   }
1152   assert(RHSFloat);
1153   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1154                                     /*convertInt=*/ true,
1155                                     /*convertFloat=*/!IsCompAssign);
1156 }
1157 
1158 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1159 
1160 namespace {
1161 /// These helper callbacks are placed in an anonymous namespace to
1162 /// permit their use as function template parameters.
1163 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1164   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1165 }
1166 
1167 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1168   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1169                              CK_IntegralComplexCast);
1170 }
1171 }
1172 
1173 /// \brief Handle integer arithmetic conversions.  Helper function of
1174 /// UsualArithmeticConversions()
1175 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1176 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1177                                         ExprResult &RHS, QualType LHSType,
1178                                         QualType RHSType, bool IsCompAssign) {
1179   // The rules for this case are in C99 6.3.1.8
1180   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1181   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1182   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1183   if (LHSSigned == RHSSigned) {
1184     // Same signedness; use the higher-ranked type
1185     if (order >= 0) {
1186       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1187       return LHSType;
1188     } else if (!IsCompAssign)
1189       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1190     return RHSType;
1191   } else if (order != (LHSSigned ? 1 : -1)) {
1192     // The unsigned type has greater than or equal rank to the
1193     // signed type, so use the unsigned type
1194     if (RHSSigned) {
1195       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1196       return LHSType;
1197     } else if (!IsCompAssign)
1198       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1199     return RHSType;
1200   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1201     // The two types are different widths; if we are here, that
1202     // means the signed type is larger than the unsigned type, so
1203     // use the signed type.
1204     if (LHSSigned) {
1205       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1206       return LHSType;
1207     } else if (!IsCompAssign)
1208       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1209     return RHSType;
1210   } else {
1211     // The signed type is higher-ranked than the unsigned type,
1212     // but isn't actually any bigger (like unsigned int and long
1213     // on most 32-bit systems).  Use the unsigned type corresponding
1214     // to the signed type.
1215     QualType result =
1216       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1217     RHS = (*doRHSCast)(S, RHS.get(), result);
1218     if (!IsCompAssign)
1219       LHS = (*doLHSCast)(S, LHS.get(), result);
1220     return result;
1221   }
1222 }
1223 
1224 /// \brief Handle conversions with GCC complex int extension.  Helper function
1225 /// of UsualArithmeticConversions()
1226 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1227                                            ExprResult &RHS, QualType LHSType,
1228                                            QualType RHSType,
1229                                            bool IsCompAssign) {
1230   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1231   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1232 
1233   if (LHSComplexInt && RHSComplexInt) {
1234     QualType LHSEltType = LHSComplexInt->getElementType();
1235     QualType RHSEltType = RHSComplexInt->getElementType();
1236     QualType ScalarType =
1237       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1238         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1239 
1240     return S.Context.getComplexType(ScalarType);
1241   }
1242 
1243   if (LHSComplexInt) {
1244     QualType LHSEltType = LHSComplexInt->getElementType();
1245     QualType ScalarType =
1246       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1247         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1248     QualType ComplexType = S.Context.getComplexType(ScalarType);
1249     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1250                               CK_IntegralRealToComplex);
1251 
1252     return ComplexType;
1253   }
1254 
1255   assert(RHSComplexInt);
1256 
1257   QualType RHSEltType = RHSComplexInt->getElementType();
1258   QualType ScalarType =
1259     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1260       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1261   QualType ComplexType = S.Context.getComplexType(ScalarType);
1262 
1263   if (!IsCompAssign)
1264     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1265                               CK_IntegralRealToComplex);
1266   return ComplexType;
1267 }
1268 
1269 /// UsualArithmeticConversions - Performs various conversions that are common to
1270 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1271 /// routine returns the first non-arithmetic type found. The client is
1272 /// responsible for emitting appropriate error diagnostics.
1273 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1274                                           bool IsCompAssign) {
1275   if (!IsCompAssign) {
1276     LHS = UsualUnaryConversions(LHS.get());
1277     if (LHS.isInvalid())
1278       return QualType();
1279   }
1280 
1281   RHS = UsualUnaryConversions(RHS.get());
1282   if (RHS.isInvalid())
1283     return QualType();
1284 
1285   // For conversion purposes, we ignore any qualifiers.
1286   // For example, "const float" and "float" are equivalent.
1287   QualType LHSType =
1288     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1289   QualType RHSType =
1290     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1291 
1292   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1293   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1294     LHSType = AtomicLHS->getValueType();
1295 
1296   // If both types are identical, no conversion is needed.
1297   if (LHSType == RHSType)
1298     return LHSType;
1299 
1300   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1301   // The caller can deal with this (e.g. pointer + int).
1302   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1303     return QualType();
1304 
1305   // Apply unary and bitfield promotions to the LHS's type.
1306   QualType LHSUnpromotedType = LHSType;
1307   if (LHSType->isPromotableIntegerType())
1308     LHSType = Context.getPromotedIntegerType(LHSType);
1309   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1310   if (!LHSBitfieldPromoteTy.isNull())
1311     LHSType = LHSBitfieldPromoteTy;
1312   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1313     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1314 
1315   // If both types are identical, no conversion is needed.
1316   if (LHSType == RHSType)
1317     return LHSType;
1318 
1319   // At this point, we have two different arithmetic types.
1320 
1321   // Handle complex types first (C99 6.3.1.8p1).
1322   if (LHSType->isComplexType() || RHSType->isComplexType())
1323     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1324                                         IsCompAssign);
1325 
1326   // Now handle "real" floating types (i.e. float, double, long double).
1327   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1328     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1329                                  IsCompAssign);
1330 
1331   // Handle GCC complex int extension.
1332   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1333     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1334                                       IsCompAssign);
1335 
1336   // Finally, we have two differing integer types.
1337   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1338            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1339 }
1340 
1341 
1342 //===----------------------------------------------------------------------===//
1343 //  Semantic Analysis for various Expression Types
1344 //===----------------------------------------------------------------------===//
1345 
1346 
1347 ExprResult
1348 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1349                                 SourceLocation DefaultLoc,
1350                                 SourceLocation RParenLoc,
1351                                 Expr *ControllingExpr,
1352                                 ArrayRef<ParsedType> ArgTypes,
1353                                 ArrayRef<Expr *> ArgExprs) {
1354   unsigned NumAssocs = ArgTypes.size();
1355   assert(NumAssocs == ArgExprs.size());
1356 
1357   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1358   for (unsigned i = 0; i < NumAssocs; ++i) {
1359     if (ArgTypes[i])
1360       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1361     else
1362       Types[i] = nullptr;
1363   }
1364 
1365   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1366                                              ControllingExpr,
1367                                              llvm::makeArrayRef(Types, NumAssocs),
1368                                              ArgExprs);
1369   delete [] Types;
1370   return ER;
1371 }
1372 
1373 ExprResult
1374 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1375                                  SourceLocation DefaultLoc,
1376                                  SourceLocation RParenLoc,
1377                                  Expr *ControllingExpr,
1378                                  ArrayRef<TypeSourceInfo *> Types,
1379                                  ArrayRef<Expr *> Exprs) {
1380   unsigned NumAssocs = Types.size();
1381   assert(NumAssocs == Exprs.size());
1382 
1383   // Decay and strip qualifiers for the controlling expression type, and handle
1384   // placeholder type replacement. See committee discussion from WG14 DR423.
1385   {
1386     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1387     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1388     if (R.isInvalid())
1389       return ExprError();
1390     ControllingExpr = R.get();
1391   }
1392 
1393   // The controlling expression is an unevaluated operand, so side effects are
1394   // likely unintended.
1395   if (ActiveTemplateInstantiations.empty() &&
1396       ControllingExpr->HasSideEffects(Context, false))
1397     Diag(ControllingExpr->getExprLoc(),
1398          diag::warn_side_effects_unevaluated_context);
1399 
1400   bool TypeErrorFound = false,
1401        IsResultDependent = ControllingExpr->isTypeDependent(),
1402        ContainsUnexpandedParameterPack
1403          = ControllingExpr->containsUnexpandedParameterPack();
1404 
1405   for (unsigned i = 0; i < NumAssocs; ++i) {
1406     if (Exprs[i]->containsUnexpandedParameterPack())
1407       ContainsUnexpandedParameterPack = true;
1408 
1409     if (Types[i]) {
1410       if (Types[i]->getType()->containsUnexpandedParameterPack())
1411         ContainsUnexpandedParameterPack = true;
1412 
1413       if (Types[i]->getType()->isDependentType()) {
1414         IsResultDependent = true;
1415       } else {
1416         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1417         // complete object type other than a variably modified type."
1418         unsigned D = 0;
1419         if (Types[i]->getType()->isIncompleteType())
1420           D = diag::err_assoc_type_incomplete;
1421         else if (!Types[i]->getType()->isObjectType())
1422           D = diag::err_assoc_type_nonobject;
1423         else if (Types[i]->getType()->isVariablyModifiedType())
1424           D = diag::err_assoc_type_variably_modified;
1425 
1426         if (D != 0) {
1427           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1428             << Types[i]->getTypeLoc().getSourceRange()
1429             << Types[i]->getType();
1430           TypeErrorFound = true;
1431         }
1432 
1433         // C11 6.5.1.1p2 "No two generic associations in the same generic
1434         // selection shall specify compatible types."
1435         for (unsigned j = i+1; j < NumAssocs; ++j)
1436           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1437               Context.typesAreCompatible(Types[i]->getType(),
1438                                          Types[j]->getType())) {
1439             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1440                  diag::err_assoc_compatible_types)
1441               << Types[j]->getTypeLoc().getSourceRange()
1442               << Types[j]->getType()
1443               << Types[i]->getType();
1444             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1445                  diag::note_compat_assoc)
1446               << Types[i]->getTypeLoc().getSourceRange()
1447               << Types[i]->getType();
1448             TypeErrorFound = true;
1449           }
1450       }
1451     }
1452   }
1453   if (TypeErrorFound)
1454     return ExprError();
1455 
1456   // If we determined that the generic selection is result-dependent, don't
1457   // try to compute the result expression.
1458   if (IsResultDependent)
1459     return new (Context) GenericSelectionExpr(
1460         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1461         ContainsUnexpandedParameterPack);
1462 
1463   SmallVector<unsigned, 1> CompatIndices;
1464   unsigned DefaultIndex = -1U;
1465   for (unsigned i = 0; i < NumAssocs; ++i) {
1466     if (!Types[i])
1467       DefaultIndex = i;
1468     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1469                                         Types[i]->getType()))
1470       CompatIndices.push_back(i);
1471   }
1472 
1473   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1474   // type compatible with at most one of the types named in its generic
1475   // association list."
1476   if (CompatIndices.size() > 1) {
1477     // We strip parens here because the controlling expression is typically
1478     // parenthesized in macro definitions.
1479     ControllingExpr = ControllingExpr->IgnoreParens();
1480     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1481       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1482       << (unsigned) CompatIndices.size();
1483     for (unsigned I : CompatIndices) {
1484       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1485            diag::note_compat_assoc)
1486         << Types[I]->getTypeLoc().getSourceRange()
1487         << Types[I]->getType();
1488     }
1489     return ExprError();
1490   }
1491 
1492   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1493   // its controlling expression shall have type compatible with exactly one of
1494   // the types named in its generic association list."
1495   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1496     // We strip parens here because the controlling expression is typically
1497     // parenthesized in macro definitions.
1498     ControllingExpr = ControllingExpr->IgnoreParens();
1499     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1500       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1501     return ExprError();
1502   }
1503 
1504   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1505   // type name that is compatible with the type of the controlling expression,
1506   // then the result expression of the generic selection is the expression
1507   // in that generic association. Otherwise, the result expression of the
1508   // generic selection is the expression in the default generic association."
1509   unsigned ResultIndex =
1510     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1511 
1512   return new (Context) GenericSelectionExpr(
1513       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1514       ContainsUnexpandedParameterPack, ResultIndex);
1515 }
1516 
1517 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1518 /// location of the token and the offset of the ud-suffix within it.
1519 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1520                                      unsigned Offset) {
1521   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1522                                         S.getLangOpts());
1523 }
1524 
1525 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1526 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1527 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1528                                                  IdentifierInfo *UDSuffix,
1529                                                  SourceLocation UDSuffixLoc,
1530                                                  ArrayRef<Expr*> Args,
1531                                                  SourceLocation LitEndLoc) {
1532   assert(Args.size() <= 2 && "too many arguments for literal operator");
1533 
1534   QualType ArgTy[2];
1535   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1536     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1537     if (ArgTy[ArgIdx]->isArrayType())
1538       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1539   }
1540 
1541   DeclarationName OpName =
1542     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1543   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1544   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1545 
1546   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1547   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1548                               /*AllowRaw*/false, /*AllowTemplate*/false,
1549                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1550     return ExprError();
1551 
1552   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1553 }
1554 
1555 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1556 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1557 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1558 /// multiple tokens.  However, the common case is that StringToks points to one
1559 /// string.
1560 ///
1561 ExprResult
1562 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1563   assert(!StringToks.empty() && "Must have at least one string!");
1564 
1565   StringLiteralParser Literal(StringToks, PP);
1566   if (Literal.hadError)
1567     return ExprError();
1568 
1569   SmallVector<SourceLocation, 4> StringTokLocs;
1570   for (const Token &Tok : StringToks)
1571     StringTokLocs.push_back(Tok.getLocation());
1572 
1573   QualType CharTy = Context.CharTy;
1574   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1575   if (Literal.isWide()) {
1576     CharTy = Context.getWideCharType();
1577     Kind = StringLiteral::Wide;
1578   } else if (Literal.isUTF8()) {
1579     Kind = StringLiteral::UTF8;
1580   } else if (Literal.isUTF16()) {
1581     CharTy = Context.Char16Ty;
1582     Kind = StringLiteral::UTF16;
1583   } else if (Literal.isUTF32()) {
1584     CharTy = Context.Char32Ty;
1585     Kind = StringLiteral::UTF32;
1586   } else if (Literal.isPascal()) {
1587     CharTy = Context.UnsignedCharTy;
1588   }
1589 
1590   QualType CharTyConst = CharTy;
1591   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1592   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1593     CharTyConst.addConst();
1594 
1595   // Get an array type for the string, according to C99 6.4.5.  This includes
1596   // the nul terminator character as well as the string length for pascal
1597   // strings.
1598   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1599                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1600                                  ArrayType::Normal, 0);
1601 
1602   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1603   if (getLangOpts().OpenCL) {
1604     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1605   }
1606 
1607   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1608   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1609                                              Kind, Literal.Pascal, StrTy,
1610                                              &StringTokLocs[0],
1611                                              StringTokLocs.size());
1612   if (Literal.getUDSuffix().empty())
1613     return Lit;
1614 
1615   // We're building a user-defined literal.
1616   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1617   SourceLocation UDSuffixLoc =
1618     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1619                    Literal.getUDSuffixOffset());
1620 
1621   // Make sure we're allowed user-defined literals here.
1622   if (!UDLScope)
1623     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1624 
1625   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1626   //   operator "" X (str, len)
1627   QualType SizeType = Context.getSizeType();
1628 
1629   DeclarationName OpName =
1630     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1631   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1632   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1633 
1634   QualType ArgTy[] = {
1635     Context.getArrayDecayedType(StrTy), SizeType
1636   };
1637 
1638   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1639   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1640                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1641                                 /*AllowStringTemplate*/true)) {
1642 
1643   case LOLR_Cooked: {
1644     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1645     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1646                                                     StringTokLocs[0]);
1647     Expr *Args[] = { Lit, LenArg };
1648 
1649     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1650   }
1651 
1652   case LOLR_StringTemplate: {
1653     TemplateArgumentListInfo ExplicitArgs;
1654 
1655     unsigned CharBits = Context.getIntWidth(CharTy);
1656     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1657     llvm::APSInt Value(CharBits, CharIsUnsigned);
1658 
1659     TemplateArgument TypeArg(CharTy);
1660     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1661     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1662 
1663     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1664       Value = Lit->getCodeUnit(I);
1665       TemplateArgument Arg(Context, Value, CharTy);
1666       TemplateArgumentLocInfo ArgInfo;
1667       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1668     }
1669     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1670                                     &ExplicitArgs);
1671   }
1672   case LOLR_Raw:
1673   case LOLR_Template:
1674     llvm_unreachable("unexpected literal operator lookup result");
1675   case LOLR_Error:
1676     return ExprError();
1677   }
1678   llvm_unreachable("unexpected literal operator lookup result");
1679 }
1680 
1681 ExprResult
1682 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1683                        SourceLocation Loc,
1684                        const CXXScopeSpec *SS) {
1685   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1686   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1687 }
1688 
1689 /// BuildDeclRefExpr - Build an expression that references a
1690 /// declaration that does not require a closure capture.
1691 ExprResult
1692 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1693                        const DeclarationNameInfo &NameInfo,
1694                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1695                        const TemplateArgumentListInfo *TemplateArgs) {
1696   if (getLangOpts().CUDA)
1697     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1698       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1699         if (CheckCUDATarget(Caller, Callee)) {
1700           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1701             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1702             << IdentifyCUDATarget(Caller);
1703           Diag(D->getLocation(), diag::note_previous_decl)
1704             << D->getIdentifier();
1705           return ExprError();
1706         }
1707       }
1708 
1709   bool RefersToCapturedVariable =
1710       isa<VarDecl>(D) &&
1711       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1712 
1713   DeclRefExpr *E;
1714   if (isa<VarTemplateSpecializationDecl>(D)) {
1715     VarTemplateSpecializationDecl *VarSpec =
1716         cast<VarTemplateSpecializationDecl>(D);
1717 
1718     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1719                                         : NestedNameSpecifierLoc(),
1720                             VarSpec->getTemplateKeywordLoc(), D,
1721                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1722                             FoundD, TemplateArgs);
1723   } else {
1724     assert(!TemplateArgs && "No template arguments for non-variable"
1725                             " template specialization references");
1726     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1727                                         : NestedNameSpecifierLoc(),
1728                             SourceLocation(), D, RefersToCapturedVariable,
1729                             NameInfo, Ty, VK, FoundD);
1730   }
1731 
1732   MarkDeclRefReferenced(E);
1733 
1734   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1735       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1736       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1737       recordUseOfEvaluatedWeak(E);
1738 
1739   // Just in case we're building an illegal pointer-to-member.
1740   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1741   if (FD && FD->isBitField())
1742     E->setObjectKind(OK_BitField);
1743 
1744   return E;
1745 }
1746 
1747 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1748 /// possibly a list of template arguments.
1749 ///
1750 /// If this produces template arguments, it is permitted to call
1751 /// DecomposeTemplateName.
1752 ///
1753 /// This actually loses a lot of source location information for
1754 /// non-standard name kinds; we should consider preserving that in
1755 /// some way.
1756 void
1757 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1758                              TemplateArgumentListInfo &Buffer,
1759                              DeclarationNameInfo &NameInfo,
1760                              const TemplateArgumentListInfo *&TemplateArgs) {
1761   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1762     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1763     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1764 
1765     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1766                                        Id.TemplateId->NumArgs);
1767     translateTemplateArguments(TemplateArgsPtr, Buffer);
1768 
1769     TemplateName TName = Id.TemplateId->Template.get();
1770     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1771     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1772     TemplateArgs = &Buffer;
1773   } else {
1774     NameInfo = GetNameFromUnqualifiedId(Id);
1775     TemplateArgs = nullptr;
1776   }
1777 }
1778 
1779 static void emitEmptyLookupTypoDiagnostic(
1780     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1781     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1782     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1783   DeclContext *Ctx =
1784       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1785   if (!TC) {
1786     // Emit a special diagnostic for failed member lookups.
1787     // FIXME: computing the declaration context might fail here (?)
1788     if (Ctx)
1789       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1790                                                  << SS.getRange();
1791     else
1792       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1793     return;
1794   }
1795 
1796   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1797   bool DroppedSpecifier =
1798       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1799   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1800                         ? diag::note_implicit_param_decl
1801                         : diag::note_previous_decl;
1802   if (!Ctx)
1803     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1804                          SemaRef.PDiag(NoteID));
1805   else
1806     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1807                                  << Typo << Ctx << DroppedSpecifier
1808                                  << SS.getRange(),
1809                          SemaRef.PDiag(NoteID));
1810 }
1811 
1812 /// Diagnose an empty lookup.
1813 ///
1814 /// \return false if new lookup candidates were found
1815 bool
1816 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1817                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1818                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1819                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1820   DeclarationName Name = R.getLookupName();
1821 
1822   unsigned diagnostic = diag::err_undeclared_var_use;
1823   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1824   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1825       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1826       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1827     diagnostic = diag::err_undeclared_use;
1828     diagnostic_suggest = diag::err_undeclared_use_suggest;
1829   }
1830 
1831   // If the original lookup was an unqualified lookup, fake an
1832   // unqualified lookup.  This is useful when (for example) the
1833   // original lookup would not have found something because it was a
1834   // dependent name.
1835   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1836   while (DC) {
1837     if (isa<CXXRecordDecl>(DC)) {
1838       LookupQualifiedName(R, DC);
1839 
1840       if (!R.empty()) {
1841         // Don't give errors about ambiguities in this lookup.
1842         R.suppressDiagnostics();
1843 
1844         // During a default argument instantiation the CurContext points
1845         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1846         // function parameter list, hence add an explicit check.
1847         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1848                               ActiveTemplateInstantiations.back().Kind ==
1849             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1850         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1851         bool isInstance = CurMethod &&
1852                           CurMethod->isInstance() &&
1853                           DC == CurMethod->getParent() && !isDefaultArgument;
1854 
1855         // Give a code modification hint to insert 'this->'.
1856         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1857         // Actually quite difficult!
1858         if (getLangOpts().MSVCCompat)
1859           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1860         if (isInstance) {
1861           Diag(R.getNameLoc(), diagnostic) << Name
1862             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1863           CheckCXXThisCapture(R.getNameLoc());
1864         } else {
1865           Diag(R.getNameLoc(), diagnostic) << Name;
1866         }
1867 
1868         // Do we really want to note all of these?
1869         for (NamedDecl *D : R)
1870           Diag(D->getLocation(), diag::note_dependent_var_use);
1871 
1872         // Return true if we are inside a default argument instantiation
1873         // and the found name refers to an instance member function, otherwise
1874         // the function calling DiagnoseEmptyLookup will try to create an
1875         // implicit member call and this is wrong for default argument.
1876         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1877           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1878           return true;
1879         }
1880 
1881         // Tell the callee to try to recover.
1882         return false;
1883       }
1884 
1885       R.clear();
1886     }
1887 
1888     // In Microsoft mode, if we are performing lookup from within a friend
1889     // function definition declared at class scope then we must set
1890     // DC to the lexical parent to be able to search into the parent
1891     // class.
1892     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1893         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1894         DC->getLexicalParent()->isRecord())
1895       DC = DC->getLexicalParent();
1896     else
1897       DC = DC->getParent();
1898   }
1899 
1900   // We didn't find anything, so try to correct for a typo.
1901   TypoCorrection Corrected;
1902   if (S && Out) {
1903     SourceLocation TypoLoc = R.getNameLoc();
1904     assert(!ExplicitTemplateArgs &&
1905            "Diagnosing an empty lookup with explicit template args!");
1906     *Out = CorrectTypoDelayed(
1907         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1908         [=](const TypoCorrection &TC) {
1909           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1910                                         diagnostic, diagnostic_suggest);
1911         },
1912         nullptr, CTK_ErrorRecovery);
1913     if (*Out)
1914       return true;
1915   } else if (S && (Corrected =
1916                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1917                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1918     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1919     bool DroppedSpecifier =
1920         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1921     R.setLookupName(Corrected.getCorrection());
1922 
1923     bool AcceptableWithRecovery = false;
1924     bool AcceptableWithoutRecovery = false;
1925     NamedDecl *ND = Corrected.getFoundDecl();
1926     if (ND) {
1927       if (Corrected.isOverloaded()) {
1928         OverloadCandidateSet OCS(R.getNameLoc(),
1929                                  OverloadCandidateSet::CSK_Normal);
1930         OverloadCandidateSet::iterator Best;
1931         for (NamedDecl *CD : Corrected) {
1932           if (FunctionTemplateDecl *FTD =
1933                    dyn_cast<FunctionTemplateDecl>(CD))
1934             AddTemplateOverloadCandidate(
1935                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1936                 Args, OCS);
1937           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1938             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1939               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1940                                    Args, OCS);
1941         }
1942         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1943         case OR_Success:
1944           ND = Best->FoundDecl;
1945           Corrected.setCorrectionDecl(ND);
1946           break;
1947         default:
1948           // FIXME: Arbitrarily pick the first declaration for the note.
1949           Corrected.setCorrectionDecl(ND);
1950           break;
1951         }
1952       }
1953       R.addDecl(ND);
1954       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1955         CXXRecordDecl *Record = nullptr;
1956         if (Corrected.getCorrectionSpecifier()) {
1957           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1958           Record = Ty->getAsCXXRecordDecl();
1959         }
1960         if (!Record)
1961           Record = cast<CXXRecordDecl>(
1962               ND->getDeclContext()->getRedeclContext());
1963         R.setNamingClass(Record);
1964       }
1965 
1966       auto *UnderlyingND = ND->getUnderlyingDecl();
1967       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1968                                isa<FunctionTemplateDecl>(UnderlyingND);
1969       // FIXME: If we ended up with a typo for a type name or
1970       // Objective-C class name, we're in trouble because the parser
1971       // is in the wrong place to recover. Suggest the typo
1972       // correction, but don't make it a fix-it since we're not going
1973       // to recover well anyway.
1974       AcceptableWithoutRecovery =
1975           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1976     } else {
1977       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1978       // because we aren't able to recover.
1979       AcceptableWithoutRecovery = true;
1980     }
1981 
1982     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1983       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1984                             ? diag::note_implicit_param_decl
1985                             : diag::note_previous_decl;
1986       if (SS.isEmpty())
1987         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1988                      PDiag(NoteID), AcceptableWithRecovery);
1989       else
1990         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1991                                   << Name << computeDeclContext(SS, false)
1992                                   << DroppedSpecifier << SS.getRange(),
1993                      PDiag(NoteID), AcceptableWithRecovery);
1994 
1995       // Tell the callee whether to try to recover.
1996       return !AcceptableWithRecovery;
1997     }
1998   }
1999   R.clear();
2000 
2001   // Emit a special diagnostic for failed member lookups.
2002   // FIXME: computing the declaration context might fail here (?)
2003   if (!SS.isEmpty()) {
2004     Diag(R.getNameLoc(), diag::err_no_member)
2005       << Name << computeDeclContext(SS, false)
2006       << SS.getRange();
2007     return true;
2008   }
2009 
2010   // Give up, we can't recover.
2011   Diag(R.getNameLoc(), diagnostic) << Name;
2012   return true;
2013 }
2014 
2015 /// In Microsoft mode, if we are inside a template class whose parent class has
2016 /// dependent base classes, and we can't resolve an unqualified identifier, then
2017 /// assume the identifier is a member of a dependent base class.  We can only
2018 /// recover successfully in static methods, instance methods, and other contexts
2019 /// where 'this' is available.  This doesn't precisely match MSVC's
2020 /// instantiation model, but it's close enough.
2021 static Expr *
2022 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2023                                DeclarationNameInfo &NameInfo,
2024                                SourceLocation TemplateKWLoc,
2025                                const TemplateArgumentListInfo *TemplateArgs) {
2026   // Only try to recover from lookup into dependent bases in static methods or
2027   // contexts where 'this' is available.
2028   QualType ThisType = S.getCurrentThisType();
2029   const CXXRecordDecl *RD = nullptr;
2030   if (!ThisType.isNull())
2031     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2032   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2033     RD = MD->getParent();
2034   if (!RD || !RD->hasAnyDependentBases())
2035     return nullptr;
2036 
2037   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2038   // is available, suggest inserting 'this->' as a fixit.
2039   SourceLocation Loc = NameInfo.getLoc();
2040   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2041   DB << NameInfo.getName() << RD;
2042 
2043   if (!ThisType.isNull()) {
2044     DB << FixItHint::CreateInsertion(Loc, "this->");
2045     return CXXDependentScopeMemberExpr::Create(
2046         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2047         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2048         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2049   }
2050 
2051   // Synthesize a fake NNS that points to the derived class.  This will
2052   // perform name lookup during template instantiation.
2053   CXXScopeSpec SS;
2054   auto *NNS =
2055       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2056   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2057   return DependentScopeDeclRefExpr::Create(
2058       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2059       TemplateArgs);
2060 }
2061 
2062 ExprResult
2063 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2064                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2065                         bool HasTrailingLParen, bool IsAddressOfOperand,
2066                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2067                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2068   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2069          "cannot be direct & operand and have a trailing lparen");
2070   if (SS.isInvalid())
2071     return ExprError();
2072 
2073   TemplateArgumentListInfo TemplateArgsBuffer;
2074 
2075   // Decompose the UnqualifiedId into the following data.
2076   DeclarationNameInfo NameInfo;
2077   const TemplateArgumentListInfo *TemplateArgs;
2078   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2079 
2080   DeclarationName Name = NameInfo.getName();
2081   IdentifierInfo *II = Name.getAsIdentifierInfo();
2082   SourceLocation NameLoc = NameInfo.getLoc();
2083 
2084   // C++ [temp.dep.expr]p3:
2085   //   An id-expression is type-dependent if it contains:
2086   //     -- an identifier that was declared with a dependent type,
2087   //        (note: handled after lookup)
2088   //     -- a template-id that is dependent,
2089   //        (note: handled in BuildTemplateIdExpr)
2090   //     -- a conversion-function-id that specifies a dependent type,
2091   //     -- a nested-name-specifier that contains a class-name that
2092   //        names a dependent type.
2093   // Determine whether this is a member of an unknown specialization;
2094   // we need to handle these differently.
2095   bool DependentID = false;
2096   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2097       Name.getCXXNameType()->isDependentType()) {
2098     DependentID = true;
2099   } else if (SS.isSet()) {
2100     if (DeclContext *DC = computeDeclContext(SS, false)) {
2101       if (RequireCompleteDeclContext(SS, DC))
2102         return ExprError();
2103     } else {
2104       DependentID = true;
2105     }
2106   }
2107 
2108   if (DependentID)
2109     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2110                                       IsAddressOfOperand, TemplateArgs);
2111 
2112   // Perform the required lookup.
2113   LookupResult R(*this, NameInfo,
2114                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2115                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2116   if (TemplateArgs) {
2117     // Lookup the template name again to correctly establish the context in
2118     // which it was found. This is really unfortunate as we already did the
2119     // lookup to determine that it was a template name in the first place. If
2120     // this becomes a performance hit, we can work harder to preserve those
2121     // results until we get here but it's likely not worth it.
2122     bool MemberOfUnknownSpecialization;
2123     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2124                        MemberOfUnknownSpecialization);
2125 
2126     if (MemberOfUnknownSpecialization ||
2127         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2128       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2129                                         IsAddressOfOperand, TemplateArgs);
2130   } else {
2131     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2132     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2133 
2134     // If the result might be in a dependent base class, this is a dependent
2135     // id-expression.
2136     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2137       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2138                                         IsAddressOfOperand, TemplateArgs);
2139 
2140     // If this reference is in an Objective-C method, then we need to do
2141     // some special Objective-C lookup, too.
2142     if (IvarLookupFollowUp) {
2143       ExprResult E(LookupInObjCMethod(R, S, II, true));
2144       if (E.isInvalid())
2145         return ExprError();
2146 
2147       if (Expr *Ex = E.getAs<Expr>())
2148         return Ex;
2149     }
2150   }
2151 
2152   if (R.isAmbiguous())
2153     return ExprError();
2154 
2155   // This could be an implicitly declared function reference (legal in C90,
2156   // extension in C99, forbidden in C++).
2157   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2158     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2159     if (D) R.addDecl(D);
2160   }
2161 
2162   // Determine whether this name might be a candidate for
2163   // argument-dependent lookup.
2164   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2165 
2166   if (R.empty() && !ADL) {
2167     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2168       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2169                                                    TemplateKWLoc, TemplateArgs))
2170         return E;
2171     }
2172 
2173     // Don't diagnose an empty lookup for inline assembly.
2174     if (IsInlineAsmIdentifier)
2175       return ExprError();
2176 
2177     // If this name wasn't predeclared and if this is not a function
2178     // call, diagnose the problem.
2179     TypoExpr *TE = nullptr;
2180     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2181         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2182     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2183     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2184            "Typo correction callback misconfigured");
2185     if (CCC) {
2186       // Make sure the callback knows what the typo being diagnosed is.
2187       CCC->setTypoName(II);
2188       if (SS.isValid())
2189         CCC->setTypoNNS(SS.getScopeRep());
2190     }
2191     if (DiagnoseEmptyLookup(S, SS, R,
2192                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2193                             nullptr, None, &TE)) {
2194       if (TE && KeywordReplacement) {
2195         auto &State = getTypoExprState(TE);
2196         auto BestTC = State.Consumer->getNextCorrection();
2197         if (BestTC.isKeyword()) {
2198           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2199           if (State.DiagHandler)
2200             State.DiagHandler(BestTC);
2201           KeywordReplacement->startToken();
2202           KeywordReplacement->setKind(II->getTokenID());
2203           KeywordReplacement->setIdentifierInfo(II);
2204           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2205           // Clean up the state associated with the TypoExpr, since it has
2206           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2207           clearDelayedTypo(TE);
2208           // Signal that a correction to a keyword was performed by returning a
2209           // valid-but-null ExprResult.
2210           return (Expr*)nullptr;
2211         }
2212         State.Consumer->resetCorrectionStream();
2213       }
2214       return TE ? TE : ExprError();
2215     }
2216 
2217     assert(!R.empty() &&
2218            "DiagnoseEmptyLookup returned false but added no results");
2219 
2220     // If we found an Objective-C instance variable, let
2221     // LookupInObjCMethod build the appropriate expression to
2222     // reference the ivar.
2223     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2224       R.clear();
2225       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2226       // In a hopelessly buggy code, Objective-C instance variable
2227       // lookup fails and no expression will be built to reference it.
2228       if (!E.isInvalid() && !E.get())
2229         return ExprError();
2230       return E;
2231     }
2232   }
2233 
2234   // This is guaranteed from this point on.
2235   assert(!R.empty() || ADL);
2236 
2237   // Check whether this might be a C++ implicit instance member access.
2238   // C++ [class.mfct.non-static]p3:
2239   //   When an id-expression that is not part of a class member access
2240   //   syntax and not used to form a pointer to member is used in the
2241   //   body of a non-static member function of class X, if name lookup
2242   //   resolves the name in the id-expression to a non-static non-type
2243   //   member of some class C, the id-expression is transformed into a
2244   //   class member access expression using (*this) as the
2245   //   postfix-expression to the left of the . operator.
2246   //
2247   // But we don't actually need to do this for '&' operands if R
2248   // resolved to a function or overloaded function set, because the
2249   // expression is ill-formed if it actually works out to be a
2250   // non-static member function:
2251   //
2252   // C++ [expr.ref]p4:
2253   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2254   //   [t]he expression can be used only as the left-hand operand of a
2255   //   member function call.
2256   //
2257   // There are other safeguards against such uses, but it's important
2258   // to get this right here so that we don't end up making a
2259   // spuriously dependent expression if we're inside a dependent
2260   // instance method.
2261   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2262     bool MightBeImplicitMember;
2263     if (!IsAddressOfOperand)
2264       MightBeImplicitMember = true;
2265     else if (!SS.isEmpty())
2266       MightBeImplicitMember = false;
2267     else if (R.isOverloadedResult())
2268       MightBeImplicitMember = false;
2269     else if (R.isUnresolvableResult())
2270       MightBeImplicitMember = true;
2271     else
2272       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2273                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2274                               isa<MSPropertyDecl>(R.getFoundDecl());
2275 
2276     if (MightBeImplicitMember)
2277       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2278                                              R, TemplateArgs, S);
2279   }
2280 
2281   if (TemplateArgs || TemplateKWLoc.isValid()) {
2282 
2283     // In C++1y, if this is a variable template id, then check it
2284     // in BuildTemplateIdExpr().
2285     // The single lookup result must be a variable template declaration.
2286     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2287         Id.TemplateId->Kind == TNK_Var_template) {
2288       assert(R.getAsSingle<VarTemplateDecl>() &&
2289              "There should only be one declaration found.");
2290     }
2291 
2292     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2293   }
2294 
2295   return BuildDeclarationNameExpr(SS, R, ADL);
2296 }
2297 
2298 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2299 /// declaration name, generally during template instantiation.
2300 /// There's a large number of things which don't need to be done along
2301 /// this path.
2302 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2303     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2304     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2305   DeclContext *DC = computeDeclContext(SS, false);
2306   if (!DC)
2307     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2308                                      NameInfo, /*TemplateArgs=*/nullptr);
2309 
2310   if (RequireCompleteDeclContext(SS, DC))
2311     return ExprError();
2312 
2313   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2314   LookupQualifiedName(R, DC);
2315 
2316   if (R.isAmbiguous())
2317     return ExprError();
2318 
2319   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2320     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2321                                      NameInfo, /*TemplateArgs=*/nullptr);
2322 
2323   if (R.empty()) {
2324     Diag(NameInfo.getLoc(), diag::err_no_member)
2325       << NameInfo.getName() << DC << SS.getRange();
2326     return ExprError();
2327   }
2328 
2329   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2330     // Diagnose a missing typename if this resolved unambiguously to a type in
2331     // a dependent context.  If we can recover with a type, downgrade this to
2332     // a warning in Microsoft compatibility mode.
2333     unsigned DiagID = diag::err_typename_missing;
2334     if (RecoveryTSI && getLangOpts().MSVCCompat)
2335       DiagID = diag::ext_typename_missing;
2336     SourceLocation Loc = SS.getBeginLoc();
2337     auto D = Diag(Loc, DiagID);
2338     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2339       << SourceRange(Loc, NameInfo.getEndLoc());
2340 
2341     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2342     // context.
2343     if (!RecoveryTSI)
2344       return ExprError();
2345 
2346     // Only issue the fixit if we're prepared to recover.
2347     D << FixItHint::CreateInsertion(Loc, "typename ");
2348 
2349     // Recover by pretending this was an elaborated type.
2350     QualType Ty = Context.getTypeDeclType(TD);
2351     TypeLocBuilder TLB;
2352     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2353 
2354     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2355     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2356     QTL.setElaboratedKeywordLoc(SourceLocation());
2357     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2358 
2359     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2360 
2361     return ExprEmpty();
2362   }
2363 
2364   // Defend against this resolving to an implicit member access. We usually
2365   // won't get here if this might be a legitimate a class member (we end up in
2366   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2367   // a pointer-to-member or in an unevaluated context in C++11.
2368   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2369     return BuildPossibleImplicitMemberExpr(SS,
2370                                            /*TemplateKWLoc=*/SourceLocation(),
2371                                            R, /*TemplateArgs=*/nullptr, S);
2372 
2373   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2374 }
2375 
2376 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2377 /// detected that we're currently inside an ObjC method.  Perform some
2378 /// additional lookup.
2379 ///
2380 /// Ideally, most of this would be done by lookup, but there's
2381 /// actually quite a lot of extra work involved.
2382 ///
2383 /// Returns a null sentinel to indicate trivial success.
2384 ExprResult
2385 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2386                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2387   SourceLocation Loc = Lookup.getNameLoc();
2388   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2389 
2390   // Check for error condition which is already reported.
2391   if (!CurMethod)
2392     return ExprError();
2393 
2394   // There are two cases to handle here.  1) scoped lookup could have failed,
2395   // in which case we should look for an ivar.  2) scoped lookup could have
2396   // found a decl, but that decl is outside the current instance method (i.e.
2397   // a global variable).  In these two cases, we do a lookup for an ivar with
2398   // this name, if the lookup sucedes, we replace it our current decl.
2399 
2400   // If we're in a class method, we don't normally want to look for
2401   // ivars.  But if we don't find anything else, and there's an
2402   // ivar, that's an error.
2403   bool IsClassMethod = CurMethod->isClassMethod();
2404 
2405   bool LookForIvars;
2406   if (Lookup.empty())
2407     LookForIvars = true;
2408   else if (IsClassMethod)
2409     LookForIvars = false;
2410   else
2411     LookForIvars = (Lookup.isSingleResult() &&
2412                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2413   ObjCInterfaceDecl *IFace = nullptr;
2414   if (LookForIvars) {
2415     IFace = CurMethod->getClassInterface();
2416     ObjCInterfaceDecl *ClassDeclared;
2417     ObjCIvarDecl *IV = nullptr;
2418     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2419       // Diagnose using an ivar in a class method.
2420       if (IsClassMethod)
2421         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2422                          << IV->getDeclName());
2423 
2424       // If we're referencing an invalid decl, just return this as a silent
2425       // error node.  The error diagnostic was already emitted on the decl.
2426       if (IV->isInvalidDecl())
2427         return ExprError();
2428 
2429       // Check if referencing a field with __attribute__((deprecated)).
2430       if (DiagnoseUseOfDecl(IV, Loc))
2431         return ExprError();
2432 
2433       // Diagnose the use of an ivar outside of the declaring class.
2434       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2435           !declaresSameEntity(ClassDeclared, IFace) &&
2436           !getLangOpts().DebuggerSupport)
2437         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2438 
2439       // FIXME: This should use a new expr for a direct reference, don't
2440       // turn this into Self->ivar, just return a BareIVarExpr or something.
2441       IdentifierInfo &II = Context.Idents.get("self");
2442       UnqualifiedId SelfName;
2443       SelfName.setIdentifier(&II, SourceLocation());
2444       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2445       CXXScopeSpec SelfScopeSpec;
2446       SourceLocation TemplateKWLoc;
2447       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2448                                               SelfName, false, false);
2449       if (SelfExpr.isInvalid())
2450         return ExprError();
2451 
2452       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2453       if (SelfExpr.isInvalid())
2454         return ExprError();
2455 
2456       MarkAnyDeclReferenced(Loc, IV, true);
2457 
2458       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2459       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2460           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2461         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2462 
2463       ObjCIvarRefExpr *Result = new (Context)
2464           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2465                           IV->getLocation(), SelfExpr.get(), true, true);
2466 
2467       if (getLangOpts().ObjCAutoRefCount) {
2468         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2469           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2470             recordUseOfEvaluatedWeak(Result);
2471         }
2472         if (CurContext->isClosure())
2473           Diag(Loc, diag::warn_implicitly_retains_self)
2474             << FixItHint::CreateInsertion(Loc, "self->");
2475       }
2476 
2477       return Result;
2478     }
2479   } else if (CurMethod->isInstanceMethod()) {
2480     // We should warn if a local variable hides an ivar.
2481     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2482       ObjCInterfaceDecl *ClassDeclared;
2483       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2484         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2485             declaresSameEntity(IFace, ClassDeclared))
2486           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2487       }
2488     }
2489   } else if (Lookup.isSingleResult() &&
2490              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2491     // If accessing a stand-alone ivar in a class method, this is an error.
2492     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2493       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2494                        << IV->getDeclName());
2495   }
2496 
2497   if (Lookup.empty() && II && AllowBuiltinCreation) {
2498     // FIXME. Consolidate this with similar code in LookupName.
2499     if (unsigned BuiltinID = II->getBuiltinID()) {
2500       if (!(getLangOpts().CPlusPlus &&
2501             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2502         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2503                                            S, Lookup.isForRedeclaration(),
2504                                            Lookup.getNameLoc());
2505         if (D) Lookup.addDecl(D);
2506       }
2507     }
2508   }
2509   // Sentinel value saying that we didn't do anything special.
2510   return ExprResult((Expr *)nullptr);
2511 }
2512 
2513 /// \brief Cast a base object to a member's actual type.
2514 ///
2515 /// Logically this happens in three phases:
2516 ///
2517 /// * First we cast from the base type to the naming class.
2518 ///   The naming class is the class into which we were looking
2519 ///   when we found the member;  it's the qualifier type if a
2520 ///   qualifier was provided, and otherwise it's the base type.
2521 ///
2522 /// * Next we cast from the naming class to the declaring class.
2523 ///   If the member we found was brought into a class's scope by
2524 ///   a using declaration, this is that class;  otherwise it's
2525 ///   the class declaring the member.
2526 ///
2527 /// * Finally we cast from the declaring class to the "true"
2528 ///   declaring class of the member.  This conversion does not
2529 ///   obey access control.
2530 ExprResult
2531 Sema::PerformObjectMemberConversion(Expr *From,
2532                                     NestedNameSpecifier *Qualifier,
2533                                     NamedDecl *FoundDecl,
2534                                     NamedDecl *Member) {
2535   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2536   if (!RD)
2537     return From;
2538 
2539   QualType DestRecordType;
2540   QualType DestType;
2541   QualType FromRecordType;
2542   QualType FromType = From->getType();
2543   bool PointerConversions = false;
2544   if (isa<FieldDecl>(Member)) {
2545     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2546 
2547     if (FromType->getAs<PointerType>()) {
2548       DestType = Context.getPointerType(DestRecordType);
2549       FromRecordType = FromType->getPointeeType();
2550       PointerConversions = true;
2551     } else {
2552       DestType = DestRecordType;
2553       FromRecordType = FromType;
2554     }
2555   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2556     if (Method->isStatic())
2557       return From;
2558 
2559     DestType = Method->getThisType(Context);
2560     DestRecordType = DestType->getPointeeType();
2561 
2562     if (FromType->getAs<PointerType>()) {
2563       FromRecordType = FromType->getPointeeType();
2564       PointerConversions = true;
2565     } else {
2566       FromRecordType = FromType;
2567       DestType = DestRecordType;
2568     }
2569   } else {
2570     // No conversion necessary.
2571     return From;
2572   }
2573 
2574   if (DestType->isDependentType() || FromType->isDependentType())
2575     return From;
2576 
2577   // If the unqualified types are the same, no conversion is necessary.
2578   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2579     return From;
2580 
2581   SourceRange FromRange = From->getSourceRange();
2582   SourceLocation FromLoc = FromRange.getBegin();
2583 
2584   ExprValueKind VK = From->getValueKind();
2585 
2586   // C++ [class.member.lookup]p8:
2587   //   [...] Ambiguities can often be resolved by qualifying a name with its
2588   //   class name.
2589   //
2590   // If the member was a qualified name and the qualified referred to a
2591   // specific base subobject type, we'll cast to that intermediate type
2592   // first and then to the object in which the member is declared. That allows
2593   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2594   //
2595   //   class Base { public: int x; };
2596   //   class Derived1 : public Base { };
2597   //   class Derived2 : public Base { };
2598   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2599   //
2600   //   void VeryDerived::f() {
2601   //     x = 17; // error: ambiguous base subobjects
2602   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2603   //   }
2604   if (Qualifier && Qualifier->getAsType()) {
2605     QualType QType = QualType(Qualifier->getAsType(), 0);
2606     assert(QType->isRecordType() && "lookup done with non-record type");
2607 
2608     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2609 
2610     // In C++98, the qualifier type doesn't actually have to be a base
2611     // type of the object type, in which case we just ignore it.
2612     // Otherwise build the appropriate casts.
2613     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2614       CXXCastPath BasePath;
2615       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2616                                        FromLoc, FromRange, &BasePath))
2617         return ExprError();
2618 
2619       if (PointerConversions)
2620         QType = Context.getPointerType(QType);
2621       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2622                                VK, &BasePath).get();
2623 
2624       FromType = QType;
2625       FromRecordType = QRecordType;
2626 
2627       // If the qualifier type was the same as the destination type,
2628       // we're done.
2629       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2630         return From;
2631     }
2632   }
2633 
2634   bool IgnoreAccess = false;
2635 
2636   // If we actually found the member through a using declaration, cast
2637   // down to the using declaration's type.
2638   //
2639   // Pointer equality is fine here because only one declaration of a
2640   // class ever has member declarations.
2641   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2642     assert(isa<UsingShadowDecl>(FoundDecl));
2643     QualType URecordType = Context.getTypeDeclType(
2644                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2645 
2646     // We only need to do this if the naming-class to declaring-class
2647     // conversion is non-trivial.
2648     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2649       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2650       CXXCastPath BasePath;
2651       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2652                                        FromLoc, FromRange, &BasePath))
2653         return ExprError();
2654 
2655       QualType UType = URecordType;
2656       if (PointerConversions)
2657         UType = Context.getPointerType(UType);
2658       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2659                                VK, &BasePath).get();
2660       FromType = UType;
2661       FromRecordType = URecordType;
2662     }
2663 
2664     // We don't do access control for the conversion from the
2665     // declaring class to the true declaring class.
2666     IgnoreAccess = true;
2667   }
2668 
2669   CXXCastPath BasePath;
2670   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2671                                    FromLoc, FromRange, &BasePath,
2672                                    IgnoreAccess))
2673     return ExprError();
2674 
2675   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2676                            VK, &BasePath);
2677 }
2678 
2679 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2680                                       const LookupResult &R,
2681                                       bool HasTrailingLParen) {
2682   // Only when used directly as the postfix-expression of a call.
2683   if (!HasTrailingLParen)
2684     return false;
2685 
2686   // Never if a scope specifier was provided.
2687   if (SS.isSet())
2688     return false;
2689 
2690   // Only in C++ or ObjC++.
2691   if (!getLangOpts().CPlusPlus)
2692     return false;
2693 
2694   // Turn off ADL when we find certain kinds of declarations during
2695   // normal lookup:
2696   for (NamedDecl *D : R) {
2697     // C++0x [basic.lookup.argdep]p3:
2698     //     -- a declaration of a class member
2699     // Since using decls preserve this property, we check this on the
2700     // original decl.
2701     if (D->isCXXClassMember())
2702       return false;
2703 
2704     // C++0x [basic.lookup.argdep]p3:
2705     //     -- a block-scope function declaration that is not a
2706     //        using-declaration
2707     // NOTE: we also trigger this for function templates (in fact, we
2708     // don't check the decl type at all, since all other decl types
2709     // turn off ADL anyway).
2710     if (isa<UsingShadowDecl>(D))
2711       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2712     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2713       return false;
2714 
2715     // C++0x [basic.lookup.argdep]p3:
2716     //     -- a declaration that is neither a function or a function
2717     //        template
2718     // And also for builtin functions.
2719     if (isa<FunctionDecl>(D)) {
2720       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2721 
2722       // But also builtin functions.
2723       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2724         return false;
2725     } else if (!isa<FunctionTemplateDecl>(D))
2726       return false;
2727   }
2728 
2729   return true;
2730 }
2731 
2732 
2733 /// Diagnoses obvious problems with the use of the given declaration
2734 /// as an expression.  This is only actually called for lookups that
2735 /// were not overloaded, and it doesn't promise that the declaration
2736 /// will in fact be used.
2737 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2738   if (isa<TypedefNameDecl>(D)) {
2739     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2740     return true;
2741   }
2742 
2743   if (isa<ObjCInterfaceDecl>(D)) {
2744     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2745     return true;
2746   }
2747 
2748   if (isa<NamespaceDecl>(D)) {
2749     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2750     return true;
2751   }
2752 
2753   return false;
2754 }
2755 
2756 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2757                                           LookupResult &R, bool NeedsADL,
2758                                           bool AcceptInvalidDecl) {
2759   // If this is a single, fully-resolved result and we don't need ADL,
2760   // just build an ordinary singleton decl ref.
2761   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2762     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2763                                     R.getRepresentativeDecl(), nullptr,
2764                                     AcceptInvalidDecl);
2765 
2766   // We only need to check the declaration if there's exactly one
2767   // result, because in the overloaded case the results can only be
2768   // functions and function templates.
2769   if (R.isSingleResult() &&
2770       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2771     return ExprError();
2772 
2773   // Otherwise, just build an unresolved lookup expression.  Suppress
2774   // any lookup-related diagnostics; we'll hash these out later, when
2775   // we've picked a target.
2776   R.suppressDiagnostics();
2777 
2778   UnresolvedLookupExpr *ULE
2779     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2780                                    SS.getWithLocInContext(Context),
2781                                    R.getLookupNameInfo(),
2782                                    NeedsADL, R.isOverloadedResult(),
2783                                    R.begin(), R.end());
2784 
2785   return ULE;
2786 }
2787 
2788 /// \brief Complete semantic analysis for a reference to the given declaration.
2789 ExprResult Sema::BuildDeclarationNameExpr(
2790     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2791     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2792     bool AcceptInvalidDecl) {
2793   assert(D && "Cannot refer to a NULL declaration");
2794   assert(!isa<FunctionTemplateDecl>(D) &&
2795          "Cannot refer unambiguously to a function template");
2796 
2797   SourceLocation Loc = NameInfo.getLoc();
2798   if (CheckDeclInExpr(*this, Loc, D))
2799     return ExprError();
2800 
2801   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2802     // Specifically diagnose references to class templates that are missing
2803     // a template argument list.
2804     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2805                                            << Template << SS.getRange();
2806     Diag(Template->getLocation(), diag::note_template_decl_here);
2807     return ExprError();
2808   }
2809 
2810   // Make sure that we're referring to a value.
2811   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2812   if (!VD) {
2813     Diag(Loc, diag::err_ref_non_value)
2814       << D << SS.getRange();
2815     Diag(D->getLocation(), diag::note_declared_at);
2816     return ExprError();
2817   }
2818 
2819   // Check whether this declaration can be used. Note that we suppress
2820   // this check when we're going to perform argument-dependent lookup
2821   // on this function name, because this might not be the function
2822   // that overload resolution actually selects.
2823   if (DiagnoseUseOfDecl(VD, Loc))
2824     return ExprError();
2825 
2826   // Only create DeclRefExpr's for valid Decl's.
2827   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2828     return ExprError();
2829 
2830   // Handle members of anonymous structs and unions.  If we got here,
2831   // and the reference is to a class member indirect field, then this
2832   // must be the subject of a pointer-to-member expression.
2833   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2834     if (!indirectField->isCXXClassMember())
2835       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2836                                                       indirectField);
2837 
2838   {
2839     QualType type = VD->getType();
2840     ExprValueKind valueKind = VK_RValue;
2841 
2842     switch (D->getKind()) {
2843     // Ignore all the non-ValueDecl kinds.
2844 #define ABSTRACT_DECL(kind)
2845 #define VALUE(type, base)
2846 #define DECL(type, base) \
2847     case Decl::type:
2848 #include "clang/AST/DeclNodes.inc"
2849       llvm_unreachable("invalid value decl kind");
2850 
2851     // These shouldn't make it here.
2852     case Decl::ObjCAtDefsField:
2853     case Decl::ObjCIvar:
2854       llvm_unreachable("forming non-member reference to ivar?");
2855 
2856     // Enum constants are always r-values and never references.
2857     // Unresolved using declarations are dependent.
2858     case Decl::EnumConstant:
2859     case Decl::UnresolvedUsingValue:
2860     case Decl::OMPDeclareReduction:
2861       valueKind = VK_RValue;
2862       break;
2863 
2864     // Fields and indirect fields that got here must be for
2865     // pointer-to-member expressions; we just call them l-values for
2866     // internal consistency, because this subexpression doesn't really
2867     // exist in the high-level semantics.
2868     case Decl::Field:
2869     case Decl::IndirectField:
2870       assert(getLangOpts().CPlusPlus &&
2871              "building reference to field in C?");
2872 
2873       // These can't have reference type in well-formed programs, but
2874       // for internal consistency we do this anyway.
2875       type = type.getNonReferenceType();
2876       valueKind = VK_LValue;
2877       break;
2878 
2879     // Non-type template parameters are either l-values or r-values
2880     // depending on the type.
2881     case Decl::NonTypeTemplateParm: {
2882       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2883         type = reftype->getPointeeType();
2884         valueKind = VK_LValue; // even if the parameter is an r-value reference
2885         break;
2886       }
2887 
2888       // For non-references, we need to strip qualifiers just in case
2889       // the template parameter was declared as 'const int' or whatever.
2890       valueKind = VK_RValue;
2891       type = type.getUnqualifiedType();
2892       break;
2893     }
2894 
2895     case Decl::Var:
2896     case Decl::VarTemplateSpecialization:
2897     case Decl::VarTemplatePartialSpecialization:
2898     case Decl::OMPCapturedExpr:
2899       // In C, "extern void blah;" is valid and is an r-value.
2900       if (!getLangOpts().CPlusPlus &&
2901           !type.hasQualifiers() &&
2902           type->isVoidType()) {
2903         valueKind = VK_RValue;
2904         break;
2905       }
2906       // fallthrough
2907 
2908     case Decl::ImplicitParam:
2909     case Decl::ParmVar: {
2910       // These are always l-values.
2911       valueKind = VK_LValue;
2912       type = type.getNonReferenceType();
2913 
2914       // FIXME: Does the addition of const really only apply in
2915       // potentially-evaluated contexts? Since the variable isn't actually
2916       // captured in an unevaluated context, it seems that the answer is no.
2917       if (!isUnevaluatedContext()) {
2918         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2919         if (!CapturedType.isNull())
2920           type = CapturedType;
2921       }
2922 
2923       break;
2924     }
2925 
2926     case Decl::Function: {
2927       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2928         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2929           type = Context.BuiltinFnTy;
2930           valueKind = VK_RValue;
2931           break;
2932         }
2933       }
2934 
2935       const FunctionType *fty = type->castAs<FunctionType>();
2936 
2937       // If we're referring to a function with an __unknown_anytype
2938       // result type, make the entire expression __unknown_anytype.
2939       if (fty->getReturnType() == Context.UnknownAnyTy) {
2940         type = Context.UnknownAnyTy;
2941         valueKind = VK_RValue;
2942         break;
2943       }
2944 
2945       // Functions are l-values in C++.
2946       if (getLangOpts().CPlusPlus) {
2947         valueKind = VK_LValue;
2948         break;
2949       }
2950 
2951       // C99 DR 316 says that, if a function type comes from a
2952       // function definition (without a prototype), that type is only
2953       // used for checking compatibility. Therefore, when referencing
2954       // the function, we pretend that we don't have the full function
2955       // type.
2956       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2957           isa<FunctionProtoType>(fty))
2958         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2959                                               fty->getExtInfo());
2960 
2961       // Functions are r-values in C.
2962       valueKind = VK_RValue;
2963       break;
2964     }
2965 
2966     case Decl::MSProperty:
2967       valueKind = VK_LValue;
2968       break;
2969 
2970     case Decl::CXXMethod:
2971       // If we're referring to a method with an __unknown_anytype
2972       // result type, make the entire expression __unknown_anytype.
2973       // This should only be possible with a type written directly.
2974       if (const FunctionProtoType *proto
2975             = dyn_cast<FunctionProtoType>(VD->getType()))
2976         if (proto->getReturnType() == Context.UnknownAnyTy) {
2977           type = Context.UnknownAnyTy;
2978           valueKind = VK_RValue;
2979           break;
2980         }
2981 
2982       // C++ methods are l-values if static, r-values if non-static.
2983       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2984         valueKind = VK_LValue;
2985         break;
2986       }
2987       // fallthrough
2988 
2989     case Decl::CXXConversion:
2990     case Decl::CXXDestructor:
2991     case Decl::CXXConstructor:
2992       valueKind = VK_RValue;
2993       break;
2994     }
2995 
2996     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2997                             TemplateArgs);
2998   }
2999 }
3000 
3001 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3002                                     SmallString<32> &Target) {
3003   Target.resize(CharByteWidth * (Source.size() + 1));
3004   char *ResultPtr = &Target[0];
3005   const UTF8 *ErrorPtr;
3006   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3007   (void)success;
3008   assert(success);
3009   Target.resize(ResultPtr - &Target[0]);
3010 }
3011 
3012 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3013                                      PredefinedExpr::IdentType IT) {
3014   // Pick the current block, lambda, captured statement or function.
3015   Decl *currentDecl = nullptr;
3016   if (const BlockScopeInfo *BSI = getCurBlock())
3017     currentDecl = BSI->TheDecl;
3018   else if (const LambdaScopeInfo *LSI = getCurLambda())
3019     currentDecl = LSI->CallOperator;
3020   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3021     currentDecl = CSI->TheCapturedDecl;
3022   else
3023     currentDecl = getCurFunctionOrMethodDecl();
3024 
3025   if (!currentDecl) {
3026     Diag(Loc, diag::ext_predef_outside_function);
3027     currentDecl = Context.getTranslationUnitDecl();
3028   }
3029 
3030   QualType ResTy;
3031   StringLiteral *SL = nullptr;
3032   if (cast<DeclContext>(currentDecl)->isDependentContext())
3033     ResTy = Context.DependentTy;
3034   else {
3035     // Pre-defined identifiers are of type char[x], where x is the length of
3036     // the string.
3037     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3038     unsigned Length = Str.length();
3039 
3040     llvm::APInt LengthI(32, Length + 1);
3041     if (IT == PredefinedExpr::LFunction) {
3042       ResTy = Context.WideCharTy.withConst();
3043       SmallString<32> RawChars;
3044       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3045                               Str, RawChars);
3046       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3047                                            /*IndexTypeQuals*/ 0);
3048       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3049                                  /*Pascal*/ false, ResTy, Loc);
3050     } else {
3051       ResTy = Context.CharTy.withConst();
3052       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3053                                            /*IndexTypeQuals*/ 0);
3054       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3055                                  /*Pascal*/ false, ResTy, Loc);
3056     }
3057   }
3058 
3059   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3060 }
3061 
3062 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3063   PredefinedExpr::IdentType IT;
3064 
3065   switch (Kind) {
3066   default: llvm_unreachable("Unknown simple primary expr!");
3067   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3068   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3069   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3070   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3071   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3072   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3073   }
3074 
3075   return BuildPredefinedExpr(Loc, IT);
3076 }
3077 
3078 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3079   SmallString<16> CharBuffer;
3080   bool Invalid = false;
3081   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3082   if (Invalid)
3083     return ExprError();
3084 
3085   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3086                             PP, Tok.getKind());
3087   if (Literal.hadError())
3088     return ExprError();
3089 
3090   QualType Ty;
3091   if (Literal.isWide())
3092     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3093   else if (Literal.isUTF16())
3094     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3095   else if (Literal.isUTF32())
3096     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3097   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3098     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3099   else
3100     Ty = Context.CharTy;  // 'x' -> char in C++
3101 
3102   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3103   if (Literal.isWide())
3104     Kind = CharacterLiteral::Wide;
3105   else if (Literal.isUTF16())
3106     Kind = CharacterLiteral::UTF16;
3107   else if (Literal.isUTF32())
3108     Kind = CharacterLiteral::UTF32;
3109   else if (Literal.isUTF8())
3110     Kind = CharacterLiteral::UTF8;
3111 
3112   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3113                                              Tok.getLocation());
3114 
3115   if (Literal.getUDSuffix().empty())
3116     return Lit;
3117 
3118   // We're building a user-defined literal.
3119   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3120   SourceLocation UDSuffixLoc =
3121     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3122 
3123   // Make sure we're allowed user-defined literals here.
3124   if (!UDLScope)
3125     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3126 
3127   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3128   //   operator "" X (ch)
3129   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3130                                         Lit, Tok.getLocation());
3131 }
3132 
3133 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3134   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3135   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3136                                 Context.IntTy, Loc);
3137 }
3138 
3139 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3140                                   QualType Ty, SourceLocation Loc) {
3141   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3142 
3143   using llvm::APFloat;
3144   APFloat Val(Format);
3145 
3146   APFloat::opStatus result = Literal.GetFloatValue(Val);
3147 
3148   // Overflow is always an error, but underflow is only an error if
3149   // we underflowed to zero (APFloat reports denormals as underflow).
3150   if ((result & APFloat::opOverflow) ||
3151       ((result & APFloat::opUnderflow) && Val.isZero())) {
3152     unsigned diagnostic;
3153     SmallString<20> buffer;
3154     if (result & APFloat::opOverflow) {
3155       diagnostic = diag::warn_float_overflow;
3156       APFloat::getLargest(Format).toString(buffer);
3157     } else {
3158       diagnostic = diag::warn_float_underflow;
3159       APFloat::getSmallest(Format).toString(buffer);
3160     }
3161 
3162     S.Diag(Loc, diagnostic)
3163       << Ty
3164       << StringRef(buffer.data(), buffer.size());
3165   }
3166 
3167   bool isExact = (result == APFloat::opOK);
3168   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3169 }
3170 
3171 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3172   assert(E && "Invalid expression");
3173 
3174   if (E->isValueDependent())
3175     return false;
3176 
3177   QualType QT = E->getType();
3178   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3179     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3180     return true;
3181   }
3182 
3183   llvm::APSInt ValueAPS;
3184   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3185 
3186   if (R.isInvalid())
3187     return true;
3188 
3189   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3190   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3191     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3192         << ValueAPS.toString(10) << ValueIsPositive;
3193     return true;
3194   }
3195 
3196   return false;
3197 }
3198 
3199 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3200   // Fast path for a single digit (which is quite common).  A single digit
3201   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3202   if (Tok.getLength() == 1) {
3203     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3204     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3205   }
3206 
3207   SmallString<128> SpellingBuffer;
3208   // NumericLiteralParser wants to overread by one character.  Add padding to
3209   // the buffer in case the token is copied to the buffer.  If getSpelling()
3210   // returns a StringRef to the memory buffer, it should have a null char at
3211   // the EOF, so it is also safe.
3212   SpellingBuffer.resize(Tok.getLength() + 1);
3213 
3214   // Get the spelling of the token, which eliminates trigraphs, etc.
3215   bool Invalid = false;
3216   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3217   if (Invalid)
3218     return ExprError();
3219 
3220   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3221   if (Literal.hadError)
3222     return ExprError();
3223 
3224   if (Literal.hasUDSuffix()) {
3225     // We're building a user-defined literal.
3226     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3227     SourceLocation UDSuffixLoc =
3228       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3229 
3230     // Make sure we're allowed user-defined literals here.
3231     if (!UDLScope)
3232       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3233 
3234     QualType CookedTy;
3235     if (Literal.isFloatingLiteral()) {
3236       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3237       // long double, the literal is treated as a call of the form
3238       //   operator "" X (f L)
3239       CookedTy = Context.LongDoubleTy;
3240     } else {
3241       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3242       // unsigned long long, the literal is treated as a call of the form
3243       //   operator "" X (n ULL)
3244       CookedTy = Context.UnsignedLongLongTy;
3245     }
3246 
3247     DeclarationName OpName =
3248       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3249     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3250     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3251 
3252     SourceLocation TokLoc = Tok.getLocation();
3253 
3254     // Perform literal operator lookup to determine if we're building a raw
3255     // literal or a cooked one.
3256     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3257     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3258                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3259                                   /*AllowStringTemplate*/false)) {
3260     case LOLR_Error:
3261       return ExprError();
3262 
3263     case LOLR_Cooked: {
3264       Expr *Lit;
3265       if (Literal.isFloatingLiteral()) {
3266         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3267       } else {
3268         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3269         if (Literal.GetIntegerValue(ResultVal))
3270           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3271               << /* Unsigned */ 1;
3272         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3273                                      Tok.getLocation());
3274       }
3275       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3276     }
3277 
3278     case LOLR_Raw: {
3279       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3280       // literal is treated as a call of the form
3281       //   operator "" X ("n")
3282       unsigned Length = Literal.getUDSuffixOffset();
3283       QualType StrTy = Context.getConstantArrayType(
3284           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3285           ArrayType::Normal, 0);
3286       Expr *Lit = StringLiteral::Create(
3287           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3288           /*Pascal*/false, StrTy, &TokLoc, 1);
3289       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3290     }
3291 
3292     case LOLR_Template: {
3293       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3294       // template), L is treated as a call fo the form
3295       //   operator "" X <'c1', 'c2', ... 'ck'>()
3296       // where n is the source character sequence c1 c2 ... ck.
3297       TemplateArgumentListInfo ExplicitArgs;
3298       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3299       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3300       llvm::APSInt Value(CharBits, CharIsUnsigned);
3301       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3302         Value = TokSpelling[I];
3303         TemplateArgument Arg(Context, Value, Context.CharTy);
3304         TemplateArgumentLocInfo ArgInfo;
3305         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3306       }
3307       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3308                                       &ExplicitArgs);
3309     }
3310     case LOLR_StringTemplate:
3311       llvm_unreachable("unexpected literal operator lookup result");
3312     }
3313   }
3314 
3315   Expr *Res;
3316 
3317   if (Literal.isFloatingLiteral()) {
3318     QualType Ty;
3319     if (Literal.isHalf){
3320       if (getOpenCLOptions().cl_khr_fp16)
3321         Ty = Context.HalfTy;
3322       else {
3323         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3324         return ExprError();
3325       }
3326     } else if (Literal.isFloat)
3327       Ty = Context.FloatTy;
3328     else if (!Literal.isLong)
3329       Ty = Context.DoubleTy;
3330     else
3331       Ty = Context.LongDoubleTy;
3332 
3333     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3334 
3335     if (Ty == Context.DoubleTy) {
3336       if (getLangOpts().SinglePrecisionConstants) {
3337         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3338       } else if (getLangOpts().OpenCL &&
3339                  !((getLangOpts().OpenCLVersion >= 120) ||
3340                    getOpenCLOptions().cl_khr_fp64)) {
3341         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3342         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3343       }
3344     }
3345   } else if (!Literal.isIntegerLiteral()) {
3346     return ExprError();
3347   } else {
3348     QualType Ty;
3349 
3350     // 'long long' is a C99 or C++11 feature.
3351     if (!getLangOpts().C99 && Literal.isLongLong) {
3352       if (getLangOpts().CPlusPlus)
3353         Diag(Tok.getLocation(),
3354              getLangOpts().CPlusPlus11 ?
3355              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3356       else
3357         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3358     }
3359 
3360     // Get the value in the widest-possible width.
3361     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3362     llvm::APInt ResultVal(MaxWidth, 0);
3363 
3364     if (Literal.GetIntegerValue(ResultVal)) {
3365       // If this value didn't fit into uintmax_t, error and force to ull.
3366       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3367           << /* Unsigned */ 1;
3368       Ty = Context.UnsignedLongLongTy;
3369       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3370              "long long is not intmax_t?");
3371     } else {
3372       // If this value fits into a ULL, try to figure out what else it fits into
3373       // according to the rules of C99 6.4.4.1p5.
3374 
3375       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3376       // be an unsigned int.
3377       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3378 
3379       // Check from smallest to largest, picking the smallest type we can.
3380       unsigned Width = 0;
3381 
3382       // Microsoft specific integer suffixes are explicitly sized.
3383       if (Literal.MicrosoftInteger) {
3384         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3385           Width = 8;
3386           Ty = Context.CharTy;
3387         } else {
3388           Width = Literal.MicrosoftInteger;
3389           Ty = Context.getIntTypeForBitwidth(Width,
3390                                              /*Signed=*/!Literal.isUnsigned);
3391         }
3392       }
3393 
3394       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3395         // Are int/unsigned possibilities?
3396         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3397 
3398         // Does it fit in a unsigned int?
3399         if (ResultVal.isIntN(IntSize)) {
3400           // Does it fit in a signed int?
3401           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3402             Ty = Context.IntTy;
3403           else if (AllowUnsigned)
3404             Ty = Context.UnsignedIntTy;
3405           Width = IntSize;
3406         }
3407       }
3408 
3409       // Are long/unsigned long possibilities?
3410       if (Ty.isNull() && !Literal.isLongLong) {
3411         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3412 
3413         // Does it fit in a unsigned long?
3414         if (ResultVal.isIntN(LongSize)) {
3415           // Does it fit in a signed long?
3416           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3417             Ty = Context.LongTy;
3418           else if (AllowUnsigned)
3419             Ty = Context.UnsignedLongTy;
3420           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3421           // is compatible.
3422           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3423             const unsigned LongLongSize =
3424                 Context.getTargetInfo().getLongLongWidth();
3425             Diag(Tok.getLocation(),
3426                  getLangOpts().CPlusPlus
3427                      ? Literal.isLong
3428                            ? diag::warn_old_implicitly_unsigned_long_cxx
3429                            : /*C++98 UB*/ diag::
3430                                  ext_old_implicitly_unsigned_long_cxx
3431                      : diag::warn_old_implicitly_unsigned_long)
3432                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3433                                             : /*will be ill-formed*/ 1);
3434             Ty = Context.UnsignedLongTy;
3435           }
3436           Width = LongSize;
3437         }
3438       }
3439 
3440       // Check long long if needed.
3441       if (Ty.isNull()) {
3442         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3443 
3444         // Does it fit in a unsigned long long?
3445         if (ResultVal.isIntN(LongLongSize)) {
3446           // Does it fit in a signed long long?
3447           // To be compatible with MSVC, hex integer literals ending with the
3448           // LL or i64 suffix are always signed in Microsoft mode.
3449           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3450               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3451             Ty = Context.LongLongTy;
3452           else if (AllowUnsigned)
3453             Ty = Context.UnsignedLongLongTy;
3454           Width = LongLongSize;
3455         }
3456       }
3457 
3458       // If we still couldn't decide a type, we probably have something that
3459       // does not fit in a signed long long, but has no U suffix.
3460       if (Ty.isNull()) {
3461         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3462         Ty = Context.UnsignedLongLongTy;
3463         Width = Context.getTargetInfo().getLongLongWidth();
3464       }
3465 
3466       if (ResultVal.getBitWidth() != Width)
3467         ResultVal = ResultVal.trunc(Width);
3468     }
3469     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3470   }
3471 
3472   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3473   if (Literal.isImaginary)
3474     Res = new (Context) ImaginaryLiteral(Res,
3475                                         Context.getComplexType(Res->getType()));
3476 
3477   return Res;
3478 }
3479 
3480 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3481   assert(E && "ActOnParenExpr() missing expr");
3482   return new (Context) ParenExpr(L, R, E);
3483 }
3484 
3485 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3486                                          SourceLocation Loc,
3487                                          SourceRange ArgRange) {
3488   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3489   // scalar or vector data type argument..."
3490   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3491   // type (C99 6.2.5p18) or void.
3492   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3493     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3494       << T << ArgRange;
3495     return true;
3496   }
3497 
3498   assert((T->isVoidType() || !T->isIncompleteType()) &&
3499          "Scalar types should always be complete");
3500   return false;
3501 }
3502 
3503 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3504                                            SourceLocation Loc,
3505                                            SourceRange ArgRange,
3506                                            UnaryExprOrTypeTrait TraitKind) {
3507   // Invalid types must be hard errors for SFINAE in C++.
3508   if (S.LangOpts.CPlusPlus)
3509     return true;
3510 
3511   // C99 6.5.3.4p1:
3512   if (T->isFunctionType() &&
3513       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3514     // sizeof(function)/alignof(function) is allowed as an extension.
3515     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3516       << TraitKind << ArgRange;
3517     return false;
3518   }
3519 
3520   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3521   // this is an error (OpenCL v1.1 s6.3.k)
3522   if (T->isVoidType()) {
3523     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3524                                         : diag::ext_sizeof_alignof_void_type;
3525     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3526     return false;
3527   }
3528 
3529   return true;
3530 }
3531 
3532 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3533                                              SourceLocation Loc,
3534                                              SourceRange ArgRange,
3535                                              UnaryExprOrTypeTrait TraitKind) {
3536   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3537   // runtime doesn't allow it.
3538   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3539     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3540       << T << (TraitKind == UETT_SizeOf)
3541       << ArgRange;
3542     return true;
3543   }
3544 
3545   return false;
3546 }
3547 
3548 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3549 /// pointer type is equal to T) and emit a warning if it is.
3550 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3551                                      Expr *E) {
3552   // Don't warn if the operation changed the type.
3553   if (T != E->getType())
3554     return;
3555 
3556   // Now look for array decays.
3557   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3558   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3559     return;
3560 
3561   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3562                                              << ICE->getType()
3563                                              << ICE->getSubExpr()->getType();
3564 }
3565 
3566 /// \brief Check the constraints on expression operands to unary type expression
3567 /// and type traits.
3568 ///
3569 /// Completes any types necessary and validates the constraints on the operand
3570 /// expression. The logic mostly mirrors the type-based overload, but may modify
3571 /// the expression as it completes the type for that expression through template
3572 /// instantiation, etc.
3573 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3574                                             UnaryExprOrTypeTrait ExprKind) {
3575   QualType ExprTy = E->getType();
3576   assert(!ExprTy->isReferenceType());
3577 
3578   if (ExprKind == UETT_VecStep)
3579     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3580                                         E->getSourceRange());
3581 
3582   // Whitelist some types as extensions
3583   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3584                                       E->getSourceRange(), ExprKind))
3585     return false;
3586 
3587   // 'alignof' applied to an expression only requires the base element type of
3588   // the expression to be complete. 'sizeof' requires the expression's type to
3589   // be complete (and will attempt to complete it if it's an array of unknown
3590   // bound).
3591   if (ExprKind == UETT_AlignOf) {
3592     if (RequireCompleteType(E->getExprLoc(),
3593                             Context.getBaseElementType(E->getType()),
3594                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3595                             E->getSourceRange()))
3596       return true;
3597   } else {
3598     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3599                                 ExprKind, E->getSourceRange()))
3600       return true;
3601   }
3602 
3603   // Completing the expression's type may have changed it.
3604   ExprTy = E->getType();
3605   assert(!ExprTy->isReferenceType());
3606 
3607   if (ExprTy->isFunctionType()) {
3608     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3609       << ExprKind << E->getSourceRange();
3610     return true;
3611   }
3612 
3613   // The operand for sizeof and alignof is in an unevaluated expression context,
3614   // so side effects could result in unintended consequences.
3615   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3616       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3617     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3618 
3619   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3620                                        E->getSourceRange(), ExprKind))
3621     return true;
3622 
3623   if (ExprKind == UETT_SizeOf) {
3624     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3625       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3626         QualType OType = PVD->getOriginalType();
3627         QualType Type = PVD->getType();
3628         if (Type->isPointerType() && OType->isArrayType()) {
3629           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3630             << Type << OType;
3631           Diag(PVD->getLocation(), diag::note_declared_at);
3632         }
3633       }
3634     }
3635 
3636     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3637     // decays into a pointer and returns an unintended result. This is most
3638     // likely a typo for "sizeof(array) op x".
3639     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3640       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3641                                BO->getLHS());
3642       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3643                                BO->getRHS());
3644     }
3645   }
3646 
3647   return false;
3648 }
3649 
3650 /// \brief Check the constraints on operands to unary expression and type
3651 /// traits.
3652 ///
3653 /// This will complete any types necessary, and validate the various constraints
3654 /// on those operands.
3655 ///
3656 /// The UsualUnaryConversions() function is *not* called by this routine.
3657 /// C99 6.3.2.1p[2-4] all state:
3658 ///   Except when it is the operand of the sizeof operator ...
3659 ///
3660 /// C++ [expr.sizeof]p4
3661 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3662 ///   standard conversions are not applied to the operand of sizeof.
3663 ///
3664 /// This policy is followed for all of the unary trait expressions.
3665 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3666                                             SourceLocation OpLoc,
3667                                             SourceRange ExprRange,
3668                                             UnaryExprOrTypeTrait ExprKind) {
3669   if (ExprType->isDependentType())
3670     return false;
3671 
3672   // C++ [expr.sizeof]p2:
3673   //     When applied to a reference or a reference type, the result
3674   //     is the size of the referenced type.
3675   // C++11 [expr.alignof]p3:
3676   //     When alignof is applied to a reference type, the result
3677   //     shall be the alignment of the referenced type.
3678   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3679     ExprType = Ref->getPointeeType();
3680 
3681   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3682   //   When alignof or _Alignof is applied to an array type, the result
3683   //   is the alignment of the element type.
3684   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3685     ExprType = Context.getBaseElementType(ExprType);
3686 
3687   if (ExprKind == UETT_VecStep)
3688     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3689 
3690   // Whitelist some types as extensions
3691   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3692                                       ExprKind))
3693     return false;
3694 
3695   if (RequireCompleteType(OpLoc, ExprType,
3696                           diag::err_sizeof_alignof_incomplete_type,
3697                           ExprKind, ExprRange))
3698     return true;
3699 
3700   if (ExprType->isFunctionType()) {
3701     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3702       << ExprKind << ExprRange;
3703     return true;
3704   }
3705 
3706   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3707                                        ExprKind))
3708     return true;
3709 
3710   return false;
3711 }
3712 
3713 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3714   E = E->IgnoreParens();
3715 
3716   // Cannot know anything else if the expression is dependent.
3717   if (E->isTypeDependent())
3718     return false;
3719 
3720   if (E->getObjectKind() == OK_BitField) {
3721     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3722        << 1 << E->getSourceRange();
3723     return true;
3724   }
3725 
3726   ValueDecl *D = nullptr;
3727   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3728     D = DRE->getDecl();
3729   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3730     D = ME->getMemberDecl();
3731   }
3732 
3733   // If it's a field, require the containing struct to have a
3734   // complete definition so that we can compute the layout.
3735   //
3736   // This can happen in C++11 onwards, either by naming the member
3737   // in a way that is not transformed into a member access expression
3738   // (in an unevaluated operand, for instance), or by naming the member
3739   // in a trailing-return-type.
3740   //
3741   // For the record, since __alignof__ on expressions is a GCC
3742   // extension, GCC seems to permit this but always gives the
3743   // nonsensical answer 0.
3744   //
3745   // We don't really need the layout here --- we could instead just
3746   // directly check for all the appropriate alignment-lowing
3747   // attributes --- but that would require duplicating a lot of
3748   // logic that just isn't worth duplicating for such a marginal
3749   // use-case.
3750   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3751     // Fast path this check, since we at least know the record has a
3752     // definition if we can find a member of it.
3753     if (!FD->getParent()->isCompleteDefinition()) {
3754       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3755         << E->getSourceRange();
3756       return true;
3757     }
3758 
3759     // Otherwise, if it's a field, and the field doesn't have
3760     // reference type, then it must have a complete type (or be a
3761     // flexible array member, which we explicitly want to
3762     // white-list anyway), which makes the following checks trivial.
3763     if (!FD->getType()->isReferenceType())
3764       return false;
3765   }
3766 
3767   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3768 }
3769 
3770 bool Sema::CheckVecStepExpr(Expr *E) {
3771   E = E->IgnoreParens();
3772 
3773   // Cannot know anything else if the expression is dependent.
3774   if (E->isTypeDependent())
3775     return false;
3776 
3777   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3778 }
3779 
3780 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3781                                         CapturingScopeInfo *CSI) {
3782   assert(T->isVariablyModifiedType());
3783   assert(CSI != nullptr);
3784 
3785   // We're going to walk down into the type and look for VLA expressions.
3786   do {
3787     const Type *Ty = T.getTypePtr();
3788     switch (Ty->getTypeClass()) {
3789 #define TYPE(Class, Base)
3790 #define ABSTRACT_TYPE(Class, Base)
3791 #define NON_CANONICAL_TYPE(Class, Base)
3792 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3793 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3794 #include "clang/AST/TypeNodes.def"
3795       T = QualType();
3796       break;
3797     // These types are never variably-modified.
3798     case Type::Builtin:
3799     case Type::Complex:
3800     case Type::Vector:
3801     case Type::ExtVector:
3802     case Type::Record:
3803     case Type::Enum:
3804     case Type::Elaborated:
3805     case Type::TemplateSpecialization:
3806     case Type::ObjCObject:
3807     case Type::ObjCInterface:
3808     case Type::ObjCObjectPointer:
3809     case Type::Pipe:
3810       llvm_unreachable("type class is never variably-modified!");
3811     case Type::Adjusted:
3812       T = cast<AdjustedType>(Ty)->getOriginalType();
3813       break;
3814     case Type::Decayed:
3815       T = cast<DecayedType>(Ty)->getPointeeType();
3816       break;
3817     case Type::Pointer:
3818       T = cast<PointerType>(Ty)->getPointeeType();
3819       break;
3820     case Type::BlockPointer:
3821       T = cast<BlockPointerType>(Ty)->getPointeeType();
3822       break;
3823     case Type::LValueReference:
3824     case Type::RValueReference:
3825       T = cast<ReferenceType>(Ty)->getPointeeType();
3826       break;
3827     case Type::MemberPointer:
3828       T = cast<MemberPointerType>(Ty)->getPointeeType();
3829       break;
3830     case Type::ConstantArray:
3831     case Type::IncompleteArray:
3832       // Losing element qualification here is fine.
3833       T = cast<ArrayType>(Ty)->getElementType();
3834       break;
3835     case Type::VariableArray: {
3836       // Losing element qualification here is fine.
3837       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3838 
3839       // Unknown size indication requires no size computation.
3840       // Otherwise, evaluate and record it.
3841       if (auto Size = VAT->getSizeExpr()) {
3842         if (!CSI->isVLATypeCaptured(VAT)) {
3843           RecordDecl *CapRecord = nullptr;
3844           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3845             CapRecord = LSI->Lambda;
3846           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3847             CapRecord = CRSI->TheRecordDecl;
3848           }
3849           if (CapRecord) {
3850             auto ExprLoc = Size->getExprLoc();
3851             auto SizeType = Context.getSizeType();
3852             // Build the non-static data member.
3853             auto Field =
3854                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3855                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3856                                   /*BW*/ nullptr, /*Mutable*/ false,
3857                                   /*InitStyle*/ ICIS_NoInit);
3858             Field->setImplicit(true);
3859             Field->setAccess(AS_private);
3860             Field->setCapturedVLAType(VAT);
3861             CapRecord->addDecl(Field);
3862 
3863             CSI->addVLATypeCapture(ExprLoc, SizeType);
3864           }
3865         }
3866       }
3867       T = VAT->getElementType();
3868       break;
3869     }
3870     case Type::FunctionProto:
3871     case Type::FunctionNoProto:
3872       T = cast<FunctionType>(Ty)->getReturnType();
3873       break;
3874     case Type::Paren:
3875     case Type::TypeOf:
3876     case Type::UnaryTransform:
3877     case Type::Attributed:
3878     case Type::SubstTemplateTypeParm:
3879     case Type::PackExpansion:
3880       // Keep walking after single level desugaring.
3881       T = T.getSingleStepDesugaredType(Context);
3882       break;
3883     case Type::Typedef:
3884       T = cast<TypedefType>(Ty)->desugar();
3885       break;
3886     case Type::Decltype:
3887       T = cast<DecltypeType>(Ty)->desugar();
3888       break;
3889     case Type::Auto:
3890       T = cast<AutoType>(Ty)->getDeducedType();
3891       break;
3892     case Type::TypeOfExpr:
3893       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3894       break;
3895     case Type::Atomic:
3896       T = cast<AtomicType>(Ty)->getValueType();
3897       break;
3898     }
3899   } while (!T.isNull() && T->isVariablyModifiedType());
3900 }
3901 
3902 /// \brief Build a sizeof or alignof expression given a type operand.
3903 ExprResult
3904 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3905                                      SourceLocation OpLoc,
3906                                      UnaryExprOrTypeTrait ExprKind,
3907                                      SourceRange R) {
3908   if (!TInfo)
3909     return ExprError();
3910 
3911   QualType T = TInfo->getType();
3912 
3913   if (!T->isDependentType() &&
3914       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3915     return ExprError();
3916 
3917   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3918     if (auto *TT = T->getAs<TypedefType>()) {
3919       for (auto I = FunctionScopes.rbegin(),
3920                 E = std::prev(FunctionScopes.rend());
3921            I != E; ++I) {
3922         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3923         if (CSI == nullptr)
3924           break;
3925         DeclContext *DC = nullptr;
3926         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3927           DC = LSI->CallOperator;
3928         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3929           DC = CRSI->TheCapturedDecl;
3930         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3931           DC = BSI->TheDecl;
3932         if (DC) {
3933           if (DC->containsDecl(TT->getDecl()))
3934             break;
3935           captureVariablyModifiedType(Context, T, CSI);
3936         }
3937       }
3938     }
3939   }
3940 
3941   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3942   return new (Context) UnaryExprOrTypeTraitExpr(
3943       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3944 }
3945 
3946 /// \brief Build a sizeof or alignof expression given an expression
3947 /// operand.
3948 ExprResult
3949 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3950                                      UnaryExprOrTypeTrait ExprKind) {
3951   ExprResult PE = CheckPlaceholderExpr(E);
3952   if (PE.isInvalid())
3953     return ExprError();
3954 
3955   E = PE.get();
3956 
3957   // Verify that the operand is valid.
3958   bool isInvalid = false;
3959   if (E->isTypeDependent()) {
3960     // Delay type-checking for type-dependent expressions.
3961   } else if (ExprKind == UETT_AlignOf) {
3962     isInvalid = CheckAlignOfExpr(*this, E);
3963   } else if (ExprKind == UETT_VecStep) {
3964     isInvalid = CheckVecStepExpr(E);
3965   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3966       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3967       isInvalid = true;
3968   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3969     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3970     isInvalid = true;
3971   } else {
3972     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3973   }
3974 
3975   if (isInvalid)
3976     return ExprError();
3977 
3978   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3979     PE = TransformToPotentiallyEvaluated(E);
3980     if (PE.isInvalid()) return ExprError();
3981     E = PE.get();
3982   }
3983 
3984   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3985   return new (Context) UnaryExprOrTypeTraitExpr(
3986       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3987 }
3988 
3989 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3990 /// expr and the same for @c alignof and @c __alignof
3991 /// Note that the ArgRange is invalid if isType is false.
3992 ExprResult
3993 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3994                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3995                                     void *TyOrEx, SourceRange ArgRange) {
3996   // If error parsing type, ignore.
3997   if (!TyOrEx) return ExprError();
3998 
3999   if (IsType) {
4000     TypeSourceInfo *TInfo;
4001     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4002     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4003   }
4004 
4005   Expr *ArgEx = (Expr *)TyOrEx;
4006   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4007   return Result;
4008 }
4009 
4010 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4011                                      bool IsReal) {
4012   if (V.get()->isTypeDependent())
4013     return S.Context.DependentTy;
4014 
4015   // _Real and _Imag are only l-values for normal l-values.
4016   if (V.get()->getObjectKind() != OK_Ordinary) {
4017     V = S.DefaultLvalueConversion(V.get());
4018     if (V.isInvalid())
4019       return QualType();
4020   }
4021 
4022   // These operators return the element type of a complex type.
4023   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4024     return CT->getElementType();
4025 
4026   // Otherwise they pass through real integer and floating point types here.
4027   if (V.get()->getType()->isArithmeticType())
4028     return V.get()->getType();
4029 
4030   // Test for placeholders.
4031   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4032   if (PR.isInvalid()) return QualType();
4033   if (PR.get() != V.get()) {
4034     V = PR;
4035     return CheckRealImagOperand(S, V, Loc, IsReal);
4036   }
4037 
4038   // Reject anything else.
4039   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4040     << (IsReal ? "__real" : "__imag");
4041   return QualType();
4042 }
4043 
4044 
4045 
4046 ExprResult
4047 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4048                           tok::TokenKind Kind, Expr *Input) {
4049   UnaryOperatorKind Opc;
4050   switch (Kind) {
4051   default: llvm_unreachable("Unknown unary op!");
4052   case tok::plusplus:   Opc = UO_PostInc; break;
4053   case tok::minusminus: Opc = UO_PostDec; break;
4054   }
4055 
4056   // Since this might is a postfix expression, get rid of ParenListExprs.
4057   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4058   if (Result.isInvalid()) return ExprError();
4059   Input = Result.get();
4060 
4061   return BuildUnaryOp(S, OpLoc, Opc, Input);
4062 }
4063 
4064 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4065 ///
4066 /// \return true on error
4067 static bool checkArithmeticOnObjCPointer(Sema &S,
4068                                          SourceLocation opLoc,
4069                                          Expr *op) {
4070   assert(op->getType()->isObjCObjectPointerType());
4071   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4072       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4073     return false;
4074 
4075   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4076     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4077     << op->getSourceRange();
4078   return true;
4079 }
4080 
4081 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4082   auto *BaseNoParens = Base->IgnoreParens();
4083   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4084     return MSProp->getPropertyDecl()->getType()->isArrayType();
4085   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4086 }
4087 
4088 ExprResult
4089 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4090                               Expr *idx, SourceLocation rbLoc) {
4091   if (base && !base->getType().isNull() &&
4092       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4093     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4094                                     /*Length=*/nullptr, rbLoc);
4095 
4096   // Since this might be a postfix expression, get rid of ParenListExprs.
4097   if (isa<ParenListExpr>(base)) {
4098     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4099     if (result.isInvalid()) return ExprError();
4100     base = result.get();
4101   }
4102 
4103   // Handle any non-overload placeholder types in the base and index
4104   // expressions.  We can't handle overloads here because the other
4105   // operand might be an overloadable type, in which case the overload
4106   // resolution for the operator overload should get the first crack
4107   // at the overload.
4108   bool IsMSPropertySubscript = false;
4109   if (base->getType()->isNonOverloadPlaceholderType()) {
4110     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4111     if (!IsMSPropertySubscript) {
4112       ExprResult result = CheckPlaceholderExpr(base);
4113       if (result.isInvalid())
4114         return ExprError();
4115       base = result.get();
4116     }
4117   }
4118   if (idx->getType()->isNonOverloadPlaceholderType()) {
4119     ExprResult result = CheckPlaceholderExpr(idx);
4120     if (result.isInvalid()) return ExprError();
4121     idx = result.get();
4122   }
4123 
4124   // Build an unanalyzed expression if either operand is type-dependent.
4125   if (getLangOpts().CPlusPlus &&
4126       (base->isTypeDependent() || idx->isTypeDependent())) {
4127     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4128                                             VK_LValue, OK_Ordinary, rbLoc);
4129   }
4130 
4131   // MSDN, property (C++)
4132   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4133   // This attribute can also be used in the declaration of an empty array in a
4134   // class or structure definition. For example:
4135   // __declspec(property(get=GetX, put=PutX)) int x[];
4136   // The above statement indicates that x[] can be used with one or more array
4137   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4138   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4139   if (IsMSPropertySubscript) {
4140     // Build MS property subscript expression if base is MS property reference
4141     // or MS property subscript.
4142     return new (Context) MSPropertySubscriptExpr(
4143         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4144   }
4145 
4146   // Use C++ overloaded-operator rules if either operand has record
4147   // type.  The spec says to do this if either type is *overloadable*,
4148   // but enum types can't declare subscript operators or conversion
4149   // operators, so there's nothing interesting for overload resolution
4150   // to do if there aren't any record types involved.
4151   //
4152   // ObjC pointers have their own subscripting logic that is not tied
4153   // to overload resolution and so should not take this path.
4154   if (getLangOpts().CPlusPlus &&
4155       (base->getType()->isRecordType() ||
4156        (!base->getType()->isObjCObjectPointerType() &&
4157         idx->getType()->isRecordType()))) {
4158     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4159   }
4160 
4161   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4162 }
4163 
4164 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4165                                           Expr *LowerBound,
4166                                           SourceLocation ColonLoc, Expr *Length,
4167                                           SourceLocation RBLoc) {
4168   if (Base->getType()->isPlaceholderType() &&
4169       !Base->getType()->isSpecificPlaceholderType(
4170           BuiltinType::OMPArraySection)) {
4171     ExprResult Result = CheckPlaceholderExpr(Base);
4172     if (Result.isInvalid())
4173       return ExprError();
4174     Base = Result.get();
4175   }
4176   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4177     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4178     if (Result.isInvalid())
4179       return ExprError();
4180     Result = DefaultLvalueConversion(Result.get());
4181     if (Result.isInvalid())
4182       return ExprError();
4183     LowerBound = Result.get();
4184   }
4185   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4186     ExprResult Result = CheckPlaceholderExpr(Length);
4187     if (Result.isInvalid())
4188       return ExprError();
4189     Result = DefaultLvalueConversion(Result.get());
4190     if (Result.isInvalid())
4191       return ExprError();
4192     Length = Result.get();
4193   }
4194 
4195   // Build an unanalyzed expression if either operand is type-dependent.
4196   if (Base->isTypeDependent() ||
4197       (LowerBound &&
4198        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4199       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4200     return new (Context)
4201         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4202                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4203   }
4204 
4205   // Perform default conversions.
4206   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4207   QualType ResultTy;
4208   if (OriginalTy->isAnyPointerType()) {
4209     ResultTy = OriginalTy->getPointeeType();
4210   } else if (OriginalTy->isArrayType()) {
4211     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4212   } else {
4213     return ExprError(
4214         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4215         << Base->getSourceRange());
4216   }
4217   // C99 6.5.2.1p1
4218   if (LowerBound) {
4219     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4220                                                       LowerBound);
4221     if (Res.isInvalid())
4222       return ExprError(Diag(LowerBound->getExprLoc(),
4223                             diag::err_omp_typecheck_section_not_integer)
4224                        << 0 << LowerBound->getSourceRange());
4225     LowerBound = Res.get();
4226 
4227     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4228         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4229       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4230           << 0 << LowerBound->getSourceRange();
4231   }
4232   if (Length) {
4233     auto Res =
4234         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4235     if (Res.isInvalid())
4236       return ExprError(Diag(Length->getExprLoc(),
4237                             diag::err_omp_typecheck_section_not_integer)
4238                        << 1 << Length->getSourceRange());
4239     Length = Res.get();
4240 
4241     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4242         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4243       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4244           << 1 << Length->getSourceRange();
4245   }
4246 
4247   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4248   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4249   // type. Note that functions are not objects, and that (in C99 parlance)
4250   // incomplete types are not object types.
4251   if (ResultTy->isFunctionType()) {
4252     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4253         << ResultTy << Base->getSourceRange();
4254     return ExprError();
4255   }
4256 
4257   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4258                           diag::err_omp_section_incomplete_type, Base))
4259     return ExprError();
4260 
4261   if (LowerBound) {
4262     llvm::APSInt LowerBoundValue;
4263     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4264       // OpenMP 4.0, [2.4 Array Sections]
4265       // The lower-bound and length must evaluate to non-negative integers.
4266       if (LowerBoundValue.isNegative()) {
4267         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4268             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4269             << LowerBound->getSourceRange();
4270         return ExprError();
4271       }
4272     }
4273   }
4274 
4275   if (Length) {
4276     llvm::APSInt LengthValue;
4277     if (Length->EvaluateAsInt(LengthValue, Context)) {
4278       // OpenMP 4.0, [2.4 Array Sections]
4279       // The lower-bound and length must evaluate to non-negative integers.
4280       if (LengthValue.isNegative()) {
4281         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4282             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4283             << Length->getSourceRange();
4284         return ExprError();
4285       }
4286     }
4287   } else if (ColonLoc.isValid() &&
4288              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4289                                       !OriginalTy->isVariableArrayType()))) {
4290     // OpenMP 4.0, [2.4 Array Sections]
4291     // When the size of the array dimension is not known, the length must be
4292     // specified explicitly.
4293     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4294         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4295     return ExprError();
4296   }
4297 
4298   if (!Base->getType()->isSpecificPlaceholderType(
4299           BuiltinType::OMPArraySection)) {
4300     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4301     if (Result.isInvalid())
4302       return ExprError();
4303     Base = Result.get();
4304   }
4305   return new (Context)
4306       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4307                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4308 }
4309 
4310 ExprResult
4311 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4312                                       Expr *Idx, SourceLocation RLoc) {
4313   Expr *LHSExp = Base;
4314   Expr *RHSExp = Idx;
4315 
4316   // Perform default conversions.
4317   if (!LHSExp->getType()->getAs<VectorType>()) {
4318     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4319     if (Result.isInvalid())
4320       return ExprError();
4321     LHSExp = Result.get();
4322   }
4323   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4324   if (Result.isInvalid())
4325     return ExprError();
4326   RHSExp = Result.get();
4327 
4328   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4329   ExprValueKind VK = VK_LValue;
4330   ExprObjectKind OK = OK_Ordinary;
4331 
4332   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4333   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4334   // in the subscript position. As a result, we need to derive the array base
4335   // and index from the expression types.
4336   Expr *BaseExpr, *IndexExpr;
4337   QualType ResultType;
4338   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4339     BaseExpr = LHSExp;
4340     IndexExpr = RHSExp;
4341     ResultType = Context.DependentTy;
4342   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4343     BaseExpr = LHSExp;
4344     IndexExpr = RHSExp;
4345     ResultType = PTy->getPointeeType();
4346   } else if (const ObjCObjectPointerType *PTy =
4347                LHSTy->getAs<ObjCObjectPointerType>()) {
4348     BaseExpr = LHSExp;
4349     IndexExpr = RHSExp;
4350 
4351     // Use custom logic if this should be the pseudo-object subscript
4352     // expression.
4353     if (!LangOpts.isSubscriptPointerArithmetic())
4354       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4355                                           nullptr);
4356 
4357     ResultType = PTy->getPointeeType();
4358   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4359      // Handle the uncommon case of "123[Ptr]".
4360     BaseExpr = RHSExp;
4361     IndexExpr = LHSExp;
4362     ResultType = PTy->getPointeeType();
4363   } else if (const ObjCObjectPointerType *PTy =
4364                RHSTy->getAs<ObjCObjectPointerType>()) {
4365      // Handle the uncommon case of "123[Ptr]".
4366     BaseExpr = RHSExp;
4367     IndexExpr = LHSExp;
4368     ResultType = PTy->getPointeeType();
4369     if (!LangOpts.isSubscriptPointerArithmetic()) {
4370       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4371         << ResultType << BaseExpr->getSourceRange();
4372       return ExprError();
4373     }
4374   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4375     BaseExpr = LHSExp;    // vectors: V[123]
4376     IndexExpr = RHSExp;
4377     VK = LHSExp->getValueKind();
4378     if (VK != VK_RValue)
4379       OK = OK_VectorComponent;
4380 
4381     // FIXME: need to deal with const...
4382     ResultType = VTy->getElementType();
4383   } else if (LHSTy->isArrayType()) {
4384     // If we see an array that wasn't promoted by
4385     // DefaultFunctionArrayLvalueConversion, it must be an array that
4386     // wasn't promoted because of the C90 rule that doesn't
4387     // allow promoting non-lvalue arrays.  Warn, then
4388     // force the promotion here.
4389     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4390         LHSExp->getSourceRange();
4391     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4392                                CK_ArrayToPointerDecay).get();
4393     LHSTy = LHSExp->getType();
4394 
4395     BaseExpr = LHSExp;
4396     IndexExpr = RHSExp;
4397     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4398   } else if (RHSTy->isArrayType()) {
4399     // Same as previous, except for 123[f().a] case
4400     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4401         RHSExp->getSourceRange();
4402     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4403                                CK_ArrayToPointerDecay).get();
4404     RHSTy = RHSExp->getType();
4405 
4406     BaseExpr = RHSExp;
4407     IndexExpr = LHSExp;
4408     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4409   } else {
4410     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4411        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4412   }
4413   // C99 6.5.2.1p1
4414   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4415     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4416                      << IndexExpr->getSourceRange());
4417 
4418   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4419        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4420          && !IndexExpr->isTypeDependent())
4421     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4422 
4423   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4424   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4425   // type. Note that Functions are not objects, and that (in C99 parlance)
4426   // incomplete types are not object types.
4427   if (ResultType->isFunctionType()) {
4428     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4429       << ResultType << BaseExpr->getSourceRange();
4430     return ExprError();
4431   }
4432 
4433   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4434     // GNU extension: subscripting on pointer to void
4435     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4436       << BaseExpr->getSourceRange();
4437 
4438     // C forbids expressions of unqualified void type from being l-values.
4439     // See IsCForbiddenLValueType.
4440     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4441   } else if (!ResultType->isDependentType() &&
4442       RequireCompleteType(LLoc, ResultType,
4443                           diag::err_subscript_incomplete_type, BaseExpr))
4444     return ExprError();
4445 
4446   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4447          !ResultType.isCForbiddenLValueType());
4448 
4449   return new (Context)
4450       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4451 }
4452 
4453 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4454                                         FunctionDecl *FD,
4455                                         ParmVarDecl *Param) {
4456   if (Param->hasUnparsedDefaultArg()) {
4457     Diag(CallLoc,
4458          diag::err_use_of_default_argument_to_function_declared_later) <<
4459       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4460     Diag(UnparsedDefaultArgLocs[Param],
4461          diag::note_default_argument_declared_here);
4462     return ExprError();
4463   }
4464 
4465   if (Param->hasUninstantiatedDefaultArg()) {
4466     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4467 
4468     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4469                                                  Param);
4470 
4471     // Instantiate the expression.
4472     MultiLevelTemplateArgumentList MutiLevelArgList
4473       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4474 
4475     InstantiatingTemplate Inst(*this, CallLoc, Param,
4476                                MutiLevelArgList.getInnermost());
4477     if (Inst.isInvalid())
4478       return ExprError();
4479 
4480     ExprResult Result;
4481     {
4482       // C++ [dcl.fct.default]p5:
4483       //   The names in the [default argument] expression are bound, and
4484       //   the semantic constraints are checked, at the point where the
4485       //   default argument expression appears.
4486       ContextRAII SavedContext(*this, FD);
4487       LocalInstantiationScope Local(*this);
4488       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4489     }
4490     if (Result.isInvalid())
4491       return ExprError();
4492 
4493     // Check the expression as an initializer for the parameter.
4494     InitializedEntity Entity
4495       = InitializedEntity::InitializeParameter(Context, Param);
4496     InitializationKind Kind
4497       = InitializationKind::CreateCopy(Param->getLocation(),
4498              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4499     Expr *ResultE = Result.getAs<Expr>();
4500 
4501     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4502     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4503     if (Result.isInvalid())
4504       return ExprError();
4505 
4506     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4507                                  Param->getOuterLocStart());
4508     if (Result.isInvalid())
4509       return ExprError();
4510 
4511     // Remember the instantiated default argument.
4512     Param->setDefaultArg(Result.getAs<Expr>());
4513     if (ASTMutationListener *L = getASTMutationListener()) {
4514       L->DefaultArgumentInstantiated(Param);
4515     }
4516   }
4517 
4518   // If the default expression creates temporaries, we need to
4519   // push them to the current stack of expression temporaries so they'll
4520   // be properly destroyed.
4521   // FIXME: We should really be rebuilding the default argument with new
4522   // bound temporaries; see the comment in PR5810.
4523   // We don't need to do that with block decls, though, because
4524   // blocks in default argument expression can never capture anything.
4525   if (isa<ExprWithCleanups>(Param->getInit())) {
4526     // Set the "needs cleanups" bit regardless of whether there are
4527     // any explicit objects.
4528     ExprNeedsCleanups = true;
4529 
4530     // Append all the objects to the cleanup list.  Right now, this
4531     // should always be a no-op, because blocks in default argument
4532     // expressions should never be able to capture anything.
4533     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4534            "default argument expression has capturing blocks?");
4535   }
4536 
4537   // We already type-checked the argument, so we know it works.
4538   // Just mark all of the declarations in this potentially-evaluated expression
4539   // as being "referenced".
4540   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4541                                    /*SkipLocalVariables=*/true);
4542   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4543 }
4544 
4545 
4546 Sema::VariadicCallType
4547 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4548                           Expr *Fn) {
4549   if (Proto && Proto->isVariadic()) {
4550     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4551       return VariadicConstructor;
4552     else if (Fn && Fn->getType()->isBlockPointerType())
4553       return VariadicBlock;
4554     else if (FDecl) {
4555       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4556         if (Method->isInstance())
4557           return VariadicMethod;
4558     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4559       return VariadicMethod;
4560     return VariadicFunction;
4561   }
4562   return VariadicDoesNotApply;
4563 }
4564 
4565 namespace {
4566 class FunctionCallCCC : public FunctionCallFilterCCC {
4567 public:
4568   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4569                   unsigned NumArgs, MemberExpr *ME)
4570       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4571         FunctionName(FuncName) {}
4572 
4573   bool ValidateCandidate(const TypoCorrection &candidate) override {
4574     if (!candidate.getCorrectionSpecifier() ||
4575         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4576       return false;
4577     }
4578 
4579     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4580   }
4581 
4582 private:
4583   const IdentifierInfo *const FunctionName;
4584 };
4585 }
4586 
4587 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4588                                                FunctionDecl *FDecl,
4589                                                ArrayRef<Expr *> Args) {
4590   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4591   DeclarationName FuncName = FDecl->getDeclName();
4592   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4593 
4594   if (TypoCorrection Corrected = S.CorrectTypo(
4595           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4596           S.getScopeForContext(S.CurContext), nullptr,
4597           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4598                                              Args.size(), ME),
4599           Sema::CTK_ErrorRecovery)) {
4600     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4601       if (Corrected.isOverloaded()) {
4602         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4603         OverloadCandidateSet::iterator Best;
4604         for (NamedDecl *CD : Corrected) {
4605           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4606             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4607                                    OCS);
4608         }
4609         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4610         case OR_Success:
4611           ND = Best->FoundDecl;
4612           Corrected.setCorrectionDecl(ND);
4613           break;
4614         default:
4615           break;
4616         }
4617       }
4618       ND = ND->getUnderlyingDecl();
4619       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4620         return Corrected;
4621     }
4622   }
4623   return TypoCorrection();
4624 }
4625 
4626 /// ConvertArgumentsForCall - Converts the arguments specified in
4627 /// Args/NumArgs to the parameter types of the function FDecl with
4628 /// function prototype Proto. Call is the call expression itself, and
4629 /// Fn is the function expression. For a C++ member function, this
4630 /// routine does not attempt to convert the object argument. Returns
4631 /// true if the call is ill-formed.
4632 bool
4633 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4634                               FunctionDecl *FDecl,
4635                               const FunctionProtoType *Proto,
4636                               ArrayRef<Expr *> Args,
4637                               SourceLocation RParenLoc,
4638                               bool IsExecConfig) {
4639   // Bail out early if calling a builtin with custom typechecking.
4640   if (FDecl)
4641     if (unsigned ID = FDecl->getBuiltinID())
4642       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4643         return false;
4644 
4645   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4646   // assignment, to the types of the corresponding parameter, ...
4647   unsigned NumParams = Proto->getNumParams();
4648   bool Invalid = false;
4649   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4650   unsigned FnKind = Fn->getType()->isBlockPointerType()
4651                        ? 1 /* block */
4652                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4653                                        : 0 /* function */);
4654 
4655   // If too few arguments are available (and we don't have default
4656   // arguments for the remaining parameters), don't make the call.
4657   if (Args.size() < NumParams) {
4658     if (Args.size() < MinArgs) {
4659       TypoCorrection TC;
4660       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4661         unsigned diag_id =
4662             MinArgs == NumParams && !Proto->isVariadic()
4663                 ? diag::err_typecheck_call_too_few_args_suggest
4664                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4665         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4666                                         << static_cast<unsigned>(Args.size())
4667                                         << TC.getCorrectionRange());
4668       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4669         Diag(RParenLoc,
4670              MinArgs == NumParams && !Proto->isVariadic()
4671                  ? diag::err_typecheck_call_too_few_args_one
4672                  : diag::err_typecheck_call_too_few_args_at_least_one)
4673             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4674       else
4675         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4676                             ? diag::err_typecheck_call_too_few_args
4677                             : diag::err_typecheck_call_too_few_args_at_least)
4678             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4679             << Fn->getSourceRange();
4680 
4681       // Emit the location of the prototype.
4682       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4683         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4684           << FDecl;
4685 
4686       return true;
4687     }
4688     Call->setNumArgs(Context, NumParams);
4689   }
4690 
4691   // If too many are passed and not variadic, error on the extras and drop
4692   // them.
4693   if (Args.size() > NumParams) {
4694     if (!Proto->isVariadic()) {
4695       TypoCorrection TC;
4696       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4697         unsigned diag_id =
4698             MinArgs == NumParams && !Proto->isVariadic()
4699                 ? diag::err_typecheck_call_too_many_args_suggest
4700                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4701         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4702                                         << static_cast<unsigned>(Args.size())
4703                                         << TC.getCorrectionRange());
4704       } else if (NumParams == 1 && FDecl &&
4705                  FDecl->getParamDecl(0)->getDeclName())
4706         Diag(Args[NumParams]->getLocStart(),
4707              MinArgs == NumParams
4708                  ? diag::err_typecheck_call_too_many_args_one
4709                  : diag::err_typecheck_call_too_many_args_at_most_one)
4710             << FnKind << FDecl->getParamDecl(0)
4711             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4712             << SourceRange(Args[NumParams]->getLocStart(),
4713                            Args.back()->getLocEnd());
4714       else
4715         Diag(Args[NumParams]->getLocStart(),
4716              MinArgs == NumParams
4717                  ? diag::err_typecheck_call_too_many_args
4718                  : diag::err_typecheck_call_too_many_args_at_most)
4719             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4720             << Fn->getSourceRange()
4721             << SourceRange(Args[NumParams]->getLocStart(),
4722                            Args.back()->getLocEnd());
4723 
4724       // Emit the location of the prototype.
4725       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4726         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4727           << FDecl;
4728 
4729       // This deletes the extra arguments.
4730       Call->setNumArgs(Context, NumParams);
4731       return true;
4732     }
4733   }
4734   SmallVector<Expr *, 8> AllArgs;
4735   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4736 
4737   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4738                                    Proto, 0, Args, AllArgs, CallType);
4739   if (Invalid)
4740     return true;
4741   unsigned TotalNumArgs = AllArgs.size();
4742   for (unsigned i = 0; i < TotalNumArgs; ++i)
4743     Call->setArg(i, AllArgs[i]);
4744 
4745   return false;
4746 }
4747 
4748 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4749                                   const FunctionProtoType *Proto,
4750                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4751                                   SmallVectorImpl<Expr *> &AllArgs,
4752                                   VariadicCallType CallType, bool AllowExplicit,
4753                                   bool IsListInitialization) {
4754   unsigned NumParams = Proto->getNumParams();
4755   bool Invalid = false;
4756   size_t ArgIx = 0;
4757   // Continue to check argument types (even if we have too few/many args).
4758   for (unsigned i = FirstParam; i < NumParams; i++) {
4759     QualType ProtoArgType = Proto->getParamType(i);
4760 
4761     Expr *Arg;
4762     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4763     if (ArgIx < Args.size()) {
4764       Arg = Args[ArgIx++];
4765 
4766       if (RequireCompleteType(Arg->getLocStart(),
4767                               ProtoArgType,
4768                               diag::err_call_incomplete_argument, Arg))
4769         return true;
4770 
4771       // Strip the unbridged-cast placeholder expression off, if applicable.
4772       bool CFAudited = false;
4773       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4774           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4775           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4776         Arg = stripARCUnbridgedCast(Arg);
4777       else if (getLangOpts().ObjCAutoRefCount &&
4778                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4779                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4780         CFAudited = true;
4781 
4782       InitializedEntity Entity =
4783           Param ? InitializedEntity::InitializeParameter(Context, Param,
4784                                                          ProtoArgType)
4785                 : InitializedEntity::InitializeParameter(
4786                       Context, ProtoArgType, Proto->isParamConsumed(i));
4787 
4788       // Remember that parameter belongs to a CF audited API.
4789       if (CFAudited)
4790         Entity.setParameterCFAudited();
4791 
4792       ExprResult ArgE = PerformCopyInitialization(
4793           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4794       if (ArgE.isInvalid())
4795         return true;
4796 
4797       Arg = ArgE.getAs<Expr>();
4798     } else {
4799       assert(Param && "can't use default arguments without a known callee");
4800 
4801       ExprResult ArgExpr =
4802         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4803       if (ArgExpr.isInvalid())
4804         return true;
4805 
4806       Arg = ArgExpr.getAs<Expr>();
4807     }
4808 
4809     // Check for array bounds violations for each argument to the call. This
4810     // check only triggers warnings when the argument isn't a more complex Expr
4811     // with its own checking, such as a BinaryOperator.
4812     CheckArrayAccess(Arg);
4813 
4814     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4815     CheckStaticArrayArgument(CallLoc, Param, Arg);
4816 
4817     AllArgs.push_back(Arg);
4818   }
4819 
4820   // If this is a variadic call, handle args passed through "...".
4821   if (CallType != VariadicDoesNotApply) {
4822     // Assume that extern "C" functions with variadic arguments that
4823     // return __unknown_anytype aren't *really* variadic.
4824     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4825         FDecl->isExternC()) {
4826       for (Expr *A : Args.slice(ArgIx)) {
4827         QualType paramType; // ignored
4828         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4829         Invalid |= arg.isInvalid();
4830         AllArgs.push_back(arg.get());
4831       }
4832 
4833     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4834     } else {
4835       for (Expr *A : Args.slice(ArgIx)) {
4836         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4837         Invalid |= Arg.isInvalid();
4838         AllArgs.push_back(Arg.get());
4839       }
4840     }
4841 
4842     // Check for array bounds violations.
4843     for (Expr *A : Args.slice(ArgIx))
4844       CheckArrayAccess(A);
4845   }
4846   return Invalid;
4847 }
4848 
4849 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4850   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4851   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4852     TL = DTL.getOriginalLoc();
4853   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4854     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4855       << ATL.getLocalSourceRange();
4856 }
4857 
4858 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4859 /// array parameter, check that it is non-null, and that if it is formed by
4860 /// array-to-pointer decay, the underlying array is sufficiently large.
4861 ///
4862 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4863 /// array type derivation, then for each call to the function, the value of the
4864 /// corresponding actual argument shall provide access to the first element of
4865 /// an array with at least as many elements as specified by the size expression.
4866 void
4867 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4868                                ParmVarDecl *Param,
4869                                const Expr *ArgExpr) {
4870   // Static array parameters are not supported in C++.
4871   if (!Param || getLangOpts().CPlusPlus)
4872     return;
4873 
4874   QualType OrigTy = Param->getOriginalType();
4875 
4876   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4877   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4878     return;
4879 
4880   if (ArgExpr->isNullPointerConstant(Context,
4881                                      Expr::NPC_NeverValueDependent)) {
4882     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4883     DiagnoseCalleeStaticArrayParam(*this, Param);
4884     return;
4885   }
4886 
4887   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4888   if (!CAT)
4889     return;
4890 
4891   const ConstantArrayType *ArgCAT =
4892     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4893   if (!ArgCAT)
4894     return;
4895 
4896   if (ArgCAT->getSize().ult(CAT->getSize())) {
4897     Diag(CallLoc, diag::warn_static_array_too_small)
4898       << ArgExpr->getSourceRange()
4899       << (unsigned) ArgCAT->getSize().getZExtValue()
4900       << (unsigned) CAT->getSize().getZExtValue();
4901     DiagnoseCalleeStaticArrayParam(*this, Param);
4902   }
4903 }
4904 
4905 /// Given a function expression of unknown-any type, try to rebuild it
4906 /// to have a function type.
4907 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4908 
4909 /// Is the given type a placeholder that we need to lower out
4910 /// immediately during argument processing?
4911 static bool isPlaceholderToRemoveAsArg(QualType type) {
4912   // Placeholders are never sugared.
4913   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4914   if (!placeholder) return false;
4915 
4916   switch (placeholder->getKind()) {
4917   // Ignore all the non-placeholder types.
4918 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4919 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4920 #include "clang/AST/BuiltinTypes.def"
4921     return false;
4922 
4923   // We cannot lower out overload sets; they might validly be resolved
4924   // by the call machinery.
4925   case BuiltinType::Overload:
4926     return false;
4927 
4928   // Unbridged casts in ARC can be handled in some call positions and
4929   // should be left in place.
4930   case BuiltinType::ARCUnbridgedCast:
4931     return false;
4932 
4933   // Pseudo-objects should be converted as soon as possible.
4934   case BuiltinType::PseudoObject:
4935     return true;
4936 
4937   // The debugger mode could theoretically but currently does not try
4938   // to resolve unknown-typed arguments based on known parameter types.
4939   case BuiltinType::UnknownAny:
4940     return true;
4941 
4942   // These are always invalid as call arguments and should be reported.
4943   case BuiltinType::BoundMember:
4944   case BuiltinType::BuiltinFn:
4945   case BuiltinType::OMPArraySection:
4946     return true;
4947 
4948   }
4949   llvm_unreachable("bad builtin type kind");
4950 }
4951 
4952 /// Check an argument list for placeholders that we won't try to
4953 /// handle later.
4954 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4955   // Apply this processing to all the arguments at once instead of
4956   // dying at the first failure.
4957   bool hasInvalid = false;
4958   for (size_t i = 0, e = args.size(); i != e; i++) {
4959     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4960       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4961       if (result.isInvalid()) hasInvalid = true;
4962       else args[i] = result.get();
4963     } else if (hasInvalid) {
4964       (void)S.CorrectDelayedTyposInExpr(args[i]);
4965     }
4966   }
4967   return hasInvalid;
4968 }
4969 
4970 /// If a builtin function has a pointer argument with no explicit address
4971 /// space, then it should be able to accept a pointer to any address
4972 /// space as input.  In order to do this, we need to replace the
4973 /// standard builtin declaration with one that uses the same address space
4974 /// as the call.
4975 ///
4976 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4977 ///                  it does not contain any pointer arguments without
4978 ///                  an address space qualifer.  Otherwise the rewritten
4979 ///                  FunctionDecl is returned.
4980 /// TODO: Handle pointer return types.
4981 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4982                                                 const FunctionDecl *FDecl,
4983                                                 MultiExprArg ArgExprs) {
4984 
4985   QualType DeclType = FDecl->getType();
4986   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4987 
4988   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4989       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4990     return nullptr;
4991 
4992   bool NeedsNewDecl = false;
4993   unsigned i = 0;
4994   SmallVector<QualType, 8> OverloadParams;
4995 
4996   for (QualType ParamType : FT->param_types()) {
4997 
4998     // Convert array arguments to pointer to simplify type lookup.
4999     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
5000     QualType ArgType = Arg->getType();
5001     if (!ParamType->isPointerType() ||
5002         ParamType.getQualifiers().hasAddressSpace() ||
5003         !ArgType->isPointerType() ||
5004         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5005       OverloadParams.push_back(ParamType);
5006       continue;
5007     }
5008 
5009     NeedsNewDecl = true;
5010     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5011 
5012     QualType PointeeType = ParamType->getPointeeType();
5013     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5014     OverloadParams.push_back(Context.getPointerType(PointeeType));
5015   }
5016 
5017   if (!NeedsNewDecl)
5018     return nullptr;
5019 
5020   FunctionProtoType::ExtProtoInfo EPI;
5021   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5022                                                 OverloadParams, EPI);
5023   DeclContext *Parent = Context.getTranslationUnitDecl();
5024   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5025                                                     FDecl->getLocation(),
5026                                                     FDecl->getLocation(),
5027                                                     FDecl->getIdentifier(),
5028                                                     OverloadTy,
5029                                                     /*TInfo=*/nullptr,
5030                                                     SC_Extern, false,
5031                                                     /*hasPrototype=*/true);
5032   SmallVector<ParmVarDecl*, 16> Params;
5033   FT = cast<FunctionProtoType>(OverloadTy);
5034   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5035     QualType ParamType = FT->getParamType(i);
5036     ParmVarDecl *Parm =
5037         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5038                                 SourceLocation(), nullptr, ParamType,
5039                                 /*TInfo=*/nullptr, SC_None, nullptr);
5040     Parm->setScopeInfo(0, i);
5041     Params.push_back(Parm);
5042   }
5043   OverloadDecl->setParams(Params);
5044   return OverloadDecl;
5045 }
5046 
5047 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5048                                        std::size_t NumArgs) {
5049   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5050                          /*PartialOverloading=*/false))
5051     return Callee->isVariadic();
5052   return Callee->getMinRequiredArguments() <= NumArgs;
5053 }
5054 
5055 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5056 /// This provides the location of the left/right parens and a list of comma
5057 /// locations.
5058 ExprResult
5059 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5060                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
5061                     Expr *ExecConfig, bool IsExecConfig) {
5062   // Since this might be a postfix expression, get rid of ParenListExprs.
5063   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
5064   if (Result.isInvalid()) return ExprError();
5065   Fn = Result.get();
5066 
5067   if (checkArgsForPlaceholders(*this, ArgExprs))
5068     return ExprError();
5069 
5070   if (getLangOpts().CPlusPlus) {
5071     // If this is a pseudo-destructor expression, build the call immediately.
5072     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5073       if (!ArgExprs.empty()) {
5074         // Pseudo-destructor calls should not have any arguments.
5075         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5076           << FixItHint::CreateRemoval(
5077                                     SourceRange(ArgExprs.front()->getLocStart(),
5078                                                 ArgExprs.back()->getLocEnd()));
5079       }
5080 
5081       return new (Context)
5082           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5083     }
5084     if (Fn->getType() == Context.PseudoObjectTy) {
5085       ExprResult result = CheckPlaceholderExpr(Fn);
5086       if (result.isInvalid()) return ExprError();
5087       Fn = result.get();
5088     }
5089 
5090     // Determine whether this is a dependent call inside a C++ template,
5091     // in which case we won't do any semantic analysis now.
5092     bool Dependent = false;
5093     if (Fn->isTypeDependent())
5094       Dependent = true;
5095     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5096       Dependent = true;
5097 
5098     if (Dependent) {
5099       if (ExecConfig) {
5100         return new (Context) CUDAKernelCallExpr(
5101             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5102             Context.DependentTy, VK_RValue, RParenLoc);
5103       } else {
5104         return new (Context) CallExpr(
5105             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5106       }
5107     }
5108 
5109     // Determine whether this is a call to an object (C++ [over.call.object]).
5110     if (Fn->getType()->isRecordType())
5111       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5112                                           RParenLoc);
5113 
5114     if (Fn->getType() == Context.UnknownAnyTy) {
5115       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5116       if (result.isInvalid()) return ExprError();
5117       Fn = result.get();
5118     }
5119 
5120     if (Fn->getType() == Context.BoundMemberTy) {
5121       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5122     }
5123   }
5124 
5125   // Check for overloaded calls.  This can happen even in C due to extensions.
5126   if (Fn->getType() == Context.OverloadTy) {
5127     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5128 
5129     // We aren't supposed to apply this logic for if there's an '&' involved.
5130     if (!find.HasFormOfMemberPointer) {
5131       OverloadExpr *ovl = find.Expression;
5132       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5133         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
5134                                        RParenLoc, ExecConfig,
5135                                        /*AllowTypoCorrection=*/true,
5136                                        find.IsAddressOfOperand);
5137       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5138     }
5139   }
5140 
5141   // If we're directly calling a function, get the appropriate declaration.
5142   if (Fn->getType() == Context.UnknownAnyTy) {
5143     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5144     if (result.isInvalid()) return ExprError();
5145     Fn = result.get();
5146   }
5147 
5148   Expr *NakedFn = Fn->IgnoreParens();
5149 
5150   bool CallingNDeclIndirectly = false;
5151   NamedDecl *NDecl = nullptr;
5152   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5153     if (UnOp->getOpcode() == UO_AddrOf) {
5154       CallingNDeclIndirectly = true;
5155       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5156     }
5157   }
5158 
5159   if (isa<DeclRefExpr>(NakedFn)) {
5160     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5161 
5162     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5163     if (FDecl && FDecl->getBuiltinID()) {
5164       // Rewrite the function decl for this builtin by replacing parameters
5165       // with no explicit address space with the address space of the arguments
5166       // in ArgExprs.
5167       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5168         NDecl = FDecl;
5169         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5170                            SourceLocation(), FDecl, false,
5171                            SourceLocation(), FDecl->getType(),
5172                            Fn->getValueKind(), FDecl);
5173       }
5174     }
5175   } else if (isa<MemberExpr>(NakedFn))
5176     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5177 
5178   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5179     if (CallingNDeclIndirectly &&
5180         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5181                                            Fn->getLocStart()))
5182       return ExprError();
5183 
5184     // CheckEnableIf assumes that the we're passing in a sane number of args for
5185     // FD, but that doesn't always hold true here. This is because, in some
5186     // cases, we'll emit a diag about an ill-formed function call, but then
5187     // we'll continue on as if the function call wasn't ill-formed. So, if the
5188     // number of args looks incorrect, don't do enable_if checks; we should've
5189     // already emitted an error about the bad call.
5190     if (FD->hasAttr<EnableIfAttr>() &&
5191         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5192       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5193         Diag(Fn->getLocStart(),
5194              isa<CXXMethodDecl>(FD) ?
5195                  diag::err_ovl_no_viable_member_function_in_call :
5196                  diag::err_ovl_no_viable_function_in_call)
5197           << FD << FD->getSourceRange();
5198         Diag(FD->getLocation(),
5199              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5200             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5201       }
5202     }
5203   }
5204 
5205   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5206                                ExecConfig, IsExecConfig);
5207 }
5208 
5209 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5210 ///
5211 /// __builtin_astype( value, dst type )
5212 ///
5213 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5214                                  SourceLocation BuiltinLoc,
5215                                  SourceLocation RParenLoc) {
5216   ExprValueKind VK = VK_RValue;
5217   ExprObjectKind OK = OK_Ordinary;
5218   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5219   QualType SrcTy = E->getType();
5220   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5221     return ExprError(Diag(BuiltinLoc,
5222                           diag::err_invalid_astype_of_different_size)
5223                      << DstTy
5224                      << SrcTy
5225                      << E->getSourceRange());
5226   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5227 }
5228 
5229 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5230 /// provided arguments.
5231 ///
5232 /// __builtin_convertvector( value, dst type )
5233 ///
5234 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5235                                         SourceLocation BuiltinLoc,
5236                                         SourceLocation RParenLoc) {
5237   TypeSourceInfo *TInfo;
5238   GetTypeFromParser(ParsedDestTy, &TInfo);
5239   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5240 }
5241 
5242 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5243 /// i.e. an expression not of \p OverloadTy.  The expression should
5244 /// unary-convert to an expression of function-pointer or
5245 /// block-pointer type.
5246 ///
5247 /// \param NDecl the declaration being called, if available
5248 ExprResult
5249 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5250                             SourceLocation LParenLoc,
5251                             ArrayRef<Expr *> Args,
5252                             SourceLocation RParenLoc,
5253                             Expr *Config, bool IsExecConfig) {
5254   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5255   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5256 
5257   // Functions with 'interrupt' attribute cannot be called directly.
5258   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5259     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5260     return ExprError();
5261   }
5262 
5263   // Promote the function operand.
5264   // We special-case function promotion here because we only allow promoting
5265   // builtin functions to function pointers in the callee of a call.
5266   ExprResult Result;
5267   if (BuiltinID &&
5268       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5269     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5270                                CK_BuiltinFnToFnPtr).get();
5271   } else {
5272     Result = CallExprUnaryConversions(Fn);
5273   }
5274   if (Result.isInvalid())
5275     return ExprError();
5276   Fn = Result.get();
5277 
5278   // Make the call expr early, before semantic checks.  This guarantees cleanup
5279   // of arguments and function on error.
5280   CallExpr *TheCall;
5281   if (Config)
5282     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5283                                                cast<CallExpr>(Config), Args,
5284                                                Context.BoolTy, VK_RValue,
5285                                                RParenLoc);
5286   else
5287     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5288                                      VK_RValue, RParenLoc);
5289 
5290   if (!getLangOpts().CPlusPlus) {
5291     // C cannot always handle TypoExpr nodes in builtin calls and direct
5292     // function calls as their argument checking don't necessarily handle
5293     // dependent types properly, so make sure any TypoExprs have been
5294     // dealt with.
5295     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5296     if (!Result.isUsable()) return ExprError();
5297     TheCall = dyn_cast<CallExpr>(Result.get());
5298     if (!TheCall) return Result;
5299     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5300   }
5301 
5302   // Bail out early if calling a builtin with custom typechecking.
5303   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5304     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5305 
5306  retry:
5307   const FunctionType *FuncT;
5308   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5309     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5310     // have type pointer to function".
5311     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5312     if (!FuncT)
5313       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5314                          << Fn->getType() << Fn->getSourceRange());
5315   } else if (const BlockPointerType *BPT =
5316                Fn->getType()->getAs<BlockPointerType>()) {
5317     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5318   } else {
5319     // Handle calls to expressions of unknown-any type.
5320     if (Fn->getType() == Context.UnknownAnyTy) {
5321       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5322       if (rewrite.isInvalid()) return ExprError();
5323       Fn = rewrite.get();
5324       TheCall->setCallee(Fn);
5325       goto retry;
5326     }
5327 
5328     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5329       << Fn->getType() << Fn->getSourceRange());
5330   }
5331 
5332   if (getLangOpts().CUDA) {
5333     if (Config) {
5334       // CUDA: Kernel calls must be to global functions
5335       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5336         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5337             << FDecl->getName() << Fn->getSourceRange());
5338 
5339       // CUDA: Kernel function must have 'void' return type
5340       if (!FuncT->getReturnType()->isVoidType())
5341         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5342             << Fn->getType() << Fn->getSourceRange());
5343     } else {
5344       // CUDA: Calls to global functions must be configured
5345       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5346         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5347             << FDecl->getName() << Fn->getSourceRange());
5348     }
5349   }
5350 
5351   // Check for a valid return type
5352   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5353                           FDecl))
5354     return ExprError();
5355 
5356   // We know the result type of the call, set it.
5357   TheCall->setType(FuncT->getCallResultType(Context));
5358   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5359 
5360   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5361   if (Proto) {
5362     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5363                                 IsExecConfig))
5364       return ExprError();
5365   } else {
5366     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5367 
5368     if (FDecl) {
5369       // Check if we have too few/too many template arguments, based
5370       // on our knowledge of the function definition.
5371       const FunctionDecl *Def = nullptr;
5372       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5373         Proto = Def->getType()->getAs<FunctionProtoType>();
5374        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5375           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5376           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5377       }
5378 
5379       // If the function we're calling isn't a function prototype, but we have
5380       // a function prototype from a prior declaratiom, use that prototype.
5381       if (!FDecl->hasPrototype())
5382         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5383     }
5384 
5385     // Promote the arguments (C99 6.5.2.2p6).
5386     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5387       Expr *Arg = Args[i];
5388 
5389       if (Proto && i < Proto->getNumParams()) {
5390         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5391             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5392         ExprResult ArgE =
5393             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5394         if (ArgE.isInvalid())
5395           return true;
5396 
5397         Arg = ArgE.getAs<Expr>();
5398 
5399       } else {
5400         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5401 
5402         if (ArgE.isInvalid())
5403           return true;
5404 
5405         Arg = ArgE.getAs<Expr>();
5406       }
5407 
5408       if (RequireCompleteType(Arg->getLocStart(),
5409                               Arg->getType(),
5410                               diag::err_call_incomplete_argument, Arg))
5411         return ExprError();
5412 
5413       TheCall->setArg(i, Arg);
5414     }
5415   }
5416 
5417   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5418     if (!Method->isStatic())
5419       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5420         << Fn->getSourceRange());
5421 
5422   // Check for sentinels
5423   if (NDecl)
5424     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5425 
5426   // Do special checking on direct calls to functions.
5427   if (FDecl) {
5428     if (CheckFunctionCall(FDecl, TheCall, Proto))
5429       return ExprError();
5430 
5431     if (BuiltinID)
5432       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5433   } else if (NDecl) {
5434     if (CheckPointerCall(NDecl, TheCall, Proto))
5435       return ExprError();
5436   } else {
5437     if (CheckOtherCall(TheCall, Proto))
5438       return ExprError();
5439   }
5440 
5441   return MaybeBindToTemporary(TheCall);
5442 }
5443 
5444 ExprResult
5445 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5446                            SourceLocation RParenLoc, Expr *InitExpr) {
5447   assert(Ty && "ActOnCompoundLiteral(): missing type");
5448   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5449 
5450   TypeSourceInfo *TInfo;
5451   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5452   if (!TInfo)
5453     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5454 
5455   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5456 }
5457 
5458 ExprResult
5459 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5460                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5461   QualType literalType = TInfo->getType();
5462 
5463   if (literalType->isArrayType()) {
5464     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5465           diag::err_illegal_decl_array_incomplete_type,
5466           SourceRange(LParenLoc,
5467                       LiteralExpr->getSourceRange().getEnd())))
5468       return ExprError();
5469     if (literalType->isVariableArrayType())
5470       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5471         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5472   } else if (!literalType->isDependentType() &&
5473              RequireCompleteType(LParenLoc, literalType,
5474                diag::err_typecheck_decl_incomplete_type,
5475                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5476     return ExprError();
5477 
5478   InitializedEntity Entity
5479     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5480   InitializationKind Kind
5481     = InitializationKind::CreateCStyleCast(LParenLoc,
5482                                            SourceRange(LParenLoc, RParenLoc),
5483                                            /*InitList=*/true);
5484   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5485   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5486                                       &literalType);
5487   if (Result.isInvalid())
5488     return ExprError();
5489   LiteralExpr = Result.get();
5490 
5491   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5492   if (isFileScope &&
5493       !LiteralExpr->isTypeDependent() &&
5494       !LiteralExpr->isValueDependent() &&
5495       !literalType->isDependentType()) { // 6.5.2.5p3
5496     if (CheckForConstantInitializer(LiteralExpr, literalType))
5497       return ExprError();
5498   }
5499 
5500   // In C, compound literals are l-values for some reason.
5501   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5502 
5503   return MaybeBindToTemporary(
5504            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5505                                              VK, LiteralExpr, isFileScope));
5506 }
5507 
5508 ExprResult
5509 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5510                     SourceLocation RBraceLoc) {
5511   // Immediately handle non-overload placeholders.  Overloads can be
5512   // resolved contextually, but everything else here can't.
5513   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5514     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5515       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5516 
5517       // Ignore failures; dropping the entire initializer list because
5518       // of one failure would be terrible for indexing/etc.
5519       if (result.isInvalid()) continue;
5520 
5521       InitArgList[I] = result.get();
5522     }
5523   }
5524 
5525   // Semantic analysis for initializers is done by ActOnDeclarator() and
5526   // CheckInitializer() - it requires knowledge of the object being intialized.
5527 
5528   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5529                                                RBraceLoc);
5530   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5531   return E;
5532 }
5533 
5534 /// Do an explicit extend of the given block pointer if we're in ARC.
5535 void Sema::maybeExtendBlockObject(ExprResult &E) {
5536   assert(E.get()->getType()->isBlockPointerType());
5537   assert(E.get()->isRValue());
5538 
5539   // Only do this in an r-value context.
5540   if (!getLangOpts().ObjCAutoRefCount) return;
5541 
5542   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5543                                CK_ARCExtendBlockObject, E.get(),
5544                                /*base path*/ nullptr, VK_RValue);
5545   ExprNeedsCleanups = true;
5546 }
5547 
5548 /// Prepare a conversion of the given expression to an ObjC object
5549 /// pointer type.
5550 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5551   QualType type = E.get()->getType();
5552   if (type->isObjCObjectPointerType()) {
5553     return CK_BitCast;
5554   } else if (type->isBlockPointerType()) {
5555     maybeExtendBlockObject(E);
5556     return CK_BlockPointerToObjCPointerCast;
5557   } else {
5558     assert(type->isPointerType());
5559     return CK_CPointerToObjCPointerCast;
5560   }
5561 }
5562 
5563 /// Prepares for a scalar cast, performing all the necessary stages
5564 /// except the final cast and returning the kind required.
5565 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5566   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5567   // Also, callers should have filtered out the invalid cases with
5568   // pointers.  Everything else should be possible.
5569 
5570   QualType SrcTy = Src.get()->getType();
5571   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5572     return CK_NoOp;
5573 
5574   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5575   case Type::STK_MemberPointer:
5576     llvm_unreachable("member pointer type in C");
5577 
5578   case Type::STK_CPointer:
5579   case Type::STK_BlockPointer:
5580   case Type::STK_ObjCObjectPointer:
5581     switch (DestTy->getScalarTypeKind()) {
5582     case Type::STK_CPointer: {
5583       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5584       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5585       if (SrcAS != DestAS)
5586         return CK_AddressSpaceConversion;
5587       return CK_BitCast;
5588     }
5589     case Type::STK_BlockPointer:
5590       return (SrcKind == Type::STK_BlockPointer
5591                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5592     case Type::STK_ObjCObjectPointer:
5593       if (SrcKind == Type::STK_ObjCObjectPointer)
5594         return CK_BitCast;
5595       if (SrcKind == Type::STK_CPointer)
5596         return CK_CPointerToObjCPointerCast;
5597       maybeExtendBlockObject(Src);
5598       return CK_BlockPointerToObjCPointerCast;
5599     case Type::STK_Bool:
5600       return CK_PointerToBoolean;
5601     case Type::STK_Integral:
5602       return CK_PointerToIntegral;
5603     case Type::STK_Floating:
5604     case Type::STK_FloatingComplex:
5605     case Type::STK_IntegralComplex:
5606     case Type::STK_MemberPointer:
5607       llvm_unreachable("illegal cast from pointer");
5608     }
5609     llvm_unreachable("Should have returned before this");
5610 
5611   case Type::STK_Bool: // casting from bool is like casting from an integer
5612   case Type::STK_Integral:
5613     switch (DestTy->getScalarTypeKind()) {
5614     case Type::STK_CPointer:
5615     case Type::STK_ObjCObjectPointer:
5616     case Type::STK_BlockPointer:
5617       if (Src.get()->isNullPointerConstant(Context,
5618                                            Expr::NPC_ValueDependentIsNull))
5619         return CK_NullToPointer;
5620       return CK_IntegralToPointer;
5621     case Type::STK_Bool:
5622       return CK_IntegralToBoolean;
5623     case Type::STK_Integral:
5624       return CK_IntegralCast;
5625     case Type::STK_Floating:
5626       return CK_IntegralToFloating;
5627     case Type::STK_IntegralComplex:
5628       Src = ImpCastExprToType(Src.get(),
5629                       DestTy->castAs<ComplexType>()->getElementType(),
5630                       CK_IntegralCast);
5631       return CK_IntegralRealToComplex;
5632     case Type::STK_FloatingComplex:
5633       Src = ImpCastExprToType(Src.get(),
5634                       DestTy->castAs<ComplexType>()->getElementType(),
5635                       CK_IntegralToFloating);
5636       return CK_FloatingRealToComplex;
5637     case Type::STK_MemberPointer:
5638       llvm_unreachable("member pointer type in C");
5639     }
5640     llvm_unreachable("Should have returned before this");
5641 
5642   case Type::STK_Floating:
5643     switch (DestTy->getScalarTypeKind()) {
5644     case Type::STK_Floating:
5645       return CK_FloatingCast;
5646     case Type::STK_Bool:
5647       return CK_FloatingToBoolean;
5648     case Type::STK_Integral:
5649       return CK_FloatingToIntegral;
5650     case Type::STK_FloatingComplex:
5651       Src = ImpCastExprToType(Src.get(),
5652                               DestTy->castAs<ComplexType>()->getElementType(),
5653                               CK_FloatingCast);
5654       return CK_FloatingRealToComplex;
5655     case Type::STK_IntegralComplex:
5656       Src = ImpCastExprToType(Src.get(),
5657                               DestTy->castAs<ComplexType>()->getElementType(),
5658                               CK_FloatingToIntegral);
5659       return CK_IntegralRealToComplex;
5660     case Type::STK_CPointer:
5661     case Type::STK_ObjCObjectPointer:
5662     case Type::STK_BlockPointer:
5663       llvm_unreachable("valid float->pointer cast?");
5664     case Type::STK_MemberPointer:
5665       llvm_unreachable("member pointer type in C");
5666     }
5667     llvm_unreachable("Should have returned before this");
5668 
5669   case Type::STK_FloatingComplex:
5670     switch (DestTy->getScalarTypeKind()) {
5671     case Type::STK_FloatingComplex:
5672       return CK_FloatingComplexCast;
5673     case Type::STK_IntegralComplex:
5674       return CK_FloatingComplexToIntegralComplex;
5675     case Type::STK_Floating: {
5676       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5677       if (Context.hasSameType(ET, DestTy))
5678         return CK_FloatingComplexToReal;
5679       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5680       return CK_FloatingCast;
5681     }
5682     case Type::STK_Bool:
5683       return CK_FloatingComplexToBoolean;
5684     case Type::STK_Integral:
5685       Src = ImpCastExprToType(Src.get(),
5686                               SrcTy->castAs<ComplexType>()->getElementType(),
5687                               CK_FloatingComplexToReal);
5688       return CK_FloatingToIntegral;
5689     case Type::STK_CPointer:
5690     case Type::STK_ObjCObjectPointer:
5691     case Type::STK_BlockPointer:
5692       llvm_unreachable("valid complex float->pointer cast?");
5693     case Type::STK_MemberPointer:
5694       llvm_unreachable("member pointer type in C");
5695     }
5696     llvm_unreachable("Should have returned before this");
5697 
5698   case Type::STK_IntegralComplex:
5699     switch (DestTy->getScalarTypeKind()) {
5700     case Type::STK_FloatingComplex:
5701       return CK_IntegralComplexToFloatingComplex;
5702     case Type::STK_IntegralComplex:
5703       return CK_IntegralComplexCast;
5704     case Type::STK_Integral: {
5705       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5706       if (Context.hasSameType(ET, DestTy))
5707         return CK_IntegralComplexToReal;
5708       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5709       return CK_IntegralCast;
5710     }
5711     case Type::STK_Bool:
5712       return CK_IntegralComplexToBoolean;
5713     case Type::STK_Floating:
5714       Src = ImpCastExprToType(Src.get(),
5715                               SrcTy->castAs<ComplexType>()->getElementType(),
5716                               CK_IntegralComplexToReal);
5717       return CK_IntegralToFloating;
5718     case Type::STK_CPointer:
5719     case Type::STK_ObjCObjectPointer:
5720     case Type::STK_BlockPointer:
5721       llvm_unreachable("valid complex int->pointer cast?");
5722     case Type::STK_MemberPointer:
5723       llvm_unreachable("member pointer type in C");
5724     }
5725     llvm_unreachable("Should have returned before this");
5726   }
5727 
5728   llvm_unreachable("Unhandled scalar cast");
5729 }
5730 
5731 static bool breakDownVectorType(QualType type, uint64_t &len,
5732                                 QualType &eltType) {
5733   // Vectors are simple.
5734   if (const VectorType *vecType = type->getAs<VectorType>()) {
5735     len = vecType->getNumElements();
5736     eltType = vecType->getElementType();
5737     assert(eltType->isScalarType());
5738     return true;
5739   }
5740 
5741   // We allow lax conversion to and from non-vector types, but only if
5742   // they're real types (i.e. non-complex, non-pointer scalar types).
5743   if (!type->isRealType()) return false;
5744 
5745   len = 1;
5746   eltType = type;
5747   return true;
5748 }
5749 
5750 /// Are the two types lax-compatible vector types?  That is, given
5751 /// that one of them is a vector, do they have equal storage sizes,
5752 /// where the storage size is the number of elements times the element
5753 /// size?
5754 ///
5755 /// This will also return false if either of the types is neither a
5756 /// vector nor a real type.
5757 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5758   assert(destTy->isVectorType() || srcTy->isVectorType());
5759 
5760   // Disallow lax conversions between scalars and ExtVectors (these
5761   // conversions are allowed for other vector types because common headers
5762   // depend on them).  Most scalar OP ExtVector cases are handled by the
5763   // splat path anyway, which does what we want (convert, not bitcast).
5764   // What this rules out for ExtVectors is crazy things like char4*float.
5765   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5766   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5767 
5768   uint64_t srcLen, destLen;
5769   QualType srcEltTy, destEltTy;
5770   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5771   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5772 
5773   // ASTContext::getTypeSize will return the size rounded up to a
5774   // power of 2, so instead of using that, we need to use the raw
5775   // element size multiplied by the element count.
5776   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5777   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5778 
5779   return (srcLen * srcEltSize == destLen * destEltSize);
5780 }
5781 
5782 /// Is this a legal conversion between two types, one of which is
5783 /// known to be a vector type?
5784 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5785   assert(destTy->isVectorType() || srcTy->isVectorType());
5786 
5787   if (!Context.getLangOpts().LaxVectorConversions)
5788     return false;
5789   return areLaxCompatibleVectorTypes(srcTy, destTy);
5790 }
5791 
5792 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5793                            CastKind &Kind) {
5794   assert(VectorTy->isVectorType() && "Not a vector type!");
5795 
5796   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5797     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5798       return Diag(R.getBegin(),
5799                   Ty->isVectorType() ?
5800                   diag::err_invalid_conversion_between_vectors :
5801                   diag::err_invalid_conversion_between_vector_and_integer)
5802         << VectorTy << Ty << R;
5803   } else
5804     return Diag(R.getBegin(),
5805                 diag::err_invalid_conversion_between_vector_and_scalar)
5806       << VectorTy << Ty << R;
5807 
5808   Kind = CK_BitCast;
5809   return false;
5810 }
5811 
5812 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5813   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5814 
5815   if (DestElemTy == SplattedExpr->getType())
5816     return SplattedExpr;
5817 
5818   assert(DestElemTy->isFloatingType() ||
5819          DestElemTy->isIntegralOrEnumerationType());
5820 
5821   CastKind CK;
5822   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5823     // OpenCL requires that we convert `true` boolean expressions to -1, but
5824     // only when splatting vectors.
5825     if (DestElemTy->isFloatingType()) {
5826       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5827       // in two steps: boolean to signed integral, then to floating.
5828       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5829                                                  CK_BooleanToSignedIntegral);
5830       SplattedExpr = CastExprRes.get();
5831       CK = CK_IntegralToFloating;
5832     } else {
5833       CK = CK_BooleanToSignedIntegral;
5834     }
5835   } else {
5836     ExprResult CastExprRes = SplattedExpr;
5837     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5838     if (CastExprRes.isInvalid())
5839       return ExprError();
5840     SplattedExpr = CastExprRes.get();
5841   }
5842   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5843 }
5844 
5845 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5846                                     Expr *CastExpr, CastKind &Kind) {
5847   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5848 
5849   QualType SrcTy = CastExpr->getType();
5850 
5851   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5852   // an ExtVectorType.
5853   // In OpenCL, casts between vectors of different types are not allowed.
5854   // (See OpenCL 6.2).
5855   if (SrcTy->isVectorType()) {
5856     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5857         || (getLangOpts().OpenCL &&
5858             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5859       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5860         << DestTy << SrcTy << R;
5861       return ExprError();
5862     }
5863     Kind = CK_BitCast;
5864     return CastExpr;
5865   }
5866 
5867   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5868   // conversion will take place first from scalar to elt type, and then
5869   // splat from elt type to vector.
5870   if (SrcTy->isPointerType())
5871     return Diag(R.getBegin(),
5872                 diag::err_invalid_conversion_between_vector_and_scalar)
5873       << DestTy << SrcTy << R;
5874 
5875   Kind = CK_VectorSplat;
5876   return prepareVectorSplat(DestTy, CastExpr);
5877 }
5878 
5879 ExprResult
5880 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5881                     Declarator &D, ParsedType &Ty,
5882                     SourceLocation RParenLoc, Expr *CastExpr) {
5883   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5884          "ActOnCastExpr(): missing type or expr");
5885 
5886   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5887   if (D.isInvalidType())
5888     return ExprError();
5889 
5890   if (getLangOpts().CPlusPlus) {
5891     // Check that there are no default arguments (C++ only).
5892     CheckExtraCXXDefaultArguments(D);
5893   } else {
5894     // Make sure any TypoExprs have been dealt with.
5895     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5896     if (!Res.isUsable())
5897       return ExprError();
5898     CastExpr = Res.get();
5899   }
5900 
5901   checkUnusedDeclAttributes(D);
5902 
5903   QualType castType = castTInfo->getType();
5904   Ty = CreateParsedType(castType, castTInfo);
5905 
5906   bool isVectorLiteral = false;
5907 
5908   // Check for an altivec or OpenCL literal,
5909   // i.e. all the elements are integer constants.
5910   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5911   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5912   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5913        && castType->isVectorType() && (PE || PLE)) {
5914     if (PLE && PLE->getNumExprs() == 0) {
5915       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5916       return ExprError();
5917     }
5918     if (PE || PLE->getNumExprs() == 1) {
5919       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5920       if (!E->getType()->isVectorType())
5921         isVectorLiteral = true;
5922     }
5923     else
5924       isVectorLiteral = true;
5925   }
5926 
5927   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5928   // then handle it as such.
5929   if (isVectorLiteral)
5930     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5931 
5932   // If the Expr being casted is a ParenListExpr, handle it specially.
5933   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5934   // sequence of BinOp comma operators.
5935   if (isa<ParenListExpr>(CastExpr)) {
5936     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5937     if (Result.isInvalid()) return ExprError();
5938     CastExpr = Result.get();
5939   }
5940 
5941   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5942       !getSourceManager().isInSystemMacro(LParenLoc))
5943     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5944 
5945   CheckTollFreeBridgeCast(castType, CastExpr);
5946 
5947   CheckObjCBridgeRelatedCast(castType, CastExpr);
5948 
5949   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5950 }
5951 
5952 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5953                                     SourceLocation RParenLoc, Expr *E,
5954                                     TypeSourceInfo *TInfo) {
5955   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5956          "Expected paren or paren list expression");
5957 
5958   Expr **exprs;
5959   unsigned numExprs;
5960   Expr *subExpr;
5961   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5962   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5963     LiteralLParenLoc = PE->getLParenLoc();
5964     LiteralRParenLoc = PE->getRParenLoc();
5965     exprs = PE->getExprs();
5966     numExprs = PE->getNumExprs();
5967   } else { // isa<ParenExpr> by assertion at function entrance
5968     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5969     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5970     subExpr = cast<ParenExpr>(E)->getSubExpr();
5971     exprs = &subExpr;
5972     numExprs = 1;
5973   }
5974 
5975   QualType Ty = TInfo->getType();
5976   assert(Ty->isVectorType() && "Expected vector type");
5977 
5978   SmallVector<Expr *, 8> initExprs;
5979   const VectorType *VTy = Ty->getAs<VectorType>();
5980   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5981 
5982   // '(...)' form of vector initialization in AltiVec: the number of
5983   // initializers must be one or must match the size of the vector.
5984   // If a single value is specified in the initializer then it will be
5985   // replicated to all the components of the vector
5986   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5987     // The number of initializers must be one or must match the size of the
5988     // vector. If a single value is specified in the initializer then it will
5989     // be replicated to all the components of the vector
5990     if (numExprs == 1) {
5991       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5992       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5993       if (Literal.isInvalid())
5994         return ExprError();
5995       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5996                                   PrepareScalarCast(Literal, ElemTy));
5997       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5998     }
5999     else if (numExprs < numElems) {
6000       Diag(E->getExprLoc(),
6001            diag::err_incorrect_number_of_vector_initializers);
6002       return ExprError();
6003     }
6004     else
6005       initExprs.append(exprs, exprs + numExprs);
6006   }
6007   else {
6008     // For OpenCL, when the number of initializers is a single value,
6009     // it will be replicated to all components of the vector.
6010     if (getLangOpts().OpenCL &&
6011         VTy->getVectorKind() == VectorType::GenericVector &&
6012         numExprs == 1) {
6013         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6014         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6015         if (Literal.isInvalid())
6016           return ExprError();
6017         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6018                                     PrepareScalarCast(Literal, ElemTy));
6019         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6020     }
6021 
6022     initExprs.append(exprs, exprs + numExprs);
6023   }
6024   // FIXME: This means that pretty-printing the final AST will produce curly
6025   // braces instead of the original commas.
6026   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6027                                                    initExprs, LiteralRParenLoc);
6028   initE->setType(Ty);
6029   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6030 }
6031 
6032 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6033 /// the ParenListExpr into a sequence of comma binary operators.
6034 ExprResult
6035 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6036   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6037   if (!E)
6038     return OrigExpr;
6039 
6040   ExprResult Result(E->getExpr(0));
6041 
6042   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6043     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6044                         E->getExpr(i));
6045 
6046   if (Result.isInvalid()) return ExprError();
6047 
6048   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6049 }
6050 
6051 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6052                                     SourceLocation R,
6053                                     MultiExprArg Val) {
6054   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6055   return expr;
6056 }
6057 
6058 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6059 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6060 /// emitted.
6061 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6062                                       SourceLocation QuestionLoc) {
6063   Expr *NullExpr = LHSExpr;
6064   Expr *NonPointerExpr = RHSExpr;
6065   Expr::NullPointerConstantKind NullKind =
6066       NullExpr->isNullPointerConstant(Context,
6067                                       Expr::NPC_ValueDependentIsNotNull);
6068 
6069   if (NullKind == Expr::NPCK_NotNull) {
6070     NullExpr = RHSExpr;
6071     NonPointerExpr = LHSExpr;
6072     NullKind =
6073         NullExpr->isNullPointerConstant(Context,
6074                                         Expr::NPC_ValueDependentIsNotNull);
6075   }
6076 
6077   if (NullKind == Expr::NPCK_NotNull)
6078     return false;
6079 
6080   if (NullKind == Expr::NPCK_ZeroExpression)
6081     return false;
6082 
6083   if (NullKind == Expr::NPCK_ZeroLiteral) {
6084     // In this case, check to make sure that we got here from a "NULL"
6085     // string in the source code.
6086     NullExpr = NullExpr->IgnoreParenImpCasts();
6087     SourceLocation loc = NullExpr->getExprLoc();
6088     if (!findMacroSpelling(loc, "NULL"))
6089       return false;
6090   }
6091 
6092   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6093   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6094       << NonPointerExpr->getType() << DiagType
6095       << NonPointerExpr->getSourceRange();
6096   return true;
6097 }
6098 
6099 /// \brief Return false if the condition expression is valid, true otherwise.
6100 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6101   QualType CondTy = Cond->getType();
6102 
6103   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6104   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6105     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6106       << CondTy << Cond->getSourceRange();
6107     return true;
6108   }
6109 
6110   // C99 6.5.15p2
6111   if (CondTy->isScalarType()) return false;
6112 
6113   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6114     << CondTy << Cond->getSourceRange();
6115   return true;
6116 }
6117 
6118 /// \brief Handle when one or both operands are void type.
6119 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6120                                          ExprResult &RHS) {
6121     Expr *LHSExpr = LHS.get();
6122     Expr *RHSExpr = RHS.get();
6123 
6124     if (!LHSExpr->getType()->isVoidType())
6125       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6126         << RHSExpr->getSourceRange();
6127     if (!RHSExpr->getType()->isVoidType())
6128       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6129         << LHSExpr->getSourceRange();
6130     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6131     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6132     return S.Context.VoidTy;
6133 }
6134 
6135 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6136 /// true otherwise.
6137 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6138                                         QualType PointerTy) {
6139   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6140       !NullExpr.get()->isNullPointerConstant(S.Context,
6141                                             Expr::NPC_ValueDependentIsNull))
6142     return true;
6143 
6144   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6145   return false;
6146 }
6147 
6148 /// \brief Checks compatibility between two pointers and return the resulting
6149 /// type.
6150 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6151                                                      ExprResult &RHS,
6152                                                      SourceLocation Loc) {
6153   QualType LHSTy = LHS.get()->getType();
6154   QualType RHSTy = RHS.get()->getType();
6155 
6156   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6157     // Two identical pointers types are always compatible.
6158     return LHSTy;
6159   }
6160 
6161   QualType lhptee, rhptee;
6162 
6163   // Get the pointee types.
6164   bool IsBlockPointer = false;
6165   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6166     lhptee = LHSBTy->getPointeeType();
6167     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6168     IsBlockPointer = true;
6169   } else {
6170     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6171     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6172   }
6173 
6174   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6175   // differently qualified versions of compatible types, the result type is
6176   // a pointer to an appropriately qualified version of the composite
6177   // type.
6178 
6179   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6180   // clause doesn't make sense for our extensions. E.g. address space 2 should
6181   // be incompatible with address space 3: they may live on different devices or
6182   // anything.
6183   Qualifiers lhQual = lhptee.getQualifiers();
6184   Qualifiers rhQual = rhptee.getQualifiers();
6185 
6186   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6187   lhQual.removeCVRQualifiers();
6188   rhQual.removeCVRQualifiers();
6189 
6190   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6191   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6192 
6193   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6194 
6195   if (CompositeTy.isNull()) {
6196     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6197       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6198       << RHS.get()->getSourceRange();
6199     // In this situation, we assume void* type. No especially good
6200     // reason, but this is what gcc does, and we do have to pick
6201     // to get a consistent AST.
6202     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6203     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6204     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6205     return incompatTy;
6206   }
6207 
6208   // The pointer types are compatible.
6209   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6210   if (IsBlockPointer)
6211     ResultTy = S.Context.getBlockPointerType(ResultTy);
6212   else
6213     ResultTy = S.Context.getPointerType(ResultTy);
6214 
6215   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
6216   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
6217   return ResultTy;
6218 }
6219 
6220 /// \brief Return the resulting type when the operands are both block pointers.
6221 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6222                                                           ExprResult &LHS,
6223                                                           ExprResult &RHS,
6224                                                           SourceLocation Loc) {
6225   QualType LHSTy = LHS.get()->getType();
6226   QualType RHSTy = RHS.get()->getType();
6227 
6228   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6229     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6230       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6231       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6232       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6233       return destType;
6234     }
6235     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6236       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6237       << RHS.get()->getSourceRange();
6238     return QualType();
6239   }
6240 
6241   // We have 2 block pointer types.
6242   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6243 }
6244 
6245 /// \brief Return the resulting type when the operands are both pointers.
6246 static QualType
6247 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6248                                             ExprResult &RHS,
6249                                             SourceLocation Loc) {
6250   // get the pointer types
6251   QualType LHSTy = LHS.get()->getType();
6252   QualType RHSTy = RHS.get()->getType();
6253 
6254   // get the "pointed to" types
6255   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6256   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6257 
6258   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6259   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6260     // Figure out necessary qualifiers (C99 6.5.15p6)
6261     QualType destPointee
6262       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6263     QualType destType = S.Context.getPointerType(destPointee);
6264     // Add qualifiers if necessary.
6265     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6266     // Promote to void*.
6267     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6268     return destType;
6269   }
6270   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6271     QualType destPointee
6272       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6273     QualType destType = S.Context.getPointerType(destPointee);
6274     // Add qualifiers if necessary.
6275     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6276     // Promote to void*.
6277     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6278     return destType;
6279   }
6280 
6281   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6282 }
6283 
6284 /// \brief Return false if the first expression is not an integer and the second
6285 /// expression is not a pointer, true otherwise.
6286 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6287                                         Expr* PointerExpr, SourceLocation Loc,
6288                                         bool IsIntFirstExpr) {
6289   if (!PointerExpr->getType()->isPointerType() ||
6290       !Int.get()->getType()->isIntegerType())
6291     return false;
6292 
6293   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6294   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6295 
6296   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6297     << Expr1->getType() << Expr2->getType()
6298     << Expr1->getSourceRange() << Expr2->getSourceRange();
6299   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6300                             CK_IntegralToPointer);
6301   return true;
6302 }
6303 
6304 /// \brief Simple conversion between integer and floating point types.
6305 ///
6306 /// Used when handling the OpenCL conditional operator where the
6307 /// condition is a vector while the other operands are scalar.
6308 ///
6309 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6310 /// types are either integer or floating type. Between the two
6311 /// operands, the type with the higher rank is defined as the "result
6312 /// type". The other operand needs to be promoted to the same type. No
6313 /// other type promotion is allowed. We cannot use
6314 /// UsualArithmeticConversions() for this purpose, since it always
6315 /// promotes promotable types.
6316 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6317                                             ExprResult &RHS,
6318                                             SourceLocation QuestionLoc) {
6319   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6320   if (LHS.isInvalid())
6321     return QualType();
6322   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6323   if (RHS.isInvalid())
6324     return QualType();
6325 
6326   // For conversion purposes, we ignore any qualifiers.
6327   // For example, "const float" and "float" are equivalent.
6328   QualType LHSType =
6329     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6330   QualType RHSType =
6331     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6332 
6333   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6334     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6335       << LHSType << LHS.get()->getSourceRange();
6336     return QualType();
6337   }
6338 
6339   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6340     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6341       << RHSType << RHS.get()->getSourceRange();
6342     return QualType();
6343   }
6344 
6345   // If both types are identical, no conversion is needed.
6346   if (LHSType == RHSType)
6347     return LHSType;
6348 
6349   // Now handle "real" floating types (i.e. float, double, long double).
6350   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6351     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6352                                  /*IsCompAssign = */ false);
6353 
6354   // Finally, we have two differing integer types.
6355   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6356   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6357 }
6358 
6359 /// \brief Convert scalar operands to a vector that matches the
6360 ///        condition in length.
6361 ///
6362 /// Used when handling the OpenCL conditional operator where the
6363 /// condition is a vector while the other operands are scalar.
6364 ///
6365 /// We first compute the "result type" for the scalar operands
6366 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6367 /// into a vector of that type where the length matches the condition
6368 /// vector type. s6.11.6 requires that the element types of the result
6369 /// and the condition must have the same number of bits.
6370 static QualType
6371 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6372                               QualType CondTy, SourceLocation QuestionLoc) {
6373   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6374   if (ResTy.isNull()) return QualType();
6375 
6376   const VectorType *CV = CondTy->getAs<VectorType>();
6377   assert(CV);
6378 
6379   // Determine the vector result type
6380   unsigned NumElements = CV->getNumElements();
6381   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6382 
6383   // Ensure that all types have the same number of bits
6384   if (S.Context.getTypeSize(CV->getElementType())
6385       != S.Context.getTypeSize(ResTy)) {
6386     // Since VectorTy is created internally, it does not pretty print
6387     // with an OpenCL name. Instead, we just print a description.
6388     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6389     SmallString<64> Str;
6390     llvm::raw_svector_ostream OS(Str);
6391     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6392     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6393       << CondTy << OS.str();
6394     return QualType();
6395   }
6396 
6397   // Convert operands to the vector result type
6398   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6399   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6400 
6401   return VectorTy;
6402 }
6403 
6404 /// \brief Return false if this is a valid OpenCL condition vector
6405 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6406                                        SourceLocation QuestionLoc) {
6407   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6408   // integral type.
6409   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6410   assert(CondTy);
6411   QualType EleTy = CondTy->getElementType();
6412   if (EleTy->isIntegerType()) return false;
6413 
6414   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6415     << Cond->getType() << Cond->getSourceRange();
6416   return true;
6417 }
6418 
6419 /// \brief Return false if the vector condition type and the vector
6420 ///        result type are compatible.
6421 ///
6422 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6423 /// number of elements, and their element types have the same number
6424 /// of bits.
6425 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6426                               SourceLocation QuestionLoc) {
6427   const VectorType *CV = CondTy->getAs<VectorType>();
6428   const VectorType *RV = VecResTy->getAs<VectorType>();
6429   assert(CV && RV);
6430 
6431   if (CV->getNumElements() != RV->getNumElements()) {
6432     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6433       << CondTy << VecResTy;
6434     return true;
6435   }
6436 
6437   QualType CVE = CV->getElementType();
6438   QualType RVE = RV->getElementType();
6439 
6440   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6441     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6442       << CondTy << VecResTy;
6443     return true;
6444   }
6445 
6446   return false;
6447 }
6448 
6449 /// \brief Return the resulting type for the conditional operator in
6450 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6451 ///        s6.3.i) when the condition is a vector type.
6452 static QualType
6453 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6454                              ExprResult &LHS, ExprResult &RHS,
6455                              SourceLocation QuestionLoc) {
6456   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6457   if (Cond.isInvalid())
6458     return QualType();
6459   QualType CondTy = Cond.get()->getType();
6460 
6461   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6462     return QualType();
6463 
6464   // If either operand is a vector then find the vector type of the
6465   // result as specified in OpenCL v1.1 s6.3.i.
6466   if (LHS.get()->getType()->isVectorType() ||
6467       RHS.get()->getType()->isVectorType()) {
6468     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6469                                               /*isCompAssign*/false,
6470                                               /*AllowBothBool*/true,
6471                                               /*AllowBoolConversions*/false);
6472     if (VecResTy.isNull()) return QualType();
6473     // The result type must match the condition type as specified in
6474     // OpenCL v1.1 s6.11.6.
6475     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6476       return QualType();
6477     return VecResTy;
6478   }
6479 
6480   // Both operands are scalar.
6481   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6482 }
6483 
6484 /// \brief Return true if the Expr is block type
6485 static bool checkBlockType(Sema &S, const Expr *E) {
6486   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6487     QualType Ty = CE->getCallee()->getType();
6488     if (Ty->isBlockPointerType()) {
6489       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6490       return true;
6491     }
6492   }
6493   return false;
6494 }
6495 
6496 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6497 /// In that case, LHS = cond.
6498 /// C99 6.5.15
6499 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6500                                         ExprResult &RHS, ExprValueKind &VK,
6501                                         ExprObjectKind &OK,
6502                                         SourceLocation QuestionLoc) {
6503 
6504   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6505   if (!LHSResult.isUsable()) return QualType();
6506   LHS = LHSResult;
6507 
6508   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6509   if (!RHSResult.isUsable()) return QualType();
6510   RHS = RHSResult;
6511 
6512   // C++ is sufficiently different to merit its own checker.
6513   if (getLangOpts().CPlusPlus)
6514     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6515 
6516   VK = VK_RValue;
6517   OK = OK_Ordinary;
6518 
6519   // The OpenCL operator with a vector condition is sufficiently
6520   // different to merit its own checker.
6521   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6522     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6523 
6524   // First, check the condition.
6525   Cond = UsualUnaryConversions(Cond.get());
6526   if (Cond.isInvalid())
6527     return QualType();
6528   if (checkCondition(*this, Cond.get(), QuestionLoc))
6529     return QualType();
6530 
6531   // Now check the two expressions.
6532   if (LHS.get()->getType()->isVectorType() ||
6533       RHS.get()->getType()->isVectorType())
6534     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6535                                /*AllowBothBool*/true,
6536                                /*AllowBoolConversions*/false);
6537 
6538   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6539   if (LHS.isInvalid() || RHS.isInvalid())
6540     return QualType();
6541 
6542   QualType LHSTy = LHS.get()->getType();
6543   QualType RHSTy = RHS.get()->getType();
6544 
6545   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6546   // selection operator (?:).
6547   if (getLangOpts().OpenCL &&
6548       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6549     return QualType();
6550   }
6551 
6552   // If both operands have arithmetic type, do the usual arithmetic conversions
6553   // to find a common type: C99 6.5.15p3,5.
6554   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6555     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6556     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6557 
6558     return ResTy;
6559   }
6560 
6561   // If both operands are the same structure or union type, the result is that
6562   // type.
6563   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6564     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6565       if (LHSRT->getDecl() == RHSRT->getDecl())
6566         // "If both the operands have structure or union type, the result has
6567         // that type."  This implies that CV qualifiers are dropped.
6568         return LHSTy.getUnqualifiedType();
6569     // FIXME: Type of conditional expression must be complete in C mode.
6570   }
6571 
6572   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6573   // The following || allows only one side to be void (a GCC-ism).
6574   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6575     return checkConditionalVoidType(*this, LHS, RHS);
6576   }
6577 
6578   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6579   // the type of the other operand."
6580   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6581   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6582 
6583   // All objective-c pointer type analysis is done here.
6584   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6585                                                         QuestionLoc);
6586   if (LHS.isInvalid() || RHS.isInvalid())
6587     return QualType();
6588   if (!compositeType.isNull())
6589     return compositeType;
6590 
6591 
6592   // Handle block pointer types.
6593   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6594     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6595                                                      QuestionLoc);
6596 
6597   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6598   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6599     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6600                                                        QuestionLoc);
6601 
6602   // GCC compatibility: soften pointer/integer mismatch.  Note that
6603   // null pointers have been filtered out by this point.
6604   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6605       /*isIntFirstExpr=*/true))
6606     return RHSTy;
6607   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6608       /*isIntFirstExpr=*/false))
6609     return LHSTy;
6610 
6611   // Emit a better diagnostic if one of the expressions is a null pointer
6612   // constant and the other is not a pointer type. In this case, the user most
6613   // likely forgot to take the address of the other expression.
6614   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6615     return QualType();
6616 
6617   // Otherwise, the operands are not compatible.
6618   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6619     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6620     << RHS.get()->getSourceRange();
6621   return QualType();
6622 }
6623 
6624 /// FindCompositeObjCPointerType - Helper method to find composite type of
6625 /// two objective-c pointer types of the two input expressions.
6626 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6627                                             SourceLocation QuestionLoc) {
6628   QualType LHSTy = LHS.get()->getType();
6629   QualType RHSTy = RHS.get()->getType();
6630 
6631   // Handle things like Class and struct objc_class*.  Here we case the result
6632   // to the pseudo-builtin, because that will be implicitly cast back to the
6633   // redefinition type if an attempt is made to access its fields.
6634   if (LHSTy->isObjCClassType() &&
6635       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6636     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6637     return LHSTy;
6638   }
6639   if (RHSTy->isObjCClassType() &&
6640       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6641     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6642     return RHSTy;
6643   }
6644   // And the same for struct objc_object* / id
6645   if (LHSTy->isObjCIdType() &&
6646       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6647     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6648     return LHSTy;
6649   }
6650   if (RHSTy->isObjCIdType() &&
6651       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6652     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6653     return RHSTy;
6654   }
6655   // And the same for struct objc_selector* / SEL
6656   if (Context.isObjCSelType(LHSTy) &&
6657       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6658     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6659     return LHSTy;
6660   }
6661   if (Context.isObjCSelType(RHSTy) &&
6662       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6663     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6664     return RHSTy;
6665   }
6666   // Check constraints for Objective-C object pointers types.
6667   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6668 
6669     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6670       // Two identical object pointer types are always compatible.
6671       return LHSTy;
6672     }
6673     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6674     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6675     QualType compositeType = LHSTy;
6676 
6677     // If both operands are interfaces and either operand can be
6678     // assigned to the other, use that type as the composite
6679     // type. This allows
6680     //   xxx ? (A*) a : (B*) b
6681     // where B is a subclass of A.
6682     //
6683     // Additionally, as for assignment, if either type is 'id'
6684     // allow silent coercion. Finally, if the types are
6685     // incompatible then make sure to use 'id' as the composite
6686     // type so the result is acceptable for sending messages to.
6687 
6688     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6689     // It could return the composite type.
6690     if (!(compositeType =
6691           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6692       // Nothing more to do.
6693     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6694       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6695     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6696       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6697     } else if ((LHSTy->isObjCQualifiedIdType() ||
6698                 RHSTy->isObjCQualifiedIdType()) &&
6699                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6700       // Need to handle "id<xx>" explicitly.
6701       // GCC allows qualified id and any Objective-C type to devolve to
6702       // id. Currently localizing to here until clear this should be
6703       // part of ObjCQualifiedIdTypesAreCompatible.
6704       compositeType = Context.getObjCIdType();
6705     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6706       compositeType = Context.getObjCIdType();
6707     } else {
6708       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6709       << LHSTy << RHSTy
6710       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6711       QualType incompatTy = Context.getObjCIdType();
6712       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6713       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6714       return incompatTy;
6715     }
6716     // The object pointer types are compatible.
6717     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6718     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6719     return compositeType;
6720   }
6721   // Check Objective-C object pointer types and 'void *'
6722   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6723     if (getLangOpts().ObjCAutoRefCount) {
6724       // ARC forbids the implicit conversion of object pointers to 'void *',
6725       // so these types are not compatible.
6726       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6727           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6728       LHS = RHS = true;
6729       return QualType();
6730     }
6731     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6732     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6733     QualType destPointee
6734     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6735     QualType destType = Context.getPointerType(destPointee);
6736     // Add qualifiers if necessary.
6737     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6738     // Promote to void*.
6739     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6740     return destType;
6741   }
6742   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6743     if (getLangOpts().ObjCAutoRefCount) {
6744       // ARC forbids the implicit conversion of object pointers to 'void *',
6745       // so these types are not compatible.
6746       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6747           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6748       LHS = RHS = true;
6749       return QualType();
6750     }
6751     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6752     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6753     QualType destPointee
6754     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6755     QualType destType = Context.getPointerType(destPointee);
6756     // Add qualifiers if necessary.
6757     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6758     // Promote to void*.
6759     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6760     return destType;
6761   }
6762   return QualType();
6763 }
6764 
6765 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6766 /// ParenRange in parentheses.
6767 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6768                                const PartialDiagnostic &Note,
6769                                SourceRange ParenRange) {
6770   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6771   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6772       EndLoc.isValid()) {
6773     Self.Diag(Loc, Note)
6774       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6775       << FixItHint::CreateInsertion(EndLoc, ")");
6776   } else {
6777     // We can't display the parentheses, so just show the bare note.
6778     Self.Diag(Loc, Note) << ParenRange;
6779   }
6780 }
6781 
6782 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6783   return BinaryOperator::isAdditiveOp(Opc) ||
6784          BinaryOperator::isMultiplicativeOp(Opc) ||
6785          BinaryOperator::isShiftOp(Opc);
6786 }
6787 
6788 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6789 /// expression, either using a built-in or overloaded operator,
6790 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6791 /// expression.
6792 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6793                                    Expr **RHSExprs) {
6794   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6795   E = E->IgnoreImpCasts();
6796   E = E->IgnoreConversionOperator();
6797   E = E->IgnoreImpCasts();
6798 
6799   // Built-in binary operator.
6800   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6801     if (IsArithmeticOp(OP->getOpcode())) {
6802       *Opcode = OP->getOpcode();
6803       *RHSExprs = OP->getRHS();
6804       return true;
6805     }
6806   }
6807 
6808   // Overloaded operator.
6809   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6810     if (Call->getNumArgs() != 2)
6811       return false;
6812 
6813     // Make sure this is really a binary operator that is safe to pass into
6814     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6815     OverloadedOperatorKind OO = Call->getOperator();
6816     if (OO < OO_Plus || OO > OO_Arrow ||
6817         OO == OO_PlusPlus || OO == OO_MinusMinus)
6818       return false;
6819 
6820     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6821     if (IsArithmeticOp(OpKind)) {
6822       *Opcode = OpKind;
6823       *RHSExprs = Call->getArg(1);
6824       return true;
6825     }
6826   }
6827 
6828   return false;
6829 }
6830 
6831 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6832 /// or is a logical expression such as (x==y) which has int type, but is
6833 /// commonly interpreted as boolean.
6834 static bool ExprLooksBoolean(Expr *E) {
6835   E = E->IgnoreParenImpCasts();
6836 
6837   if (E->getType()->isBooleanType())
6838     return true;
6839   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6840     return OP->isComparisonOp() || OP->isLogicalOp();
6841   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6842     return OP->getOpcode() == UO_LNot;
6843   if (E->getType()->isPointerType())
6844     return true;
6845 
6846   return false;
6847 }
6848 
6849 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6850 /// and binary operator are mixed in a way that suggests the programmer assumed
6851 /// the conditional operator has higher precedence, for example:
6852 /// "int x = a + someBinaryCondition ? 1 : 2".
6853 static void DiagnoseConditionalPrecedence(Sema &Self,
6854                                           SourceLocation OpLoc,
6855                                           Expr *Condition,
6856                                           Expr *LHSExpr,
6857                                           Expr *RHSExpr) {
6858   BinaryOperatorKind CondOpcode;
6859   Expr *CondRHS;
6860 
6861   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6862     return;
6863   if (!ExprLooksBoolean(CondRHS))
6864     return;
6865 
6866   // The condition is an arithmetic binary expression, with a right-
6867   // hand side that looks boolean, so warn.
6868 
6869   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6870       << Condition->getSourceRange()
6871       << BinaryOperator::getOpcodeStr(CondOpcode);
6872 
6873   SuggestParentheses(Self, OpLoc,
6874     Self.PDiag(diag::note_precedence_silence)
6875       << BinaryOperator::getOpcodeStr(CondOpcode),
6876     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6877 
6878   SuggestParentheses(Self, OpLoc,
6879     Self.PDiag(diag::note_precedence_conditional_first),
6880     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6881 }
6882 
6883 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6884 /// in the case of a the GNU conditional expr extension.
6885 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6886                                     SourceLocation ColonLoc,
6887                                     Expr *CondExpr, Expr *LHSExpr,
6888                                     Expr *RHSExpr) {
6889   if (!getLangOpts().CPlusPlus) {
6890     // C cannot handle TypoExpr nodes in the condition because it
6891     // doesn't handle dependent types properly, so make sure any TypoExprs have
6892     // been dealt with before checking the operands.
6893     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6894     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
6895     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
6896 
6897     if (!CondResult.isUsable())
6898       return ExprError();
6899 
6900     if (LHSExpr) {
6901       if (!LHSResult.isUsable())
6902         return ExprError();
6903     }
6904 
6905     if (!RHSResult.isUsable())
6906       return ExprError();
6907 
6908     CondExpr = CondResult.get();
6909     LHSExpr = LHSResult.get();
6910     RHSExpr = RHSResult.get();
6911   }
6912 
6913   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6914   // was the condition.
6915   OpaqueValueExpr *opaqueValue = nullptr;
6916   Expr *commonExpr = nullptr;
6917   if (!LHSExpr) {
6918     commonExpr = CondExpr;
6919     // Lower out placeholder types first.  This is important so that we don't
6920     // try to capture a placeholder. This happens in few cases in C++; such
6921     // as Objective-C++'s dictionary subscripting syntax.
6922     if (commonExpr->hasPlaceholderType()) {
6923       ExprResult result = CheckPlaceholderExpr(commonExpr);
6924       if (!result.isUsable()) return ExprError();
6925       commonExpr = result.get();
6926     }
6927     // We usually want to apply unary conversions *before* saving, except
6928     // in the special case of a C++ l-value conditional.
6929     if (!(getLangOpts().CPlusPlus
6930           && !commonExpr->isTypeDependent()
6931           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6932           && commonExpr->isGLValue()
6933           && commonExpr->isOrdinaryOrBitFieldObject()
6934           && RHSExpr->isOrdinaryOrBitFieldObject()
6935           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6936       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6937       if (commonRes.isInvalid())
6938         return ExprError();
6939       commonExpr = commonRes.get();
6940     }
6941 
6942     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6943                                                 commonExpr->getType(),
6944                                                 commonExpr->getValueKind(),
6945                                                 commonExpr->getObjectKind(),
6946                                                 commonExpr);
6947     LHSExpr = CondExpr = opaqueValue;
6948   }
6949 
6950   ExprValueKind VK = VK_RValue;
6951   ExprObjectKind OK = OK_Ordinary;
6952   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6953   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6954                                              VK, OK, QuestionLoc);
6955   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6956       RHS.isInvalid())
6957     return ExprError();
6958 
6959   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6960                                 RHS.get());
6961 
6962   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
6963 
6964   if (!commonExpr)
6965     return new (Context)
6966         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6967                             RHS.get(), result, VK, OK);
6968 
6969   return new (Context) BinaryConditionalOperator(
6970       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6971       ColonLoc, result, VK, OK);
6972 }
6973 
6974 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6975 // being closely modeled after the C99 spec:-). The odd characteristic of this
6976 // routine is it effectively iqnores the qualifiers on the top level pointee.
6977 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6978 // FIXME: add a couple examples in this comment.
6979 static Sema::AssignConvertType
6980 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6981   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6982   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6983 
6984   // get the "pointed to" type (ignoring qualifiers at the top level)
6985   const Type *lhptee, *rhptee;
6986   Qualifiers lhq, rhq;
6987   std::tie(lhptee, lhq) =
6988       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6989   std::tie(rhptee, rhq) =
6990       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6991 
6992   Sema::AssignConvertType ConvTy = Sema::Compatible;
6993 
6994   // C99 6.5.16.1p1: This following citation is common to constraints
6995   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6996   // qualifiers of the type *pointed to* by the right;
6997 
6998   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6999   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7000       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7001     // Ignore lifetime for further calculation.
7002     lhq.removeObjCLifetime();
7003     rhq.removeObjCLifetime();
7004   }
7005 
7006   if (!lhq.compatiblyIncludes(rhq)) {
7007     // Treat address-space mismatches as fatal.  TODO: address subspaces
7008     if (!lhq.isAddressSpaceSupersetOf(rhq))
7009       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7010 
7011     // It's okay to add or remove GC or lifetime qualifiers when converting to
7012     // and from void*.
7013     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7014                         .compatiblyIncludes(
7015                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7016              && (lhptee->isVoidType() || rhptee->isVoidType()))
7017       ; // keep old
7018 
7019     // Treat lifetime mismatches as fatal.
7020     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7021       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7022 
7023     // For GCC compatibility, other qualifier mismatches are treated
7024     // as still compatible in C.
7025     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7026   }
7027 
7028   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7029   // incomplete type and the other is a pointer to a qualified or unqualified
7030   // version of void...
7031   if (lhptee->isVoidType()) {
7032     if (rhptee->isIncompleteOrObjectType())
7033       return ConvTy;
7034 
7035     // As an extension, we allow cast to/from void* to function pointer.
7036     assert(rhptee->isFunctionType());
7037     return Sema::FunctionVoidPointer;
7038   }
7039 
7040   if (rhptee->isVoidType()) {
7041     if (lhptee->isIncompleteOrObjectType())
7042       return ConvTy;
7043 
7044     // As an extension, we allow cast to/from void* to function pointer.
7045     assert(lhptee->isFunctionType());
7046     return Sema::FunctionVoidPointer;
7047   }
7048 
7049   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7050   // unqualified versions of compatible types, ...
7051   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7052   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7053     // Check if the pointee types are compatible ignoring the sign.
7054     // We explicitly check for char so that we catch "char" vs
7055     // "unsigned char" on systems where "char" is unsigned.
7056     if (lhptee->isCharType())
7057       ltrans = S.Context.UnsignedCharTy;
7058     else if (lhptee->hasSignedIntegerRepresentation())
7059       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7060 
7061     if (rhptee->isCharType())
7062       rtrans = S.Context.UnsignedCharTy;
7063     else if (rhptee->hasSignedIntegerRepresentation())
7064       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7065 
7066     if (ltrans == rtrans) {
7067       // Types are compatible ignoring the sign. Qualifier incompatibility
7068       // takes priority over sign incompatibility because the sign
7069       // warning can be disabled.
7070       if (ConvTy != Sema::Compatible)
7071         return ConvTy;
7072 
7073       return Sema::IncompatiblePointerSign;
7074     }
7075 
7076     // If we are a multi-level pointer, it's possible that our issue is simply
7077     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7078     // the eventual target type is the same and the pointers have the same
7079     // level of indirection, this must be the issue.
7080     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7081       do {
7082         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7083         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7084       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7085 
7086       if (lhptee == rhptee)
7087         return Sema::IncompatibleNestedPointerQualifiers;
7088     }
7089 
7090     // General pointer incompatibility takes priority over qualifiers.
7091     return Sema::IncompatiblePointer;
7092   }
7093   if (!S.getLangOpts().CPlusPlus &&
7094       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7095     return Sema::IncompatiblePointer;
7096   return ConvTy;
7097 }
7098 
7099 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7100 /// block pointer types are compatible or whether a block and normal pointer
7101 /// are compatible. It is more restrict than comparing two function pointer
7102 // types.
7103 static Sema::AssignConvertType
7104 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7105                                     QualType RHSType) {
7106   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7107   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7108 
7109   QualType lhptee, rhptee;
7110 
7111   // get the "pointed to" type (ignoring qualifiers at the top level)
7112   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7113   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7114 
7115   // In C++, the types have to match exactly.
7116   if (S.getLangOpts().CPlusPlus)
7117     return Sema::IncompatibleBlockPointer;
7118 
7119   Sema::AssignConvertType ConvTy = Sema::Compatible;
7120 
7121   // For blocks we enforce that qualifiers are identical.
7122   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7123     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7124 
7125   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7126     return Sema::IncompatibleBlockPointer;
7127 
7128   return ConvTy;
7129 }
7130 
7131 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7132 /// for assignment compatibility.
7133 static Sema::AssignConvertType
7134 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7135                                    QualType RHSType) {
7136   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7137   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7138 
7139   if (LHSType->isObjCBuiltinType()) {
7140     // Class is not compatible with ObjC object pointers.
7141     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7142         !RHSType->isObjCQualifiedClassType())
7143       return Sema::IncompatiblePointer;
7144     return Sema::Compatible;
7145   }
7146   if (RHSType->isObjCBuiltinType()) {
7147     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7148         !LHSType->isObjCQualifiedClassType())
7149       return Sema::IncompatiblePointer;
7150     return Sema::Compatible;
7151   }
7152   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7153   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7154 
7155   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7156       // make an exception for id<P>
7157       !LHSType->isObjCQualifiedIdType())
7158     return Sema::CompatiblePointerDiscardsQualifiers;
7159 
7160   if (S.Context.typesAreCompatible(LHSType, RHSType))
7161     return Sema::Compatible;
7162   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7163     return Sema::IncompatibleObjCQualifiedId;
7164   return Sema::IncompatiblePointer;
7165 }
7166 
7167 Sema::AssignConvertType
7168 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7169                                  QualType LHSType, QualType RHSType) {
7170   // Fake up an opaque expression.  We don't actually care about what
7171   // cast operations are required, so if CheckAssignmentConstraints
7172   // adds casts to this they'll be wasted, but fortunately that doesn't
7173   // usually happen on valid code.
7174   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7175   ExprResult RHSPtr = &RHSExpr;
7176   CastKind K = CK_Invalid;
7177 
7178   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7179 }
7180 
7181 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7182 /// has code to accommodate several GCC extensions when type checking
7183 /// pointers. Here are some objectionable examples that GCC considers warnings:
7184 ///
7185 ///  int a, *pint;
7186 ///  short *pshort;
7187 ///  struct foo *pfoo;
7188 ///
7189 ///  pint = pshort; // warning: assignment from incompatible pointer type
7190 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7191 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7192 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7193 ///
7194 /// As a result, the code for dealing with pointers is more complex than the
7195 /// C99 spec dictates.
7196 ///
7197 /// Sets 'Kind' for any result kind except Incompatible.
7198 Sema::AssignConvertType
7199 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7200                                  CastKind &Kind, bool ConvertRHS) {
7201   QualType RHSType = RHS.get()->getType();
7202   QualType OrigLHSType = LHSType;
7203 
7204   // Get canonical types.  We're not formatting these types, just comparing
7205   // them.
7206   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7207   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7208 
7209   // Common case: no conversion required.
7210   if (LHSType == RHSType) {
7211     Kind = CK_NoOp;
7212     return Compatible;
7213   }
7214 
7215   // If we have an atomic type, try a non-atomic assignment, then just add an
7216   // atomic qualification step.
7217   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7218     Sema::AssignConvertType result =
7219       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7220     if (result != Compatible)
7221       return result;
7222     if (Kind != CK_NoOp && ConvertRHS)
7223       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7224     Kind = CK_NonAtomicToAtomic;
7225     return Compatible;
7226   }
7227 
7228   // If the left-hand side is a reference type, then we are in a
7229   // (rare!) case where we've allowed the use of references in C,
7230   // e.g., as a parameter type in a built-in function. In this case,
7231   // just make sure that the type referenced is compatible with the
7232   // right-hand side type. The caller is responsible for adjusting
7233   // LHSType so that the resulting expression does not have reference
7234   // type.
7235   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7236     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7237       Kind = CK_LValueBitCast;
7238       return Compatible;
7239     }
7240     return Incompatible;
7241   }
7242 
7243   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7244   // to the same ExtVector type.
7245   if (LHSType->isExtVectorType()) {
7246     if (RHSType->isExtVectorType())
7247       return Incompatible;
7248     if (RHSType->isArithmeticType()) {
7249       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7250       if (ConvertRHS)
7251         RHS = prepareVectorSplat(LHSType, RHS.get());
7252       Kind = CK_VectorSplat;
7253       return Compatible;
7254     }
7255   }
7256 
7257   // Conversions to or from vector type.
7258   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7259     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7260       // Allow assignments of an AltiVec vector type to an equivalent GCC
7261       // vector type and vice versa
7262       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7263         Kind = CK_BitCast;
7264         return Compatible;
7265       }
7266 
7267       // If we are allowing lax vector conversions, and LHS and RHS are both
7268       // vectors, the total size only needs to be the same. This is a bitcast;
7269       // no bits are changed but the result type is different.
7270       if (isLaxVectorConversion(RHSType, LHSType)) {
7271         Kind = CK_BitCast;
7272         return IncompatibleVectors;
7273       }
7274     }
7275     return Incompatible;
7276   }
7277 
7278   // Arithmetic conversions.
7279   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7280       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7281     if (ConvertRHS)
7282       Kind = PrepareScalarCast(RHS, LHSType);
7283     return Compatible;
7284   }
7285 
7286   // Conversions to normal pointers.
7287   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7288     // U* -> T*
7289     if (isa<PointerType>(RHSType)) {
7290       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7291       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7292       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7293       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7294     }
7295 
7296     // int -> T*
7297     if (RHSType->isIntegerType()) {
7298       Kind = CK_IntegralToPointer; // FIXME: null?
7299       return IntToPointer;
7300     }
7301 
7302     // C pointers are not compatible with ObjC object pointers,
7303     // with two exceptions:
7304     if (isa<ObjCObjectPointerType>(RHSType)) {
7305       //  - conversions to void*
7306       if (LHSPointer->getPointeeType()->isVoidType()) {
7307         Kind = CK_BitCast;
7308         return Compatible;
7309       }
7310 
7311       //  - conversions from 'Class' to the redefinition type
7312       if (RHSType->isObjCClassType() &&
7313           Context.hasSameType(LHSType,
7314                               Context.getObjCClassRedefinitionType())) {
7315         Kind = CK_BitCast;
7316         return Compatible;
7317       }
7318 
7319       Kind = CK_BitCast;
7320       return IncompatiblePointer;
7321     }
7322 
7323     // U^ -> void*
7324     if (RHSType->getAs<BlockPointerType>()) {
7325       if (LHSPointer->getPointeeType()->isVoidType()) {
7326         Kind = CK_BitCast;
7327         return Compatible;
7328       }
7329     }
7330 
7331     return Incompatible;
7332   }
7333 
7334   // Conversions to block pointers.
7335   if (isa<BlockPointerType>(LHSType)) {
7336     // U^ -> T^
7337     if (RHSType->isBlockPointerType()) {
7338       Kind = CK_BitCast;
7339       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7340     }
7341 
7342     // int or null -> T^
7343     if (RHSType->isIntegerType()) {
7344       Kind = CK_IntegralToPointer; // FIXME: null
7345       return IntToBlockPointer;
7346     }
7347 
7348     // id -> T^
7349     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7350       Kind = CK_AnyPointerToBlockPointerCast;
7351       return Compatible;
7352     }
7353 
7354     // void* -> T^
7355     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7356       if (RHSPT->getPointeeType()->isVoidType()) {
7357         Kind = CK_AnyPointerToBlockPointerCast;
7358         return Compatible;
7359       }
7360 
7361     return Incompatible;
7362   }
7363 
7364   // Conversions to Objective-C pointers.
7365   if (isa<ObjCObjectPointerType>(LHSType)) {
7366     // A* -> B*
7367     if (RHSType->isObjCObjectPointerType()) {
7368       Kind = CK_BitCast;
7369       Sema::AssignConvertType result =
7370         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7371       if (getLangOpts().ObjCAutoRefCount &&
7372           result == Compatible &&
7373           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7374         result = IncompatibleObjCWeakRef;
7375       return result;
7376     }
7377 
7378     // int or null -> A*
7379     if (RHSType->isIntegerType()) {
7380       Kind = CK_IntegralToPointer; // FIXME: null
7381       return IntToPointer;
7382     }
7383 
7384     // In general, C pointers are not compatible with ObjC object pointers,
7385     // with two exceptions:
7386     if (isa<PointerType>(RHSType)) {
7387       Kind = CK_CPointerToObjCPointerCast;
7388 
7389       //  - conversions from 'void*'
7390       if (RHSType->isVoidPointerType()) {
7391         return Compatible;
7392       }
7393 
7394       //  - conversions to 'Class' from its redefinition type
7395       if (LHSType->isObjCClassType() &&
7396           Context.hasSameType(RHSType,
7397                               Context.getObjCClassRedefinitionType())) {
7398         return Compatible;
7399       }
7400 
7401       return IncompatiblePointer;
7402     }
7403 
7404     // Only under strict condition T^ is compatible with an Objective-C pointer.
7405     if (RHSType->isBlockPointerType() &&
7406         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7407       if (ConvertRHS)
7408         maybeExtendBlockObject(RHS);
7409       Kind = CK_BlockPointerToObjCPointerCast;
7410       return Compatible;
7411     }
7412 
7413     return Incompatible;
7414   }
7415 
7416   // Conversions from pointers that are not covered by the above.
7417   if (isa<PointerType>(RHSType)) {
7418     // T* -> _Bool
7419     if (LHSType == Context.BoolTy) {
7420       Kind = CK_PointerToBoolean;
7421       return Compatible;
7422     }
7423 
7424     // T* -> int
7425     if (LHSType->isIntegerType()) {
7426       Kind = CK_PointerToIntegral;
7427       return PointerToInt;
7428     }
7429 
7430     return Incompatible;
7431   }
7432 
7433   // Conversions from Objective-C pointers that are not covered by the above.
7434   if (isa<ObjCObjectPointerType>(RHSType)) {
7435     // T* -> _Bool
7436     if (LHSType == Context.BoolTy) {
7437       Kind = CK_PointerToBoolean;
7438       return Compatible;
7439     }
7440 
7441     // T* -> int
7442     if (LHSType->isIntegerType()) {
7443       Kind = CK_PointerToIntegral;
7444       return PointerToInt;
7445     }
7446 
7447     return Incompatible;
7448   }
7449 
7450   // struct A -> struct B
7451   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7452     if (Context.typesAreCompatible(LHSType, RHSType)) {
7453       Kind = CK_NoOp;
7454       return Compatible;
7455     }
7456   }
7457 
7458   return Incompatible;
7459 }
7460 
7461 /// \brief Constructs a transparent union from an expression that is
7462 /// used to initialize the transparent union.
7463 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7464                                       ExprResult &EResult, QualType UnionType,
7465                                       FieldDecl *Field) {
7466   // Build an initializer list that designates the appropriate member
7467   // of the transparent union.
7468   Expr *E = EResult.get();
7469   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7470                                                    E, SourceLocation());
7471   Initializer->setType(UnionType);
7472   Initializer->setInitializedFieldInUnion(Field);
7473 
7474   // Build a compound literal constructing a value of the transparent
7475   // union type from this initializer list.
7476   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7477   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7478                                         VK_RValue, Initializer, false);
7479 }
7480 
7481 Sema::AssignConvertType
7482 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7483                                                ExprResult &RHS) {
7484   QualType RHSType = RHS.get()->getType();
7485 
7486   // If the ArgType is a Union type, we want to handle a potential
7487   // transparent_union GCC extension.
7488   const RecordType *UT = ArgType->getAsUnionType();
7489   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7490     return Incompatible;
7491 
7492   // The field to initialize within the transparent union.
7493   RecordDecl *UD = UT->getDecl();
7494   FieldDecl *InitField = nullptr;
7495   // It's compatible if the expression matches any of the fields.
7496   for (auto *it : UD->fields()) {
7497     if (it->getType()->isPointerType()) {
7498       // If the transparent union contains a pointer type, we allow:
7499       // 1) void pointer
7500       // 2) null pointer constant
7501       if (RHSType->isPointerType())
7502         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7503           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7504           InitField = it;
7505           break;
7506         }
7507 
7508       if (RHS.get()->isNullPointerConstant(Context,
7509                                            Expr::NPC_ValueDependentIsNull)) {
7510         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7511                                 CK_NullToPointer);
7512         InitField = it;
7513         break;
7514       }
7515     }
7516 
7517     CastKind Kind = CK_Invalid;
7518     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7519           == Compatible) {
7520       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7521       InitField = it;
7522       break;
7523     }
7524   }
7525 
7526   if (!InitField)
7527     return Incompatible;
7528 
7529   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7530   return Compatible;
7531 }
7532 
7533 Sema::AssignConvertType
7534 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7535                                        bool Diagnose,
7536                                        bool DiagnoseCFAudited,
7537                                        bool ConvertRHS) {
7538   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7539   // we can't avoid *all* modifications at the moment, so we need some somewhere
7540   // to put the updated value.
7541   ExprResult LocalRHS = CallerRHS;
7542   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7543 
7544   if (getLangOpts().CPlusPlus) {
7545     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7546       // C++ 5.17p3: If the left operand is not of class type, the
7547       // expression is implicitly converted (C++ 4) to the
7548       // cv-unqualified type of the left operand.
7549       ExprResult Res;
7550       if (Diagnose) {
7551         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7552                                         AA_Assigning);
7553       } else {
7554         ImplicitConversionSequence ICS =
7555             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7556                                   /*SuppressUserConversions=*/false,
7557                                   /*AllowExplicit=*/false,
7558                                   /*InOverloadResolution=*/false,
7559                                   /*CStyle=*/false,
7560                                   /*AllowObjCWritebackConversion=*/false);
7561         if (ICS.isFailure())
7562           return Incompatible;
7563         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7564                                         ICS, AA_Assigning);
7565       }
7566       if (Res.isInvalid())
7567         return Incompatible;
7568       Sema::AssignConvertType result = Compatible;
7569       if (getLangOpts().ObjCAutoRefCount &&
7570           !CheckObjCARCUnavailableWeakConversion(LHSType,
7571                                                  RHS.get()->getType()))
7572         result = IncompatibleObjCWeakRef;
7573       RHS = Res;
7574       return result;
7575     }
7576 
7577     // FIXME: Currently, we fall through and treat C++ classes like C
7578     // structures.
7579     // FIXME: We also fall through for atomics; not sure what should
7580     // happen there, though.
7581   } else if (RHS.get()->getType() == Context.OverloadTy) {
7582     // As a set of extensions to C, we support overloading on functions. These
7583     // functions need to be resolved here.
7584     DeclAccessPair DAP;
7585     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7586             RHS.get(), LHSType, /*Complain=*/false, DAP))
7587       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7588     else
7589       return Incompatible;
7590   }
7591 
7592   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7593   // a null pointer constant.
7594   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7595        LHSType->isBlockPointerType()) &&
7596       RHS.get()->isNullPointerConstant(Context,
7597                                        Expr::NPC_ValueDependentIsNull)) {
7598     if (Diagnose || ConvertRHS) {
7599       CastKind Kind;
7600       CXXCastPath Path;
7601       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7602                              /*IgnoreBaseAccess=*/false, Diagnose);
7603       if (ConvertRHS)
7604         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7605     }
7606     return Compatible;
7607   }
7608 
7609   // This check seems unnatural, however it is necessary to ensure the proper
7610   // conversion of functions/arrays. If the conversion were done for all
7611   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7612   // expressions that suppress this implicit conversion (&, sizeof).
7613   //
7614   // Suppress this for references: C++ 8.5.3p5.
7615   if (!LHSType->isReferenceType()) {
7616     // FIXME: We potentially allocate here even if ConvertRHS is false.
7617     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7618     if (RHS.isInvalid())
7619       return Incompatible;
7620   }
7621 
7622   Expr *PRE = RHS.get()->IgnoreParenCasts();
7623   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7624     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7625     if (PDecl && !PDecl->hasDefinition()) {
7626       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7627       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7628     }
7629   }
7630 
7631   CastKind Kind = CK_Invalid;
7632   Sema::AssignConvertType result =
7633     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7634 
7635   // C99 6.5.16.1p2: The value of the right operand is converted to the
7636   // type of the assignment expression.
7637   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7638   // so that we can use references in built-in functions even in C.
7639   // The getNonReferenceType() call makes sure that the resulting expression
7640   // does not have reference type.
7641   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7642     QualType Ty = LHSType.getNonLValueExprType(Context);
7643     Expr *E = RHS.get();
7644 
7645     // Check for various Objective-C errors. If we are not reporting
7646     // diagnostics and just checking for errors, e.g., during overload
7647     // resolution, return Incompatible to indicate the failure.
7648     if (getLangOpts().ObjCAutoRefCount &&
7649         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7650                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7651       if (!Diagnose)
7652         return Incompatible;
7653     }
7654     if (getLangOpts().ObjC1 &&
7655         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7656                                            E->getType(), E, Diagnose) ||
7657          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7658       if (!Diagnose)
7659         return Incompatible;
7660       // Replace the expression with a corrected version and continue so we
7661       // can find further errors.
7662       RHS = E;
7663       return Compatible;
7664     }
7665 
7666     if (ConvertRHS)
7667       RHS = ImpCastExprToType(E, Ty, Kind);
7668   }
7669   return result;
7670 }
7671 
7672 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7673                                ExprResult &RHS) {
7674   Diag(Loc, diag::err_typecheck_invalid_operands)
7675     << LHS.get()->getType() << RHS.get()->getType()
7676     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7677   return QualType();
7678 }
7679 
7680 /// Try to convert a value of non-vector type to a vector type by converting
7681 /// the type to the element type of the vector and then performing a splat.
7682 /// If the language is OpenCL, we only use conversions that promote scalar
7683 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7684 /// for float->int.
7685 ///
7686 /// \param scalar - if non-null, actually perform the conversions
7687 /// \return true if the operation fails (but without diagnosing the failure)
7688 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7689                                      QualType scalarTy,
7690                                      QualType vectorEltTy,
7691                                      QualType vectorTy) {
7692   // The conversion to apply to the scalar before splatting it,
7693   // if necessary.
7694   CastKind scalarCast = CK_Invalid;
7695 
7696   if (vectorEltTy->isIntegralType(S.Context)) {
7697     if (!scalarTy->isIntegralType(S.Context))
7698       return true;
7699     if (S.getLangOpts().OpenCL &&
7700         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7701       return true;
7702     scalarCast = CK_IntegralCast;
7703   } else if (vectorEltTy->isRealFloatingType()) {
7704     if (scalarTy->isRealFloatingType()) {
7705       if (S.getLangOpts().OpenCL &&
7706           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7707         return true;
7708       scalarCast = CK_FloatingCast;
7709     }
7710     else if (scalarTy->isIntegralType(S.Context))
7711       scalarCast = CK_IntegralToFloating;
7712     else
7713       return true;
7714   } else {
7715     return true;
7716   }
7717 
7718   // Adjust scalar if desired.
7719   if (scalar) {
7720     if (scalarCast != CK_Invalid)
7721       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7722     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7723   }
7724   return false;
7725 }
7726 
7727 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7728                                    SourceLocation Loc, bool IsCompAssign,
7729                                    bool AllowBothBool,
7730                                    bool AllowBoolConversions) {
7731   if (!IsCompAssign) {
7732     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7733     if (LHS.isInvalid())
7734       return QualType();
7735   }
7736   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7737   if (RHS.isInvalid())
7738     return QualType();
7739 
7740   // For conversion purposes, we ignore any qualifiers.
7741   // For example, "const float" and "float" are equivalent.
7742   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7743   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7744 
7745   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7746   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7747   assert(LHSVecType || RHSVecType);
7748 
7749   // AltiVec-style "vector bool op vector bool" combinations are allowed
7750   // for some operators but not others.
7751   if (!AllowBothBool &&
7752       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7753       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7754     return InvalidOperands(Loc, LHS, RHS);
7755 
7756   // If the vector types are identical, return.
7757   if (Context.hasSameType(LHSType, RHSType))
7758     return LHSType;
7759 
7760   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7761   if (LHSVecType && RHSVecType &&
7762       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7763     if (isa<ExtVectorType>(LHSVecType)) {
7764       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7765       return LHSType;
7766     }
7767 
7768     if (!IsCompAssign)
7769       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7770     return RHSType;
7771   }
7772 
7773   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7774   // can be mixed, with the result being the non-bool type.  The non-bool
7775   // operand must have integer element type.
7776   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7777       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7778       (Context.getTypeSize(LHSVecType->getElementType()) ==
7779        Context.getTypeSize(RHSVecType->getElementType()))) {
7780     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7781         LHSVecType->getElementType()->isIntegerType() &&
7782         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7783       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7784       return LHSType;
7785     }
7786     if (!IsCompAssign &&
7787         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7788         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7789         RHSVecType->getElementType()->isIntegerType()) {
7790       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7791       return RHSType;
7792     }
7793   }
7794 
7795   // If there's an ext-vector type and a scalar, try to convert the scalar to
7796   // the vector element type and splat.
7797   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7798     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7799                                   LHSVecType->getElementType(), LHSType))
7800       return LHSType;
7801   }
7802   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7803     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7804                                   LHSType, RHSVecType->getElementType(),
7805                                   RHSType))
7806       return RHSType;
7807   }
7808 
7809   // If we're allowing lax vector conversions, only the total (data) size
7810   // needs to be the same.
7811   // FIXME: Should we really be allowing this?
7812   // FIXME: We really just pick the LHS type arbitrarily?
7813   if (isLaxVectorConversion(RHSType, LHSType)) {
7814     QualType resultType = LHSType;
7815     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7816     return resultType;
7817   }
7818 
7819   // Okay, the expression is invalid.
7820 
7821   // If there's a non-vector, non-real operand, diagnose that.
7822   if ((!RHSVecType && !RHSType->isRealType()) ||
7823       (!LHSVecType && !LHSType->isRealType())) {
7824     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7825       << LHSType << RHSType
7826       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7827     return QualType();
7828   }
7829 
7830   // OpenCL V1.1 6.2.6.p1:
7831   // If the operands are of more than one vector type, then an error shall
7832   // occur. Implicit conversions between vector types are not permitted, per
7833   // section 6.2.1.
7834   if (getLangOpts().OpenCL &&
7835       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7836       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7837     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7838                                                            << RHSType;
7839     return QualType();
7840   }
7841 
7842   // Otherwise, use the generic diagnostic.
7843   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7844     << LHSType << RHSType
7845     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7846   return QualType();
7847 }
7848 
7849 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7850 // expression.  These are mainly cases where the null pointer is used as an
7851 // integer instead of a pointer.
7852 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7853                                 SourceLocation Loc, bool IsCompare) {
7854   // The canonical way to check for a GNU null is with isNullPointerConstant,
7855   // but we use a bit of a hack here for speed; this is a relatively
7856   // hot path, and isNullPointerConstant is slow.
7857   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7858   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7859 
7860   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7861 
7862   // Avoid analyzing cases where the result will either be invalid (and
7863   // diagnosed as such) or entirely valid and not something to warn about.
7864   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7865       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7866     return;
7867 
7868   // Comparison operations would not make sense with a null pointer no matter
7869   // what the other expression is.
7870   if (!IsCompare) {
7871     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7872         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7873         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7874     return;
7875   }
7876 
7877   // The rest of the operations only make sense with a null pointer
7878   // if the other expression is a pointer.
7879   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7880       NonNullType->canDecayToPointerType())
7881     return;
7882 
7883   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7884       << LHSNull /* LHS is NULL */ << NonNullType
7885       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7886 }
7887 
7888 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
7889                                                ExprResult &RHS,
7890                                                SourceLocation Loc, bool IsDiv) {
7891   // Check for division/remainder by zero.
7892   llvm::APSInt RHSValue;
7893   if (!RHS.get()->isValueDependent() &&
7894       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
7895     S.DiagRuntimeBehavior(Loc, RHS.get(),
7896                           S.PDiag(diag::warn_remainder_division_by_zero)
7897                             << IsDiv << RHS.get()->getSourceRange());
7898 }
7899 
7900 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7901                                            SourceLocation Loc,
7902                                            bool IsCompAssign, bool IsDiv) {
7903   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7904 
7905   if (LHS.get()->getType()->isVectorType() ||
7906       RHS.get()->getType()->isVectorType())
7907     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7908                                /*AllowBothBool*/getLangOpts().AltiVec,
7909                                /*AllowBoolConversions*/false);
7910 
7911   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7912   if (LHS.isInvalid() || RHS.isInvalid())
7913     return QualType();
7914 
7915 
7916   if (compType.isNull() || !compType->isArithmeticType())
7917     return InvalidOperands(Loc, LHS, RHS);
7918   if (IsDiv)
7919     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
7920   return compType;
7921 }
7922 
7923 QualType Sema::CheckRemainderOperands(
7924   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7925   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7926 
7927   if (LHS.get()->getType()->isVectorType() ||
7928       RHS.get()->getType()->isVectorType()) {
7929     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7930         RHS.get()->getType()->hasIntegerRepresentation())
7931       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7932                                  /*AllowBothBool*/getLangOpts().AltiVec,
7933                                  /*AllowBoolConversions*/false);
7934     return InvalidOperands(Loc, LHS, RHS);
7935   }
7936 
7937   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7938   if (LHS.isInvalid() || RHS.isInvalid())
7939     return QualType();
7940 
7941   if (compType.isNull() || !compType->isIntegerType())
7942     return InvalidOperands(Loc, LHS, RHS);
7943   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
7944   return compType;
7945 }
7946 
7947 /// \brief Diagnose invalid arithmetic on two void pointers.
7948 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7949                                                 Expr *LHSExpr, Expr *RHSExpr) {
7950   S.Diag(Loc, S.getLangOpts().CPlusPlus
7951                 ? diag::err_typecheck_pointer_arith_void_type
7952                 : diag::ext_gnu_void_ptr)
7953     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7954                             << RHSExpr->getSourceRange();
7955 }
7956 
7957 /// \brief Diagnose invalid arithmetic on a void pointer.
7958 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7959                                             Expr *Pointer) {
7960   S.Diag(Loc, S.getLangOpts().CPlusPlus
7961                 ? diag::err_typecheck_pointer_arith_void_type
7962                 : diag::ext_gnu_void_ptr)
7963     << 0 /* one pointer */ << Pointer->getSourceRange();
7964 }
7965 
7966 /// \brief Diagnose invalid arithmetic on two function pointers.
7967 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7968                                                     Expr *LHS, Expr *RHS) {
7969   assert(LHS->getType()->isAnyPointerType());
7970   assert(RHS->getType()->isAnyPointerType());
7971   S.Diag(Loc, S.getLangOpts().CPlusPlus
7972                 ? diag::err_typecheck_pointer_arith_function_type
7973                 : diag::ext_gnu_ptr_func_arith)
7974     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7975     // We only show the second type if it differs from the first.
7976     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7977                                                    RHS->getType())
7978     << RHS->getType()->getPointeeType()
7979     << LHS->getSourceRange() << RHS->getSourceRange();
7980 }
7981 
7982 /// \brief Diagnose invalid arithmetic on a function pointer.
7983 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7984                                                 Expr *Pointer) {
7985   assert(Pointer->getType()->isAnyPointerType());
7986   S.Diag(Loc, S.getLangOpts().CPlusPlus
7987                 ? diag::err_typecheck_pointer_arith_function_type
7988                 : diag::ext_gnu_ptr_func_arith)
7989     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7990     << 0 /* one pointer, so only one type */
7991     << Pointer->getSourceRange();
7992 }
7993 
7994 /// \brief Emit error if Operand is incomplete pointer type
7995 ///
7996 /// \returns True if pointer has incomplete type
7997 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7998                                                  Expr *Operand) {
7999   QualType ResType = Operand->getType();
8000   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8001     ResType = ResAtomicType->getValueType();
8002 
8003   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8004   QualType PointeeTy = ResType->getPointeeType();
8005   return S.RequireCompleteType(Loc, PointeeTy,
8006                                diag::err_typecheck_arithmetic_incomplete_type,
8007                                PointeeTy, Operand->getSourceRange());
8008 }
8009 
8010 /// \brief Check the validity of an arithmetic pointer operand.
8011 ///
8012 /// If the operand has pointer type, this code will check for pointer types
8013 /// which are invalid in arithmetic operations. These will be diagnosed
8014 /// appropriately, including whether or not the use is supported as an
8015 /// extension.
8016 ///
8017 /// \returns True when the operand is valid to use (even if as an extension).
8018 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8019                                             Expr *Operand) {
8020   QualType ResType = Operand->getType();
8021   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8022     ResType = ResAtomicType->getValueType();
8023 
8024   if (!ResType->isAnyPointerType()) return true;
8025 
8026   QualType PointeeTy = ResType->getPointeeType();
8027   if (PointeeTy->isVoidType()) {
8028     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8029     return !S.getLangOpts().CPlusPlus;
8030   }
8031   if (PointeeTy->isFunctionType()) {
8032     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8033     return !S.getLangOpts().CPlusPlus;
8034   }
8035 
8036   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8037 
8038   return true;
8039 }
8040 
8041 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8042 /// operands.
8043 ///
8044 /// This routine will diagnose any invalid arithmetic on pointer operands much
8045 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8046 /// for emitting a single diagnostic even for operations where both LHS and RHS
8047 /// are (potentially problematic) pointers.
8048 ///
8049 /// \returns True when the operand is valid to use (even if as an extension).
8050 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8051                                                 Expr *LHSExpr, Expr *RHSExpr) {
8052   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8053   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8054   if (!isLHSPointer && !isRHSPointer) return true;
8055 
8056   QualType LHSPointeeTy, RHSPointeeTy;
8057   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8058   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8059 
8060   // if both are pointers check if operation is valid wrt address spaces
8061   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8062     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8063     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8064     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8065       S.Diag(Loc,
8066              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8067           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8068           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8069       return false;
8070     }
8071   }
8072 
8073   // Check for arithmetic on pointers to incomplete types.
8074   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8075   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8076   if (isLHSVoidPtr || isRHSVoidPtr) {
8077     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8078     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8079     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8080 
8081     return !S.getLangOpts().CPlusPlus;
8082   }
8083 
8084   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8085   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8086   if (isLHSFuncPtr || isRHSFuncPtr) {
8087     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8088     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8089                                                                 RHSExpr);
8090     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8091 
8092     return !S.getLangOpts().CPlusPlus;
8093   }
8094 
8095   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8096     return false;
8097   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8098     return false;
8099 
8100   return true;
8101 }
8102 
8103 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8104 /// literal.
8105 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8106                                   Expr *LHSExpr, Expr *RHSExpr) {
8107   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8108   Expr* IndexExpr = RHSExpr;
8109   if (!StrExpr) {
8110     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8111     IndexExpr = LHSExpr;
8112   }
8113 
8114   bool IsStringPlusInt = StrExpr &&
8115       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8116   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8117     return;
8118 
8119   llvm::APSInt index;
8120   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8121     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8122     if (index.isNonNegative() &&
8123         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8124                               index.isUnsigned()))
8125       return;
8126   }
8127 
8128   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8129   Self.Diag(OpLoc, diag::warn_string_plus_int)
8130       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8131 
8132   // Only print a fixit for "str" + int, not for int + "str".
8133   if (IndexExpr == RHSExpr) {
8134     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8135     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8136         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8137         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8138         << FixItHint::CreateInsertion(EndLoc, "]");
8139   } else
8140     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8141 }
8142 
8143 /// \brief Emit a warning when adding a char literal to a string.
8144 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8145                                    Expr *LHSExpr, Expr *RHSExpr) {
8146   const Expr *StringRefExpr = LHSExpr;
8147   const CharacterLiteral *CharExpr =
8148       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8149 
8150   if (!CharExpr) {
8151     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8152     StringRefExpr = RHSExpr;
8153   }
8154 
8155   if (!CharExpr || !StringRefExpr)
8156     return;
8157 
8158   const QualType StringType = StringRefExpr->getType();
8159 
8160   // Return if not a PointerType.
8161   if (!StringType->isAnyPointerType())
8162     return;
8163 
8164   // Return if not a CharacterType.
8165   if (!StringType->getPointeeType()->isAnyCharacterType())
8166     return;
8167 
8168   ASTContext &Ctx = Self.getASTContext();
8169   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8170 
8171   const QualType CharType = CharExpr->getType();
8172   if (!CharType->isAnyCharacterType() &&
8173       CharType->isIntegerType() &&
8174       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8175     Self.Diag(OpLoc, diag::warn_string_plus_char)
8176         << DiagRange << Ctx.CharTy;
8177   } else {
8178     Self.Diag(OpLoc, diag::warn_string_plus_char)
8179         << DiagRange << CharExpr->getType();
8180   }
8181 
8182   // Only print a fixit for str + char, not for char + str.
8183   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8184     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8185     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8186         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8187         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8188         << FixItHint::CreateInsertion(EndLoc, "]");
8189   } else {
8190     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8191   }
8192 }
8193 
8194 /// \brief Emit error when two pointers are incompatible.
8195 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8196                                            Expr *LHSExpr, Expr *RHSExpr) {
8197   assert(LHSExpr->getType()->isAnyPointerType());
8198   assert(RHSExpr->getType()->isAnyPointerType());
8199   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8200     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8201     << RHSExpr->getSourceRange();
8202 }
8203 
8204 // C99 6.5.6
8205 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8206                                      SourceLocation Loc, BinaryOperatorKind Opc,
8207                                      QualType* CompLHSTy) {
8208   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8209 
8210   if (LHS.get()->getType()->isVectorType() ||
8211       RHS.get()->getType()->isVectorType()) {
8212     QualType compType = CheckVectorOperands(
8213         LHS, RHS, Loc, CompLHSTy,
8214         /*AllowBothBool*/getLangOpts().AltiVec,
8215         /*AllowBoolConversions*/getLangOpts().ZVector);
8216     if (CompLHSTy) *CompLHSTy = compType;
8217     return compType;
8218   }
8219 
8220   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8221   if (LHS.isInvalid() || RHS.isInvalid())
8222     return QualType();
8223 
8224   // Diagnose "string literal" '+' int and string '+' "char literal".
8225   if (Opc == BO_Add) {
8226     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8227     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8228   }
8229 
8230   // handle the common case first (both operands are arithmetic).
8231   if (!compType.isNull() && compType->isArithmeticType()) {
8232     if (CompLHSTy) *CompLHSTy = compType;
8233     return compType;
8234   }
8235 
8236   // Type-checking.  Ultimately the pointer's going to be in PExp;
8237   // note that we bias towards the LHS being the pointer.
8238   Expr *PExp = LHS.get(), *IExp = RHS.get();
8239 
8240   bool isObjCPointer;
8241   if (PExp->getType()->isPointerType()) {
8242     isObjCPointer = false;
8243   } else if (PExp->getType()->isObjCObjectPointerType()) {
8244     isObjCPointer = true;
8245   } else {
8246     std::swap(PExp, IExp);
8247     if (PExp->getType()->isPointerType()) {
8248       isObjCPointer = false;
8249     } else if (PExp->getType()->isObjCObjectPointerType()) {
8250       isObjCPointer = true;
8251     } else {
8252       return InvalidOperands(Loc, LHS, RHS);
8253     }
8254   }
8255   assert(PExp->getType()->isAnyPointerType());
8256 
8257   if (!IExp->getType()->isIntegerType())
8258     return InvalidOperands(Loc, LHS, RHS);
8259 
8260   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8261     return QualType();
8262 
8263   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8264     return QualType();
8265 
8266   // Check array bounds for pointer arithemtic
8267   CheckArrayAccess(PExp, IExp);
8268 
8269   if (CompLHSTy) {
8270     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8271     if (LHSTy.isNull()) {
8272       LHSTy = LHS.get()->getType();
8273       if (LHSTy->isPromotableIntegerType())
8274         LHSTy = Context.getPromotedIntegerType(LHSTy);
8275     }
8276     *CompLHSTy = LHSTy;
8277   }
8278 
8279   return PExp->getType();
8280 }
8281 
8282 // C99 6.5.6
8283 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8284                                         SourceLocation Loc,
8285                                         QualType* CompLHSTy) {
8286   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8287 
8288   if (LHS.get()->getType()->isVectorType() ||
8289       RHS.get()->getType()->isVectorType()) {
8290     QualType compType = CheckVectorOperands(
8291         LHS, RHS, Loc, CompLHSTy,
8292         /*AllowBothBool*/getLangOpts().AltiVec,
8293         /*AllowBoolConversions*/getLangOpts().ZVector);
8294     if (CompLHSTy) *CompLHSTy = compType;
8295     return compType;
8296   }
8297 
8298   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8299   if (LHS.isInvalid() || RHS.isInvalid())
8300     return QualType();
8301 
8302   // Enforce type constraints: C99 6.5.6p3.
8303 
8304   // Handle the common case first (both operands are arithmetic).
8305   if (!compType.isNull() && compType->isArithmeticType()) {
8306     if (CompLHSTy) *CompLHSTy = compType;
8307     return compType;
8308   }
8309 
8310   // Either ptr - int   or   ptr - ptr.
8311   if (LHS.get()->getType()->isAnyPointerType()) {
8312     QualType lpointee = LHS.get()->getType()->getPointeeType();
8313 
8314     // Diagnose bad cases where we step over interface counts.
8315     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8316         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8317       return QualType();
8318 
8319     // The result type of a pointer-int computation is the pointer type.
8320     if (RHS.get()->getType()->isIntegerType()) {
8321       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8322         return QualType();
8323 
8324       // Check array bounds for pointer arithemtic
8325       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8326                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8327 
8328       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8329       return LHS.get()->getType();
8330     }
8331 
8332     // Handle pointer-pointer subtractions.
8333     if (const PointerType *RHSPTy
8334           = RHS.get()->getType()->getAs<PointerType>()) {
8335       QualType rpointee = RHSPTy->getPointeeType();
8336 
8337       if (getLangOpts().CPlusPlus) {
8338         // Pointee types must be the same: C++ [expr.add]
8339         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8340           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8341         }
8342       } else {
8343         // Pointee types must be compatible C99 6.5.6p3
8344         if (!Context.typesAreCompatible(
8345                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8346                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8347           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8348           return QualType();
8349         }
8350       }
8351 
8352       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8353                                                LHS.get(), RHS.get()))
8354         return QualType();
8355 
8356       // The pointee type may have zero size.  As an extension, a structure or
8357       // union may have zero size or an array may have zero length.  In this
8358       // case subtraction does not make sense.
8359       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8360         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8361         if (ElementSize.isZero()) {
8362           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8363             << rpointee.getUnqualifiedType()
8364             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8365         }
8366       }
8367 
8368       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8369       return Context.getPointerDiffType();
8370     }
8371   }
8372 
8373   return InvalidOperands(Loc, LHS, RHS);
8374 }
8375 
8376 static bool isScopedEnumerationType(QualType T) {
8377   if (const EnumType *ET = T->getAs<EnumType>())
8378     return ET->getDecl()->isScoped();
8379   return false;
8380 }
8381 
8382 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8383                                    SourceLocation Loc, BinaryOperatorKind Opc,
8384                                    QualType LHSType) {
8385   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8386   // so skip remaining warnings as we don't want to modify values within Sema.
8387   if (S.getLangOpts().OpenCL)
8388     return;
8389 
8390   llvm::APSInt Right;
8391   // Check right/shifter operand
8392   if (RHS.get()->isValueDependent() ||
8393       !RHS.get()->EvaluateAsInt(Right, S.Context))
8394     return;
8395 
8396   if (Right.isNegative()) {
8397     S.DiagRuntimeBehavior(Loc, RHS.get(),
8398                           S.PDiag(diag::warn_shift_negative)
8399                             << RHS.get()->getSourceRange());
8400     return;
8401   }
8402   llvm::APInt LeftBits(Right.getBitWidth(),
8403                        S.Context.getTypeSize(LHS.get()->getType()));
8404   if (Right.uge(LeftBits)) {
8405     S.DiagRuntimeBehavior(Loc, RHS.get(),
8406                           S.PDiag(diag::warn_shift_gt_typewidth)
8407                             << RHS.get()->getSourceRange());
8408     return;
8409   }
8410   if (Opc != BO_Shl)
8411     return;
8412 
8413   // When left shifting an ICE which is signed, we can check for overflow which
8414   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8415   // integers have defined behavior modulo one more than the maximum value
8416   // representable in the result type, so never warn for those.
8417   llvm::APSInt Left;
8418   if (LHS.get()->isValueDependent() ||
8419       LHSType->hasUnsignedIntegerRepresentation() ||
8420       !LHS.get()->EvaluateAsInt(Left, S.Context))
8421     return;
8422 
8423   // If LHS does not have a signed type and non-negative value
8424   // then, the behavior is undefined. Warn about it.
8425   if (Left.isNegative()) {
8426     S.DiagRuntimeBehavior(Loc, LHS.get(),
8427                           S.PDiag(diag::warn_shift_lhs_negative)
8428                             << LHS.get()->getSourceRange());
8429     return;
8430   }
8431 
8432   llvm::APInt ResultBits =
8433       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8434   if (LeftBits.uge(ResultBits))
8435     return;
8436   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8437   Result = Result.shl(Right);
8438 
8439   // Print the bit representation of the signed integer as an unsigned
8440   // hexadecimal number.
8441   SmallString<40> HexResult;
8442   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8443 
8444   // If we are only missing a sign bit, this is less likely to result in actual
8445   // bugs -- if the result is cast back to an unsigned type, it will have the
8446   // expected value. Thus we place this behind a different warning that can be
8447   // turned off separately if needed.
8448   if (LeftBits == ResultBits - 1) {
8449     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8450         << HexResult << LHSType
8451         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8452     return;
8453   }
8454 
8455   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8456     << HexResult.str() << Result.getMinSignedBits() << LHSType
8457     << Left.getBitWidth() << LHS.get()->getSourceRange()
8458     << RHS.get()->getSourceRange();
8459 }
8460 
8461 /// \brief Return the resulting type when an OpenCL vector is shifted
8462 ///        by a scalar or vector shift amount.
8463 static QualType checkOpenCLVectorShift(Sema &S,
8464                                        ExprResult &LHS, ExprResult &RHS,
8465                                        SourceLocation Loc, bool IsCompAssign) {
8466   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8467   if (!LHS.get()->getType()->isVectorType()) {
8468     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8469       << RHS.get()->getType() << LHS.get()->getType()
8470       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8471     return QualType();
8472   }
8473 
8474   if (!IsCompAssign) {
8475     LHS = S.UsualUnaryConversions(LHS.get());
8476     if (LHS.isInvalid()) return QualType();
8477   }
8478 
8479   RHS = S.UsualUnaryConversions(RHS.get());
8480   if (RHS.isInvalid()) return QualType();
8481 
8482   QualType LHSType = LHS.get()->getType();
8483   const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8484   QualType LHSEleType = LHSVecTy->getElementType();
8485 
8486   // Note that RHS might not be a vector.
8487   QualType RHSType = RHS.get()->getType();
8488   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8489   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8490 
8491   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8492   if (!LHSEleType->isIntegerType()) {
8493     S.Diag(Loc, diag::err_typecheck_expect_int)
8494       << LHS.get()->getType() << LHS.get()->getSourceRange();
8495     return QualType();
8496   }
8497 
8498   if (!RHSEleType->isIntegerType()) {
8499     S.Diag(Loc, diag::err_typecheck_expect_int)
8500       << RHS.get()->getType() << RHS.get()->getSourceRange();
8501     return QualType();
8502   }
8503 
8504   if (RHSVecTy) {
8505     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8506     // are applied component-wise. So if RHS is a vector, then ensure
8507     // that the number of elements is the same as LHS...
8508     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8509       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8510         << LHS.get()->getType() << RHS.get()->getType()
8511         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8512       return QualType();
8513     }
8514   } else {
8515     // ...else expand RHS to match the number of elements in LHS.
8516     QualType VecTy =
8517       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8518     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8519   }
8520 
8521   return LHSType;
8522 }
8523 
8524 // C99 6.5.7
8525 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8526                                   SourceLocation Loc, BinaryOperatorKind Opc,
8527                                   bool IsCompAssign) {
8528   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8529 
8530   // Vector shifts promote their scalar inputs to vector type.
8531   if (LHS.get()->getType()->isVectorType() ||
8532       RHS.get()->getType()->isVectorType()) {
8533     if (LangOpts.OpenCL)
8534       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8535     if (LangOpts.ZVector) {
8536       // The shift operators for the z vector extensions work basically
8537       // like OpenCL shifts, except that neither the LHS nor the RHS is
8538       // allowed to be a "vector bool".
8539       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8540         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8541           return InvalidOperands(Loc, LHS, RHS);
8542       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8543         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8544           return InvalidOperands(Loc, LHS, RHS);
8545       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8546     }
8547     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8548                                /*AllowBothBool*/true,
8549                                /*AllowBoolConversions*/false);
8550   }
8551 
8552   // Shifts don't perform usual arithmetic conversions, they just do integer
8553   // promotions on each operand. C99 6.5.7p3
8554 
8555   // For the LHS, do usual unary conversions, but then reset them away
8556   // if this is a compound assignment.
8557   ExprResult OldLHS = LHS;
8558   LHS = UsualUnaryConversions(LHS.get());
8559   if (LHS.isInvalid())
8560     return QualType();
8561   QualType LHSType = LHS.get()->getType();
8562   if (IsCompAssign) LHS = OldLHS;
8563 
8564   // The RHS is simpler.
8565   RHS = UsualUnaryConversions(RHS.get());
8566   if (RHS.isInvalid())
8567     return QualType();
8568   QualType RHSType = RHS.get()->getType();
8569 
8570   // C99 6.5.7p2: Each of the operands shall have integer type.
8571   if (!LHSType->hasIntegerRepresentation() ||
8572       !RHSType->hasIntegerRepresentation())
8573     return InvalidOperands(Loc, LHS, RHS);
8574 
8575   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8576   // hasIntegerRepresentation() above instead of this.
8577   if (isScopedEnumerationType(LHSType) ||
8578       isScopedEnumerationType(RHSType)) {
8579     return InvalidOperands(Loc, LHS, RHS);
8580   }
8581   // Sanity-check shift operands
8582   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8583 
8584   // "The type of the result is that of the promoted left operand."
8585   return LHSType;
8586 }
8587 
8588 static bool IsWithinTemplateSpecialization(Decl *D) {
8589   if (DeclContext *DC = D->getDeclContext()) {
8590     if (isa<ClassTemplateSpecializationDecl>(DC))
8591       return true;
8592     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8593       return FD->isFunctionTemplateSpecialization();
8594   }
8595   return false;
8596 }
8597 
8598 /// If two different enums are compared, raise a warning.
8599 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8600                                 Expr *RHS) {
8601   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8602   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8603 
8604   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8605   if (!LHSEnumType)
8606     return;
8607   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8608   if (!RHSEnumType)
8609     return;
8610 
8611   // Ignore anonymous enums.
8612   if (!LHSEnumType->getDecl()->getIdentifier())
8613     return;
8614   if (!RHSEnumType->getDecl()->getIdentifier())
8615     return;
8616 
8617   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8618     return;
8619 
8620   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8621       << LHSStrippedType << RHSStrippedType
8622       << LHS->getSourceRange() << RHS->getSourceRange();
8623 }
8624 
8625 /// \brief Diagnose bad pointer comparisons.
8626 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8627                                               ExprResult &LHS, ExprResult &RHS,
8628                                               bool IsError) {
8629   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8630                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8631     << LHS.get()->getType() << RHS.get()->getType()
8632     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8633 }
8634 
8635 /// \brief Returns false if the pointers are converted to a composite type,
8636 /// true otherwise.
8637 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8638                                            ExprResult &LHS, ExprResult &RHS) {
8639   // C++ [expr.rel]p2:
8640   //   [...] Pointer conversions (4.10) and qualification
8641   //   conversions (4.4) are performed on pointer operands (or on
8642   //   a pointer operand and a null pointer constant) to bring
8643   //   them to their composite pointer type. [...]
8644   //
8645   // C++ [expr.eq]p1 uses the same notion for (in)equality
8646   // comparisons of pointers.
8647 
8648   // C++ [expr.eq]p2:
8649   //   In addition, pointers to members can be compared, or a pointer to
8650   //   member and a null pointer constant. Pointer to member conversions
8651   //   (4.11) and qualification conversions (4.4) are performed to bring
8652   //   them to a common type. If one operand is a null pointer constant,
8653   //   the common type is the type of the other operand. Otherwise, the
8654   //   common type is a pointer to member type similar (4.4) to the type
8655   //   of one of the operands, with a cv-qualification signature (4.4)
8656   //   that is the union of the cv-qualification signatures of the operand
8657   //   types.
8658 
8659   QualType LHSType = LHS.get()->getType();
8660   QualType RHSType = RHS.get()->getType();
8661   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8662          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8663 
8664   bool NonStandardCompositeType = false;
8665   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8666   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8667   if (T.isNull()) {
8668     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8669     return true;
8670   }
8671 
8672   if (NonStandardCompositeType)
8673     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8674       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8675       << RHS.get()->getSourceRange();
8676 
8677   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8678   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8679   return false;
8680 }
8681 
8682 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8683                                                     ExprResult &LHS,
8684                                                     ExprResult &RHS,
8685                                                     bool IsError) {
8686   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8687                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8688     << LHS.get()->getType() << RHS.get()->getType()
8689     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8690 }
8691 
8692 static bool isObjCObjectLiteral(ExprResult &E) {
8693   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8694   case Stmt::ObjCArrayLiteralClass:
8695   case Stmt::ObjCDictionaryLiteralClass:
8696   case Stmt::ObjCStringLiteralClass:
8697   case Stmt::ObjCBoxedExprClass:
8698     return true;
8699   default:
8700     // Note that ObjCBoolLiteral is NOT an object literal!
8701     return false;
8702   }
8703 }
8704 
8705 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8706   const ObjCObjectPointerType *Type =
8707     LHS->getType()->getAs<ObjCObjectPointerType>();
8708 
8709   // If this is not actually an Objective-C object, bail out.
8710   if (!Type)
8711     return false;
8712 
8713   // Get the LHS object's interface type.
8714   QualType InterfaceType = Type->getPointeeType();
8715 
8716   // If the RHS isn't an Objective-C object, bail out.
8717   if (!RHS->getType()->isObjCObjectPointerType())
8718     return false;
8719 
8720   // Try to find the -isEqual: method.
8721   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8722   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8723                                                       InterfaceType,
8724                                                       /*instance=*/true);
8725   if (!Method) {
8726     if (Type->isObjCIdType()) {
8727       // For 'id', just check the global pool.
8728       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8729                                                   /*receiverId=*/true);
8730     } else {
8731       // Check protocols.
8732       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8733                                              /*instance=*/true);
8734     }
8735   }
8736 
8737   if (!Method)
8738     return false;
8739 
8740   QualType T = Method->parameters()[0]->getType();
8741   if (!T->isObjCObjectPointerType())
8742     return false;
8743 
8744   QualType R = Method->getReturnType();
8745   if (!R->isScalarType())
8746     return false;
8747 
8748   return true;
8749 }
8750 
8751 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8752   FromE = FromE->IgnoreParenImpCasts();
8753   switch (FromE->getStmtClass()) {
8754     default:
8755       break;
8756     case Stmt::ObjCStringLiteralClass:
8757       // "string literal"
8758       return LK_String;
8759     case Stmt::ObjCArrayLiteralClass:
8760       // "array literal"
8761       return LK_Array;
8762     case Stmt::ObjCDictionaryLiteralClass:
8763       // "dictionary literal"
8764       return LK_Dictionary;
8765     case Stmt::BlockExprClass:
8766       return LK_Block;
8767     case Stmt::ObjCBoxedExprClass: {
8768       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8769       switch (Inner->getStmtClass()) {
8770         case Stmt::IntegerLiteralClass:
8771         case Stmt::FloatingLiteralClass:
8772         case Stmt::CharacterLiteralClass:
8773         case Stmt::ObjCBoolLiteralExprClass:
8774         case Stmt::CXXBoolLiteralExprClass:
8775           // "numeric literal"
8776           return LK_Numeric;
8777         case Stmt::ImplicitCastExprClass: {
8778           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8779           // Boolean literals can be represented by implicit casts.
8780           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8781             return LK_Numeric;
8782           break;
8783         }
8784         default:
8785           break;
8786       }
8787       return LK_Boxed;
8788     }
8789   }
8790   return LK_None;
8791 }
8792 
8793 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8794                                           ExprResult &LHS, ExprResult &RHS,
8795                                           BinaryOperator::Opcode Opc){
8796   Expr *Literal;
8797   Expr *Other;
8798   if (isObjCObjectLiteral(LHS)) {
8799     Literal = LHS.get();
8800     Other = RHS.get();
8801   } else {
8802     Literal = RHS.get();
8803     Other = LHS.get();
8804   }
8805 
8806   // Don't warn on comparisons against nil.
8807   Other = Other->IgnoreParenCasts();
8808   if (Other->isNullPointerConstant(S.getASTContext(),
8809                                    Expr::NPC_ValueDependentIsNotNull))
8810     return;
8811 
8812   // This should be kept in sync with warn_objc_literal_comparison.
8813   // LK_String should always be after the other literals, since it has its own
8814   // warning flag.
8815   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8816   assert(LiteralKind != Sema::LK_Block);
8817   if (LiteralKind == Sema::LK_None) {
8818     llvm_unreachable("Unknown Objective-C object literal kind");
8819   }
8820 
8821   if (LiteralKind == Sema::LK_String)
8822     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8823       << Literal->getSourceRange();
8824   else
8825     S.Diag(Loc, diag::warn_objc_literal_comparison)
8826       << LiteralKind << Literal->getSourceRange();
8827 
8828   if (BinaryOperator::isEqualityOp(Opc) &&
8829       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8830     SourceLocation Start = LHS.get()->getLocStart();
8831     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8832     CharSourceRange OpRange =
8833       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8834 
8835     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8836       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8837       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8838       << FixItHint::CreateInsertion(End, "]");
8839   }
8840 }
8841 
8842 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8843                                                 ExprResult &RHS,
8844                                                 SourceLocation Loc,
8845                                                 BinaryOperatorKind Opc) {
8846   // Check that left hand side is !something.
8847   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8848   if (!UO || UO->getOpcode() != UO_LNot) return;
8849 
8850   // Only check if the right hand side is non-bool arithmetic type.
8851   if (RHS.get()->isKnownToHaveBooleanValue()) return;
8852 
8853   // Make sure that the something in !something is not bool.
8854   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8855   if (SubExpr->isKnownToHaveBooleanValue()) return;
8856 
8857   // Emit warning.
8858   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8859       << Loc;
8860 
8861   // First note suggest !(x < y)
8862   SourceLocation FirstOpen = SubExpr->getLocStart();
8863   SourceLocation FirstClose = RHS.get()->getLocEnd();
8864   FirstClose = S.getLocForEndOfToken(FirstClose);
8865   if (FirstClose.isInvalid())
8866     FirstOpen = SourceLocation();
8867   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8868       << FixItHint::CreateInsertion(FirstOpen, "(")
8869       << FixItHint::CreateInsertion(FirstClose, ")");
8870 
8871   // Second note suggests (!x) < y
8872   SourceLocation SecondOpen = LHS.get()->getLocStart();
8873   SourceLocation SecondClose = LHS.get()->getLocEnd();
8874   SecondClose = S.getLocForEndOfToken(SecondClose);
8875   if (SecondClose.isInvalid())
8876     SecondOpen = SourceLocation();
8877   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8878       << FixItHint::CreateInsertion(SecondOpen, "(")
8879       << FixItHint::CreateInsertion(SecondClose, ")");
8880 }
8881 
8882 // Get the decl for a simple expression: a reference to a variable,
8883 // an implicit C++ field reference, or an implicit ObjC ivar reference.
8884 static ValueDecl *getCompareDecl(Expr *E) {
8885   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8886     return DR->getDecl();
8887   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8888     if (Ivar->isFreeIvar())
8889       return Ivar->getDecl();
8890   }
8891   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8892     if (Mem->isImplicitAccess())
8893       return Mem->getMemberDecl();
8894   }
8895   return nullptr;
8896 }
8897 
8898 // C99 6.5.8, C++ [expr.rel]
8899 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
8900                                     SourceLocation Loc, BinaryOperatorKind Opc,
8901                                     bool IsRelational) {
8902   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8903 
8904   // Handle vector comparisons separately.
8905   if (LHS.get()->getType()->isVectorType() ||
8906       RHS.get()->getType()->isVectorType())
8907     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
8908 
8909   QualType LHSType = LHS.get()->getType();
8910   QualType RHSType = RHS.get()->getType();
8911 
8912   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8913   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
8914 
8915   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
8916   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
8917 
8918   if (!LHSType->hasFloatingRepresentation() &&
8919       !(LHSType->isBlockPointerType() && IsRelational) &&
8920       !LHS.get()->getLocStart().isMacroID() &&
8921       !RHS.get()->getLocStart().isMacroID() &&
8922       ActiveTemplateInstantiations.empty()) {
8923     // For non-floating point types, check for self-comparisons of the form
8924     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8925     // often indicate logic errors in the program.
8926     //
8927     // NOTE: Don't warn about comparison expressions resulting from macro
8928     // expansion. Also don't warn about comparisons which are only self
8929     // comparisons within a template specialization. The warnings should catch
8930     // obvious cases in the definition of the template anyways. The idea is to
8931     // warn when the typed comparison operator will always evaluate to the same
8932     // result.
8933     ValueDecl *DL = getCompareDecl(LHSStripped);
8934     ValueDecl *DR = getCompareDecl(RHSStripped);
8935     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8936       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8937                           << 0 // self-
8938                           << (Opc == BO_EQ
8939                               || Opc == BO_LE
8940                               || Opc == BO_GE));
8941     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8942                !DL->getType()->isReferenceType() &&
8943                !DR->getType()->isReferenceType()) {
8944         // what is it always going to eval to?
8945         char always_evals_to;
8946         switch(Opc) {
8947         case BO_EQ: // e.g. array1 == array2
8948           always_evals_to = 0; // false
8949           break;
8950         case BO_NE: // e.g. array1 != array2
8951           always_evals_to = 1; // true
8952           break;
8953         default:
8954           // best we can say is 'a constant'
8955           always_evals_to = 2; // e.g. array1 <= array2
8956           break;
8957         }
8958         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8959                             << 1 // array
8960                             << always_evals_to);
8961     }
8962 
8963     if (isa<CastExpr>(LHSStripped))
8964       LHSStripped = LHSStripped->IgnoreParenCasts();
8965     if (isa<CastExpr>(RHSStripped))
8966       RHSStripped = RHSStripped->IgnoreParenCasts();
8967 
8968     // Warn about comparisons against a string constant (unless the other
8969     // operand is null), the user probably wants strcmp.
8970     Expr *literalString = nullptr;
8971     Expr *literalStringStripped = nullptr;
8972     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8973         !RHSStripped->isNullPointerConstant(Context,
8974                                             Expr::NPC_ValueDependentIsNull)) {
8975       literalString = LHS.get();
8976       literalStringStripped = LHSStripped;
8977     } else if ((isa<StringLiteral>(RHSStripped) ||
8978                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8979                !LHSStripped->isNullPointerConstant(Context,
8980                                             Expr::NPC_ValueDependentIsNull)) {
8981       literalString = RHS.get();
8982       literalStringStripped = RHSStripped;
8983     }
8984 
8985     if (literalString) {
8986       DiagRuntimeBehavior(Loc, nullptr,
8987         PDiag(diag::warn_stringcompare)
8988           << isa<ObjCEncodeExpr>(literalStringStripped)
8989           << literalString->getSourceRange());
8990     }
8991   }
8992 
8993   // C99 6.5.8p3 / C99 6.5.9p4
8994   UsualArithmeticConversions(LHS, RHS);
8995   if (LHS.isInvalid() || RHS.isInvalid())
8996     return QualType();
8997 
8998   LHSType = LHS.get()->getType();
8999   RHSType = RHS.get()->getType();
9000 
9001   // The result of comparisons is 'bool' in C++, 'int' in C.
9002   QualType ResultTy = Context.getLogicalOperationType();
9003 
9004   if (IsRelational) {
9005     if (LHSType->isRealType() && RHSType->isRealType())
9006       return ResultTy;
9007   } else {
9008     // Check for comparisons of floating point operands using != and ==.
9009     if (LHSType->hasFloatingRepresentation())
9010       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9011 
9012     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9013       return ResultTy;
9014   }
9015 
9016   const Expr::NullPointerConstantKind LHSNullKind =
9017       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9018   const Expr::NullPointerConstantKind RHSNullKind =
9019       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9020   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9021   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9022 
9023   if (!IsRelational && LHSIsNull != RHSIsNull) {
9024     bool IsEquality = Opc == BO_EQ;
9025     if (RHSIsNull)
9026       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9027                                    RHS.get()->getSourceRange());
9028     else
9029       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9030                                    LHS.get()->getSourceRange());
9031   }
9032 
9033   // All of the following pointer-related warnings are GCC extensions, except
9034   // when handling null pointer constants.
9035   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9036     QualType LCanPointeeTy =
9037       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9038     QualType RCanPointeeTy =
9039       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9040 
9041     if (getLangOpts().CPlusPlus) {
9042       if (LCanPointeeTy == RCanPointeeTy)
9043         return ResultTy;
9044       if (!IsRelational &&
9045           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9046         // Valid unless comparison between non-null pointer and function pointer
9047         // This is a gcc extension compatibility comparison.
9048         // In a SFINAE context, we treat this as a hard error to maintain
9049         // conformance with the C++ standard.
9050         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9051             && !LHSIsNull && !RHSIsNull) {
9052           diagnoseFunctionPointerToVoidComparison(
9053               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9054 
9055           if (isSFINAEContext())
9056             return QualType();
9057 
9058           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9059           return ResultTy;
9060         }
9061       }
9062 
9063       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9064         return QualType();
9065       else
9066         return ResultTy;
9067     }
9068     // C99 6.5.9p2 and C99 6.5.8p2
9069     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9070                                    RCanPointeeTy.getUnqualifiedType())) {
9071       // Valid unless a relational comparison of function pointers
9072       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9073         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9074           << LHSType << RHSType << LHS.get()->getSourceRange()
9075           << RHS.get()->getSourceRange();
9076       }
9077     } else if (!IsRelational &&
9078                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9079       // Valid unless comparison between non-null pointer and function pointer
9080       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9081           && !LHSIsNull && !RHSIsNull)
9082         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9083                                                 /*isError*/false);
9084     } else {
9085       // Invalid
9086       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9087     }
9088     if (LCanPointeeTy != RCanPointeeTy) {
9089       // Treat NULL constant as a special case in OpenCL.
9090       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9091         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9092         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9093           Diag(Loc,
9094                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9095               << LHSType << RHSType << 0 /* comparison */
9096               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9097         }
9098       }
9099       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9100       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9101       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9102                                                : CK_BitCast;
9103       if (LHSIsNull && !RHSIsNull)
9104         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9105       else
9106         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9107     }
9108     return ResultTy;
9109   }
9110 
9111   if (getLangOpts().CPlusPlus) {
9112     // Comparison of nullptr_t with itself.
9113     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9114       return ResultTy;
9115 
9116     // Comparison of pointers with null pointer constants and equality
9117     // comparisons of member pointers to null pointer constants.
9118     if (RHSIsNull &&
9119         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9120          (!IsRelational &&
9121           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9122       RHS = ImpCastExprToType(RHS.get(), LHSType,
9123                         LHSType->isMemberPointerType()
9124                           ? CK_NullToMemberPointer
9125                           : CK_NullToPointer);
9126       return ResultTy;
9127     }
9128     if (LHSIsNull &&
9129         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9130          (!IsRelational &&
9131           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9132       LHS = ImpCastExprToType(LHS.get(), RHSType,
9133                         RHSType->isMemberPointerType()
9134                           ? CK_NullToMemberPointer
9135                           : CK_NullToPointer);
9136       return ResultTy;
9137     }
9138 
9139     // Comparison of member pointers.
9140     if (!IsRelational &&
9141         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9142       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9143         return QualType();
9144       else
9145         return ResultTy;
9146     }
9147 
9148     // Handle scoped enumeration types specifically, since they don't promote
9149     // to integers.
9150     if (LHS.get()->getType()->isEnumeralType() &&
9151         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9152                                        RHS.get()->getType()))
9153       return ResultTy;
9154   }
9155 
9156   // Handle block pointer types.
9157   if (!IsRelational && LHSType->isBlockPointerType() &&
9158       RHSType->isBlockPointerType()) {
9159     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9160     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9161 
9162     if (!LHSIsNull && !RHSIsNull &&
9163         !Context.typesAreCompatible(lpointee, rpointee)) {
9164       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9165         << LHSType << RHSType << LHS.get()->getSourceRange()
9166         << RHS.get()->getSourceRange();
9167     }
9168     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9169     return ResultTy;
9170   }
9171 
9172   // Allow block pointers to be compared with null pointer constants.
9173   if (!IsRelational
9174       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9175           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9176     if (!LHSIsNull && !RHSIsNull) {
9177       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9178              ->getPointeeType()->isVoidType())
9179             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9180                 ->getPointeeType()->isVoidType())))
9181         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9182           << LHSType << RHSType << LHS.get()->getSourceRange()
9183           << RHS.get()->getSourceRange();
9184     }
9185     if (LHSIsNull && !RHSIsNull)
9186       LHS = ImpCastExprToType(LHS.get(), RHSType,
9187                               RHSType->isPointerType() ? CK_BitCast
9188                                 : CK_AnyPointerToBlockPointerCast);
9189     else
9190       RHS = ImpCastExprToType(RHS.get(), LHSType,
9191                               LHSType->isPointerType() ? CK_BitCast
9192                                 : CK_AnyPointerToBlockPointerCast);
9193     return ResultTy;
9194   }
9195 
9196   if (LHSType->isObjCObjectPointerType() ||
9197       RHSType->isObjCObjectPointerType()) {
9198     const PointerType *LPT = LHSType->getAs<PointerType>();
9199     const PointerType *RPT = RHSType->getAs<PointerType>();
9200     if (LPT || RPT) {
9201       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9202       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9203 
9204       if (!LPtrToVoid && !RPtrToVoid &&
9205           !Context.typesAreCompatible(LHSType, RHSType)) {
9206         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9207                                           /*isError*/false);
9208       }
9209       if (LHSIsNull && !RHSIsNull) {
9210         Expr *E = LHS.get();
9211         if (getLangOpts().ObjCAutoRefCount)
9212           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9213         LHS = ImpCastExprToType(E, RHSType,
9214                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9215       }
9216       else {
9217         Expr *E = RHS.get();
9218         if (getLangOpts().ObjCAutoRefCount)
9219           CheckObjCARCConversion(SourceRange(), LHSType, E,
9220                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9221                                  /*DiagnoseCFAudited=*/false, Opc);
9222         RHS = ImpCastExprToType(E, LHSType,
9223                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9224       }
9225       return ResultTy;
9226     }
9227     if (LHSType->isObjCObjectPointerType() &&
9228         RHSType->isObjCObjectPointerType()) {
9229       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9230         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9231                                           /*isError*/false);
9232       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9233         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9234 
9235       if (LHSIsNull && !RHSIsNull)
9236         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9237       else
9238         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9239       return ResultTy;
9240     }
9241   }
9242   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9243       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9244     unsigned DiagID = 0;
9245     bool isError = false;
9246     if (LangOpts.DebuggerSupport) {
9247       // Under a debugger, allow the comparison of pointers to integers,
9248       // since users tend to want to compare addresses.
9249     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9250         (RHSIsNull && RHSType->isIntegerType())) {
9251       if (IsRelational && !getLangOpts().CPlusPlus)
9252         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9253     } else if (IsRelational && !getLangOpts().CPlusPlus)
9254       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9255     else if (getLangOpts().CPlusPlus) {
9256       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9257       isError = true;
9258     } else
9259       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9260 
9261     if (DiagID) {
9262       Diag(Loc, DiagID)
9263         << LHSType << RHSType << LHS.get()->getSourceRange()
9264         << RHS.get()->getSourceRange();
9265       if (isError)
9266         return QualType();
9267     }
9268 
9269     if (LHSType->isIntegerType())
9270       LHS = ImpCastExprToType(LHS.get(), RHSType,
9271                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9272     else
9273       RHS = ImpCastExprToType(RHS.get(), LHSType,
9274                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9275     return ResultTy;
9276   }
9277 
9278   // Handle block pointers.
9279   if (!IsRelational && RHSIsNull
9280       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9281     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9282     return ResultTy;
9283   }
9284   if (!IsRelational && LHSIsNull
9285       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9286     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9287     return ResultTy;
9288   }
9289 
9290   return InvalidOperands(Loc, LHS, RHS);
9291 }
9292 
9293 
9294 // Return a signed type that is of identical size and number of elements.
9295 // For floating point vectors, return an integer type of identical size
9296 // and number of elements.
9297 QualType Sema::GetSignedVectorType(QualType V) {
9298   const VectorType *VTy = V->getAs<VectorType>();
9299   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9300   if (TypeSize == Context.getTypeSize(Context.CharTy))
9301     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9302   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9303     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9304   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9305     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9306   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9307     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9308   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9309          "Unhandled vector element size in vector compare");
9310   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9311 }
9312 
9313 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9314 /// operates on extended vector types.  Instead of producing an IntTy result,
9315 /// like a scalar comparison, a vector comparison produces a vector of integer
9316 /// types.
9317 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9318                                           SourceLocation Loc,
9319                                           bool IsRelational) {
9320   // Check to make sure we're operating on vectors of the same type and width,
9321   // Allowing one side to be a scalar of element type.
9322   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9323                               /*AllowBothBool*/true,
9324                               /*AllowBoolConversions*/getLangOpts().ZVector);
9325   if (vType.isNull())
9326     return vType;
9327 
9328   QualType LHSType = LHS.get()->getType();
9329 
9330   // If AltiVec, the comparison results in a numeric type, i.e.
9331   // bool for C++, int for C
9332   if (getLangOpts().AltiVec &&
9333       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9334     return Context.getLogicalOperationType();
9335 
9336   // For non-floating point types, check for self-comparisons of the form
9337   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9338   // often indicate logic errors in the program.
9339   if (!LHSType->hasFloatingRepresentation() &&
9340       ActiveTemplateInstantiations.empty()) {
9341     if (DeclRefExpr* DRL
9342           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9343       if (DeclRefExpr* DRR
9344             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9345         if (DRL->getDecl() == DRR->getDecl())
9346           DiagRuntimeBehavior(Loc, nullptr,
9347                               PDiag(diag::warn_comparison_always)
9348                                 << 0 // self-
9349                                 << 2 // "a constant"
9350                               );
9351   }
9352 
9353   // Check for comparisons of floating point operands using != and ==.
9354   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9355     assert (RHS.get()->getType()->hasFloatingRepresentation());
9356     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9357   }
9358 
9359   // Return a signed type for the vector.
9360   return GetSignedVectorType(LHSType);
9361 }
9362 
9363 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9364                                           SourceLocation Loc) {
9365   // Ensure that either both operands are of the same vector type, or
9366   // one operand is of a vector type and the other is of its element type.
9367   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9368                                        /*AllowBothBool*/true,
9369                                        /*AllowBoolConversions*/false);
9370   if (vType.isNull())
9371     return InvalidOperands(Loc, LHS, RHS);
9372   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9373       vType->hasFloatingRepresentation())
9374     return InvalidOperands(Loc, LHS, RHS);
9375 
9376   return GetSignedVectorType(LHS.get()->getType());
9377 }
9378 
9379 inline QualType Sema::CheckBitwiseOperands(
9380   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9381   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9382 
9383   if (LHS.get()->getType()->isVectorType() ||
9384       RHS.get()->getType()->isVectorType()) {
9385     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9386         RHS.get()->getType()->hasIntegerRepresentation())
9387       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9388                         /*AllowBothBool*/true,
9389                         /*AllowBoolConversions*/getLangOpts().ZVector);
9390     return InvalidOperands(Loc, LHS, RHS);
9391   }
9392 
9393   ExprResult LHSResult = LHS, RHSResult = RHS;
9394   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9395                                                  IsCompAssign);
9396   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9397     return QualType();
9398   LHS = LHSResult.get();
9399   RHS = RHSResult.get();
9400 
9401   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9402     return compType;
9403   return InvalidOperands(Loc, LHS, RHS);
9404 }
9405 
9406 // C99 6.5.[13,14]
9407 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9408                                            SourceLocation Loc,
9409                                            BinaryOperatorKind Opc) {
9410   // Check vector operands differently.
9411   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9412     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9413 
9414   // Diagnose cases where the user write a logical and/or but probably meant a
9415   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9416   // is a constant.
9417   if (LHS.get()->getType()->isIntegerType() &&
9418       !LHS.get()->getType()->isBooleanType() &&
9419       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9420       // Don't warn in macros or template instantiations.
9421       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9422     // If the RHS can be constant folded, and if it constant folds to something
9423     // that isn't 0 or 1 (which indicate a potential logical operation that
9424     // happened to fold to true/false) then warn.
9425     // Parens on the RHS are ignored.
9426     llvm::APSInt Result;
9427     if (RHS.get()->EvaluateAsInt(Result, Context))
9428       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9429            !RHS.get()->getExprLoc().isMacroID()) ||
9430           (Result != 0 && Result != 1)) {
9431         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9432           << RHS.get()->getSourceRange()
9433           << (Opc == BO_LAnd ? "&&" : "||");
9434         // Suggest replacing the logical operator with the bitwise version
9435         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9436             << (Opc == BO_LAnd ? "&" : "|")
9437             << FixItHint::CreateReplacement(SourceRange(
9438                                                  Loc, getLocForEndOfToken(Loc)),
9439                                             Opc == BO_LAnd ? "&" : "|");
9440         if (Opc == BO_LAnd)
9441           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9442           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9443               << FixItHint::CreateRemoval(
9444                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9445                               RHS.get()->getLocEnd()));
9446       }
9447   }
9448 
9449   if (!Context.getLangOpts().CPlusPlus) {
9450     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9451     // not operate on the built-in scalar and vector float types.
9452     if (Context.getLangOpts().OpenCL &&
9453         Context.getLangOpts().OpenCLVersion < 120) {
9454       if (LHS.get()->getType()->isFloatingType() ||
9455           RHS.get()->getType()->isFloatingType())
9456         return InvalidOperands(Loc, LHS, RHS);
9457     }
9458 
9459     LHS = UsualUnaryConversions(LHS.get());
9460     if (LHS.isInvalid())
9461       return QualType();
9462 
9463     RHS = UsualUnaryConversions(RHS.get());
9464     if (RHS.isInvalid())
9465       return QualType();
9466 
9467     if (!LHS.get()->getType()->isScalarType() ||
9468         !RHS.get()->getType()->isScalarType())
9469       return InvalidOperands(Loc, LHS, RHS);
9470 
9471     return Context.IntTy;
9472   }
9473 
9474   // The following is safe because we only use this method for
9475   // non-overloadable operands.
9476 
9477   // C++ [expr.log.and]p1
9478   // C++ [expr.log.or]p1
9479   // The operands are both contextually converted to type bool.
9480   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9481   if (LHSRes.isInvalid())
9482     return InvalidOperands(Loc, LHS, RHS);
9483   LHS = LHSRes;
9484 
9485   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9486   if (RHSRes.isInvalid())
9487     return InvalidOperands(Loc, LHS, RHS);
9488   RHS = RHSRes;
9489 
9490   // C++ [expr.log.and]p2
9491   // C++ [expr.log.or]p2
9492   // The result is a bool.
9493   return Context.BoolTy;
9494 }
9495 
9496 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9497   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9498   if (!ME) return false;
9499   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9500   ObjCMessageExpr *Base =
9501     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9502   if (!Base) return false;
9503   return Base->getMethodDecl() != nullptr;
9504 }
9505 
9506 /// Is the given expression (which must be 'const') a reference to a
9507 /// variable which was originally non-const, but which has become
9508 /// 'const' due to being captured within a block?
9509 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9510 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9511   assert(E->isLValue() && E->getType().isConstQualified());
9512   E = E->IgnoreParens();
9513 
9514   // Must be a reference to a declaration from an enclosing scope.
9515   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9516   if (!DRE) return NCCK_None;
9517   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9518 
9519   // The declaration must be a variable which is not declared 'const'.
9520   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9521   if (!var) return NCCK_None;
9522   if (var->getType().isConstQualified()) return NCCK_None;
9523   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9524 
9525   // Decide whether the first capture was for a block or a lambda.
9526   DeclContext *DC = S.CurContext, *Prev = nullptr;
9527   while (DC != var->getDeclContext()) {
9528     Prev = DC;
9529     DC = DC->getParent();
9530   }
9531   // Unless we have an init-capture, we've gone one step too far.
9532   if (!var->isInitCapture())
9533     DC = Prev;
9534   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9535 }
9536 
9537 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9538   Ty = Ty.getNonReferenceType();
9539   if (IsDereference && Ty->isPointerType())
9540     Ty = Ty->getPointeeType();
9541   return !Ty.isConstQualified();
9542 }
9543 
9544 /// Emit the "read-only variable not assignable" error and print notes to give
9545 /// more information about why the variable is not assignable, such as pointing
9546 /// to the declaration of a const variable, showing that a method is const, or
9547 /// that the function is returning a const reference.
9548 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9549                                     SourceLocation Loc) {
9550   // Update err_typecheck_assign_const and note_typecheck_assign_const
9551   // when this enum is changed.
9552   enum {
9553     ConstFunction,
9554     ConstVariable,
9555     ConstMember,
9556     ConstMethod,
9557     ConstUnknown,  // Keep as last element
9558   };
9559 
9560   SourceRange ExprRange = E->getSourceRange();
9561 
9562   // Only emit one error on the first const found.  All other consts will emit
9563   // a note to the error.
9564   bool DiagnosticEmitted = false;
9565 
9566   // Track if the current expression is the result of a derefence, and if the
9567   // next checked expression is the result of a derefence.
9568   bool IsDereference = false;
9569   bool NextIsDereference = false;
9570 
9571   // Loop to process MemberExpr chains.
9572   while (true) {
9573     IsDereference = NextIsDereference;
9574     NextIsDereference = false;
9575 
9576     E = E->IgnoreParenImpCasts();
9577     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9578       NextIsDereference = ME->isArrow();
9579       const ValueDecl *VD = ME->getMemberDecl();
9580       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9581         // Mutable fields can be modified even if the class is const.
9582         if (Field->isMutable()) {
9583           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9584           break;
9585         }
9586 
9587         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9588           if (!DiagnosticEmitted) {
9589             S.Diag(Loc, diag::err_typecheck_assign_const)
9590                 << ExprRange << ConstMember << false /*static*/ << Field
9591                 << Field->getType();
9592             DiagnosticEmitted = true;
9593           }
9594           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9595               << ConstMember << false /*static*/ << Field << Field->getType()
9596               << Field->getSourceRange();
9597         }
9598         E = ME->getBase();
9599         continue;
9600       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9601         if (VDecl->getType().isConstQualified()) {
9602           if (!DiagnosticEmitted) {
9603             S.Diag(Loc, diag::err_typecheck_assign_const)
9604                 << ExprRange << ConstMember << true /*static*/ << VDecl
9605                 << VDecl->getType();
9606             DiagnosticEmitted = true;
9607           }
9608           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9609               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9610               << VDecl->getSourceRange();
9611         }
9612         // Static fields do not inherit constness from parents.
9613         break;
9614       }
9615       break;
9616     } // End MemberExpr
9617     break;
9618   }
9619 
9620   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9621     // Function calls
9622     const FunctionDecl *FD = CE->getDirectCallee();
9623     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9624       if (!DiagnosticEmitted) {
9625         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9626                                                       << ConstFunction << FD;
9627         DiagnosticEmitted = true;
9628       }
9629       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9630              diag::note_typecheck_assign_const)
9631           << ConstFunction << FD << FD->getReturnType()
9632           << FD->getReturnTypeSourceRange();
9633     }
9634   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9635     // Point to variable declaration.
9636     if (const ValueDecl *VD = DRE->getDecl()) {
9637       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9638         if (!DiagnosticEmitted) {
9639           S.Diag(Loc, diag::err_typecheck_assign_const)
9640               << ExprRange << ConstVariable << VD << VD->getType();
9641           DiagnosticEmitted = true;
9642         }
9643         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9644             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9645       }
9646     }
9647   } else if (isa<CXXThisExpr>(E)) {
9648     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9649       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9650         if (MD->isConst()) {
9651           if (!DiagnosticEmitted) {
9652             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9653                                                           << ConstMethod << MD;
9654             DiagnosticEmitted = true;
9655           }
9656           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9657               << ConstMethod << MD << MD->getSourceRange();
9658         }
9659       }
9660     }
9661   }
9662 
9663   if (DiagnosticEmitted)
9664     return;
9665 
9666   // Can't determine a more specific message, so display the generic error.
9667   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9668 }
9669 
9670 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9671 /// emit an error and return true.  If so, return false.
9672 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9673   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9674   SourceLocation OrigLoc = Loc;
9675   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9676                                                               &Loc);
9677   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9678     IsLV = Expr::MLV_InvalidMessageExpression;
9679   if (IsLV == Expr::MLV_Valid)
9680     return false;
9681 
9682   unsigned DiagID = 0;
9683   bool NeedType = false;
9684   switch (IsLV) { // C99 6.5.16p2
9685   case Expr::MLV_ConstQualified:
9686     // Use a specialized diagnostic when we're assigning to an object
9687     // from an enclosing function or block.
9688     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9689       if (NCCK == NCCK_Block)
9690         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9691       else
9692         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9693       break;
9694     }
9695 
9696     // In ARC, use some specialized diagnostics for occasions where we
9697     // infer 'const'.  These are always pseudo-strong variables.
9698     if (S.getLangOpts().ObjCAutoRefCount) {
9699       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9700       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9701         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9702 
9703         // Use the normal diagnostic if it's pseudo-__strong but the
9704         // user actually wrote 'const'.
9705         if (var->isARCPseudoStrong() &&
9706             (!var->getTypeSourceInfo() ||
9707              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9708           // There are two pseudo-strong cases:
9709           //  - self
9710           ObjCMethodDecl *method = S.getCurMethodDecl();
9711           if (method && var == method->getSelfDecl())
9712             DiagID = method->isClassMethod()
9713               ? diag::err_typecheck_arc_assign_self_class_method
9714               : diag::err_typecheck_arc_assign_self;
9715 
9716           //  - fast enumeration variables
9717           else
9718             DiagID = diag::err_typecheck_arr_assign_enumeration;
9719 
9720           SourceRange Assign;
9721           if (Loc != OrigLoc)
9722             Assign = SourceRange(OrigLoc, OrigLoc);
9723           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9724           // We need to preserve the AST regardless, so migration tool
9725           // can do its job.
9726           return false;
9727         }
9728       }
9729     }
9730 
9731     // If none of the special cases above are triggered, then this is a
9732     // simple const assignment.
9733     if (DiagID == 0) {
9734       DiagnoseConstAssignment(S, E, Loc);
9735       return true;
9736     }
9737 
9738     break;
9739   case Expr::MLV_ConstAddrSpace:
9740     DiagnoseConstAssignment(S, E, Loc);
9741     return true;
9742   case Expr::MLV_ArrayType:
9743   case Expr::MLV_ArrayTemporary:
9744     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9745     NeedType = true;
9746     break;
9747   case Expr::MLV_NotObjectType:
9748     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9749     NeedType = true;
9750     break;
9751   case Expr::MLV_LValueCast:
9752     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9753     break;
9754   case Expr::MLV_Valid:
9755     llvm_unreachable("did not take early return for MLV_Valid");
9756   case Expr::MLV_InvalidExpression:
9757   case Expr::MLV_MemberFunction:
9758   case Expr::MLV_ClassTemporary:
9759     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9760     break;
9761   case Expr::MLV_IncompleteType:
9762   case Expr::MLV_IncompleteVoidType:
9763     return S.RequireCompleteType(Loc, E->getType(),
9764              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9765   case Expr::MLV_DuplicateVectorComponents:
9766     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9767     break;
9768   case Expr::MLV_NoSetterProperty:
9769     llvm_unreachable("readonly properties should be processed differently");
9770   case Expr::MLV_InvalidMessageExpression:
9771     DiagID = diag::error_readonly_message_assignment;
9772     break;
9773   case Expr::MLV_SubObjCPropertySetting:
9774     DiagID = diag::error_no_subobject_property_setting;
9775     break;
9776   }
9777 
9778   SourceRange Assign;
9779   if (Loc != OrigLoc)
9780     Assign = SourceRange(OrigLoc, OrigLoc);
9781   if (NeedType)
9782     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9783   else
9784     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9785   return true;
9786 }
9787 
9788 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9789                                          SourceLocation Loc,
9790                                          Sema &Sema) {
9791   // C / C++ fields
9792   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9793   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9794   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9795     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9796       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9797   }
9798 
9799   // Objective-C instance variables
9800   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9801   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9802   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9803     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9804     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9805     if (RL && RR && RL->getDecl() == RR->getDecl())
9806       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9807   }
9808 }
9809 
9810 // C99 6.5.16.1
9811 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9812                                        SourceLocation Loc,
9813                                        QualType CompoundType) {
9814   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9815 
9816   // Verify that LHS is a modifiable lvalue, and emit error if not.
9817   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9818     return QualType();
9819 
9820   QualType LHSType = LHSExpr->getType();
9821   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9822                                              CompoundType;
9823   AssignConvertType ConvTy;
9824   if (CompoundType.isNull()) {
9825     Expr *RHSCheck = RHS.get();
9826 
9827     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9828 
9829     QualType LHSTy(LHSType);
9830     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9831     if (RHS.isInvalid())
9832       return QualType();
9833     // Special case of NSObject attributes on c-style pointer types.
9834     if (ConvTy == IncompatiblePointer &&
9835         ((Context.isObjCNSObjectType(LHSType) &&
9836           RHSType->isObjCObjectPointerType()) ||
9837          (Context.isObjCNSObjectType(RHSType) &&
9838           LHSType->isObjCObjectPointerType())))
9839       ConvTy = Compatible;
9840 
9841     if (ConvTy == Compatible &&
9842         LHSType->isObjCObjectType())
9843         Diag(Loc, diag::err_objc_object_assignment)
9844           << LHSType;
9845 
9846     // If the RHS is a unary plus or minus, check to see if they = and + are
9847     // right next to each other.  If so, the user may have typo'd "x =+ 4"
9848     // instead of "x += 4".
9849     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9850       RHSCheck = ICE->getSubExpr();
9851     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9852       if ((UO->getOpcode() == UO_Plus ||
9853            UO->getOpcode() == UO_Minus) &&
9854           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9855           // Only if the two operators are exactly adjacent.
9856           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9857           // And there is a space or other character before the subexpr of the
9858           // unary +/-.  We don't want to warn on "x=-1".
9859           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9860           UO->getSubExpr()->getLocStart().isFileID()) {
9861         Diag(Loc, diag::warn_not_compound_assign)
9862           << (UO->getOpcode() == UO_Plus ? "+" : "-")
9863           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9864       }
9865     }
9866 
9867     if (ConvTy == Compatible) {
9868       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9869         // Warn about retain cycles where a block captures the LHS, but
9870         // not if the LHS is a simple variable into which the block is
9871         // being stored...unless that variable can be captured by reference!
9872         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9873         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9874         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9875           checkRetainCycles(LHSExpr, RHS.get());
9876 
9877         // It is safe to assign a weak reference into a strong variable.
9878         // Although this code can still have problems:
9879         //   id x = self.weakProp;
9880         //   id y = self.weakProp;
9881         // we do not warn to warn spuriously when 'x' and 'y' are on separate
9882         // paths through the function. This should be revisited if
9883         // -Wrepeated-use-of-weak is made flow-sensitive.
9884         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9885                              RHS.get()->getLocStart()))
9886           getCurFunction()->markSafeWeakUse(RHS.get());
9887 
9888       } else if (getLangOpts().ObjCAutoRefCount) {
9889         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
9890       }
9891     }
9892   } else {
9893     // Compound assignment "x += y"
9894     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
9895   }
9896 
9897   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
9898                                RHS.get(), AA_Assigning))
9899     return QualType();
9900 
9901   CheckForNullPointerDereference(*this, LHSExpr);
9902 
9903   // C99 6.5.16p3: The type of an assignment expression is the type of the
9904   // left operand unless the left operand has qualified type, in which case
9905   // it is the unqualified version of the type of the left operand.
9906   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9907   // is converted to the type of the assignment expression (above).
9908   // C++ 5.17p1: the type of the assignment expression is that of its left
9909   // operand.
9910   return (getLangOpts().CPlusPlus
9911           ? LHSType : LHSType.getUnqualifiedType());
9912 }
9913 
9914 // Only ignore explicit casts to void.
9915 static bool IgnoreCommaOperand(const Expr *E) {
9916   E = E->IgnoreParens();
9917 
9918   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
9919     if (CE->getCastKind() == CK_ToVoid) {
9920       return true;
9921     }
9922   }
9923 
9924   return false;
9925 }
9926 
9927 // Look for instances where it is likely the comma operator is confused with
9928 // another operator.  There is a whitelist of acceptable expressions for the
9929 // left hand side of the comma operator, otherwise emit a warning.
9930 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
9931   // No warnings in macros
9932   if (Loc.isMacroID())
9933     return;
9934 
9935   // Don't warn in template instantiations.
9936   if (!ActiveTemplateInstantiations.empty())
9937     return;
9938 
9939   // Scope isn't fine-grained enough to whitelist the specific cases, so
9940   // instead, skip more than needed, then call back into here with the
9941   // CommaVisitor in SemaStmt.cpp.
9942   // The whitelisted locations are the initialization and increment portions
9943   // of a for loop.  The additional checks are on the condition of
9944   // if statements, do/while loops, and for loops.
9945   const unsigned ForIncrementFlags =
9946       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
9947   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
9948   const unsigned ScopeFlags = getCurScope()->getFlags();
9949   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
9950       (ScopeFlags & ForInitFlags) == ForInitFlags)
9951     return;
9952 
9953   // If there are multiple comma operators used together, get the RHS of the
9954   // of the comma operator as the LHS.
9955   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
9956     if (BO->getOpcode() != BO_Comma)
9957       break;
9958     LHS = BO->getRHS();
9959   }
9960 
9961   // Only allow some expressions on LHS to not warn.
9962   if (IgnoreCommaOperand(LHS))
9963     return;
9964 
9965   Diag(Loc, diag::warn_comma_operator);
9966   Diag(LHS->getLocStart(), diag::note_cast_to_void)
9967       << LHS->getSourceRange()
9968       << FixItHint::CreateInsertion(LHS->getLocStart(),
9969                                     LangOpts.CPlusPlus ? "static_cast<void>("
9970                                                        : "(void)(")
9971       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
9972                                     ")");
9973 }
9974 
9975 // C99 6.5.17
9976 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
9977                                    SourceLocation Loc) {
9978   LHS = S.CheckPlaceholderExpr(LHS.get());
9979   RHS = S.CheckPlaceholderExpr(RHS.get());
9980   if (LHS.isInvalid() || RHS.isInvalid())
9981     return QualType();
9982 
9983   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9984   // operands, but not unary promotions.
9985   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
9986 
9987   // So we treat the LHS as a ignored value, and in C++ we allow the
9988   // containing site to determine what should be done with the RHS.
9989   LHS = S.IgnoredValueConversions(LHS.get());
9990   if (LHS.isInvalid())
9991     return QualType();
9992 
9993   S.DiagnoseUnusedExprResult(LHS.get());
9994 
9995   if (!S.getLangOpts().CPlusPlus) {
9996     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9997     if (RHS.isInvalid())
9998       return QualType();
9999     if (!RHS.get()->getType()->isVoidType())
10000       S.RequireCompleteType(Loc, RHS.get()->getType(),
10001                             diag::err_incomplete_type);
10002   }
10003 
10004   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10005     S.DiagnoseCommaOperator(LHS.get(), Loc);
10006 
10007   return RHS.get()->getType();
10008 }
10009 
10010 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10011 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10012 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10013                                                ExprValueKind &VK,
10014                                                ExprObjectKind &OK,
10015                                                SourceLocation OpLoc,
10016                                                bool IsInc, bool IsPrefix) {
10017   if (Op->isTypeDependent())
10018     return S.Context.DependentTy;
10019 
10020   QualType ResType = Op->getType();
10021   // Atomic types can be used for increment / decrement where the non-atomic
10022   // versions can, so ignore the _Atomic() specifier for the purpose of
10023   // checking.
10024   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10025     ResType = ResAtomicType->getValueType();
10026 
10027   assert(!ResType.isNull() && "no type for increment/decrement expression");
10028 
10029   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10030     // Decrement of bool is not allowed.
10031     if (!IsInc) {
10032       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10033       return QualType();
10034     }
10035     // Increment of bool sets it to true, but is deprecated.
10036     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10037                                               : diag::warn_increment_bool)
10038       << Op->getSourceRange();
10039   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10040     // Error on enum increments and decrements in C++ mode
10041     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10042     return QualType();
10043   } else if (ResType->isRealType()) {
10044     // OK!
10045   } else if (ResType->isPointerType()) {
10046     // C99 6.5.2.4p2, 6.5.6p2
10047     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10048       return QualType();
10049   } else if (ResType->isObjCObjectPointerType()) {
10050     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10051     // Otherwise, we just need a complete type.
10052     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10053         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10054       return QualType();
10055   } else if (ResType->isAnyComplexType()) {
10056     // C99 does not support ++/-- on complex types, we allow as an extension.
10057     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10058       << ResType << Op->getSourceRange();
10059   } else if (ResType->isPlaceholderType()) {
10060     ExprResult PR = S.CheckPlaceholderExpr(Op);
10061     if (PR.isInvalid()) return QualType();
10062     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10063                                           IsInc, IsPrefix);
10064   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10065     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10066   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10067              (ResType->getAs<VectorType>()->getVectorKind() !=
10068               VectorType::AltiVecBool)) {
10069     // The z vector extensions allow ++ and -- for non-bool vectors.
10070   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10071             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10072     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10073   } else {
10074     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10075       << ResType << int(IsInc) << Op->getSourceRange();
10076     return QualType();
10077   }
10078   // At this point, we know we have a real, complex or pointer type.
10079   // Now make sure the operand is a modifiable lvalue.
10080   if (CheckForModifiableLvalue(Op, OpLoc, S))
10081     return QualType();
10082   // In C++, a prefix increment is the same type as the operand. Otherwise
10083   // (in C or with postfix), the increment is the unqualified type of the
10084   // operand.
10085   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10086     VK = VK_LValue;
10087     OK = Op->getObjectKind();
10088     return ResType;
10089   } else {
10090     VK = VK_RValue;
10091     return ResType.getUnqualifiedType();
10092   }
10093 }
10094 
10095 
10096 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10097 /// This routine allows us to typecheck complex/recursive expressions
10098 /// where the declaration is needed for type checking. We only need to
10099 /// handle cases when the expression references a function designator
10100 /// or is an lvalue. Here are some examples:
10101 ///  - &(x) => x
10102 ///  - &*****f => f for f a function designator.
10103 ///  - &s.xx => s
10104 ///  - &s.zz[1].yy -> s, if zz is an array
10105 ///  - *(x + 1) -> x, if x is an array
10106 ///  - &"123"[2] -> 0
10107 ///  - & __real__ x -> x
10108 static ValueDecl *getPrimaryDecl(Expr *E) {
10109   switch (E->getStmtClass()) {
10110   case Stmt::DeclRefExprClass:
10111     return cast<DeclRefExpr>(E)->getDecl();
10112   case Stmt::MemberExprClass:
10113     // If this is an arrow operator, the address is an offset from
10114     // the base's value, so the object the base refers to is
10115     // irrelevant.
10116     if (cast<MemberExpr>(E)->isArrow())
10117       return nullptr;
10118     // Otherwise, the expression refers to a part of the base
10119     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10120   case Stmt::ArraySubscriptExprClass: {
10121     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10122     // promotion of register arrays earlier.
10123     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10124     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10125       if (ICE->getSubExpr()->getType()->isArrayType())
10126         return getPrimaryDecl(ICE->getSubExpr());
10127     }
10128     return nullptr;
10129   }
10130   case Stmt::UnaryOperatorClass: {
10131     UnaryOperator *UO = cast<UnaryOperator>(E);
10132 
10133     switch(UO->getOpcode()) {
10134     case UO_Real:
10135     case UO_Imag:
10136     case UO_Extension:
10137       return getPrimaryDecl(UO->getSubExpr());
10138     default:
10139       return nullptr;
10140     }
10141   }
10142   case Stmt::ParenExprClass:
10143     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10144   case Stmt::ImplicitCastExprClass:
10145     // If the result of an implicit cast is an l-value, we care about
10146     // the sub-expression; otherwise, the result here doesn't matter.
10147     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10148   default:
10149     return nullptr;
10150   }
10151 }
10152 
10153 namespace {
10154   enum {
10155     AO_Bit_Field = 0,
10156     AO_Vector_Element = 1,
10157     AO_Property_Expansion = 2,
10158     AO_Register_Variable = 3,
10159     AO_No_Error = 4
10160   };
10161 }
10162 /// \brief Diagnose invalid operand for address of operations.
10163 ///
10164 /// \param Type The type of operand which cannot have its address taken.
10165 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10166                                          Expr *E, unsigned Type) {
10167   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10168 }
10169 
10170 /// CheckAddressOfOperand - The operand of & must be either a function
10171 /// designator or an lvalue designating an object. If it is an lvalue, the
10172 /// object cannot be declared with storage class register or be a bit field.
10173 /// Note: The usual conversions are *not* applied to the operand of the &
10174 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10175 /// In C++, the operand might be an overloaded function name, in which case
10176 /// we allow the '&' but retain the overloaded-function type.
10177 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10178   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10179     if (PTy->getKind() == BuiltinType::Overload) {
10180       Expr *E = OrigOp.get()->IgnoreParens();
10181       if (!isa<OverloadExpr>(E)) {
10182         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10183         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10184           << OrigOp.get()->getSourceRange();
10185         return QualType();
10186       }
10187 
10188       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10189       if (isa<UnresolvedMemberExpr>(Ovl))
10190         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10191           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10192             << OrigOp.get()->getSourceRange();
10193           return QualType();
10194         }
10195 
10196       return Context.OverloadTy;
10197     }
10198 
10199     if (PTy->getKind() == BuiltinType::UnknownAny)
10200       return Context.UnknownAnyTy;
10201 
10202     if (PTy->getKind() == BuiltinType::BoundMember) {
10203       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10204         << OrigOp.get()->getSourceRange();
10205       return QualType();
10206     }
10207 
10208     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10209     if (OrigOp.isInvalid()) return QualType();
10210   }
10211 
10212   if (OrigOp.get()->isTypeDependent())
10213     return Context.DependentTy;
10214 
10215   assert(!OrigOp.get()->getType()->isPlaceholderType());
10216 
10217   // Make sure to ignore parentheses in subsequent checks
10218   Expr *op = OrigOp.get()->IgnoreParens();
10219 
10220   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10221   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10222     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10223     return QualType();
10224   }
10225 
10226   if (getLangOpts().C99) {
10227     // Implement C99-only parts of addressof rules.
10228     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10229       if (uOp->getOpcode() == UO_Deref)
10230         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10231         // (assuming the deref expression is valid).
10232         return uOp->getSubExpr()->getType();
10233     }
10234     // Technically, there should be a check for array subscript
10235     // expressions here, but the result of one is always an lvalue anyway.
10236   }
10237   ValueDecl *dcl = getPrimaryDecl(op);
10238 
10239   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10240     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10241                                            op->getLocStart()))
10242       return QualType();
10243 
10244   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10245   unsigned AddressOfError = AO_No_Error;
10246 
10247   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10248     bool sfinae = (bool)isSFINAEContext();
10249     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10250                                   : diag::ext_typecheck_addrof_temporary)
10251       << op->getType() << op->getSourceRange();
10252     if (sfinae)
10253       return QualType();
10254     // Materialize the temporary as an lvalue so that we can take its address.
10255     OrigOp = op = new (Context)
10256         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10257   } else if (isa<ObjCSelectorExpr>(op)) {
10258     return Context.getPointerType(op->getType());
10259   } else if (lval == Expr::LV_MemberFunction) {
10260     // If it's an instance method, make a member pointer.
10261     // The expression must have exactly the form &A::foo.
10262 
10263     // If the underlying expression isn't a decl ref, give up.
10264     if (!isa<DeclRefExpr>(op)) {
10265       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10266         << OrigOp.get()->getSourceRange();
10267       return QualType();
10268     }
10269     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10270     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10271 
10272     // The id-expression was parenthesized.
10273     if (OrigOp.get() != DRE) {
10274       Diag(OpLoc, diag::err_parens_pointer_member_function)
10275         << OrigOp.get()->getSourceRange();
10276 
10277     // The method was named without a qualifier.
10278     } else if (!DRE->getQualifier()) {
10279       if (MD->getParent()->getName().empty())
10280         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10281           << op->getSourceRange();
10282       else {
10283         SmallString<32> Str;
10284         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10285         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10286           << op->getSourceRange()
10287           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10288       }
10289     }
10290 
10291     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10292     if (isa<CXXDestructorDecl>(MD))
10293       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10294 
10295     QualType MPTy = Context.getMemberPointerType(
10296         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10297     // Under the MS ABI, lock down the inheritance model now.
10298     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10299       (void)isCompleteType(OpLoc, MPTy);
10300     return MPTy;
10301   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10302     // C99 6.5.3.2p1
10303     // The operand must be either an l-value or a function designator
10304     if (!op->getType()->isFunctionType()) {
10305       // Use a special diagnostic for loads from property references.
10306       if (isa<PseudoObjectExpr>(op)) {
10307         AddressOfError = AO_Property_Expansion;
10308       } else {
10309         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10310           << op->getType() << op->getSourceRange();
10311         return QualType();
10312       }
10313     }
10314   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10315     // The operand cannot be a bit-field
10316     AddressOfError = AO_Bit_Field;
10317   } else if (op->getObjectKind() == OK_VectorComponent) {
10318     // The operand cannot be an element of a vector
10319     AddressOfError = AO_Vector_Element;
10320   } else if (dcl) { // C99 6.5.3.2p1
10321     // We have an lvalue with a decl. Make sure the decl is not declared
10322     // with the register storage-class specifier.
10323     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10324       // in C++ it is not error to take address of a register
10325       // variable (c++03 7.1.1P3)
10326       if (vd->getStorageClass() == SC_Register &&
10327           !getLangOpts().CPlusPlus) {
10328         AddressOfError = AO_Register_Variable;
10329       }
10330     } else if (isa<MSPropertyDecl>(dcl)) {
10331       AddressOfError = AO_Property_Expansion;
10332     } else if (isa<FunctionTemplateDecl>(dcl)) {
10333       return Context.OverloadTy;
10334     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10335       // Okay: we can take the address of a field.
10336       // Could be a pointer to member, though, if there is an explicit
10337       // scope qualifier for the class.
10338       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10339         DeclContext *Ctx = dcl->getDeclContext();
10340         if (Ctx && Ctx->isRecord()) {
10341           if (dcl->getType()->isReferenceType()) {
10342             Diag(OpLoc,
10343                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10344               << dcl->getDeclName() << dcl->getType();
10345             return QualType();
10346           }
10347 
10348           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10349             Ctx = Ctx->getParent();
10350 
10351           QualType MPTy = Context.getMemberPointerType(
10352               op->getType(),
10353               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10354           // Under the MS ABI, lock down the inheritance model now.
10355           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10356             (void)isCompleteType(OpLoc, MPTy);
10357           return MPTy;
10358         }
10359       }
10360     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10361       llvm_unreachable("Unknown/unexpected decl type");
10362   }
10363 
10364   if (AddressOfError != AO_No_Error) {
10365     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10366     return QualType();
10367   }
10368 
10369   if (lval == Expr::LV_IncompleteVoidType) {
10370     // Taking the address of a void variable is technically illegal, but we
10371     // allow it in cases which are otherwise valid.
10372     // Example: "extern void x; void* y = &x;".
10373     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10374   }
10375 
10376   // If the operand has type "type", the result has type "pointer to type".
10377   if (op->getType()->isObjCObjectType())
10378     return Context.getObjCObjectPointerType(op->getType());
10379 
10380   // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block.
10381   if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) {
10382     Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType()
10383                                                 << op->getSourceRange();
10384     return QualType();
10385   }
10386 
10387   return Context.getPointerType(op->getType());
10388 }
10389 
10390 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10391   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10392   if (!DRE)
10393     return;
10394   const Decl *D = DRE->getDecl();
10395   if (!D)
10396     return;
10397   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10398   if (!Param)
10399     return;
10400   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10401     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10402       return;
10403   if (FunctionScopeInfo *FD = S.getCurFunction())
10404     if (!FD->ModifiedNonNullParams.count(Param))
10405       FD->ModifiedNonNullParams.insert(Param);
10406 }
10407 
10408 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10409 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10410                                         SourceLocation OpLoc) {
10411   if (Op->isTypeDependent())
10412     return S.Context.DependentTy;
10413 
10414   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10415   if (ConvResult.isInvalid())
10416     return QualType();
10417   Op = ConvResult.get();
10418   QualType OpTy = Op->getType();
10419   QualType Result;
10420 
10421   if (isa<CXXReinterpretCastExpr>(Op)) {
10422     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10423     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10424                                      Op->getSourceRange());
10425   }
10426 
10427   if (const PointerType *PT = OpTy->getAs<PointerType>())
10428   {
10429     Result = PT->getPointeeType();
10430     // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block.
10431     if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) {
10432       S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy
10433                                                     << Op->getSourceRange();
10434       return QualType();
10435     }
10436   }
10437   else if (const ObjCObjectPointerType *OPT =
10438              OpTy->getAs<ObjCObjectPointerType>())
10439     Result = OPT->getPointeeType();
10440   else {
10441     ExprResult PR = S.CheckPlaceholderExpr(Op);
10442     if (PR.isInvalid()) return QualType();
10443     if (PR.get() != Op)
10444       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10445   }
10446 
10447   if (Result.isNull()) {
10448     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10449       << OpTy << Op->getSourceRange();
10450     return QualType();
10451   }
10452 
10453   // Note that per both C89 and C99, indirection is always legal, even if Result
10454   // is an incomplete type or void.  It would be possible to warn about
10455   // dereferencing a void pointer, but it's completely well-defined, and such a
10456   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10457   // for pointers to 'void' but is fine for any other pointer type:
10458   //
10459   // C++ [expr.unary.op]p1:
10460   //   [...] the expression to which [the unary * operator] is applied shall
10461   //   be a pointer to an object type, or a pointer to a function type
10462   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10463     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10464       << OpTy << Op->getSourceRange();
10465 
10466   // Dereferences are usually l-values...
10467   VK = VK_LValue;
10468 
10469   // ...except that certain expressions are never l-values in C.
10470   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10471     VK = VK_RValue;
10472 
10473   return Result;
10474 }
10475 
10476 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10477   BinaryOperatorKind Opc;
10478   switch (Kind) {
10479   default: llvm_unreachable("Unknown binop!");
10480   case tok::periodstar:           Opc = BO_PtrMemD; break;
10481   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10482   case tok::star:                 Opc = BO_Mul; break;
10483   case tok::slash:                Opc = BO_Div; break;
10484   case tok::percent:              Opc = BO_Rem; break;
10485   case tok::plus:                 Opc = BO_Add; break;
10486   case tok::minus:                Opc = BO_Sub; break;
10487   case tok::lessless:             Opc = BO_Shl; break;
10488   case tok::greatergreater:       Opc = BO_Shr; break;
10489   case tok::lessequal:            Opc = BO_LE; break;
10490   case tok::less:                 Opc = BO_LT; break;
10491   case tok::greaterequal:         Opc = BO_GE; break;
10492   case tok::greater:              Opc = BO_GT; break;
10493   case tok::exclaimequal:         Opc = BO_NE; break;
10494   case tok::equalequal:           Opc = BO_EQ; break;
10495   case tok::amp:                  Opc = BO_And; break;
10496   case tok::caret:                Opc = BO_Xor; break;
10497   case tok::pipe:                 Opc = BO_Or; break;
10498   case tok::ampamp:               Opc = BO_LAnd; break;
10499   case tok::pipepipe:             Opc = BO_LOr; break;
10500   case tok::equal:                Opc = BO_Assign; break;
10501   case tok::starequal:            Opc = BO_MulAssign; break;
10502   case tok::slashequal:           Opc = BO_DivAssign; break;
10503   case tok::percentequal:         Opc = BO_RemAssign; break;
10504   case tok::plusequal:            Opc = BO_AddAssign; break;
10505   case tok::minusequal:           Opc = BO_SubAssign; break;
10506   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10507   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10508   case tok::ampequal:             Opc = BO_AndAssign; break;
10509   case tok::caretequal:           Opc = BO_XorAssign; break;
10510   case tok::pipeequal:            Opc = BO_OrAssign; break;
10511   case tok::comma:                Opc = BO_Comma; break;
10512   }
10513   return Opc;
10514 }
10515 
10516 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10517   tok::TokenKind Kind) {
10518   UnaryOperatorKind Opc;
10519   switch (Kind) {
10520   default: llvm_unreachable("Unknown unary op!");
10521   case tok::plusplus:     Opc = UO_PreInc; break;
10522   case tok::minusminus:   Opc = UO_PreDec; break;
10523   case tok::amp:          Opc = UO_AddrOf; break;
10524   case tok::star:         Opc = UO_Deref; break;
10525   case tok::plus:         Opc = UO_Plus; break;
10526   case tok::minus:        Opc = UO_Minus; break;
10527   case tok::tilde:        Opc = UO_Not; break;
10528   case tok::exclaim:      Opc = UO_LNot; break;
10529   case tok::kw___real:    Opc = UO_Real; break;
10530   case tok::kw___imag:    Opc = UO_Imag; break;
10531   case tok::kw___extension__: Opc = UO_Extension; break;
10532   }
10533   return Opc;
10534 }
10535 
10536 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10537 /// This warning is only emitted for builtin assignment operations. It is also
10538 /// suppressed in the event of macro expansions.
10539 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10540                                    SourceLocation OpLoc) {
10541   if (!S.ActiveTemplateInstantiations.empty())
10542     return;
10543   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10544     return;
10545   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10546   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10547   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10548   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10549   if (!LHSDeclRef || !RHSDeclRef ||
10550       LHSDeclRef->getLocation().isMacroID() ||
10551       RHSDeclRef->getLocation().isMacroID())
10552     return;
10553   const ValueDecl *LHSDecl =
10554     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10555   const ValueDecl *RHSDecl =
10556     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10557   if (LHSDecl != RHSDecl)
10558     return;
10559   if (LHSDecl->getType().isVolatileQualified())
10560     return;
10561   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10562     if (RefTy->getPointeeType().isVolatileQualified())
10563       return;
10564 
10565   S.Diag(OpLoc, diag::warn_self_assignment)
10566       << LHSDeclRef->getType()
10567       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10568 }
10569 
10570 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10571 /// is usually indicative of introspection within the Objective-C pointer.
10572 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10573                                           SourceLocation OpLoc) {
10574   if (!S.getLangOpts().ObjC1)
10575     return;
10576 
10577   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10578   const Expr *LHS = L.get();
10579   const Expr *RHS = R.get();
10580 
10581   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10582     ObjCPointerExpr = LHS;
10583     OtherExpr = RHS;
10584   }
10585   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10586     ObjCPointerExpr = RHS;
10587     OtherExpr = LHS;
10588   }
10589 
10590   // This warning is deliberately made very specific to reduce false
10591   // positives with logic that uses '&' for hashing.  This logic mainly
10592   // looks for code trying to introspect into tagged pointers, which
10593   // code should generally never do.
10594   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10595     unsigned Diag = diag::warn_objc_pointer_masking;
10596     // Determine if we are introspecting the result of performSelectorXXX.
10597     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10598     // Special case messages to -performSelector and friends, which
10599     // can return non-pointer values boxed in a pointer value.
10600     // Some clients may wish to silence warnings in this subcase.
10601     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10602       Selector S = ME->getSelector();
10603       StringRef SelArg0 = S.getNameForSlot(0);
10604       if (SelArg0.startswith("performSelector"))
10605         Diag = diag::warn_objc_pointer_masking_performSelector;
10606     }
10607 
10608     S.Diag(OpLoc, Diag)
10609       << ObjCPointerExpr->getSourceRange();
10610   }
10611 }
10612 
10613 static NamedDecl *getDeclFromExpr(Expr *E) {
10614   if (!E)
10615     return nullptr;
10616   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10617     return DRE->getDecl();
10618   if (auto *ME = dyn_cast<MemberExpr>(E))
10619     return ME->getMemberDecl();
10620   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10621     return IRE->getDecl();
10622   return nullptr;
10623 }
10624 
10625 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10626 /// operator @p Opc at location @c TokLoc. This routine only supports
10627 /// built-in operations; ActOnBinOp handles overloaded operators.
10628 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10629                                     BinaryOperatorKind Opc,
10630                                     Expr *LHSExpr, Expr *RHSExpr) {
10631   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10632     // The syntax only allows initializer lists on the RHS of assignment,
10633     // so we don't need to worry about accepting invalid code for
10634     // non-assignment operators.
10635     // C++11 5.17p9:
10636     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10637     //   of x = {} is x = T().
10638     InitializationKind Kind =
10639         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10640     InitializedEntity Entity =
10641         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10642     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10643     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10644     if (Init.isInvalid())
10645       return Init;
10646     RHSExpr = Init.get();
10647   }
10648 
10649   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10650   QualType ResultTy;     // Result type of the binary operator.
10651   // The following two variables are used for compound assignment operators
10652   QualType CompLHSTy;    // Type of LHS after promotions for computation
10653   QualType CompResultTy; // Type of computation result
10654   ExprValueKind VK = VK_RValue;
10655   ExprObjectKind OK = OK_Ordinary;
10656 
10657   if (!getLangOpts().CPlusPlus) {
10658     // C cannot handle TypoExpr nodes on either side of a binop because it
10659     // doesn't handle dependent types properly, so make sure any TypoExprs have
10660     // been dealt with before checking the operands.
10661     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10662     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10663       if (Opc != BO_Assign)
10664         return ExprResult(E);
10665       // Avoid correcting the RHS to the same Expr as the LHS.
10666       Decl *D = getDeclFromExpr(E);
10667       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10668     });
10669     if (!LHS.isUsable() || !RHS.isUsable())
10670       return ExprError();
10671   }
10672 
10673   if (getLangOpts().OpenCL) {
10674     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10675     // the ATOMIC_VAR_INIT macro.
10676     if (LHSExpr->getType()->isAtomicType() ||
10677         RHSExpr->getType()->isAtomicType()) {
10678       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10679       if (BO_Assign == Opc)
10680         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10681       else
10682         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10683       return ExprError();
10684     }
10685   }
10686 
10687   switch (Opc) {
10688   case BO_Assign:
10689     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10690     if (getLangOpts().CPlusPlus &&
10691         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10692       VK = LHS.get()->getValueKind();
10693       OK = LHS.get()->getObjectKind();
10694     }
10695     if (!ResultTy.isNull()) {
10696       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10697       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10698     }
10699     RecordModifiableNonNullParam(*this, LHS.get());
10700     break;
10701   case BO_PtrMemD:
10702   case BO_PtrMemI:
10703     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10704                                             Opc == BO_PtrMemI);
10705     break;
10706   case BO_Mul:
10707   case BO_Div:
10708     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10709                                            Opc == BO_Div);
10710     break;
10711   case BO_Rem:
10712     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10713     break;
10714   case BO_Add:
10715     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10716     break;
10717   case BO_Sub:
10718     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10719     break;
10720   case BO_Shl:
10721   case BO_Shr:
10722     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10723     break;
10724   case BO_LE:
10725   case BO_LT:
10726   case BO_GE:
10727   case BO_GT:
10728     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10729     break;
10730   case BO_EQ:
10731   case BO_NE:
10732     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10733     break;
10734   case BO_And:
10735     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10736   case BO_Xor:
10737   case BO_Or:
10738     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10739     break;
10740   case BO_LAnd:
10741   case BO_LOr:
10742     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10743     break;
10744   case BO_MulAssign:
10745   case BO_DivAssign:
10746     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10747                                                Opc == BO_DivAssign);
10748     CompLHSTy = CompResultTy;
10749     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10750       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10751     break;
10752   case BO_RemAssign:
10753     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10754     CompLHSTy = CompResultTy;
10755     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10756       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10757     break;
10758   case BO_AddAssign:
10759     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10760     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10761       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10762     break;
10763   case BO_SubAssign:
10764     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10765     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10766       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10767     break;
10768   case BO_ShlAssign:
10769   case BO_ShrAssign:
10770     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10771     CompLHSTy = CompResultTy;
10772     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10773       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10774     break;
10775   case BO_AndAssign:
10776   case BO_OrAssign: // fallthrough
10777     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10778   case BO_XorAssign:
10779     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10780     CompLHSTy = CompResultTy;
10781     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10782       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10783     break;
10784   case BO_Comma:
10785     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10786     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10787       VK = RHS.get()->getValueKind();
10788       OK = RHS.get()->getObjectKind();
10789     }
10790     break;
10791   }
10792   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10793     return ExprError();
10794 
10795   // Check for array bounds violations for both sides of the BinaryOperator
10796   CheckArrayAccess(LHS.get());
10797   CheckArrayAccess(RHS.get());
10798 
10799   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10800     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10801                                                  &Context.Idents.get("object_setClass"),
10802                                                  SourceLocation(), LookupOrdinaryName);
10803     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10804       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10805       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10806       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10807       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10808       FixItHint::CreateInsertion(RHSLocEnd, ")");
10809     }
10810     else
10811       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10812   }
10813   else if (const ObjCIvarRefExpr *OIRE =
10814            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10815     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10816 
10817   if (CompResultTy.isNull())
10818     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10819                                         OK, OpLoc, FPFeatures.fp_contract);
10820   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10821       OK_ObjCProperty) {
10822     VK = VK_LValue;
10823     OK = LHS.get()->getObjectKind();
10824   }
10825   return new (Context) CompoundAssignOperator(
10826       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10827       OpLoc, FPFeatures.fp_contract);
10828 }
10829 
10830 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10831 /// operators are mixed in a way that suggests that the programmer forgot that
10832 /// comparison operators have higher precedence. The most typical example of
10833 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
10834 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10835                                       SourceLocation OpLoc, Expr *LHSExpr,
10836                                       Expr *RHSExpr) {
10837   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10838   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10839 
10840   // Check that one of the sides is a comparison operator and the other isn't.
10841   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10842   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10843   if (isLeftComp == isRightComp)
10844     return;
10845 
10846   // Bitwise operations are sometimes used as eager logical ops.
10847   // Don't diagnose this.
10848   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10849   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10850   if (isLeftBitwise || isRightBitwise)
10851     return;
10852 
10853   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10854                                                    OpLoc)
10855                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
10856   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10857   SourceRange ParensRange = isLeftComp ?
10858       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10859     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10860 
10861   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10862     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10863   SuggestParentheses(Self, OpLoc,
10864     Self.PDiag(diag::note_precedence_silence) << OpStr,
10865     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10866   SuggestParentheses(Self, OpLoc,
10867     Self.PDiag(diag::note_precedence_bitwise_first)
10868       << BinaryOperator::getOpcodeStr(Opc),
10869     ParensRange);
10870 }
10871 
10872 /// \brief It accepts a '&&' expr that is inside a '||' one.
10873 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10874 /// in parentheses.
10875 static void
10876 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
10877                                        BinaryOperator *Bop) {
10878   assert(Bop->getOpcode() == BO_LAnd);
10879   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10880       << Bop->getSourceRange() << OpLoc;
10881   SuggestParentheses(Self, Bop->getOperatorLoc(),
10882     Self.PDiag(diag::note_precedence_silence)
10883       << Bop->getOpcodeStr(),
10884     Bop->getSourceRange());
10885 }
10886 
10887 /// \brief Returns true if the given expression can be evaluated as a constant
10888 /// 'true'.
10889 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10890   bool Res;
10891   return !E->isValueDependent() &&
10892          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
10893 }
10894 
10895 /// \brief Returns true if the given expression can be evaluated as a constant
10896 /// 'false'.
10897 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10898   bool Res;
10899   return !E->isValueDependent() &&
10900          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
10901 }
10902 
10903 /// \brief Look for '&&' in the left hand of a '||' expr.
10904 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
10905                                              Expr *LHSExpr, Expr *RHSExpr) {
10906   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
10907     if (Bop->getOpcode() == BO_LAnd) {
10908       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
10909       if (EvaluatesAsFalse(S, RHSExpr))
10910         return;
10911       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10912       if (!EvaluatesAsTrue(S, Bop->getLHS()))
10913         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10914     } else if (Bop->getOpcode() == BO_LOr) {
10915       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10916         // If it's "a || b && 1 || c" we didn't warn earlier for
10917         // "a || b && 1", but warn now.
10918         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10919           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10920       }
10921     }
10922   }
10923 }
10924 
10925 /// \brief Look for '&&' in the right hand of a '||' expr.
10926 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
10927                                              Expr *LHSExpr, Expr *RHSExpr) {
10928   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
10929     if (Bop->getOpcode() == BO_LAnd) {
10930       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
10931       if (EvaluatesAsFalse(S, LHSExpr))
10932         return;
10933       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10934       if (!EvaluatesAsTrue(S, Bop->getRHS()))
10935         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10936     }
10937   }
10938 }
10939 
10940 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
10941 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
10942 /// the '&' expression in parentheses.
10943 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
10944                                          SourceLocation OpLoc, Expr *SubExpr) {
10945   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10946     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
10947       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
10948         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
10949         << Bop->getSourceRange() << OpLoc;
10950       SuggestParentheses(S, Bop->getOperatorLoc(),
10951         S.PDiag(diag::note_precedence_silence)
10952           << Bop->getOpcodeStr(),
10953         Bop->getSourceRange());
10954     }
10955   }
10956 }
10957 
10958 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
10959                                     Expr *SubExpr, StringRef Shift) {
10960   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10961     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
10962       StringRef Op = Bop->getOpcodeStr();
10963       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
10964           << Bop->getSourceRange() << OpLoc << Shift << Op;
10965       SuggestParentheses(S, Bop->getOperatorLoc(),
10966           S.PDiag(diag::note_precedence_silence) << Op,
10967           Bop->getSourceRange());
10968     }
10969   }
10970 }
10971 
10972 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10973                                  Expr *LHSExpr, Expr *RHSExpr) {
10974   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10975   if (!OCE)
10976     return;
10977 
10978   FunctionDecl *FD = OCE->getDirectCallee();
10979   if (!FD || !FD->isOverloadedOperator())
10980     return;
10981 
10982   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10983   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10984     return;
10985 
10986   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10987       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10988       << (Kind == OO_LessLess);
10989   SuggestParentheses(S, OCE->getOperatorLoc(),
10990                      S.PDiag(diag::note_precedence_silence)
10991                          << (Kind == OO_LessLess ? "<<" : ">>"),
10992                      OCE->getSourceRange());
10993   SuggestParentheses(S, OpLoc,
10994                      S.PDiag(diag::note_evaluate_comparison_first),
10995                      SourceRange(OCE->getArg(1)->getLocStart(),
10996                                  RHSExpr->getLocEnd()));
10997 }
10998 
10999 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11000 /// precedence.
11001 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11002                                     SourceLocation OpLoc, Expr *LHSExpr,
11003                                     Expr *RHSExpr){
11004   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11005   if (BinaryOperator::isBitwiseOp(Opc))
11006     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11007 
11008   // Diagnose "arg1 & arg2 | arg3"
11009   if ((Opc == BO_Or || Opc == BO_Xor) &&
11010       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11011     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11012     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11013   }
11014 
11015   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11016   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11017   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11018     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11019     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11020   }
11021 
11022   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11023       || Opc == BO_Shr) {
11024     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11025     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11026     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11027   }
11028 
11029   // Warn on overloaded shift operators and comparisons, such as:
11030   // cout << 5 == 4;
11031   if (BinaryOperator::isComparisonOp(Opc))
11032     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11033 }
11034 
11035 // Binary Operators.  'Tok' is the token for the operator.
11036 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11037                             tok::TokenKind Kind,
11038                             Expr *LHSExpr, Expr *RHSExpr) {
11039   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11040   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11041   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11042 
11043   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11044   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11045 
11046   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11047 }
11048 
11049 /// Build an overloaded binary operator expression in the given scope.
11050 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11051                                        BinaryOperatorKind Opc,
11052                                        Expr *LHS, Expr *RHS) {
11053   // Find all of the overloaded operators visible from this
11054   // point. We perform both an operator-name lookup from the local
11055   // scope and an argument-dependent lookup based on the types of
11056   // the arguments.
11057   UnresolvedSet<16> Functions;
11058   OverloadedOperatorKind OverOp
11059     = BinaryOperator::getOverloadedOperator(Opc);
11060   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11061     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11062                                    RHS->getType(), Functions);
11063 
11064   // Build the (potentially-overloaded, potentially-dependent)
11065   // binary operation.
11066   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11067 }
11068 
11069 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11070                             BinaryOperatorKind Opc,
11071                             Expr *LHSExpr, Expr *RHSExpr) {
11072   // We want to end up calling one of checkPseudoObjectAssignment
11073   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11074   // both expressions are overloadable or either is type-dependent),
11075   // or CreateBuiltinBinOp (in any other case).  We also want to get
11076   // any placeholder types out of the way.
11077 
11078   // Handle pseudo-objects in the LHS.
11079   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11080     // Assignments with a pseudo-object l-value need special analysis.
11081     if (pty->getKind() == BuiltinType::PseudoObject &&
11082         BinaryOperator::isAssignmentOp(Opc))
11083       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11084 
11085     // Don't resolve overloads if the other type is overloadable.
11086     if (pty->getKind() == BuiltinType::Overload) {
11087       // We can't actually test that if we still have a placeholder,
11088       // though.  Fortunately, none of the exceptions we see in that
11089       // code below are valid when the LHS is an overload set.  Note
11090       // that an overload set can be dependently-typed, but it never
11091       // instantiates to having an overloadable type.
11092       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11093       if (resolvedRHS.isInvalid()) return ExprError();
11094       RHSExpr = resolvedRHS.get();
11095 
11096       if (RHSExpr->isTypeDependent() ||
11097           RHSExpr->getType()->isOverloadableType())
11098         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11099     }
11100 
11101     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11102     if (LHS.isInvalid()) return ExprError();
11103     LHSExpr = LHS.get();
11104   }
11105 
11106   // Handle pseudo-objects in the RHS.
11107   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11108     // An overload in the RHS can potentially be resolved by the type
11109     // being assigned to.
11110     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11111       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11112         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11113 
11114       if (LHSExpr->getType()->isOverloadableType())
11115         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11116 
11117       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11118     }
11119 
11120     // Don't resolve overloads if the other type is overloadable.
11121     if (pty->getKind() == BuiltinType::Overload &&
11122         LHSExpr->getType()->isOverloadableType())
11123       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11124 
11125     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11126     if (!resolvedRHS.isUsable()) return ExprError();
11127     RHSExpr = resolvedRHS.get();
11128   }
11129 
11130   if (getLangOpts().CPlusPlus) {
11131     // If either expression is type-dependent, always build an
11132     // overloaded op.
11133     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11134       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11135 
11136     // Otherwise, build an overloaded op if either expression has an
11137     // overloadable type.
11138     if (LHSExpr->getType()->isOverloadableType() ||
11139         RHSExpr->getType()->isOverloadableType())
11140       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11141   }
11142 
11143   // Build a built-in binary operation.
11144   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11145 }
11146 
11147 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11148                                       UnaryOperatorKind Opc,
11149                                       Expr *InputExpr) {
11150   ExprResult Input = InputExpr;
11151   ExprValueKind VK = VK_RValue;
11152   ExprObjectKind OK = OK_Ordinary;
11153   QualType resultType;
11154   if (getLangOpts().OpenCL) {
11155     // The only legal unary operation for atomics is '&'.
11156     if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
11157       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11158                        << InputExpr->getType()
11159                        << Input.get()->getSourceRange());
11160     }
11161   }
11162   switch (Opc) {
11163   case UO_PreInc:
11164   case UO_PreDec:
11165   case UO_PostInc:
11166   case UO_PostDec:
11167     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11168                                                 OpLoc,
11169                                                 Opc == UO_PreInc ||
11170                                                 Opc == UO_PostInc,
11171                                                 Opc == UO_PreInc ||
11172                                                 Opc == UO_PreDec);
11173     break;
11174   case UO_AddrOf:
11175     resultType = CheckAddressOfOperand(Input, OpLoc);
11176     RecordModifiableNonNullParam(*this, InputExpr);
11177     break;
11178   case UO_Deref: {
11179     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11180     if (Input.isInvalid()) return ExprError();
11181     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11182     break;
11183   }
11184   case UO_Plus:
11185   case UO_Minus:
11186     Input = UsualUnaryConversions(Input.get());
11187     if (Input.isInvalid()) return ExprError();
11188     resultType = Input.get()->getType();
11189     if (resultType->isDependentType())
11190       break;
11191     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11192       break;
11193     else if (resultType->isVectorType() &&
11194              // The z vector extensions don't allow + or - with bool vectors.
11195              (!Context.getLangOpts().ZVector ||
11196               resultType->getAs<VectorType>()->getVectorKind() !=
11197               VectorType::AltiVecBool))
11198       break;
11199     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11200              Opc == UO_Plus &&
11201              resultType->isPointerType())
11202       break;
11203 
11204     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11205       << resultType << Input.get()->getSourceRange());
11206 
11207   case UO_Not: // bitwise complement
11208     Input = UsualUnaryConversions(Input.get());
11209     if (Input.isInvalid())
11210       return ExprError();
11211     resultType = Input.get()->getType();
11212     if (resultType->isDependentType())
11213       break;
11214     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11215     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11216       // C99 does not support '~' for complex conjugation.
11217       Diag(OpLoc, diag::ext_integer_complement_complex)
11218           << resultType << Input.get()->getSourceRange();
11219     else if (resultType->hasIntegerRepresentation())
11220       break;
11221     else if (resultType->isExtVectorType()) {
11222       if (Context.getLangOpts().OpenCL) {
11223         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11224         // on vector float types.
11225         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11226         if (!T->isIntegerType())
11227           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11228                            << resultType << Input.get()->getSourceRange());
11229       }
11230       break;
11231     } else {
11232       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11233                        << resultType << Input.get()->getSourceRange());
11234     }
11235     break;
11236 
11237   case UO_LNot: // logical negation
11238     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11239     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11240     if (Input.isInvalid()) return ExprError();
11241     resultType = Input.get()->getType();
11242 
11243     // Though we still have to promote half FP to float...
11244     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11245       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11246       resultType = Context.FloatTy;
11247     }
11248 
11249     if (resultType->isDependentType())
11250       break;
11251     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11252       // C99 6.5.3.3p1: ok, fallthrough;
11253       if (Context.getLangOpts().CPlusPlus) {
11254         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11255         // operand contextually converted to bool.
11256         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11257                                   ScalarTypeToBooleanCastKind(resultType));
11258       } else if (Context.getLangOpts().OpenCL &&
11259                  Context.getLangOpts().OpenCLVersion < 120) {
11260         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11261         // operate on scalar float types.
11262         if (!resultType->isIntegerType())
11263           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11264                            << resultType << Input.get()->getSourceRange());
11265       }
11266     } else if (resultType->isExtVectorType()) {
11267       if (Context.getLangOpts().OpenCL &&
11268           Context.getLangOpts().OpenCLVersion < 120) {
11269         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11270         // operate on vector float types.
11271         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11272         if (!T->isIntegerType())
11273           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11274                            << resultType << Input.get()->getSourceRange());
11275       }
11276       // Vector logical not returns the signed variant of the operand type.
11277       resultType = GetSignedVectorType(resultType);
11278       break;
11279     } else {
11280       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11281         << resultType << Input.get()->getSourceRange());
11282     }
11283 
11284     // LNot always has type int. C99 6.5.3.3p5.
11285     // In C++, it's bool. C++ 5.3.1p8
11286     resultType = Context.getLogicalOperationType();
11287     break;
11288   case UO_Real:
11289   case UO_Imag:
11290     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11291     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11292     // complex l-values to ordinary l-values and all other values to r-values.
11293     if (Input.isInvalid()) return ExprError();
11294     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11295       if (Input.get()->getValueKind() != VK_RValue &&
11296           Input.get()->getObjectKind() == OK_Ordinary)
11297         VK = Input.get()->getValueKind();
11298     } else if (!getLangOpts().CPlusPlus) {
11299       // In C, a volatile scalar is read by __imag. In C++, it is not.
11300       Input = DefaultLvalueConversion(Input.get());
11301     }
11302     break;
11303   case UO_Extension:
11304   case UO_Coawait:
11305     resultType = Input.get()->getType();
11306     VK = Input.get()->getValueKind();
11307     OK = Input.get()->getObjectKind();
11308     break;
11309   }
11310   if (resultType.isNull() || Input.isInvalid())
11311     return ExprError();
11312 
11313   // Check for array bounds violations in the operand of the UnaryOperator,
11314   // except for the '*' and '&' operators that have to be handled specially
11315   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11316   // that are explicitly defined as valid by the standard).
11317   if (Opc != UO_AddrOf && Opc != UO_Deref)
11318     CheckArrayAccess(Input.get());
11319 
11320   return new (Context)
11321       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11322 }
11323 
11324 /// \brief Determine whether the given expression is a qualified member
11325 /// access expression, of a form that could be turned into a pointer to member
11326 /// with the address-of operator.
11327 static bool isQualifiedMemberAccess(Expr *E) {
11328   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11329     if (!DRE->getQualifier())
11330       return false;
11331 
11332     ValueDecl *VD = DRE->getDecl();
11333     if (!VD->isCXXClassMember())
11334       return false;
11335 
11336     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11337       return true;
11338     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11339       return Method->isInstance();
11340 
11341     return false;
11342   }
11343 
11344   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11345     if (!ULE->getQualifier())
11346       return false;
11347 
11348     for (NamedDecl *D : ULE->decls()) {
11349       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11350         if (Method->isInstance())
11351           return true;
11352       } else {
11353         // Overload set does not contain methods.
11354         break;
11355       }
11356     }
11357 
11358     return false;
11359   }
11360 
11361   return false;
11362 }
11363 
11364 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11365                               UnaryOperatorKind Opc, Expr *Input) {
11366   // First things first: handle placeholders so that the
11367   // overloaded-operator check considers the right type.
11368   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11369     // Increment and decrement of pseudo-object references.
11370     if (pty->getKind() == BuiltinType::PseudoObject &&
11371         UnaryOperator::isIncrementDecrementOp(Opc))
11372       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11373 
11374     // extension is always a builtin operator.
11375     if (Opc == UO_Extension)
11376       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11377 
11378     // & gets special logic for several kinds of placeholder.
11379     // The builtin code knows what to do.
11380     if (Opc == UO_AddrOf &&
11381         (pty->getKind() == BuiltinType::Overload ||
11382          pty->getKind() == BuiltinType::UnknownAny ||
11383          pty->getKind() == BuiltinType::BoundMember))
11384       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11385 
11386     // Anything else needs to be handled now.
11387     ExprResult Result = CheckPlaceholderExpr(Input);
11388     if (Result.isInvalid()) return ExprError();
11389     Input = Result.get();
11390   }
11391 
11392   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11393       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11394       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11395     // Find all of the overloaded operators visible from this
11396     // point. We perform both an operator-name lookup from the local
11397     // scope and an argument-dependent lookup based on the types of
11398     // the arguments.
11399     UnresolvedSet<16> Functions;
11400     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11401     if (S && OverOp != OO_None)
11402       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11403                                    Functions);
11404 
11405     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11406   }
11407 
11408   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11409 }
11410 
11411 // Unary Operators.  'Tok' is the token for the operator.
11412 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11413                               tok::TokenKind Op, Expr *Input) {
11414   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11415 }
11416 
11417 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11418 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11419                                 LabelDecl *TheDecl) {
11420   TheDecl->markUsed(Context);
11421   // Create the AST node.  The address of a label always has type 'void*'.
11422   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11423                                      Context.getPointerType(Context.VoidTy));
11424 }
11425 
11426 /// Given the last statement in a statement-expression, check whether
11427 /// the result is a producing expression (like a call to an
11428 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11429 /// release out of the full-expression.  Otherwise, return null.
11430 /// Cannot fail.
11431 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11432   // Should always be wrapped with one of these.
11433   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11434   if (!cleanups) return nullptr;
11435 
11436   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11437   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11438     return nullptr;
11439 
11440   // Splice out the cast.  This shouldn't modify any interesting
11441   // features of the statement.
11442   Expr *producer = cast->getSubExpr();
11443   assert(producer->getType() == cast->getType());
11444   assert(producer->getValueKind() == cast->getValueKind());
11445   cleanups->setSubExpr(producer);
11446   return cleanups;
11447 }
11448 
11449 void Sema::ActOnStartStmtExpr() {
11450   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11451 }
11452 
11453 void Sema::ActOnStmtExprError() {
11454   // Note that function is also called by TreeTransform when leaving a
11455   // StmtExpr scope without rebuilding anything.
11456 
11457   DiscardCleanupsInEvaluationContext();
11458   PopExpressionEvaluationContext();
11459 }
11460 
11461 ExprResult
11462 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11463                     SourceLocation RPLoc) { // "({..})"
11464   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11465   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11466 
11467   if (hasAnyUnrecoverableErrorsInThisFunction())
11468     DiscardCleanupsInEvaluationContext();
11469   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11470   PopExpressionEvaluationContext();
11471 
11472   // FIXME: there are a variety of strange constraints to enforce here, for
11473   // example, it is not possible to goto into a stmt expression apparently.
11474   // More semantic analysis is needed.
11475 
11476   // If there are sub-stmts in the compound stmt, take the type of the last one
11477   // as the type of the stmtexpr.
11478   QualType Ty = Context.VoidTy;
11479   bool StmtExprMayBindToTemp = false;
11480   if (!Compound->body_empty()) {
11481     Stmt *LastStmt = Compound->body_back();
11482     LabelStmt *LastLabelStmt = nullptr;
11483     // If LastStmt is a label, skip down through into the body.
11484     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11485       LastLabelStmt = Label;
11486       LastStmt = Label->getSubStmt();
11487     }
11488 
11489     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11490       // Do function/array conversion on the last expression, but not
11491       // lvalue-to-rvalue.  However, initialize an unqualified type.
11492       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11493       if (LastExpr.isInvalid())
11494         return ExprError();
11495       Ty = LastExpr.get()->getType().getUnqualifiedType();
11496 
11497       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11498         // In ARC, if the final expression ends in a consume, splice
11499         // the consume out and bind it later.  In the alternate case
11500         // (when dealing with a retainable type), the result
11501         // initialization will create a produce.  In both cases the
11502         // result will be +1, and we'll need to balance that out with
11503         // a bind.
11504         if (Expr *rebuiltLastStmt
11505               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11506           LastExpr = rebuiltLastStmt;
11507         } else {
11508           LastExpr = PerformCopyInitialization(
11509                             InitializedEntity::InitializeResult(LPLoc,
11510                                                                 Ty,
11511                                                                 false),
11512                                                    SourceLocation(),
11513                                                LastExpr);
11514         }
11515 
11516         if (LastExpr.isInvalid())
11517           return ExprError();
11518         if (LastExpr.get() != nullptr) {
11519           if (!LastLabelStmt)
11520             Compound->setLastStmt(LastExpr.get());
11521           else
11522             LastLabelStmt->setSubStmt(LastExpr.get());
11523           StmtExprMayBindToTemp = true;
11524         }
11525       }
11526     }
11527   }
11528 
11529   // FIXME: Check that expression type is complete/non-abstract; statement
11530   // expressions are not lvalues.
11531   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11532   if (StmtExprMayBindToTemp)
11533     return MaybeBindToTemporary(ResStmtExpr);
11534   return ResStmtExpr;
11535 }
11536 
11537 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11538                                       TypeSourceInfo *TInfo,
11539                                       ArrayRef<OffsetOfComponent> Components,
11540                                       SourceLocation RParenLoc) {
11541   QualType ArgTy = TInfo->getType();
11542   bool Dependent = ArgTy->isDependentType();
11543   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11544 
11545   // We must have at least one component that refers to the type, and the first
11546   // one is known to be a field designator.  Verify that the ArgTy represents
11547   // a struct/union/class.
11548   if (!Dependent && !ArgTy->isRecordType())
11549     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11550                        << ArgTy << TypeRange);
11551 
11552   // Type must be complete per C99 7.17p3 because a declaring a variable
11553   // with an incomplete type would be ill-formed.
11554   if (!Dependent
11555       && RequireCompleteType(BuiltinLoc, ArgTy,
11556                              diag::err_offsetof_incomplete_type, TypeRange))
11557     return ExprError();
11558 
11559   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11560   // GCC extension, diagnose them.
11561   // FIXME: This diagnostic isn't actually visible because the location is in
11562   // a system header!
11563   if (Components.size() != 1)
11564     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11565       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11566 
11567   bool DidWarnAboutNonPOD = false;
11568   QualType CurrentType = ArgTy;
11569   SmallVector<OffsetOfNode, 4> Comps;
11570   SmallVector<Expr*, 4> Exprs;
11571   for (const OffsetOfComponent &OC : Components) {
11572     if (OC.isBrackets) {
11573       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11574       if (!CurrentType->isDependentType()) {
11575         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11576         if(!AT)
11577           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11578                            << CurrentType);
11579         CurrentType = AT->getElementType();
11580       } else
11581         CurrentType = Context.DependentTy;
11582 
11583       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11584       if (IdxRval.isInvalid())
11585         return ExprError();
11586       Expr *Idx = IdxRval.get();
11587 
11588       // The expression must be an integral expression.
11589       // FIXME: An integral constant expression?
11590       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11591           !Idx->getType()->isIntegerType())
11592         return ExprError(Diag(Idx->getLocStart(),
11593                               diag::err_typecheck_subscript_not_integer)
11594                          << Idx->getSourceRange());
11595 
11596       // Record this array index.
11597       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11598       Exprs.push_back(Idx);
11599       continue;
11600     }
11601 
11602     // Offset of a field.
11603     if (CurrentType->isDependentType()) {
11604       // We have the offset of a field, but we can't look into the dependent
11605       // type. Just record the identifier of the field.
11606       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11607       CurrentType = Context.DependentTy;
11608       continue;
11609     }
11610 
11611     // We need to have a complete type to look into.
11612     if (RequireCompleteType(OC.LocStart, CurrentType,
11613                             diag::err_offsetof_incomplete_type))
11614       return ExprError();
11615 
11616     // Look for the designated field.
11617     const RecordType *RC = CurrentType->getAs<RecordType>();
11618     if (!RC)
11619       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11620                        << CurrentType);
11621     RecordDecl *RD = RC->getDecl();
11622 
11623     // C++ [lib.support.types]p5:
11624     //   The macro offsetof accepts a restricted set of type arguments in this
11625     //   International Standard. type shall be a POD structure or a POD union
11626     //   (clause 9).
11627     // C++11 [support.types]p4:
11628     //   If type is not a standard-layout class (Clause 9), the results are
11629     //   undefined.
11630     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11631       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11632       unsigned DiagID =
11633         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11634                             : diag::ext_offsetof_non_pod_type;
11635 
11636       if (!IsSafe && !DidWarnAboutNonPOD &&
11637           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11638                               PDiag(DiagID)
11639                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11640                               << CurrentType))
11641         DidWarnAboutNonPOD = true;
11642     }
11643 
11644     // Look for the field.
11645     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11646     LookupQualifiedName(R, RD);
11647     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11648     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11649     if (!MemberDecl) {
11650       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11651         MemberDecl = IndirectMemberDecl->getAnonField();
11652     }
11653 
11654     if (!MemberDecl)
11655       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11656                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11657                                                               OC.LocEnd));
11658 
11659     // C99 7.17p3:
11660     //   (If the specified member is a bit-field, the behavior is undefined.)
11661     //
11662     // We diagnose this as an error.
11663     if (MemberDecl->isBitField()) {
11664       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11665         << MemberDecl->getDeclName()
11666         << SourceRange(BuiltinLoc, RParenLoc);
11667       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11668       return ExprError();
11669     }
11670 
11671     RecordDecl *Parent = MemberDecl->getParent();
11672     if (IndirectMemberDecl)
11673       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11674 
11675     // If the member was found in a base class, introduce OffsetOfNodes for
11676     // the base class indirections.
11677     CXXBasePaths Paths;
11678     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11679                       Paths)) {
11680       if (Paths.getDetectedVirtual()) {
11681         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11682           << MemberDecl->getDeclName()
11683           << SourceRange(BuiltinLoc, RParenLoc);
11684         return ExprError();
11685       }
11686 
11687       CXXBasePath &Path = Paths.front();
11688       for (const CXXBasePathElement &B : Path)
11689         Comps.push_back(OffsetOfNode(B.Base));
11690     }
11691 
11692     if (IndirectMemberDecl) {
11693       for (auto *FI : IndirectMemberDecl->chain()) {
11694         assert(isa<FieldDecl>(FI));
11695         Comps.push_back(OffsetOfNode(OC.LocStart,
11696                                      cast<FieldDecl>(FI), OC.LocEnd));
11697       }
11698     } else
11699       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11700 
11701     CurrentType = MemberDecl->getType().getNonReferenceType();
11702   }
11703 
11704   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11705                               Comps, Exprs, RParenLoc);
11706 }
11707 
11708 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11709                                       SourceLocation BuiltinLoc,
11710                                       SourceLocation TypeLoc,
11711                                       ParsedType ParsedArgTy,
11712                                       ArrayRef<OffsetOfComponent> Components,
11713                                       SourceLocation RParenLoc) {
11714 
11715   TypeSourceInfo *ArgTInfo;
11716   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11717   if (ArgTy.isNull())
11718     return ExprError();
11719 
11720   if (!ArgTInfo)
11721     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11722 
11723   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11724 }
11725 
11726 
11727 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11728                                  Expr *CondExpr,
11729                                  Expr *LHSExpr, Expr *RHSExpr,
11730                                  SourceLocation RPLoc) {
11731   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11732 
11733   ExprValueKind VK = VK_RValue;
11734   ExprObjectKind OK = OK_Ordinary;
11735   QualType resType;
11736   bool ValueDependent = false;
11737   bool CondIsTrue = false;
11738   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11739     resType = Context.DependentTy;
11740     ValueDependent = true;
11741   } else {
11742     // The conditional expression is required to be a constant expression.
11743     llvm::APSInt condEval(32);
11744     ExprResult CondICE
11745       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11746           diag::err_typecheck_choose_expr_requires_constant, false);
11747     if (CondICE.isInvalid())
11748       return ExprError();
11749     CondExpr = CondICE.get();
11750     CondIsTrue = condEval.getZExtValue();
11751 
11752     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11753     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11754 
11755     resType = ActiveExpr->getType();
11756     ValueDependent = ActiveExpr->isValueDependent();
11757     VK = ActiveExpr->getValueKind();
11758     OK = ActiveExpr->getObjectKind();
11759   }
11760 
11761   return new (Context)
11762       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11763                  CondIsTrue, resType->isDependentType(), ValueDependent);
11764 }
11765 
11766 //===----------------------------------------------------------------------===//
11767 // Clang Extensions.
11768 //===----------------------------------------------------------------------===//
11769 
11770 /// ActOnBlockStart - This callback is invoked when a block literal is started.
11771 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11772   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11773 
11774   if (LangOpts.CPlusPlus) {
11775     Decl *ManglingContextDecl;
11776     if (MangleNumberingContext *MCtx =
11777             getCurrentMangleNumberContext(Block->getDeclContext(),
11778                                           ManglingContextDecl)) {
11779       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11780       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11781     }
11782   }
11783 
11784   PushBlockScope(CurScope, Block);
11785   CurContext->addDecl(Block);
11786   if (CurScope)
11787     PushDeclContext(CurScope, Block);
11788   else
11789     CurContext = Block;
11790 
11791   getCurBlock()->HasImplicitReturnType = true;
11792 
11793   // Enter a new evaluation context to insulate the block from any
11794   // cleanups from the enclosing full-expression.
11795   PushExpressionEvaluationContext(PotentiallyEvaluated);
11796 }
11797 
11798 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11799                                Scope *CurScope) {
11800   assert(ParamInfo.getIdentifier() == nullptr &&
11801          "block-id should have no identifier!");
11802   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11803   BlockScopeInfo *CurBlock = getCurBlock();
11804 
11805   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11806   QualType T = Sig->getType();
11807 
11808   // FIXME: We should allow unexpanded parameter packs here, but that would,
11809   // in turn, make the block expression contain unexpanded parameter packs.
11810   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11811     // Drop the parameters.
11812     FunctionProtoType::ExtProtoInfo EPI;
11813     EPI.HasTrailingReturn = false;
11814     EPI.TypeQuals |= DeclSpec::TQ_const;
11815     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11816     Sig = Context.getTrivialTypeSourceInfo(T);
11817   }
11818 
11819   // GetTypeForDeclarator always produces a function type for a block
11820   // literal signature.  Furthermore, it is always a FunctionProtoType
11821   // unless the function was written with a typedef.
11822   assert(T->isFunctionType() &&
11823          "GetTypeForDeclarator made a non-function block signature");
11824 
11825   // Look for an explicit signature in that function type.
11826   FunctionProtoTypeLoc ExplicitSignature;
11827 
11828   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11829   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11830 
11831     // Check whether that explicit signature was synthesized by
11832     // GetTypeForDeclarator.  If so, don't save that as part of the
11833     // written signature.
11834     if (ExplicitSignature.getLocalRangeBegin() ==
11835         ExplicitSignature.getLocalRangeEnd()) {
11836       // This would be much cheaper if we stored TypeLocs instead of
11837       // TypeSourceInfos.
11838       TypeLoc Result = ExplicitSignature.getReturnLoc();
11839       unsigned Size = Result.getFullDataSize();
11840       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11841       Sig->getTypeLoc().initializeFullCopy(Result, Size);
11842 
11843       ExplicitSignature = FunctionProtoTypeLoc();
11844     }
11845   }
11846 
11847   CurBlock->TheDecl->setSignatureAsWritten(Sig);
11848   CurBlock->FunctionType = T;
11849 
11850   const FunctionType *Fn = T->getAs<FunctionType>();
11851   QualType RetTy = Fn->getReturnType();
11852   bool isVariadic =
11853     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11854 
11855   CurBlock->TheDecl->setIsVariadic(isVariadic);
11856 
11857   // Context.DependentTy is used as a placeholder for a missing block
11858   // return type.  TODO:  what should we do with declarators like:
11859   //   ^ * { ... }
11860   // If the answer is "apply template argument deduction"....
11861   if (RetTy != Context.DependentTy) {
11862     CurBlock->ReturnType = RetTy;
11863     CurBlock->TheDecl->setBlockMissingReturnType(false);
11864     CurBlock->HasImplicitReturnType = false;
11865   }
11866 
11867   // Push block parameters from the declarator if we had them.
11868   SmallVector<ParmVarDecl*, 8> Params;
11869   if (ExplicitSignature) {
11870     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11871       ParmVarDecl *Param = ExplicitSignature.getParam(I);
11872       if (Param->getIdentifier() == nullptr &&
11873           !Param->isImplicit() &&
11874           !Param->isInvalidDecl() &&
11875           !getLangOpts().CPlusPlus)
11876         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11877       Params.push_back(Param);
11878     }
11879 
11880   // Fake up parameter variables if we have a typedef, like
11881   //   ^ fntype { ... }
11882   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
11883     for (const auto &I : Fn->param_types()) {
11884       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11885           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
11886       Params.push_back(Param);
11887     }
11888   }
11889 
11890   // Set the parameters on the block decl.
11891   if (!Params.empty()) {
11892     CurBlock->TheDecl->setParams(Params);
11893     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11894                              CurBlock->TheDecl->param_end(),
11895                              /*CheckParameterNames=*/false);
11896   }
11897 
11898   // Finally we can process decl attributes.
11899   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
11900 
11901   // Put the parameter variables in scope.
11902   for (auto AI : CurBlock->TheDecl->params()) {
11903     AI->setOwningFunction(CurBlock->TheDecl);
11904 
11905     // If this has an identifier, add it to the scope stack.
11906     if (AI->getIdentifier()) {
11907       CheckShadow(CurBlock->TheScope, AI);
11908 
11909       PushOnScopeChains(AI, CurBlock->TheScope);
11910     }
11911   }
11912 }
11913 
11914 /// ActOnBlockError - If there is an error parsing a block, this callback
11915 /// is invoked to pop the information about the block from the action impl.
11916 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
11917   // Leave the expression-evaluation context.
11918   DiscardCleanupsInEvaluationContext();
11919   PopExpressionEvaluationContext();
11920 
11921   // Pop off CurBlock, handle nested blocks.
11922   PopDeclContext();
11923   PopFunctionScopeInfo();
11924 }
11925 
11926 /// ActOnBlockStmtExpr - This is called when the body of a block statement
11927 /// literal was successfully completed.  ^(int x){...}
11928 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
11929                                     Stmt *Body, Scope *CurScope) {
11930   // If blocks are disabled, emit an error.
11931   if (!LangOpts.Blocks)
11932     Diag(CaretLoc, diag::err_blocks_disable);
11933 
11934   // Leave the expression-evaluation context.
11935   if (hasAnyUnrecoverableErrorsInThisFunction())
11936     DiscardCleanupsInEvaluationContext();
11937   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11938   PopExpressionEvaluationContext();
11939 
11940   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
11941 
11942   if (BSI->HasImplicitReturnType)
11943     deduceClosureReturnType(*BSI);
11944 
11945   PopDeclContext();
11946 
11947   QualType RetTy = Context.VoidTy;
11948   if (!BSI->ReturnType.isNull())
11949     RetTy = BSI->ReturnType;
11950 
11951   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
11952   QualType BlockTy;
11953 
11954   // Set the captured variables on the block.
11955   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11956   SmallVector<BlockDecl::Capture, 4> Captures;
11957   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
11958     if (Cap.isThisCapture())
11959       continue;
11960     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
11961                               Cap.isNested(), Cap.getInitExpr());
11962     Captures.push_back(NewCap);
11963   }
11964   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
11965 
11966   // If the user wrote a function type in some form, try to use that.
11967   if (!BSI->FunctionType.isNull()) {
11968     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11969 
11970     FunctionType::ExtInfo Ext = FTy->getExtInfo();
11971     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11972 
11973     // Turn protoless block types into nullary block types.
11974     if (isa<FunctionNoProtoType>(FTy)) {
11975       FunctionProtoType::ExtProtoInfo EPI;
11976       EPI.ExtInfo = Ext;
11977       BlockTy = Context.getFunctionType(RetTy, None, EPI);
11978 
11979     // Otherwise, if we don't need to change anything about the function type,
11980     // preserve its sugar structure.
11981     } else if (FTy->getReturnType() == RetTy &&
11982                (!NoReturn || FTy->getNoReturnAttr())) {
11983       BlockTy = BSI->FunctionType;
11984 
11985     // Otherwise, make the minimal modifications to the function type.
11986     } else {
11987       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
11988       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11989       EPI.TypeQuals = 0; // FIXME: silently?
11990       EPI.ExtInfo = Ext;
11991       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
11992     }
11993 
11994   // If we don't have a function type, just build one from nothing.
11995   } else {
11996     FunctionProtoType::ExtProtoInfo EPI;
11997     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
11998     BlockTy = Context.getFunctionType(RetTy, None, EPI);
11999   }
12000 
12001   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
12002                            BSI->TheDecl->param_end());
12003   BlockTy = Context.getBlockPointerType(BlockTy);
12004 
12005   // If needed, diagnose invalid gotos and switches in the block.
12006   if (getCurFunction()->NeedsScopeChecking() &&
12007       !PP.isCodeCompletionEnabled())
12008     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12009 
12010   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12011 
12012   // Try to apply the named return value optimization. We have to check again
12013   // if we can do this, though, because blocks keep return statements around
12014   // to deduce an implicit return type.
12015   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12016       !BSI->TheDecl->isDependentContext())
12017     computeNRVO(Body, BSI);
12018 
12019   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12020   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12021   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12022 
12023   // If the block isn't obviously global, i.e. it captures anything at
12024   // all, then we need to do a few things in the surrounding context:
12025   if (Result->getBlockDecl()->hasCaptures()) {
12026     // First, this expression has a new cleanup object.
12027     ExprCleanupObjects.push_back(Result->getBlockDecl());
12028     ExprNeedsCleanups = true;
12029 
12030     // It also gets a branch-protected scope if any of the captured
12031     // variables needs destruction.
12032     for (const auto &CI : Result->getBlockDecl()->captures()) {
12033       const VarDecl *var = CI.getVariable();
12034       if (var->getType().isDestructedType() != QualType::DK_none) {
12035         getCurFunction()->setHasBranchProtectedScope();
12036         break;
12037       }
12038     }
12039   }
12040 
12041   return Result;
12042 }
12043 
12044 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12045                             SourceLocation RPLoc) {
12046   TypeSourceInfo *TInfo;
12047   GetTypeFromParser(Ty, &TInfo);
12048   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12049 }
12050 
12051 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12052                                 Expr *E, TypeSourceInfo *TInfo,
12053                                 SourceLocation RPLoc) {
12054   Expr *OrigExpr = E;
12055   bool IsMS = false;
12056 
12057   // CUDA device code does not support varargs.
12058   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12059     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12060       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12061       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12062         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12063     }
12064   }
12065 
12066   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12067   // as Microsoft ABI on an actual Microsoft platform, where
12068   // __builtin_ms_va_list and __builtin_va_list are the same.)
12069   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12070       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12071     QualType MSVaListType = Context.getBuiltinMSVaListType();
12072     if (Context.hasSameType(MSVaListType, E->getType())) {
12073       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12074         return ExprError();
12075       IsMS = true;
12076     }
12077   }
12078 
12079   // Get the va_list type
12080   QualType VaListType = Context.getBuiltinVaListType();
12081   if (!IsMS) {
12082     if (VaListType->isArrayType()) {
12083       // Deal with implicit array decay; for example, on x86-64,
12084       // va_list is an array, but it's supposed to decay to
12085       // a pointer for va_arg.
12086       VaListType = Context.getArrayDecayedType(VaListType);
12087       // Make sure the input expression also decays appropriately.
12088       ExprResult Result = UsualUnaryConversions(E);
12089       if (Result.isInvalid())
12090         return ExprError();
12091       E = Result.get();
12092     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12093       // If va_list is a record type and we are compiling in C++ mode,
12094       // check the argument using reference binding.
12095       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12096           Context, Context.getLValueReferenceType(VaListType), false);
12097       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12098       if (Init.isInvalid())
12099         return ExprError();
12100       E = Init.getAs<Expr>();
12101     } else {
12102       // Otherwise, the va_list argument must be an l-value because
12103       // it is modified by va_arg.
12104       if (!E->isTypeDependent() &&
12105           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12106         return ExprError();
12107     }
12108   }
12109 
12110   if (!IsMS && !E->isTypeDependent() &&
12111       !Context.hasSameType(VaListType, E->getType()))
12112     return ExprError(Diag(E->getLocStart(),
12113                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12114       << OrigExpr->getType() << E->getSourceRange());
12115 
12116   if (!TInfo->getType()->isDependentType()) {
12117     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12118                             diag::err_second_parameter_to_va_arg_incomplete,
12119                             TInfo->getTypeLoc()))
12120       return ExprError();
12121 
12122     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12123                                TInfo->getType(),
12124                                diag::err_second_parameter_to_va_arg_abstract,
12125                                TInfo->getTypeLoc()))
12126       return ExprError();
12127 
12128     if (!TInfo->getType().isPODType(Context)) {
12129       Diag(TInfo->getTypeLoc().getBeginLoc(),
12130            TInfo->getType()->isObjCLifetimeType()
12131              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12132              : diag::warn_second_parameter_to_va_arg_not_pod)
12133         << TInfo->getType()
12134         << TInfo->getTypeLoc().getSourceRange();
12135     }
12136 
12137     // Check for va_arg where arguments of the given type will be promoted
12138     // (i.e. this va_arg is guaranteed to have undefined behavior).
12139     QualType PromoteType;
12140     if (TInfo->getType()->isPromotableIntegerType()) {
12141       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12142       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12143         PromoteType = QualType();
12144     }
12145     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12146       PromoteType = Context.DoubleTy;
12147     if (!PromoteType.isNull())
12148       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12149                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12150                           << TInfo->getType()
12151                           << PromoteType
12152                           << TInfo->getTypeLoc().getSourceRange());
12153   }
12154 
12155   QualType T = TInfo->getType().getNonLValueExprType(Context);
12156   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12157 }
12158 
12159 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12160   // The type of __null will be int or long, depending on the size of
12161   // pointers on the target.
12162   QualType Ty;
12163   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12164   if (pw == Context.getTargetInfo().getIntWidth())
12165     Ty = Context.IntTy;
12166   else if (pw == Context.getTargetInfo().getLongWidth())
12167     Ty = Context.LongTy;
12168   else if (pw == Context.getTargetInfo().getLongLongWidth())
12169     Ty = Context.LongLongTy;
12170   else {
12171     llvm_unreachable("I don't know size of pointer!");
12172   }
12173 
12174   return new (Context) GNUNullExpr(Ty, TokenLoc);
12175 }
12176 
12177 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12178                                               bool Diagnose) {
12179   if (!getLangOpts().ObjC1)
12180     return false;
12181 
12182   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12183   if (!PT)
12184     return false;
12185 
12186   if (!PT->isObjCIdType()) {
12187     // Check if the destination is the 'NSString' interface.
12188     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12189     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12190       return false;
12191   }
12192 
12193   // Ignore any parens, implicit casts (should only be
12194   // array-to-pointer decays), and not-so-opaque values.  The last is
12195   // important for making this trigger for property assignments.
12196   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12197   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12198     if (OV->getSourceExpr())
12199       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12200 
12201   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12202   if (!SL || !SL->isAscii())
12203     return false;
12204   if (Diagnose) {
12205     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12206       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12207     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12208   }
12209   return true;
12210 }
12211 
12212 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12213                                               const Expr *SrcExpr) {
12214   if (!DstType->isFunctionPointerType() ||
12215       !SrcExpr->getType()->isFunctionType())
12216     return false;
12217 
12218   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12219   if (!DRE)
12220     return false;
12221 
12222   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12223   if (!FD)
12224     return false;
12225 
12226   return !S.checkAddressOfFunctionIsAvailable(FD,
12227                                               /*Complain=*/true,
12228                                               SrcExpr->getLocStart());
12229 }
12230 
12231 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12232                                     SourceLocation Loc,
12233                                     QualType DstType, QualType SrcType,
12234                                     Expr *SrcExpr, AssignmentAction Action,
12235                                     bool *Complained) {
12236   if (Complained)
12237     *Complained = false;
12238 
12239   // Decode the result (notice that AST's are still created for extensions).
12240   bool CheckInferredResultType = false;
12241   bool isInvalid = false;
12242   unsigned DiagKind = 0;
12243   FixItHint Hint;
12244   ConversionFixItGenerator ConvHints;
12245   bool MayHaveConvFixit = false;
12246   bool MayHaveFunctionDiff = false;
12247   const ObjCInterfaceDecl *IFace = nullptr;
12248   const ObjCProtocolDecl *PDecl = nullptr;
12249 
12250   switch (ConvTy) {
12251   case Compatible:
12252       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12253       return false;
12254 
12255   case PointerToInt:
12256     DiagKind = diag::ext_typecheck_convert_pointer_int;
12257     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12258     MayHaveConvFixit = true;
12259     break;
12260   case IntToPointer:
12261     DiagKind = diag::ext_typecheck_convert_int_pointer;
12262     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12263     MayHaveConvFixit = true;
12264     break;
12265   case IncompatiblePointer:
12266       DiagKind =
12267         (Action == AA_Passing_CFAudited ?
12268           diag::err_arc_typecheck_convert_incompatible_pointer :
12269           diag::ext_typecheck_convert_incompatible_pointer);
12270     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12271       SrcType->isObjCObjectPointerType();
12272     if (Hint.isNull() && !CheckInferredResultType) {
12273       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12274     }
12275     else if (CheckInferredResultType) {
12276       SrcType = SrcType.getUnqualifiedType();
12277       DstType = DstType.getUnqualifiedType();
12278     }
12279     MayHaveConvFixit = true;
12280     break;
12281   case IncompatiblePointerSign:
12282     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12283     break;
12284   case FunctionVoidPointer:
12285     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12286     break;
12287   case IncompatiblePointerDiscardsQualifiers: {
12288     // Perform array-to-pointer decay if necessary.
12289     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12290 
12291     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12292     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12293     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12294       DiagKind = diag::err_typecheck_incompatible_address_space;
12295       break;
12296 
12297 
12298     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12299       DiagKind = diag::err_typecheck_incompatible_ownership;
12300       break;
12301     }
12302 
12303     llvm_unreachable("unknown error case for discarding qualifiers!");
12304     // fallthrough
12305   }
12306   case CompatiblePointerDiscardsQualifiers:
12307     // If the qualifiers lost were because we were applying the
12308     // (deprecated) C++ conversion from a string literal to a char*
12309     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12310     // Ideally, this check would be performed in
12311     // checkPointerTypesForAssignment. However, that would require a
12312     // bit of refactoring (so that the second argument is an
12313     // expression, rather than a type), which should be done as part
12314     // of a larger effort to fix checkPointerTypesForAssignment for
12315     // C++ semantics.
12316     if (getLangOpts().CPlusPlus &&
12317         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12318       return false;
12319     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12320     break;
12321   case IncompatibleNestedPointerQualifiers:
12322     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12323     break;
12324   case IntToBlockPointer:
12325     DiagKind = diag::err_int_to_block_pointer;
12326     break;
12327   case IncompatibleBlockPointer:
12328     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12329     break;
12330   case IncompatibleObjCQualifiedId: {
12331     if (SrcType->isObjCQualifiedIdType()) {
12332       const ObjCObjectPointerType *srcOPT =
12333                 SrcType->getAs<ObjCObjectPointerType>();
12334       for (auto *srcProto : srcOPT->quals()) {
12335         PDecl = srcProto;
12336         break;
12337       }
12338       if (const ObjCInterfaceType *IFaceT =
12339             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12340         IFace = IFaceT->getDecl();
12341     }
12342     else if (DstType->isObjCQualifiedIdType()) {
12343       const ObjCObjectPointerType *dstOPT =
12344         DstType->getAs<ObjCObjectPointerType>();
12345       for (auto *dstProto : dstOPT->quals()) {
12346         PDecl = dstProto;
12347         break;
12348       }
12349       if (const ObjCInterfaceType *IFaceT =
12350             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12351         IFace = IFaceT->getDecl();
12352     }
12353     DiagKind = diag::warn_incompatible_qualified_id;
12354     break;
12355   }
12356   case IncompatibleVectors:
12357     DiagKind = diag::warn_incompatible_vectors;
12358     break;
12359   case IncompatibleObjCWeakRef:
12360     DiagKind = diag::err_arc_weak_unavailable_assign;
12361     break;
12362   case Incompatible:
12363     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12364       if (Complained)
12365         *Complained = true;
12366       return true;
12367     }
12368 
12369     DiagKind = diag::err_typecheck_convert_incompatible;
12370     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12371     MayHaveConvFixit = true;
12372     isInvalid = true;
12373     MayHaveFunctionDiff = true;
12374     break;
12375   }
12376 
12377   QualType FirstType, SecondType;
12378   switch (Action) {
12379   case AA_Assigning:
12380   case AA_Initializing:
12381     // The destination type comes first.
12382     FirstType = DstType;
12383     SecondType = SrcType;
12384     break;
12385 
12386   case AA_Returning:
12387   case AA_Passing:
12388   case AA_Passing_CFAudited:
12389   case AA_Converting:
12390   case AA_Sending:
12391   case AA_Casting:
12392     // The source type comes first.
12393     FirstType = SrcType;
12394     SecondType = DstType;
12395     break;
12396   }
12397 
12398   PartialDiagnostic FDiag = PDiag(DiagKind);
12399   if (Action == AA_Passing_CFAudited)
12400     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12401   else
12402     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12403 
12404   // If we can fix the conversion, suggest the FixIts.
12405   assert(ConvHints.isNull() || Hint.isNull());
12406   if (!ConvHints.isNull()) {
12407     for (FixItHint &H : ConvHints.Hints)
12408       FDiag << H;
12409   } else {
12410     FDiag << Hint;
12411   }
12412   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12413 
12414   if (MayHaveFunctionDiff)
12415     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12416 
12417   Diag(Loc, FDiag);
12418   if (DiagKind == diag::warn_incompatible_qualified_id &&
12419       PDecl && IFace && !IFace->hasDefinition())
12420       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12421         << IFace->getName() << PDecl->getName();
12422 
12423   if (SecondType == Context.OverloadTy)
12424     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12425                               FirstType, /*TakingAddress=*/true);
12426 
12427   if (CheckInferredResultType)
12428     EmitRelatedResultTypeNote(SrcExpr);
12429 
12430   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12431     EmitRelatedResultTypeNoteForReturn(DstType);
12432 
12433   if (Complained)
12434     *Complained = true;
12435   return isInvalid;
12436 }
12437 
12438 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12439                                                  llvm::APSInt *Result) {
12440   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12441   public:
12442     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12443       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12444     }
12445   } Diagnoser;
12446 
12447   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12448 }
12449 
12450 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12451                                                  llvm::APSInt *Result,
12452                                                  unsigned DiagID,
12453                                                  bool AllowFold) {
12454   class IDDiagnoser : public VerifyICEDiagnoser {
12455     unsigned DiagID;
12456 
12457   public:
12458     IDDiagnoser(unsigned DiagID)
12459       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12460 
12461     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12462       S.Diag(Loc, DiagID) << SR;
12463     }
12464   } Diagnoser(DiagID);
12465 
12466   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12467 }
12468 
12469 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12470                                             SourceRange SR) {
12471   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12472 }
12473 
12474 ExprResult
12475 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12476                                       VerifyICEDiagnoser &Diagnoser,
12477                                       bool AllowFold) {
12478   SourceLocation DiagLoc = E->getLocStart();
12479 
12480   if (getLangOpts().CPlusPlus11) {
12481     // C++11 [expr.const]p5:
12482     //   If an expression of literal class type is used in a context where an
12483     //   integral constant expression is required, then that class type shall
12484     //   have a single non-explicit conversion function to an integral or
12485     //   unscoped enumeration type
12486     ExprResult Converted;
12487     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12488     public:
12489       CXX11ConvertDiagnoser(bool Silent)
12490           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12491                                 Silent, true) {}
12492 
12493       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12494                                            QualType T) override {
12495         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12496       }
12497 
12498       SemaDiagnosticBuilder diagnoseIncomplete(
12499           Sema &S, SourceLocation Loc, QualType T) override {
12500         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12501       }
12502 
12503       SemaDiagnosticBuilder diagnoseExplicitConv(
12504           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12505         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12506       }
12507 
12508       SemaDiagnosticBuilder noteExplicitConv(
12509           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12510         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12511                  << ConvTy->isEnumeralType() << ConvTy;
12512       }
12513 
12514       SemaDiagnosticBuilder diagnoseAmbiguous(
12515           Sema &S, SourceLocation Loc, QualType T) override {
12516         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12517       }
12518 
12519       SemaDiagnosticBuilder noteAmbiguous(
12520           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12521         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12522                  << ConvTy->isEnumeralType() << ConvTy;
12523       }
12524 
12525       SemaDiagnosticBuilder diagnoseConversion(
12526           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12527         llvm_unreachable("conversion functions are permitted");
12528       }
12529     } ConvertDiagnoser(Diagnoser.Suppress);
12530 
12531     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12532                                                     ConvertDiagnoser);
12533     if (Converted.isInvalid())
12534       return Converted;
12535     E = Converted.get();
12536     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12537       return ExprError();
12538   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12539     // An ICE must be of integral or unscoped enumeration type.
12540     if (!Diagnoser.Suppress)
12541       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12542     return ExprError();
12543   }
12544 
12545   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12546   // in the non-ICE case.
12547   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12548     if (Result)
12549       *Result = E->EvaluateKnownConstInt(Context);
12550     return E;
12551   }
12552 
12553   Expr::EvalResult EvalResult;
12554   SmallVector<PartialDiagnosticAt, 8> Notes;
12555   EvalResult.Diag = &Notes;
12556 
12557   // Try to evaluate the expression, and produce diagnostics explaining why it's
12558   // not a constant expression as a side-effect.
12559   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12560                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12561 
12562   // In C++11, we can rely on diagnostics being produced for any expression
12563   // which is not a constant expression. If no diagnostics were produced, then
12564   // this is a constant expression.
12565   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12566     if (Result)
12567       *Result = EvalResult.Val.getInt();
12568     return E;
12569   }
12570 
12571   // If our only note is the usual "invalid subexpression" note, just point
12572   // the caret at its location rather than producing an essentially
12573   // redundant note.
12574   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12575         diag::note_invalid_subexpr_in_const_expr) {
12576     DiagLoc = Notes[0].first;
12577     Notes.clear();
12578   }
12579 
12580   if (!Folded || !AllowFold) {
12581     if (!Diagnoser.Suppress) {
12582       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12583       for (const PartialDiagnosticAt &Note : Notes)
12584         Diag(Note.first, Note.second);
12585     }
12586 
12587     return ExprError();
12588   }
12589 
12590   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12591   for (const PartialDiagnosticAt &Note : Notes)
12592     Diag(Note.first, Note.second);
12593 
12594   if (Result)
12595     *Result = EvalResult.Val.getInt();
12596   return E;
12597 }
12598 
12599 namespace {
12600   // Handle the case where we conclude a expression which we speculatively
12601   // considered to be unevaluated is actually evaluated.
12602   class TransformToPE : public TreeTransform<TransformToPE> {
12603     typedef TreeTransform<TransformToPE> BaseTransform;
12604 
12605   public:
12606     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12607 
12608     // Make sure we redo semantic analysis
12609     bool AlwaysRebuild() { return true; }
12610 
12611     // Make sure we handle LabelStmts correctly.
12612     // FIXME: This does the right thing, but maybe we need a more general
12613     // fix to TreeTransform?
12614     StmtResult TransformLabelStmt(LabelStmt *S) {
12615       S->getDecl()->setStmt(nullptr);
12616       return BaseTransform::TransformLabelStmt(S);
12617     }
12618 
12619     // We need to special-case DeclRefExprs referring to FieldDecls which
12620     // are not part of a member pointer formation; normal TreeTransforming
12621     // doesn't catch this case because of the way we represent them in the AST.
12622     // FIXME: This is a bit ugly; is it really the best way to handle this
12623     // case?
12624     //
12625     // Error on DeclRefExprs referring to FieldDecls.
12626     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12627       if (isa<FieldDecl>(E->getDecl()) &&
12628           !SemaRef.isUnevaluatedContext())
12629         return SemaRef.Diag(E->getLocation(),
12630                             diag::err_invalid_non_static_member_use)
12631             << E->getDecl() << E->getSourceRange();
12632 
12633       return BaseTransform::TransformDeclRefExpr(E);
12634     }
12635 
12636     // Exception: filter out member pointer formation
12637     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12638       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12639         return E;
12640 
12641       return BaseTransform::TransformUnaryOperator(E);
12642     }
12643 
12644     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12645       // Lambdas never need to be transformed.
12646       return E;
12647     }
12648   };
12649 }
12650 
12651 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12652   assert(isUnevaluatedContext() &&
12653          "Should only transform unevaluated expressions");
12654   ExprEvalContexts.back().Context =
12655       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12656   if (isUnevaluatedContext())
12657     return E;
12658   return TransformToPE(*this).TransformExpr(E);
12659 }
12660 
12661 void
12662 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12663                                       Decl *LambdaContextDecl,
12664                                       bool IsDecltype) {
12665   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12666                                 ExprNeedsCleanups, LambdaContextDecl,
12667                                 IsDecltype);
12668   ExprNeedsCleanups = false;
12669   if (!MaybeODRUseExprs.empty())
12670     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12671 }
12672 
12673 void
12674 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12675                                       ReuseLambdaContextDecl_t,
12676                                       bool IsDecltype) {
12677   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12678   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12679 }
12680 
12681 void Sema::PopExpressionEvaluationContext() {
12682   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12683   unsigned NumTypos = Rec.NumTypos;
12684 
12685   if (!Rec.Lambdas.empty()) {
12686     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12687       unsigned D;
12688       if (Rec.isUnevaluated()) {
12689         // C++11 [expr.prim.lambda]p2:
12690         //   A lambda-expression shall not appear in an unevaluated operand
12691         //   (Clause 5).
12692         D = diag::err_lambda_unevaluated_operand;
12693       } else {
12694         // C++1y [expr.const]p2:
12695         //   A conditional-expression e is a core constant expression unless the
12696         //   evaluation of e, following the rules of the abstract machine, would
12697         //   evaluate [...] a lambda-expression.
12698         D = diag::err_lambda_in_constant_expression;
12699       }
12700       for (const auto *L : Rec.Lambdas)
12701         Diag(L->getLocStart(), D);
12702     } else {
12703       // Mark the capture expressions odr-used. This was deferred
12704       // during lambda expression creation.
12705       for (auto *Lambda : Rec.Lambdas) {
12706         for (auto *C : Lambda->capture_inits())
12707           MarkDeclarationsReferencedInExpr(C);
12708       }
12709     }
12710   }
12711 
12712   // When are coming out of an unevaluated context, clear out any
12713   // temporaries that we may have created as part of the evaluation of
12714   // the expression in that context: they aren't relevant because they
12715   // will never be constructed.
12716   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12717     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12718                              ExprCleanupObjects.end());
12719     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12720     CleanupVarDeclMarking();
12721     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12722   // Otherwise, merge the contexts together.
12723   } else {
12724     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12725     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12726                             Rec.SavedMaybeODRUseExprs.end());
12727   }
12728 
12729   // Pop the current expression evaluation context off the stack.
12730   ExprEvalContexts.pop_back();
12731 
12732   if (!ExprEvalContexts.empty())
12733     ExprEvalContexts.back().NumTypos += NumTypos;
12734   else
12735     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12736                             "last ExpressionEvaluationContextRecord");
12737 }
12738 
12739 void Sema::DiscardCleanupsInEvaluationContext() {
12740   ExprCleanupObjects.erase(
12741          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12742          ExprCleanupObjects.end());
12743   ExprNeedsCleanups = false;
12744   MaybeODRUseExprs.clear();
12745 }
12746 
12747 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12748   if (!E->getType()->isVariablyModifiedType())
12749     return E;
12750   return TransformToPotentiallyEvaluated(E);
12751 }
12752 
12753 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12754   // Do not mark anything as "used" within a dependent context; wait for
12755   // an instantiation.
12756   if (SemaRef.CurContext->isDependentContext())
12757     return false;
12758 
12759   switch (SemaRef.ExprEvalContexts.back().Context) {
12760     case Sema::Unevaluated:
12761     case Sema::UnevaluatedAbstract:
12762       // We are in an expression that is not potentially evaluated; do nothing.
12763       // (Depending on how you read the standard, we actually do need to do
12764       // something here for null pointer constants, but the standard's
12765       // definition of a null pointer constant is completely crazy.)
12766       return false;
12767 
12768     case Sema::ConstantEvaluated:
12769     case Sema::PotentiallyEvaluated:
12770       // We are in a potentially evaluated expression (or a constant-expression
12771       // in C++03); we need to do implicit template instantiation, implicitly
12772       // define class members, and mark most declarations as used.
12773       return true;
12774 
12775     case Sema::PotentiallyEvaluatedIfUsed:
12776       // Referenced declarations will only be used if the construct in the
12777       // containing expression is used.
12778       return false;
12779   }
12780   llvm_unreachable("Invalid context");
12781 }
12782 
12783 /// \brief Mark a function referenced, and check whether it is odr-used
12784 /// (C++ [basic.def.odr]p2, C99 6.9p3)
12785 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12786                                   bool MightBeOdrUse) {
12787   assert(Func && "No function?");
12788 
12789   Func->setReferenced();
12790 
12791   // C++11 [basic.def.odr]p3:
12792   //   A function whose name appears as a potentially-evaluated expression is
12793   //   odr-used if it is the unique lookup result or the selected member of a
12794   //   set of overloaded functions [...].
12795   //
12796   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12797   // can just check that here. Skip the rest of this function if we've already
12798   // marked the function as used.
12799   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
12800   if (Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) {
12801     // C++11 [temp.inst]p3:
12802     //   Unless a function template specialization has been explicitly
12803     //   instantiated or explicitly specialized, the function template
12804     //   specialization is implicitly instantiated when the specialization is
12805     //   referenced in a context that requires a function definition to exist.
12806     //
12807     // We consider constexpr function templates to be referenced in a context
12808     // that requires a definition to exist whenever they are referenced.
12809     //
12810     // FIXME: This instantiates constexpr functions too frequently. If this is
12811     // really an unevaluated context (and we're not just in the definition of a
12812     // function template or overload resolution or other cases which we
12813     // incorrectly consider to be unevaluated contexts), and we're not in a
12814     // subexpression which we actually need to evaluate (for instance, a
12815     // template argument, array bound or an expression in a braced-init-list),
12816     // we are not permitted to instantiate this constexpr function definition.
12817     //
12818     // FIXME: This also implicitly defines special members too frequently. They
12819     // are only supposed to be implicitly defined if they are odr-used, but they
12820     // are not odr-used from constant expressions in unevaluated contexts.
12821     // However, they cannot be referenced if they are deleted, and they are
12822     // deleted whenever the implicit definition of the special member would
12823     // fail.
12824     if (!Func->isConstexpr() || Func->getBody())
12825       return;
12826     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12827     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12828       return;
12829   }
12830 
12831   // Note that this declaration has been used.
12832   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12833     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12834     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12835       if (Constructor->isDefaultConstructor()) {
12836         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12837           return;
12838         DefineImplicitDefaultConstructor(Loc, Constructor);
12839       } else if (Constructor->isCopyConstructor()) {
12840         DefineImplicitCopyConstructor(Loc, Constructor);
12841       } else if (Constructor->isMoveConstructor()) {
12842         DefineImplicitMoveConstructor(Loc, Constructor);
12843       }
12844     } else if (Constructor->getInheritedConstructor()) {
12845       DefineInheritingConstructor(Loc, Constructor);
12846     }
12847   } else if (CXXDestructorDecl *Destructor =
12848                  dyn_cast<CXXDestructorDecl>(Func)) {
12849     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12850     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12851       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12852         return;
12853       DefineImplicitDestructor(Loc, Destructor);
12854     }
12855     if (Destructor->isVirtual() && getLangOpts().AppleKext)
12856       MarkVTableUsed(Loc, Destructor->getParent());
12857   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
12858     if (MethodDecl->isOverloadedOperator() &&
12859         MethodDecl->getOverloadedOperator() == OO_Equal) {
12860       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12861       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
12862         if (MethodDecl->isCopyAssignmentOperator())
12863           DefineImplicitCopyAssignment(Loc, MethodDecl);
12864         else
12865           DefineImplicitMoveAssignment(Loc, MethodDecl);
12866       }
12867     } else if (isa<CXXConversionDecl>(MethodDecl) &&
12868                MethodDecl->getParent()->isLambda()) {
12869       CXXConversionDecl *Conversion =
12870           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
12871       if (Conversion->isLambdaToBlockPointerConversion())
12872         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12873       else
12874         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
12875     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
12876       MarkVTableUsed(Loc, MethodDecl->getParent());
12877   }
12878 
12879   // Recursive functions should be marked when used from another function.
12880   // FIXME: Is this really right?
12881   if (CurContext == Func) return;
12882 
12883   // Resolve the exception specification for any function which is
12884   // used: CodeGen will need it.
12885   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
12886   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12887     ResolveExceptionSpec(Loc, FPT);
12888 
12889   // Implicit instantiation of function templates and member functions of
12890   // class templates.
12891   if (Func->isImplicitlyInstantiable()) {
12892     bool AlreadyInstantiated = false;
12893     SourceLocation PointOfInstantiation = Loc;
12894     if (FunctionTemplateSpecializationInfo *SpecInfo
12895                               = Func->getTemplateSpecializationInfo()) {
12896       if (SpecInfo->getPointOfInstantiation().isInvalid())
12897         SpecInfo->setPointOfInstantiation(Loc);
12898       else if (SpecInfo->getTemplateSpecializationKind()
12899                  == TSK_ImplicitInstantiation) {
12900         AlreadyInstantiated = true;
12901         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12902       }
12903     } else if (MemberSpecializationInfo *MSInfo
12904                                 = Func->getMemberSpecializationInfo()) {
12905       if (MSInfo->getPointOfInstantiation().isInvalid())
12906         MSInfo->setPointOfInstantiation(Loc);
12907       else if (MSInfo->getTemplateSpecializationKind()
12908                  == TSK_ImplicitInstantiation) {
12909         AlreadyInstantiated = true;
12910         PointOfInstantiation = MSInfo->getPointOfInstantiation();
12911       }
12912     }
12913 
12914     if (!AlreadyInstantiated || Func->isConstexpr()) {
12915       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
12916           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12917           ActiveTemplateInstantiations.size())
12918         PendingLocalImplicitInstantiations.push_back(
12919             std::make_pair(Func, PointOfInstantiation));
12920       else if (Func->isConstexpr())
12921         // Do not defer instantiations of constexpr functions, to avoid the
12922         // expression evaluator needing to call back into Sema if it sees a
12923         // call to such a function.
12924         InstantiateFunctionDefinition(PointOfInstantiation, Func);
12925       else {
12926         PendingInstantiations.push_back(std::make_pair(Func,
12927                                                        PointOfInstantiation));
12928         // Notify the consumer that a function was implicitly instantiated.
12929         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12930       }
12931     }
12932   } else {
12933     // Walk redefinitions, as some of them may be instantiable.
12934     for (auto i : Func->redecls()) {
12935       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
12936         MarkFunctionReferenced(Loc, i, OdrUse);
12937     }
12938   }
12939 
12940   if (!OdrUse) return;
12941 
12942   // Keep track of used but undefined functions.
12943   if (!Func->isDefined()) {
12944     if (mightHaveNonExternalLinkage(Func))
12945       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12946     else if (Func->getMostRecentDecl()->isInlined() &&
12947              !LangOpts.GNUInline &&
12948              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12949       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12950   }
12951 
12952   // Normally the most current decl is marked used while processing the use and
12953   // any subsequent decls are marked used by decl merging. This fails with
12954   // template instantiation since marking can happen at the end of the file
12955   // and, because of the two phase lookup, this function is called with at
12956   // decl in the middle of a decl chain. We loop to maintain the invariant
12957   // that once a decl is used, all decls after it are also used.
12958   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
12959     F->markUsed(Context);
12960     if (F == Func)
12961       break;
12962   }
12963 }
12964 
12965 static void
12966 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12967                                    VarDecl *var, DeclContext *DC) {
12968   DeclContext *VarDC = var->getDeclContext();
12969 
12970   //  If the parameter still belongs to the translation unit, then
12971   //  we're actually just using one parameter in the declaration of
12972   //  the next.
12973   if (isa<ParmVarDecl>(var) &&
12974       isa<TranslationUnitDecl>(VarDC))
12975     return;
12976 
12977   // For C code, don't diagnose about capture if we're not actually in code
12978   // right now; it's impossible to write a non-constant expression outside of
12979   // function context, so we'll get other (more useful) diagnostics later.
12980   //
12981   // For C++, things get a bit more nasty... it would be nice to suppress this
12982   // diagnostic for certain cases like using a local variable in an array bound
12983   // for a member of a local class, but the correct predicate is not obvious.
12984   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
12985     return;
12986 
12987   if (isa<CXXMethodDecl>(VarDC) &&
12988       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12989     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12990       << var->getIdentifier();
12991   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12992     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12993       << var->getIdentifier() << fn->getDeclName();
12994   } else if (isa<BlockDecl>(VarDC)) {
12995     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12996       << var->getIdentifier();
12997   } else {
12998     // FIXME: Is there any other context where a local variable can be
12999     // declared?
13000     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
13001       << var->getIdentifier();
13002   }
13003 
13004   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13005       << var->getIdentifier();
13006 
13007   // FIXME: Add additional diagnostic info about class etc. which prevents
13008   // capture.
13009 }
13010 
13011 
13012 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13013                                       bool &SubCapturesAreNested,
13014                                       QualType &CaptureType,
13015                                       QualType &DeclRefType) {
13016    // Check whether we've already captured it.
13017   if (CSI->CaptureMap.count(Var)) {
13018     // If we found a capture, any subcaptures are nested.
13019     SubCapturesAreNested = true;
13020 
13021     // Retrieve the capture type for this variable.
13022     CaptureType = CSI->getCapture(Var).getCaptureType();
13023 
13024     // Compute the type of an expression that refers to this variable.
13025     DeclRefType = CaptureType.getNonReferenceType();
13026 
13027     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13028     // are mutable in the sense that user can change their value - they are
13029     // private instances of the captured declarations.
13030     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13031     if (Cap.isCopyCapture() &&
13032         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13033         !(isa<CapturedRegionScopeInfo>(CSI) &&
13034           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13035       DeclRefType.addConst();
13036     return true;
13037   }
13038   return false;
13039 }
13040 
13041 // Only block literals, captured statements, and lambda expressions can
13042 // capture; other scopes don't work.
13043 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13044                                  SourceLocation Loc,
13045                                  const bool Diagnose, Sema &S) {
13046   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13047     return getLambdaAwareParentOfDeclContext(DC);
13048   else if (Var->hasLocalStorage()) {
13049     if (Diagnose)
13050        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13051   }
13052   return nullptr;
13053 }
13054 
13055 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13056 // certain types of variables (unnamed, variably modified types etc.)
13057 // so check for eligibility.
13058 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13059                                  SourceLocation Loc,
13060                                  const bool Diagnose, Sema &S) {
13061 
13062   bool IsBlock = isa<BlockScopeInfo>(CSI);
13063   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13064 
13065   // Lambdas are not allowed to capture unnamed variables
13066   // (e.g. anonymous unions).
13067   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13068   // assuming that's the intent.
13069   if (IsLambda && !Var->getDeclName()) {
13070     if (Diagnose) {
13071       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13072       S.Diag(Var->getLocation(), diag::note_declared_at);
13073     }
13074     return false;
13075   }
13076 
13077   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13078   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13079     if (Diagnose) {
13080       S.Diag(Loc, diag::err_ref_vm_type);
13081       S.Diag(Var->getLocation(), diag::note_previous_decl)
13082         << Var->getDeclName();
13083     }
13084     return false;
13085   }
13086   // Prohibit structs with flexible array members too.
13087   // We cannot capture what is in the tail end of the struct.
13088   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13089     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13090       if (Diagnose) {
13091         if (IsBlock)
13092           S.Diag(Loc, diag::err_ref_flexarray_type);
13093         else
13094           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13095             << Var->getDeclName();
13096         S.Diag(Var->getLocation(), diag::note_previous_decl)
13097           << Var->getDeclName();
13098       }
13099       return false;
13100     }
13101   }
13102   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13103   // Lambdas and captured statements are not allowed to capture __block
13104   // variables; they don't support the expected semantics.
13105   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13106     if (Diagnose) {
13107       S.Diag(Loc, diag::err_capture_block_variable)
13108         << Var->getDeclName() << !IsLambda;
13109       S.Diag(Var->getLocation(), diag::note_previous_decl)
13110         << Var->getDeclName();
13111     }
13112     return false;
13113   }
13114 
13115   return true;
13116 }
13117 
13118 // Returns true if the capture by block was successful.
13119 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13120                                  SourceLocation Loc,
13121                                  const bool BuildAndDiagnose,
13122                                  QualType &CaptureType,
13123                                  QualType &DeclRefType,
13124                                  const bool Nested,
13125                                  Sema &S) {
13126   Expr *CopyExpr = nullptr;
13127   bool ByRef = false;
13128 
13129   // Blocks are not allowed to capture arrays.
13130   if (CaptureType->isArrayType()) {
13131     if (BuildAndDiagnose) {
13132       S.Diag(Loc, diag::err_ref_array_type);
13133       S.Diag(Var->getLocation(), diag::note_previous_decl)
13134       << Var->getDeclName();
13135     }
13136     return false;
13137   }
13138 
13139   // Forbid the block-capture of autoreleasing variables.
13140   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13141     if (BuildAndDiagnose) {
13142       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13143         << /*block*/ 0;
13144       S.Diag(Var->getLocation(), diag::note_previous_decl)
13145         << Var->getDeclName();
13146     }
13147     return false;
13148   }
13149   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13150   if (HasBlocksAttr || CaptureType->isReferenceType()) {
13151     // Block capture by reference does not change the capture or
13152     // declaration reference types.
13153     ByRef = true;
13154   } else {
13155     // Block capture by copy introduces 'const'.
13156     CaptureType = CaptureType.getNonReferenceType().withConst();
13157     DeclRefType = CaptureType;
13158 
13159     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13160       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13161         // The capture logic needs the destructor, so make sure we mark it.
13162         // Usually this is unnecessary because most local variables have
13163         // their destructors marked at declaration time, but parameters are
13164         // an exception because it's technically only the call site that
13165         // actually requires the destructor.
13166         if (isa<ParmVarDecl>(Var))
13167           S.FinalizeVarWithDestructor(Var, Record);
13168 
13169         // Enter a new evaluation context to insulate the copy
13170         // full-expression.
13171         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13172 
13173         // According to the blocks spec, the capture of a variable from
13174         // the stack requires a const copy constructor.  This is not true
13175         // of the copy/move done to move a __block variable to the heap.
13176         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13177                                                   DeclRefType.withConst(),
13178                                                   VK_LValue, Loc);
13179 
13180         ExprResult Result
13181           = S.PerformCopyInitialization(
13182               InitializedEntity::InitializeBlock(Var->getLocation(),
13183                                                   CaptureType, false),
13184               Loc, DeclRef);
13185 
13186         // Build a full-expression copy expression if initialization
13187         // succeeded and used a non-trivial constructor.  Recover from
13188         // errors by pretending that the copy isn't necessary.
13189         if (!Result.isInvalid() &&
13190             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13191                 ->isTrivial()) {
13192           Result = S.MaybeCreateExprWithCleanups(Result);
13193           CopyExpr = Result.get();
13194         }
13195       }
13196     }
13197   }
13198 
13199   // Actually capture the variable.
13200   if (BuildAndDiagnose)
13201     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13202                     SourceLocation(), CaptureType, CopyExpr);
13203 
13204   return true;
13205 
13206 }
13207 
13208 
13209 /// \brief Capture the given variable in the captured region.
13210 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13211                                     VarDecl *Var,
13212                                     SourceLocation Loc,
13213                                     const bool BuildAndDiagnose,
13214                                     QualType &CaptureType,
13215                                     QualType &DeclRefType,
13216                                     const bool RefersToCapturedVariable,
13217                                     Sema &S) {
13218 
13219   // By default, capture variables by reference.
13220   bool ByRef = true;
13221   // Using an LValue reference type is consistent with Lambdas (see below).
13222   if (S.getLangOpts().OpenMP) {
13223     ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
13224     if (S.IsOpenMPCapturedDecl(Var))
13225       DeclRefType = DeclRefType.getUnqualifiedType();
13226   }
13227 
13228   if (ByRef)
13229     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13230   else
13231     CaptureType = DeclRefType;
13232 
13233   Expr *CopyExpr = nullptr;
13234   if (BuildAndDiagnose) {
13235     // The current implementation assumes that all variables are captured
13236     // by references. Since there is no capture by copy, no expression
13237     // evaluation will be needed.
13238     RecordDecl *RD = RSI->TheRecordDecl;
13239 
13240     FieldDecl *Field
13241       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13242                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13243                           nullptr, false, ICIS_NoInit);
13244     Field->setImplicit(true);
13245     Field->setAccess(AS_private);
13246     RD->addDecl(Field);
13247 
13248     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13249                                             DeclRefType, VK_LValue, Loc);
13250     Var->setReferenced(true);
13251     Var->markUsed(S.Context);
13252   }
13253 
13254   // Actually capture the variable.
13255   if (BuildAndDiagnose)
13256     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13257                     SourceLocation(), CaptureType, CopyExpr);
13258 
13259 
13260   return true;
13261 }
13262 
13263 /// \brief Create a field within the lambda class for the variable
13264 /// being captured.
13265 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13266                                     QualType FieldType, QualType DeclRefType,
13267                                     SourceLocation Loc,
13268                                     bool RefersToCapturedVariable) {
13269   CXXRecordDecl *Lambda = LSI->Lambda;
13270 
13271   // Build the non-static data member.
13272   FieldDecl *Field
13273     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13274                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13275                         nullptr, false, ICIS_NoInit);
13276   Field->setImplicit(true);
13277   Field->setAccess(AS_private);
13278   Lambda->addDecl(Field);
13279 }
13280 
13281 /// \brief Capture the given variable in the lambda.
13282 static bool captureInLambda(LambdaScopeInfo *LSI,
13283                             VarDecl *Var,
13284                             SourceLocation Loc,
13285                             const bool BuildAndDiagnose,
13286                             QualType &CaptureType,
13287                             QualType &DeclRefType,
13288                             const bool RefersToCapturedVariable,
13289                             const Sema::TryCaptureKind Kind,
13290                             SourceLocation EllipsisLoc,
13291                             const bool IsTopScope,
13292                             Sema &S) {
13293 
13294   // Determine whether we are capturing by reference or by value.
13295   bool ByRef = false;
13296   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13297     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13298   } else {
13299     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13300   }
13301 
13302   // Compute the type of the field that will capture this variable.
13303   if (ByRef) {
13304     // C++11 [expr.prim.lambda]p15:
13305     //   An entity is captured by reference if it is implicitly or
13306     //   explicitly captured but not captured by copy. It is
13307     //   unspecified whether additional unnamed non-static data
13308     //   members are declared in the closure type for entities
13309     //   captured by reference.
13310     //
13311     // FIXME: It is not clear whether we want to build an lvalue reference
13312     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13313     // to do the former, while EDG does the latter. Core issue 1249 will
13314     // clarify, but for now we follow GCC because it's a more permissive and
13315     // easily defensible position.
13316     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13317   } else {
13318     // C++11 [expr.prim.lambda]p14:
13319     //   For each entity captured by copy, an unnamed non-static
13320     //   data member is declared in the closure type. The
13321     //   declaration order of these members is unspecified. The type
13322     //   of such a data member is the type of the corresponding
13323     //   captured entity if the entity is not a reference to an
13324     //   object, or the referenced type otherwise. [Note: If the
13325     //   captured entity is a reference to a function, the
13326     //   corresponding data member is also a reference to a
13327     //   function. - end note ]
13328     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13329       if (!RefType->getPointeeType()->isFunctionType())
13330         CaptureType = RefType->getPointeeType();
13331     }
13332 
13333     // Forbid the lambda copy-capture of autoreleasing variables.
13334     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13335       if (BuildAndDiagnose) {
13336         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13337         S.Diag(Var->getLocation(), diag::note_previous_decl)
13338           << Var->getDeclName();
13339       }
13340       return false;
13341     }
13342 
13343     // Make sure that by-copy captures are of a complete and non-abstract type.
13344     if (BuildAndDiagnose) {
13345       if (!CaptureType->isDependentType() &&
13346           S.RequireCompleteType(Loc, CaptureType,
13347                                 diag::err_capture_of_incomplete_type,
13348                                 Var->getDeclName()))
13349         return false;
13350 
13351       if (S.RequireNonAbstractType(Loc, CaptureType,
13352                                    diag::err_capture_of_abstract_type))
13353         return false;
13354     }
13355   }
13356 
13357   // Capture this variable in the lambda.
13358   if (BuildAndDiagnose)
13359     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13360                             RefersToCapturedVariable);
13361 
13362   // Compute the type of a reference to this captured variable.
13363   if (ByRef)
13364     DeclRefType = CaptureType.getNonReferenceType();
13365   else {
13366     // C++ [expr.prim.lambda]p5:
13367     //   The closure type for a lambda-expression has a public inline
13368     //   function call operator [...]. This function call operator is
13369     //   declared const (9.3.1) if and only if the lambda-expression’s
13370     //   parameter-declaration-clause is not followed by mutable.
13371     DeclRefType = CaptureType.getNonReferenceType();
13372     if (!LSI->Mutable && !CaptureType->isReferenceType())
13373       DeclRefType.addConst();
13374   }
13375 
13376   // Add the capture.
13377   if (BuildAndDiagnose)
13378     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13379                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13380 
13381   return true;
13382 }
13383 
13384 bool Sema::tryCaptureVariable(
13385     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13386     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13387     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13388   // An init-capture is notionally from the context surrounding its
13389   // declaration, but its parent DC is the lambda class.
13390   DeclContext *VarDC = Var->getDeclContext();
13391   if (Var->isInitCapture())
13392     VarDC = VarDC->getParent();
13393 
13394   DeclContext *DC = CurContext;
13395   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13396       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13397   // We need to sync up the Declaration Context with the
13398   // FunctionScopeIndexToStopAt
13399   if (FunctionScopeIndexToStopAt) {
13400     unsigned FSIndex = FunctionScopes.size() - 1;
13401     while (FSIndex != MaxFunctionScopesIndex) {
13402       DC = getLambdaAwareParentOfDeclContext(DC);
13403       --FSIndex;
13404     }
13405   }
13406 
13407 
13408   // If the variable is declared in the current context, there is no need to
13409   // capture it.
13410   if (VarDC == DC) return true;
13411 
13412   // Capture global variables if it is required to use private copy of this
13413   // variable.
13414   bool IsGlobal = !Var->hasLocalStorage();
13415   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13416     return true;
13417 
13418   // Walk up the stack to determine whether we can capture the variable,
13419   // performing the "simple" checks that don't depend on type. We stop when
13420   // we've either hit the declared scope of the variable or find an existing
13421   // capture of that variable.  We start from the innermost capturing-entity
13422   // (the DC) and ensure that all intervening capturing-entities
13423   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13424   // declcontext can either capture the variable or have already captured
13425   // the variable.
13426   CaptureType = Var->getType();
13427   DeclRefType = CaptureType.getNonReferenceType();
13428   bool Nested = false;
13429   bool Explicit = (Kind != TryCapture_Implicit);
13430   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13431   unsigned OpenMPLevel = 0;
13432   do {
13433     // Only block literals, captured statements, and lambda expressions can
13434     // capture; other scopes don't work.
13435     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13436                                                               ExprLoc,
13437                                                               BuildAndDiagnose,
13438                                                               *this);
13439     // We need to check for the parent *first* because, if we *have*
13440     // private-captured a global variable, we need to recursively capture it in
13441     // intermediate blocks, lambdas, etc.
13442     if (!ParentDC) {
13443       if (IsGlobal) {
13444         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13445         break;
13446       }
13447       return true;
13448     }
13449 
13450     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13451     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13452 
13453 
13454     // Check whether we've already captured it.
13455     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13456                                              DeclRefType))
13457       break;
13458     // If we are instantiating a generic lambda call operator body,
13459     // we do not want to capture new variables.  What was captured
13460     // during either a lambdas transformation or initial parsing
13461     // should be used.
13462     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13463       if (BuildAndDiagnose) {
13464         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13465         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13466           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13467           Diag(Var->getLocation(), diag::note_previous_decl)
13468              << Var->getDeclName();
13469           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13470         } else
13471           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13472       }
13473       return true;
13474     }
13475     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13476     // certain types of variables (unnamed, variably modified types etc.)
13477     // so check for eligibility.
13478     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13479        return true;
13480 
13481     // Try to capture variable-length arrays types.
13482     if (Var->getType()->isVariablyModifiedType()) {
13483       // We're going to walk down into the type and look for VLA
13484       // expressions.
13485       QualType QTy = Var->getType();
13486       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13487         QTy = PVD->getOriginalType();
13488       captureVariablyModifiedType(Context, QTy, CSI);
13489     }
13490 
13491     if (getLangOpts().OpenMP) {
13492       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13493         // OpenMP private variables should not be captured in outer scope, so
13494         // just break here. Similarly, global variables that are captured in a
13495         // target region should not be captured outside the scope of the region.
13496         if (RSI->CapRegionKind == CR_OpenMP) {
13497           auto isTargetCap = isOpenMPTargetCapturedDecl(Var, OpenMPLevel);
13498           // When we detect target captures we are looking from inside the
13499           // target region, therefore we need to propagate the capture from the
13500           // enclosing region. Therefore, the capture is not initially nested.
13501           if (isTargetCap)
13502             FunctionScopesIndex--;
13503 
13504           if (isTargetCap || isOpenMPPrivateDecl(Var, OpenMPLevel)) {
13505             Nested = !isTargetCap;
13506             DeclRefType = DeclRefType.getUnqualifiedType();
13507             CaptureType = Context.getLValueReferenceType(DeclRefType);
13508             break;
13509           }
13510           ++OpenMPLevel;
13511         }
13512       }
13513     }
13514     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13515       // No capture-default, and this is not an explicit capture
13516       // so cannot capture this variable.
13517       if (BuildAndDiagnose) {
13518         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13519         Diag(Var->getLocation(), diag::note_previous_decl)
13520           << Var->getDeclName();
13521         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13522           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13523                diag::note_lambda_decl);
13524         // FIXME: If we error out because an outer lambda can not implicitly
13525         // capture a variable that an inner lambda explicitly captures, we
13526         // should have the inner lambda do the explicit capture - because
13527         // it makes for cleaner diagnostics later.  This would purely be done
13528         // so that the diagnostic does not misleadingly claim that a variable
13529         // can not be captured by a lambda implicitly even though it is captured
13530         // explicitly.  Suggestion:
13531         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13532         //    at the function head
13533         //  - cache the StartingDeclContext - this must be a lambda
13534         //  - captureInLambda in the innermost lambda the variable.
13535       }
13536       return true;
13537     }
13538 
13539     FunctionScopesIndex--;
13540     DC = ParentDC;
13541     Explicit = false;
13542   } while (!VarDC->Equals(DC));
13543 
13544   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13545   // computing the type of the capture at each step, checking type-specific
13546   // requirements, and adding captures if requested.
13547   // If the variable had already been captured previously, we start capturing
13548   // at the lambda nested within that one.
13549   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13550        ++I) {
13551     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13552 
13553     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13554       if (!captureInBlock(BSI, Var, ExprLoc,
13555                           BuildAndDiagnose, CaptureType,
13556                           DeclRefType, Nested, *this))
13557         return true;
13558       Nested = true;
13559     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13560       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13561                                    BuildAndDiagnose, CaptureType,
13562                                    DeclRefType, Nested, *this))
13563         return true;
13564       Nested = true;
13565     } else {
13566       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13567       if (!captureInLambda(LSI, Var, ExprLoc,
13568                            BuildAndDiagnose, CaptureType,
13569                            DeclRefType, Nested, Kind, EllipsisLoc,
13570                             /*IsTopScope*/I == N - 1, *this))
13571         return true;
13572       Nested = true;
13573     }
13574   }
13575   return false;
13576 }
13577 
13578 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13579                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13580   QualType CaptureType;
13581   QualType DeclRefType;
13582   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13583                             /*BuildAndDiagnose=*/true, CaptureType,
13584                             DeclRefType, nullptr);
13585 }
13586 
13587 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13588   QualType CaptureType;
13589   QualType DeclRefType;
13590   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13591                              /*BuildAndDiagnose=*/false, CaptureType,
13592                              DeclRefType, nullptr);
13593 }
13594 
13595 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13596   QualType CaptureType;
13597   QualType DeclRefType;
13598 
13599   // Determine whether we can capture this variable.
13600   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13601                          /*BuildAndDiagnose=*/false, CaptureType,
13602                          DeclRefType, nullptr))
13603     return QualType();
13604 
13605   return DeclRefType;
13606 }
13607 
13608 
13609 
13610 // If either the type of the variable or the initializer is dependent,
13611 // return false. Otherwise, determine whether the variable is a constant
13612 // expression. Use this if you need to know if a variable that might or
13613 // might not be dependent is truly a constant expression.
13614 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13615     ASTContext &Context) {
13616 
13617   if (Var->getType()->isDependentType())
13618     return false;
13619   const VarDecl *DefVD = nullptr;
13620   Var->getAnyInitializer(DefVD);
13621   if (!DefVD)
13622     return false;
13623   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13624   Expr *Init = cast<Expr>(Eval->Value);
13625   if (Init->isValueDependent())
13626     return false;
13627   return IsVariableAConstantExpression(Var, Context);
13628 }
13629 
13630 
13631 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13632   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13633   // an object that satisfies the requirements for appearing in a
13634   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13635   // is immediately applied."  This function handles the lvalue-to-rvalue
13636   // conversion part.
13637   MaybeODRUseExprs.erase(E->IgnoreParens());
13638 
13639   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13640   // to a variable that is a constant expression, and if so, identify it as
13641   // a reference to a variable that does not involve an odr-use of that
13642   // variable.
13643   if (LambdaScopeInfo *LSI = getCurLambda()) {
13644     Expr *SansParensExpr = E->IgnoreParens();
13645     VarDecl *Var = nullptr;
13646     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13647       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13648     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13649       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13650 
13651     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13652       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13653   }
13654 }
13655 
13656 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13657   Res = CorrectDelayedTyposInExpr(Res);
13658 
13659   if (!Res.isUsable())
13660     return Res;
13661 
13662   // If a constant-expression is a reference to a variable where we delay
13663   // deciding whether it is an odr-use, just assume we will apply the
13664   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13665   // (a non-type template argument), we have special handling anyway.
13666   UpdateMarkingForLValueToRValue(Res.get());
13667   return Res;
13668 }
13669 
13670 void Sema::CleanupVarDeclMarking() {
13671   for (Expr *E : MaybeODRUseExprs) {
13672     VarDecl *Var;
13673     SourceLocation Loc;
13674     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13675       Var = cast<VarDecl>(DRE->getDecl());
13676       Loc = DRE->getLocation();
13677     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13678       Var = cast<VarDecl>(ME->getMemberDecl());
13679       Loc = ME->getMemberLoc();
13680     } else {
13681       llvm_unreachable("Unexpected expression");
13682     }
13683 
13684     MarkVarDeclODRUsed(Var, Loc, *this,
13685                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13686   }
13687 
13688   MaybeODRUseExprs.clear();
13689 }
13690 
13691 
13692 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13693                                     VarDecl *Var, Expr *E) {
13694   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13695          "Invalid Expr argument to DoMarkVarDeclReferenced");
13696   Var->setReferenced();
13697 
13698   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13699   bool MarkODRUsed = true;
13700 
13701   // If the context is not potentially evaluated, this is not an odr-use and
13702   // does not trigger instantiation.
13703   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13704     if (SemaRef.isUnevaluatedContext())
13705       return;
13706 
13707     // If we don't yet know whether this context is going to end up being an
13708     // evaluated context, and we're referencing a variable from an enclosing
13709     // scope, add a potential capture.
13710     //
13711     // FIXME: Is this necessary? These contexts are only used for default
13712     // arguments, where local variables can't be used.
13713     const bool RefersToEnclosingScope =
13714         (SemaRef.CurContext != Var->getDeclContext() &&
13715          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13716     if (RefersToEnclosingScope) {
13717       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13718         // If a variable could potentially be odr-used, defer marking it so
13719         // until we finish analyzing the full expression for any
13720         // lvalue-to-rvalue
13721         // or discarded value conversions that would obviate odr-use.
13722         // Add it to the list of potential captures that will be analyzed
13723         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13724         // unless the variable is a reference that was initialized by a constant
13725         // expression (this will never need to be captured or odr-used).
13726         assert(E && "Capture variable should be used in an expression.");
13727         if (!Var->getType()->isReferenceType() ||
13728             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13729           LSI->addPotentialCapture(E->IgnoreParens());
13730       }
13731     }
13732 
13733     if (!isTemplateInstantiation(TSK))
13734       return;
13735 
13736     // Instantiate, but do not mark as odr-used, variable templates.
13737     MarkODRUsed = false;
13738   }
13739 
13740   VarTemplateSpecializationDecl *VarSpec =
13741       dyn_cast<VarTemplateSpecializationDecl>(Var);
13742   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13743          "Can't instantiate a partial template specialization.");
13744 
13745   // Perform implicit instantiation of static data members, static data member
13746   // templates of class templates, and variable template specializations. Delay
13747   // instantiations of variable templates, except for those that could be used
13748   // in a constant expression.
13749   if (isTemplateInstantiation(TSK)) {
13750     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13751 
13752     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13753       if (Var->getPointOfInstantiation().isInvalid()) {
13754         // This is a modification of an existing AST node. Notify listeners.
13755         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13756           L->StaticDataMemberInstantiated(Var);
13757       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13758         // Don't bother trying to instantiate it again, unless we might need
13759         // its initializer before we get to the end of the TU.
13760         TryInstantiating = false;
13761     }
13762 
13763     if (Var->getPointOfInstantiation().isInvalid())
13764       Var->setTemplateSpecializationKind(TSK, Loc);
13765 
13766     if (TryInstantiating) {
13767       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13768       bool InstantiationDependent = false;
13769       bool IsNonDependent =
13770           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13771                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13772                   : true;
13773 
13774       // Do not instantiate specializations that are still type-dependent.
13775       if (IsNonDependent) {
13776         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13777           // Do not defer instantiations of variables which could be used in a
13778           // constant expression.
13779           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13780         } else {
13781           SemaRef.PendingInstantiations
13782               .push_back(std::make_pair(Var, PointOfInstantiation));
13783         }
13784       }
13785     }
13786   }
13787 
13788   if(!MarkODRUsed) return;
13789 
13790   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13791   // the requirements for appearing in a constant expression (5.19) and, if
13792   // it is an object, the lvalue-to-rvalue conversion (4.1)
13793   // is immediately applied."  We check the first part here, and
13794   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13795   // Note that we use the C++11 definition everywhere because nothing in
13796   // C++03 depends on whether we get the C++03 version correct. The second
13797   // part does not apply to references, since they are not objects.
13798   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13799     // A reference initialized by a constant expression can never be
13800     // odr-used, so simply ignore it.
13801     if (!Var->getType()->isReferenceType())
13802       SemaRef.MaybeODRUseExprs.insert(E);
13803   } else
13804     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13805                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13806 }
13807 
13808 /// \brief Mark a variable referenced, and check whether it is odr-used
13809 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13810 /// used directly for normal expressions referring to VarDecl.
13811 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13812   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13813 }
13814 
13815 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13816                                Decl *D, Expr *E, bool MightBeOdrUse) {
13817   if (SemaRef.isInOpenMPDeclareTargetContext())
13818     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
13819 
13820   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13821     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13822     return;
13823   }
13824 
13825   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
13826 
13827   // If this is a call to a method via a cast, also mark the method in the
13828   // derived class used in case codegen can devirtualize the call.
13829   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13830   if (!ME)
13831     return;
13832   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13833   if (!MD)
13834     return;
13835   // Only attempt to devirtualize if this is truly a virtual call.
13836   bool IsVirtualCall = MD->isVirtual() &&
13837                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
13838   if (!IsVirtualCall)
13839     return;
13840   const Expr *Base = ME->getBase();
13841   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13842   if (!MostDerivedClassDecl)
13843     return;
13844   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13845   if (!DM || DM->isPure())
13846     return;
13847   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
13848 }
13849 
13850 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13851 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13852   // TODO: update this with DR# once a defect report is filed.
13853   // C++11 defect. The address of a pure member should not be an ODR use, even
13854   // if it's a qualified reference.
13855   bool OdrUse = true;
13856   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13857     if (Method->isVirtual())
13858       OdrUse = false;
13859   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
13860 }
13861 
13862 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
13863 void Sema::MarkMemberReferenced(MemberExpr *E) {
13864   // C++11 [basic.def.odr]p2:
13865   //   A non-overloaded function whose name appears as a potentially-evaluated
13866   //   expression or a member of a set of candidate functions, if selected by
13867   //   overload resolution when referred to from a potentially-evaluated
13868   //   expression, is odr-used, unless it is a pure virtual function and its
13869   //   name is not explicitly qualified.
13870   bool MightBeOdrUse = true;
13871   if (E->performsVirtualDispatch(getLangOpts())) {
13872     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13873       if (Method->isPure())
13874         MightBeOdrUse = false;
13875   }
13876   SourceLocation Loc = E->getMemberLoc().isValid() ?
13877                             E->getMemberLoc() : E->getLocStart();
13878   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
13879 }
13880 
13881 /// \brief Perform marking for a reference to an arbitrary declaration.  It
13882 /// marks the declaration referenced, and performs odr-use checking for
13883 /// functions and variables. This method should not be used when building a
13884 /// normal expression which refers to a variable.
13885 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
13886                                  bool MightBeOdrUse) {
13887   if (MightBeOdrUse) {
13888     if (auto *VD = dyn_cast<VarDecl>(D)) {
13889       MarkVariableReferenced(Loc, VD);
13890       return;
13891     }
13892   }
13893   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13894     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
13895     return;
13896   }
13897   D->setReferenced();
13898 }
13899 
13900 namespace {
13901   // Mark all of the declarations referenced
13902   // FIXME: Not fully implemented yet! We need to have a better understanding
13903   // of when we're entering
13904   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13905     Sema &S;
13906     SourceLocation Loc;
13907 
13908   public:
13909     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
13910 
13911     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
13912 
13913     bool TraverseTemplateArgument(const TemplateArgument &Arg);
13914     bool TraverseRecordType(RecordType *T);
13915   };
13916 }
13917 
13918 bool MarkReferencedDecls::TraverseTemplateArgument(
13919     const TemplateArgument &Arg) {
13920   if (Arg.getKind() == TemplateArgument::Declaration) {
13921     if (Decl *D = Arg.getAsDecl())
13922       S.MarkAnyDeclReferenced(Loc, D, true);
13923   }
13924 
13925   return Inherited::TraverseTemplateArgument(Arg);
13926 }
13927 
13928 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
13929   if (ClassTemplateSpecializationDecl *Spec
13930                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13931     const TemplateArgumentList &Args = Spec->getTemplateArgs();
13932     return TraverseTemplateArguments(Args.data(), Args.size());
13933   }
13934 
13935   return true;
13936 }
13937 
13938 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13939   MarkReferencedDecls Marker(*this, Loc);
13940   Marker.TraverseType(Context.getCanonicalType(T));
13941 }
13942 
13943 namespace {
13944   /// \brief Helper class that marks all of the declarations referenced by
13945   /// potentially-evaluated subexpressions as "referenced".
13946   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13947     Sema &S;
13948     bool SkipLocalVariables;
13949 
13950   public:
13951     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13952 
13953     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13954       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
13955 
13956     void VisitDeclRefExpr(DeclRefExpr *E) {
13957       // If we were asked not to visit local variables, don't.
13958       if (SkipLocalVariables) {
13959         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13960           if (VD->hasLocalStorage())
13961             return;
13962       }
13963 
13964       S.MarkDeclRefReferenced(E);
13965     }
13966 
13967     void VisitMemberExpr(MemberExpr *E) {
13968       S.MarkMemberReferenced(E);
13969       Inherited::VisitMemberExpr(E);
13970     }
13971 
13972     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13973       S.MarkFunctionReferenced(E->getLocStart(),
13974             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13975       Visit(E->getSubExpr());
13976     }
13977 
13978     void VisitCXXNewExpr(CXXNewExpr *E) {
13979       if (E->getOperatorNew())
13980         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
13981       if (E->getOperatorDelete())
13982         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13983       Inherited::VisitCXXNewExpr(E);
13984     }
13985 
13986     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13987       if (E->getOperatorDelete())
13988         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13989       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13990       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13991         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
13992         S.MarkFunctionReferenced(E->getLocStart(),
13993                                     S.LookupDestructor(Record));
13994       }
13995 
13996       Inherited::VisitCXXDeleteExpr(E);
13997     }
13998 
13999     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14000       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14001       Inherited::VisitCXXConstructExpr(E);
14002     }
14003 
14004     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14005       Visit(E->getExpr());
14006     }
14007 
14008     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14009       Inherited::VisitImplicitCastExpr(E);
14010 
14011       if (E->getCastKind() == CK_LValueToRValue)
14012         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14013     }
14014   };
14015 }
14016 
14017 /// \brief Mark any declarations that appear within this expression or any
14018 /// potentially-evaluated subexpressions as "referenced".
14019 ///
14020 /// \param SkipLocalVariables If true, don't mark local variables as
14021 /// 'referenced'.
14022 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14023                                             bool SkipLocalVariables) {
14024   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14025 }
14026 
14027 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14028 /// of the program being compiled.
14029 ///
14030 /// This routine emits the given diagnostic when the code currently being
14031 /// type-checked is "potentially evaluated", meaning that there is a
14032 /// possibility that the code will actually be executable. Code in sizeof()
14033 /// expressions, code used only during overload resolution, etc., are not
14034 /// potentially evaluated. This routine will suppress such diagnostics or,
14035 /// in the absolutely nutty case of potentially potentially evaluated
14036 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14037 /// later.
14038 ///
14039 /// This routine should be used for all diagnostics that describe the run-time
14040 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14041 /// Failure to do so will likely result in spurious diagnostics or failures
14042 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14043 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14044                                const PartialDiagnostic &PD) {
14045   switch (ExprEvalContexts.back().Context) {
14046   case Unevaluated:
14047   case UnevaluatedAbstract:
14048     // The argument will never be evaluated, so don't complain.
14049     break;
14050 
14051   case ConstantEvaluated:
14052     // Relevant diagnostics should be produced by constant evaluation.
14053     break;
14054 
14055   case PotentiallyEvaluated:
14056   case PotentiallyEvaluatedIfUsed:
14057     if (Statement && getCurFunctionOrMethodDecl()) {
14058       FunctionScopes.back()->PossiblyUnreachableDiags.
14059         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14060     }
14061     else
14062       Diag(Loc, PD);
14063 
14064     return true;
14065   }
14066 
14067   return false;
14068 }
14069 
14070 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14071                                CallExpr *CE, FunctionDecl *FD) {
14072   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14073     return false;
14074 
14075   // If we're inside a decltype's expression, don't check for a valid return
14076   // type or construct temporaries until we know whether this is the last call.
14077   if (ExprEvalContexts.back().IsDecltype) {
14078     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14079     return false;
14080   }
14081 
14082   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14083     FunctionDecl *FD;
14084     CallExpr *CE;
14085 
14086   public:
14087     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14088       : FD(FD), CE(CE) { }
14089 
14090     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14091       if (!FD) {
14092         S.Diag(Loc, diag::err_call_incomplete_return)
14093           << T << CE->getSourceRange();
14094         return;
14095       }
14096 
14097       S.Diag(Loc, diag::err_call_function_incomplete_return)
14098         << CE->getSourceRange() << FD->getDeclName() << T;
14099       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14100           << FD->getDeclName();
14101     }
14102   } Diagnoser(FD, CE);
14103 
14104   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14105     return true;
14106 
14107   return false;
14108 }
14109 
14110 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14111 // will prevent this condition from triggering, which is what we want.
14112 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14113   SourceLocation Loc;
14114 
14115   unsigned diagnostic = diag::warn_condition_is_assignment;
14116   bool IsOrAssign = false;
14117 
14118   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14119     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14120       return;
14121 
14122     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14123 
14124     // Greylist some idioms by putting them into a warning subcategory.
14125     if (ObjCMessageExpr *ME
14126           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14127       Selector Sel = ME->getSelector();
14128 
14129       // self = [<foo> init...]
14130       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14131         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14132 
14133       // <foo> = [<bar> nextObject]
14134       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14135         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14136     }
14137 
14138     Loc = Op->getOperatorLoc();
14139   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14140     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14141       return;
14142 
14143     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14144     Loc = Op->getOperatorLoc();
14145   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14146     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14147   else {
14148     // Not an assignment.
14149     return;
14150   }
14151 
14152   Diag(Loc, diagnostic) << E->getSourceRange();
14153 
14154   SourceLocation Open = E->getLocStart();
14155   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14156   Diag(Loc, diag::note_condition_assign_silence)
14157         << FixItHint::CreateInsertion(Open, "(")
14158         << FixItHint::CreateInsertion(Close, ")");
14159 
14160   if (IsOrAssign)
14161     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14162       << FixItHint::CreateReplacement(Loc, "!=");
14163   else
14164     Diag(Loc, diag::note_condition_assign_to_comparison)
14165       << FixItHint::CreateReplacement(Loc, "==");
14166 }
14167 
14168 /// \brief Redundant parentheses over an equality comparison can indicate
14169 /// that the user intended an assignment used as condition.
14170 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14171   // Don't warn if the parens came from a macro.
14172   SourceLocation parenLoc = ParenE->getLocStart();
14173   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14174     return;
14175   // Don't warn for dependent expressions.
14176   if (ParenE->isTypeDependent())
14177     return;
14178 
14179   Expr *E = ParenE->IgnoreParens();
14180 
14181   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14182     if (opE->getOpcode() == BO_EQ &&
14183         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14184                                                            == Expr::MLV_Valid) {
14185       SourceLocation Loc = opE->getOperatorLoc();
14186 
14187       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14188       SourceRange ParenERange = ParenE->getSourceRange();
14189       Diag(Loc, diag::note_equality_comparison_silence)
14190         << FixItHint::CreateRemoval(ParenERange.getBegin())
14191         << FixItHint::CreateRemoval(ParenERange.getEnd());
14192       Diag(Loc, diag::note_equality_comparison_to_assign)
14193         << FixItHint::CreateReplacement(Loc, "=");
14194     }
14195 }
14196 
14197 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
14198   DiagnoseAssignmentAsCondition(E);
14199   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14200     DiagnoseEqualityWithExtraParens(parenE);
14201 
14202   ExprResult result = CheckPlaceholderExpr(E);
14203   if (result.isInvalid()) return ExprError();
14204   E = result.get();
14205 
14206   if (!E->isTypeDependent()) {
14207     if (getLangOpts().CPlusPlus)
14208       return CheckCXXBooleanCondition(E); // C++ 6.4p4
14209 
14210     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14211     if (ERes.isInvalid())
14212       return ExprError();
14213     E = ERes.get();
14214 
14215     QualType T = E->getType();
14216     if (!T->isScalarType()) { // C99 6.8.4.1p1
14217       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14218         << T << E->getSourceRange();
14219       return ExprError();
14220     }
14221     CheckBoolLikeConversion(E, Loc);
14222   }
14223 
14224   return E;
14225 }
14226 
14227 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
14228                                        Expr *SubExpr) {
14229   if (!SubExpr)
14230     return ExprError();
14231 
14232   return CheckBooleanCondition(SubExpr, Loc);
14233 }
14234 
14235 namespace {
14236   /// A visitor for rebuilding a call to an __unknown_any expression
14237   /// to have an appropriate type.
14238   struct RebuildUnknownAnyFunction
14239     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14240 
14241     Sema &S;
14242 
14243     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14244 
14245     ExprResult VisitStmt(Stmt *S) {
14246       llvm_unreachable("unexpected statement!");
14247     }
14248 
14249     ExprResult VisitExpr(Expr *E) {
14250       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14251         << E->getSourceRange();
14252       return ExprError();
14253     }
14254 
14255     /// Rebuild an expression which simply semantically wraps another
14256     /// expression which it shares the type and value kind of.
14257     template <class T> ExprResult rebuildSugarExpr(T *E) {
14258       ExprResult SubResult = Visit(E->getSubExpr());
14259       if (SubResult.isInvalid()) return ExprError();
14260 
14261       Expr *SubExpr = SubResult.get();
14262       E->setSubExpr(SubExpr);
14263       E->setType(SubExpr->getType());
14264       E->setValueKind(SubExpr->getValueKind());
14265       assert(E->getObjectKind() == OK_Ordinary);
14266       return E;
14267     }
14268 
14269     ExprResult VisitParenExpr(ParenExpr *E) {
14270       return rebuildSugarExpr(E);
14271     }
14272 
14273     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14274       return rebuildSugarExpr(E);
14275     }
14276 
14277     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14278       ExprResult SubResult = Visit(E->getSubExpr());
14279       if (SubResult.isInvalid()) return ExprError();
14280 
14281       Expr *SubExpr = SubResult.get();
14282       E->setSubExpr(SubExpr);
14283       E->setType(S.Context.getPointerType(SubExpr->getType()));
14284       assert(E->getValueKind() == VK_RValue);
14285       assert(E->getObjectKind() == OK_Ordinary);
14286       return E;
14287     }
14288 
14289     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14290       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14291 
14292       E->setType(VD->getType());
14293 
14294       assert(E->getValueKind() == VK_RValue);
14295       if (S.getLangOpts().CPlusPlus &&
14296           !(isa<CXXMethodDecl>(VD) &&
14297             cast<CXXMethodDecl>(VD)->isInstance()))
14298         E->setValueKind(VK_LValue);
14299 
14300       return E;
14301     }
14302 
14303     ExprResult VisitMemberExpr(MemberExpr *E) {
14304       return resolveDecl(E, E->getMemberDecl());
14305     }
14306 
14307     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14308       return resolveDecl(E, E->getDecl());
14309     }
14310   };
14311 }
14312 
14313 /// Given a function expression of unknown-any type, try to rebuild it
14314 /// to have a function type.
14315 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14316   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14317   if (Result.isInvalid()) return ExprError();
14318   return S.DefaultFunctionArrayConversion(Result.get());
14319 }
14320 
14321 namespace {
14322   /// A visitor for rebuilding an expression of type __unknown_anytype
14323   /// into one which resolves the type directly on the referring
14324   /// expression.  Strict preservation of the original source
14325   /// structure is not a goal.
14326   struct RebuildUnknownAnyExpr
14327     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14328 
14329     Sema &S;
14330 
14331     /// The current destination type.
14332     QualType DestType;
14333 
14334     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14335       : S(S), DestType(CastType) {}
14336 
14337     ExprResult VisitStmt(Stmt *S) {
14338       llvm_unreachable("unexpected statement!");
14339     }
14340 
14341     ExprResult VisitExpr(Expr *E) {
14342       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14343         << E->getSourceRange();
14344       return ExprError();
14345     }
14346 
14347     ExprResult VisitCallExpr(CallExpr *E);
14348     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14349 
14350     /// Rebuild an expression which simply semantically wraps another
14351     /// expression which it shares the type and value kind of.
14352     template <class T> ExprResult rebuildSugarExpr(T *E) {
14353       ExprResult SubResult = Visit(E->getSubExpr());
14354       if (SubResult.isInvalid()) return ExprError();
14355       Expr *SubExpr = SubResult.get();
14356       E->setSubExpr(SubExpr);
14357       E->setType(SubExpr->getType());
14358       E->setValueKind(SubExpr->getValueKind());
14359       assert(E->getObjectKind() == OK_Ordinary);
14360       return E;
14361     }
14362 
14363     ExprResult VisitParenExpr(ParenExpr *E) {
14364       return rebuildSugarExpr(E);
14365     }
14366 
14367     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14368       return rebuildSugarExpr(E);
14369     }
14370 
14371     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14372       const PointerType *Ptr = DestType->getAs<PointerType>();
14373       if (!Ptr) {
14374         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14375           << E->getSourceRange();
14376         return ExprError();
14377       }
14378       assert(E->getValueKind() == VK_RValue);
14379       assert(E->getObjectKind() == OK_Ordinary);
14380       E->setType(DestType);
14381 
14382       // Build the sub-expression as if it were an object of the pointee type.
14383       DestType = Ptr->getPointeeType();
14384       ExprResult SubResult = Visit(E->getSubExpr());
14385       if (SubResult.isInvalid()) return ExprError();
14386       E->setSubExpr(SubResult.get());
14387       return E;
14388     }
14389 
14390     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14391 
14392     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14393 
14394     ExprResult VisitMemberExpr(MemberExpr *E) {
14395       return resolveDecl(E, E->getMemberDecl());
14396     }
14397 
14398     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14399       return resolveDecl(E, E->getDecl());
14400     }
14401   };
14402 }
14403 
14404 /// Rebuilds a call expression which yielded __unknown_anytype.
14405 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14406   Expr *CalleeExpr = E->getCallee();
14407 
14408   enum FnKind {
14409     FK_MemberFunction,
14410     FK_FunctionPointer,
14411     FK_BlockPointer
14412   };
14413 
14414   FnKind Kind;
14415   QualType CalleeType = CalleeExpr->getType();
14416   if (CalleeType == S.Context.BoundMemberTy) {
14417     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14418     Kind = FK_MemberFunction;
14419     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14420   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14421     CalleeType = Ptr->getPointeeType();
14422     Kind = FK_FunctionPointer;
14423   } else {
14424     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14425     Kind = FK_BlockPointer;
14426   }
14427   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14428 
14429   // Verify that this is a legal result type of a function.
14430   if (DestType->isArrayType() || DestType->isFunctionType()) {
14431     unsigned diagID = diag::err_func_returning_array_function;
14432     if (Kind == FK_BlockPointer)
14433       diagID = diag::err_block_returning_array_function;
14434 
14435     S.Diag(E->getExprLoc(), diagID)
14436       << DestType->isFunctionType() << DestType;
14437     return ExprError();
14438   }
14439 
14440   // Otherwise, go ahead and set DestType as the call's result.
14441   E->setType(DestType.getNonLValueExprType(S.Context));
14442   E->setValueKind(Expr::getValueKindForType(DestType));
14443   assert(E->getObjectKind() == OK_Ordinary);
14444 
14445   // Rebuild the function type, replacing the result type with DestType.
14446   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14447   if (Proto) {
14448     // __unknown_anytype(...) is a special case used by the debugger when
14449     // it has no idea what a function's signature is.
14450     //
14451     // We want to build this call essentially under the K&R
14452     // unprototyped rules, but making a FunctionNoProtoType in C++
14453     // would foul up all sorts of assumptions.  However, we cannot
14454     // simply pass all arguments as variadic arguments, nor can we
14455     // portably just call the function under a non-variadic type; see
14456     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14457     // However, it turns out that in practice it is generally safe to
14458     // call a function declared as "A foo(B,C,D);" under the prototype
14459     // "A foo(B,C,D,...);".  The only known exception is with the
14460     // Windows ABI, where any variadic function is implicitly cdecl
14461     // regardless of its normal CC.  Therefore we change the parameter
14462     // types to match the types of the arguments.
14463     //
14464     // This is a hack, but it is far superior to moving the
14465     // corresponding target-specific code from IR-gen to Sema/AST.
14466 
14467     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14468     SmallVector<QualType, 8> ArgTypes;
14469     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14470       ArgTypes.reserve(E->getNumArgs());
14471       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14472         Expr *Arg = E->getArg(i);
14473         QualType ArgType = Arg->getType();
14474         if (E->isLValue()) {
14475           ArgType = S.Context.getLValueReferenceType(ArgType);
14476         } else if (E->isXValue()) {
14477           ArgType = S.Context.getRValueReferenceType(ArgType);
14478         }
14479         ArgTypes.push_back(ArgType);
14480       }
14481       ParamTypes = ArgTypes;
14482     }
14483     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14484                                          Proto->getExtProtoInfo());
14485   } else {
14486     DestType = S.Context.getFunctionNoProtoType(DestType,
14487                                                 FnType->getExtInfo());
14488   }
14489 
14490   // Rebuild the appropriate pointer-to-function type.
14491   switch (Kind) {
14492   case FK_MemberFunction:
14493     // Nothing to do.
14494     break;
14495 
14496   case FK_FunctionPointer:
14497     DestType = S.Context.getPointerType(DestType);
14498     break;
14499 
14500   case FK_BlockPointer:
14501     DestType = S.Context.getBlockPointerType(DestType);
14502     break;
14503   }
14504 
14505   // Finally, we can recurse.
14506   ExprResult CalleeResult = Visit(CalleeExpr);
14507   if (!CalleeResult.isUsable()) return ExprError();
14508   E->setCallee(CalleeResult.get());
14509 
14510   // Bind a temporary if necessary.
14511   return S.MaybeBindToTemporary(E);
14512 }
14513 
14514 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14515   // Verify that this is a legal result type of a call.
14516   if (DestType->isArrayType() || DestType->isFunctionType()) {
14517     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14518       << DestType->isFunctionType() << DestType;
14519     return ExprError();
14520   }
14521 
14522   // Rewrite the method result type if available.
14523   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14524     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14525     Method->setReturnType(DestType);
14526   }
14527 
14528   // Change the type of the message.
14529   E->setType(DestType.getNonReferenceType());
14530   E->setValueKind(Expr::getValueKindForType(DestType));
14531 
14532   return S.MaybeBindToTemporary(E);
14533 }
14534 
14535 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14536   // The only case we should ever see here is a function-to-pointer decay.
14537   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14538     assert(E->getValueKind() == VK_RValue);
14539     assert(E->getObjectKind() == OK_Ordinary);
14540 
14541     E->setType(DestType);
14542 
14543     // Rebuild the sub-expression as the pointee (function) type.
14544     DestType = DestType->castAs<PointerType>()->getPointeeType();
14545 
14546     ExprResult Result = Visit(E->getSubExpr());
14547     if (!Result.isUsable()) return ExprError();
14548 
14549     E->setSubExpr(Result.get());
14550     return E;
14551   } else if (E->getCastKind() == CK_LValueToRValue) {
14552     assert(E->getValueKind() == VK_RValue);
14553     assert(E->getObjectKind() == OK_Ordinary);
14554 
14555     assert(isa<BlockPointerType>(E->getType()));
14556 
14557     E->setType(DestType);
14558 
14559     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14560     DestType = S.Context.getLValueReferenceType(DestType);
14561 
14562     ExprResult Result = Visit(E->getSubExpr());
14563     if (!Result.isUsable()) return ExprError();
14564 
14565     E->setSubExpr(Result.get());
14566     return E;
14567   } else {
14568     llvm_unreachable("Unhandled cast type!");
14569   }
14570 }
14571 
14572 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14573   ExprValueKind ValueKind = VK_LValue;
14574   QualType Type = DestType;
14575 
14576   // We know how to make this work for certain kinds of decls:
14577 
14578   //  - functions
14579   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14580     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14581       DestType = Ptr->getPointeeType();
14582       ExprResult Result = resolveDecl(E, VD);
14583       if (Result.isInvalid()) return ExprError();
14584       return S.ImpCastExprToType(Result.get(), Type,
14585                                  CK_FunctionToPointerDecay, VK_RValue);
14586     }
14587 
14588     if (!Type->isFunctionType()) {
14589       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14590         << VD << E->getSourceRange();
14591       return ExprError();
14592     }
14593     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14594       // We must match the FunctionDecl's type to the hack introduced in
14595       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14596       // type. See the lengthy commentary in that routine.
14597       QualType FDT = FD->getType();
14598       const FunctionType *FnType = FDT->castAs<FunctionType>();
14599       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14600       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14601       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14602         SourceLocation Loc = FD->getLocation();
14603         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14604                                       FD->getDeclContext(),
14605                                       Loc, Loc, FD->getNameInfo().getName(),
14606                                       DestType, FD->getTypeSourceInfo(),
14607                                       SC_None, false/*isInlineSpecified*/,
14608                                       FD->hasPrototype(),
14609                                       false/*isConstexprSpecified*/);
14610 
14611         if (FD->getQualifier())
14612           NewFD->setQualifierInfo(FD->getQualifierLoc());
14613 
14614         SmallVector<ParmVarDecl*, 16> Params;
14615         for (const auto &AI : FT->param_types()) {
14616           ParmVarDecl *Param =
14617             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14618           Param->setScopeInfo(0, Params.size());
14619           Params.push_back(Param);
14620         }
14621         NewFD->setParams(Params);
14622         DRE->setDecl(NewFD);
14623         VD = DRE->getDecl();
14624       }
14625     }
14626 
14627     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14628       if (MD->isInstance()) {
14629         ValueKind = VK_RValue;
14630         Type = S.Context.BoundMemberTy;
14631       }
14632 
14633     // Function references aren't l-values in C.
14634     if (!S.getLangOpts().CPlusPlus)
14635       ValueKind = VK_RValue;
14636 
14637   //  - variables
14638   } else if (isa<VarDecl>(VD)) {
14639     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14640       Type = RefTy->getPointeeType();
14641     } else if (Type->isFunctionType()) {
14642       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14643         << VD << E->getSourceRange();
14644       return ExprError();
14645     }
14646 
14647   //  - nothing else
14648   } else {
14649     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14650       << VD << E->getSourceRange();
14651     return ExprError();
14652   }
14653 
14654   // Modifying the declaration like this is friendly to IR-gen but
14655   // also really dangerous.
14656   VD->setType(DestType);
14657   E->setType(Type);
14658   E->setValueKind(ValueKind);
14659   return E;
14660 }
14661 
14662 /// Check a cast of an unknown-any type.  We intentionally only
14663 /// trigger this for C-style casts.
14664 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14665                                      Expr *CastExpr, CastKind &CastKind,
14666                                      ExprValueKind &VK, CXXCastPath &Path) {
14667   // The type we're casting to must be either void or complete.
14668   if (!CastType->isVoidType() &&
14669       RequireCompleteType(TypeRange.getBegin(), CastType,
14670                           diag::err_typecheck_cast_to_incomplete))
14671     return ExprError();
14672 
14673   // Rewrite the casted expression from scratch.
14674   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14675   if (!result.isUsable()) return ExprError();
14676 
14677   CastExpr = result.get();
14678   VK = CastExpr->getValueKind();
14679   CastKind = CK_NoOp;
14680 
14681   return CastExpr;
14682 }
14683 
14684 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14685   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14686 }
14687 
14688 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14689                                     Expr *arg, QualType &paramType) {
14690   // If the syntactic form of the argument is not an explicit cast of
14691   // any sort, just do default argument promotion.
14692   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14693   if (!castArg) {
14694     ExprResult result = DefaultArgumentPromotion(arg);
14695     if (result.isInvalid()) return ExprError();
14696     paramType = result.get()->getType();
14697     return result;
14698   }
14699 
14700   // Otherwise, use the type that was written in the explicit cast.
14701   assert(!arg->hasPlaceholderType());
14702   paramType = castArg->getTypeAsWritten();
14703 
14704   // Copy-initialize a parameter of that type.
14705   InitializedEntity entity =
14706     InitializedEntity::InitializeParameter(Context, paramType,
14707                                            /*consumed*/ false);
14708   return PerformCopyInitialization(entity, callLoc, arg);
14709 }
14710 
14711 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14712   Expr *orig = E;
14713   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14714   while (true) {
14715     E = E->IgnoreParenImpCasts();
14716     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14717       E = call->getCallee();
14718       diagID = diag::err_uncasted_call_of_unknown_any;
14719     } else {
14720       break;
14721     }
14722   }
14723 
14724   SourceLocation loc;
14725   NamedDecl *d;
14726   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14727     loc = ref->getLocation();
14728     d = ref->getDecl();
14729   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14730     loc = mem->getMemberLoc();
14731     d = mem->getMemberDecl();
14732   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14733     diagID = diag::err_uncasted_call_of_unknown_any;
14734     loc = msg->getSelectorStartLoc();
14735     d = msg->getMethodDecl();
14736     if (!d) {
14737       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14738         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14739         << orig->getSourceRange();
14740       return ExprError();
14741     }
14742   } else {
14743     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14744       << E->getSourceRange();
14745     return ExprError();
14746   }
14747 
14748   S.Diag(loc, diagID) << d << orig->getSourceRange();
14749 
14750   // Never recoverable.
14751   return ExprError();
14752 }
14753 
14754 /// Check for operands with placeholder types and complain if found.
14755 /// Returns true if there was an error and no recovery was possible.
14756 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14757   if (!getLangOpts().CPlusPlus) {
14758     // C cannot handle TypoExpr nodes on either side of a binop because it
14759     // doesn't handle dependent types properly, so make sure any TypoExprs have
14760     // been dealt with before checking the operands.
14761     ExprResult Result = CorrectDelayedTyposInExpr(E);
14762     if (!Result.isUsable()) return ExprError();
14763     E = Result.get();
14764   }
14765 
14766   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14767   if (!placeholderType) return E;
14768 
14769   switch (placeholderType->getKind()) {
14770 
14771   // Overloaded expressions.
14772   case BuiltinType::Overload: {
14773     // Try to resolve a single function template specialization.
14774     // This is obligatory.
14775     ExprResult result = E;
14776     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14777       return result;
14778 
14779     // If that failed, try to recover with a call.
14780     } else {
14781       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14782                            /*complain*/ true);
14783       return result;
14784     }
14785   }
14786 
14787   // Bound member functions.
14788   case BuiltinType::BoundMember: {
14789     ExprResult result = E;
14790     const Expr *BME = E->IgnoreParens();
14791     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14792     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14793     if (isa<CXXPseudoDestructorExpr>(BME)) {
14794       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14795     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14796       if (ME->getMemberNameInfo().getName().getNameKind() ==
14797           DeclarationName::CXXDestructorName)
14798         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14799     }
14800     tryToRecoverWithCall(result, PD,
14801                          /*complain*/ true);
14802     return result;
14803   }
14804 
14805   // ARC unbridged casts.
14806   case BuiltinType::ARCUnbridgedCast: {
14807     Expr *realCast = stripARCUnbridgedCast(E);
14808     diagnoseARCUnbridgedCast(realCast);
14809     return realCast;
14810   }
14811 
14812   // Expressions of unknown type.
14813   case BuiltinType::UnknownAny:
14814     return diagnoseUnknownAnyExpr(*this, E);
14815 
14816   // Pseudo-objects.
14817   case BuiltinType::PseudoObject:
14818     return checkPseudoObjectRValue(E);
14819 
14820   case BuiltinType::BuiltinFn: {
14821     // Accept __noop without parens by implicitly converting it to a call expr.
14822     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14823     if (DRE) {
14824       auto *FD = cast<FunctionDecl>(DRE->getDecl());
14825       if (FD->getBuiltinID() == Builtin::BI__noop) {
14826         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14827                               CK_BuiltinFnToFnPtr).get();
14828         return new (Context) CallExpr(Context, E, None, Context.IntTy,
14829                                       VK_RValue, SourceLocation());
14830       }
14831     }
14832 
14833     Diag(E->getLocStart(), diag::err_builtin_fn_use);
14834     return ExprError();
14835   }
14836 
14837   // Expressions of unknown type.
14838   case BuiltinType::OMPArraySection:
14839     Diag(E->getLocStart(), diag::err_omp_array_section_use);
14840     return ExprError();
14841 
14842   // Everything else should be impossible.
14843 #define BUILTIN_TYPE(Id, SingletonId) \
14844   case BuiltinType::Id:
14845 #define PLACEHOLDER_TYPE(Id, SingletonId)
14846 #include "clang/AST/BuiltinTypes.def"
14847     break;
14848   }
14849 
14850   llvm_unreachable("invalid placeholder type!");
14851 }
14852 
14853 bool Sema::CheckCaseExpression(Expr *E) {
14854   if (E->isTypeDependent())
14855     return true;
14856   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14857     return E->getType()->isIntegralOrEnumerationType();
14858   return false;
14859 }
14860 
14861 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14862 ExprResult
14863 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14864   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14865          "Unknown Objective-C Boolean value!");
14866   QualType BoolT = Context.ObjCBuiltinBoolTy;
14867   if (!Context.getBOOLDecl()) {
14868     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
14869                         Sema::LookupOrdinaryName);
14870     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
14871       NamedDecl *ND = Result.getFoundDecl();
14872       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14873         Context.setBOOLDecl(TD);
14874     }
14875   }
14876   if (Context.getBOOLDecl())
14877     BoolT = Context.getBOOLType();
14878   return new (Context)
14879       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
14880 }
14881