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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/Support/ConvertUTF.h"
46 using namespace clang;
47 using namespace sema;
48 
49 /// \brief Determine whether the use of this declaration is valid, without
50 /// emitting diagnostics.
51 bool Sema::CanUseDecl(NamedDecl *D) {
52   // See if this is an auto-typed variable whose initializer we are parsing.
53   if (ParsingInitForAutoVars.count(D))
54     return false;
55 
56   // See if this is a deleted function.
57   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
58     if (FD->isDeleted())
59       return false;
60 
61     // If the function has a deduced return type, and we can't deduce it,
62     // then we can't use it either.
63     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
64         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
65       return false;
66   }
67 
68   // See if this function is unavailable.
69   if (D->getAvailability() == AR_Unavailable &&
70       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
71     return false;
72 
73   return true;
74 }
75 
76 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
77   // Warn if this is used but marked unused.
78   if (D->hasAttr<UnusedAttr>()) {
79     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
80     if (!DC->hasAttr<UnusedAttr>())
81       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
82   }
83 }
84 
85 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
86                               NamedDecl *D, SourceLocation Loc,
87                               const ObjCInterfaceDecl *UnknownObjCClass,
88                               bool ObjCPropertyAccess) {
89   // See if this declaration is unavailable or deprecated.
90   std::string Message;
91 
92   // Forward class declarations get their attributes from their definition.
93   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
94     if (IDecl->getDefinition())
95       D = IDecl->getDefinition();
96   }
97   AvailabilityResult Result = D->getAvailability(&Message);
98   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
99     if (Result == AR_Available) {
100       const DeclContext *DC = ECD->getDeclContext();
101       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
102         Result = TheEnumDecl->getAvailability(&Message);
103     }
104 
105   const ObjCPropertyDecl *ObjCPDecl = nullptr;
106   if (Result == AR_Deprecated || Result == AR_Unavailable) {
107     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
108       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
109         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
110         if (PDeclResult == Result)
111           ObjCPDecl = PD;
112       }
113     }
114   }
115 
116   switch (Result) {
117     case AR_Available:
118     case AR_NotYetIntroduced:
119       break;
120 
121     case AR_Deprecated:
122       if (S.getCurContextAvailability() != AR_Deprecated)
123         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
124                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
125                                   ObjCPropertyAccess);
126       break;
127 
128     case AR_Unavailable:
129       if (S.getCurContextAvailability() != AR_Unavailable)
130         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
131                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
132                                   ObjCPropertyAccess);
133       break;
134 
135     }
136     return Result;
137 }
138 
139 /// \brief Emit a note explaining that this function is deleted.
140 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
141   assert(Decl->isDeleted());
142 
143   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
144 
145   if (Method && Method->isDeleted() && Method->isDefaulted()) {
146     // If the method was explicitly defaulted, point at that declaration.
147     if (!Method->isImplicit())
148       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
149 
150     // Try to diagnose why this special member function was implicitly
151     // deleted. This might fail, if that reason no longer applies.
152     CXXSpecialMember CSM = getSpecialMember(Method);
153     if (CSM != CXXInvalid)
154       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
155 
156     return;
157   }
158 
159   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
160     if (CXXConstructorDecl *BaseCD =
161             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
162       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
163       if (BaseCD->isDeleted()) {
164         NoteDeletedFunction(BaseCD);
165       } else {
166         // FIXME: An explanation of why exactly it can't be inherited
167         // would be nice.
168         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
169       }
170       return;
171     }
172   }
173 
174   Diag(Decl->getLocation(), diag::note_availability_specified_here)
175     << Decl << true;
176 }
177 
178 /// \brief Determine whether a FunctionDecl was ever declared with an
179 /// explicit storage class.
180 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
181   for (auto I : D->redecls()) {
182     if (I->getStorageClass() != SC_None)
183       return true;
184   }
185   return false;
186 }
187 
188 /// \brief Check whether we're in an extern inline function and referring to a
189 /// variable or function with internal linkage (C11 6.7.4p3).
190 ///
191 /// This is only a warning because we used to silently accept this code, but
192 /// in many cases it will not behave correctly. This is not enabled in C++ mode
193 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
194 /// and so while there may still be user mistakes, most of the time we can't
195 /// prove that there are errors.
196 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
197                                                       const NamedDecl *D,
198                                                       SourceLocation Loc) {
199   // This is disabled under C++; there are too many ways for this to fire in
200   // contexts where the warning is a false positive, or where it is technically
201   // correct but benign.
202   if (S.getLangOpts().CPlusPlus)
203     return;
204 
205   // Check if this is an inlined function or method.
206   FunctionDecl *Current = S.getCurFunctionDecl();
207   if (!Current)
208     return;
209   if (!Current->isInlined())
210     return;
211   if (!Current->isExternallyVisible())
212     return;
213 
214   // Check if the decl has internal linkage.
215   if (D->getFormalLinkage() != InternalLinkage)
216     return;
217 
218   // Downgrade from ExtWarn to Extension if
219   //  (1) the supposedly external inline function is in the main file,
220   //      and probably won't be included anywhere else.
221   //  (2) the thing we're referencing is a pure function.
222   //  (3) the thing we're referencing is another inline function.
223   // This last can give us false negatives, but it's better than warning on
224   // wrappers for simple C library functions.
225   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
226   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
227   if (!DowngradeWarning && UsedFn)
228     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
229 
230   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
231                                : diag::ext_internal_in_extern_inline)
232     << /*IsVar=*/!UsedFn << D;
233 
234   S.MaybeSuggestAddingStaticToDecl(Current);
235 
236   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
237       << D;
238 }
239 
240 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
241   const FunctionDecl *First = Cur->getFirstDecl();
242 
243   // Suggest "static" on the function, if possible.
244   if (!hasAnyExplicitStorageClass(First)) {
245     SourceLocation DeclBegin = First->getSourceRange().getBegin();
246     Diag(DeclBegin, diag::note_convert_inline_to_static)
247       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
248   }
249 }
250 
251 /// \brief Determine whether the use of this declaration is valid, and
252 /// emit any corresponding diagnostics.
253 ///
254 /// This routine diagnoses various problems with referencing
255 /// declarations that can occur when using a declaration. For example,
256 /// it might warn if a deprecated or unavailable declaration is being
257 /// used, or produce an error (and return true) if a C++0x deleted
258 /// function is being used.
259 ///
260 /// \returns true if there was an error (this declaration cannot be
261 /// referenced), false otherwise.
262 ///
263 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
264                              const ObjCInterfaceDecl *UnknownObjCClass,
265                              bool ObjCPropertyAccess) {
266   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
267     // If there were any diagnostics suppressed by template argument deduction,
268     // emit them now.
269     SuppressedDiagnosticsMap::iterator
270       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
271     if (Pos != SuppressedDiagnostics.end()) {
272       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
273       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
274         Diag(Suppressed[I].first, Suppressed[I].second);
275 
276       // Clear out the list of suppressed diagnostics, so that we don't emit
277       // them again for this specialization. However, we don't obsolete this
278       // entry from the table, because we want to avoid ever emitting these
279       // diagnostics again.
280       Suppressed.clear();
281     }
282 
283     // C++ [basic.start.main]p3:
284     //   The function 'main' shall not be used within a program.
285     if (cast<FunctionDecl>(D)->isMain())
286       Diag(Loc, diag::ext_main_used);
287   }
288 
289   // See if this is an auto-typed variable whose initializer we are parsing.
290   if (ParsingInitForAutoVars.count(D)) {
291     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
292       << D->getDeclName();
293     return true;
294   }
295 
296   // See if this is a deleted function.
297   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
298     if (FD->isDeleted()) {
299       Diag(Loc, diag::err_deleted_function_use);
300       NoteDeletedFunction(FD);
301       return true;
302     }
303 
304     // If the function has a deduced return type, and we can't deduce it,
305     // then we can't use it either.
306     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307         DeduceReturnType(FD, Loc))
308       return true;
309   }
310   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
311 
312   DiagnoseUnusedOfDecl(*this, D, Loc);
313 
314   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
315 
316   return false;
317 }
318 
319 /// \brief Retrieve the message suffix that should be added to a
320 /// diagnostic complaining about the given function being deleted or
321 /// unavailable.
322 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
323   std::string Message;
324   if (FD->getAvailability(&Message))
325     return ": " + Message;
326 
327   return std::string();
328 }
329 
330 /// DiagnoseSentinelCalls - This routine checks whether a call or
331 /// message-send is to a declaration with the sentinel attribute, and
332 /// if so, it checks that the requirements of the sentinel are
333 /// satisfied.
334 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
335                                  ArrayRef<Expr *> Args) {
336   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
337   if (!attr)
338     return;
339 
340   // The number of formal parameters of the declaration.
341   unsigned numFormalParams;
342 
343   // The kind of declaration.  This is also an index into a %select in
344   // the diagnostic.
345   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
346 
347   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
348     numFormalParams = MD->param_size();
349     calleeType = CT_Method;
350   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
351     numFormalParams = FD->param_size();
352     calleeType = CT_Function;
353   } else if (isa<VarDecl>(D)) {
354     QualType type = cast<ValueDecl>(D)->getType();
355     const FunctionType *fn = nullptr;
356     if (const PointerType *ptr = type->getAs<PointerType>()) {
357       fn = ptr->getPointeeType()->getAs<FunctionType>();
358       if (!fn) return;
359       calleeType = CT_Function;
360     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
361       fn = ptr->getPointeeType()->castAs<FunctionType>();
362       calleeType = CT_Block;
363     } else {
364       return;
365     }
366 
367     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
368       numFormalParams = proto->getNumParams();
369     } else {
370       numFormalParams = 0;
371     }
372   } else {
373     return;
374   }
375 
376   // "nullPos" is the number of formal parameters at the end which
377   // effectively count as part of the variadic arguments.  This is
378   // useful if you would prefer to not have *any* formal parameters,
379   // but the language forces you to have at least one.
380   unsigned nullPos = attr->getNullPos();
381   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
382   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
383 
384   // The number of arguments which should follow the sentinel.
385   unsigned numArgsAfterSentinel = attr->getSentinel();
386 
387   // If there aren't enough arguments for all the formal parameters,
388   // the sentinel, and the args after the sentinel, complain.
389   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
390     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
391     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
392     return;
393   }
394 
395   // Otherwise, find the sentinel expression.
396   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
397   if (!sentinelExpr) return;
398   if (sentinelExpr->isValueDependent()) return;
399   if (Context.isSentinelNullExpr(sentinelExpr)) return;
400 
401   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
402   // or 'NULL' if those are actually defined in the context.  Only use
403   // 'nil' for ObjC methods, where it's much more likely that the
404   // variadic arguments form a list of object pointers.
405   SourceLocation MissingNilLoc
406     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
407   std::string NullValue;
408   if (calleeType == CT_Method &&
409       PP.getIdentifierInfo("nil")->hasMacroDefinition())
410     NullValue = "nil";
411   else if (getLangOpts().CPlusPlus11)
412     NullValue = "nullptr";
413   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
414     NullValue = "NULL";
415   else
416     NullValue = "(void*) 0";
417 
418   if (MissingNilLoc.isInvalid())
419     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
420   else
421     Diag(MissingNilLoc, diag::warn_missing_sentinel)
422       << int(calleeType)
423       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
424   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
425 }
426 
427 SourceRange Sema::getExprRange(Expr *E) const {
428   return E ? E->getSourceRange() : SourceRange();
429 }
430 
431 //===----------------------------------------------------------------------===//
432 //  Standard Promotions and Conversions
433 //===----------------------------------------------------------------------===//
434 
435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
437   // Handle any placeholder expressions which made it here.
438   if (E->getType()->isPlaceholderType()) {
439     ExprResult result = CheckPlaceholderExpr(E);
440     if (result.isInvalid()) return ExprError();
441     E = result.get();
442   }
443 
444   QualType Ty = E->getType();
445   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
446 
447   if (Ty->isFunctionType()) {
448     // If we are here, we are not calling a function but taking
449     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
450     if (getLangOpts().OpenCL) {
451       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
452       return ExprError();
453     }
454     E = ImpCastExprToType(E, Context.getPointerType(Ty),
455                           CK_FunctionToPointerDecay).get();
456   } else if (Ty->isArrayType()) {
457     // In C90 mode, arrays only promote to pointers if the array expression is
458     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
459     // type 'array of type' is converted to an expression that has type 'pointer
460     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
461     // that has type 'array of type' ...".  The relevant change is "an lvalue"
462     // (C90) to "an expression" (C99).
463     //
464     // C++ 4.2p1:
465     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
466     // T" can be converted to an rvalue of type "pointer to T".
467     //
468     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
469       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
470                             CK_ArrayToPointerDecay).get();
471   }
472   return E;
473 }
474 
475 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
476   // Check to see if we are dereferencing a null pointer.  If so,
477   // and if not volatile-qualified, this is undefined behavior that the
478   // optimizer will delete, so warn about it.  People sometimes try to use this
479   // to get a deterministic trap and are surprised by clang's behavior.  This
480   // only handles the pattern "*null", which is a very syntactic check.
481   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
482     if (UO->getOpcode() == UO_Deref &&
483         UO->getSubExpr()->IgnoreParenCasts()->
484           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
485         !UO->getType().isVolatileQualified()) {
486     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
487                           S.PDiag(diag::warn_indirection_through_null)
488                             << UO->getSubExpr()->getSourceRange());
489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490                         S.PDiag(diag::note_indirection_through_null));
491   }
492 }
493 
494 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
495                                     SourceLocation AssignLoc,
496                                     const Expr* RHS) {
497   const ObjCIvarDecl *IV = OIRE->getDecl();
498   if (!IV)
499     return;
500 
501   DeclarationName MemberName = IV->getDeclName();
502   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
503   if (!Member || !Member->isStr("isa"))
504     return;
505 
506   const Expr *Base = OIRE->getBase();
507   QualType BaseType = Base->getType();
508   if (OIRE->isArrow())
509     BaseType = BaseType->getPointeeType();
510   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
511     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
512       ObjCInterfaceDecl *ClassDeclared = nullptr;
513       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
514       if (!ClassDeclared->getSuperClass()
515           && (*ClassDeclared->ivar_begin()) == IV) {
516         if (RHS) {
517           NamedDecl *ObjectSetClass =
518             S.LookupSingleName(S.TUScope,
519                                &S.Context.Idents.get("object_setClass"),
520                                SourceLocation(), S.LookupOrdinaryName);
521           if (ObjectSetClass) {
522             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
523             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
524             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
525             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
526                                                      AssignLoc), ",") <<
527             FixItHint::CreateInsertion(RHSLocEnd, ")");
528           }
529           else
530             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
531         } else {
532           NamedDecl *ObjectGetClass =
533             S.LookupSingleName(S.TUScope,
534                                &S.Context.Idents.get("object_getClass"),
535                                SourceLocation(), S.LookupOrdinaryName);
536           if (ObjectGetClass)
537             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
538             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
539             FixItHint::CreateReplacement(
540                                          SourceRange(OIRE->getOpLoc(),
541                                                      OIRE->getLocEnd()), ")");
542           else
543             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
544         }
545         S.Diag(IV->getLocation(), diag::note_ivar_decl);
546       }
547     }
548 }
549 
550 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
551   // Handle any placeholder expressions which made it here.
552   if (E->getType()->isPlaceholderType()) {
553     ExprResult result = CheckPlaceholderExpr(E);
554     if (result.isInvalid()) return ExprError();
555     E = result.get();
556   }
557 
558   // C++ [conv.lval]p1:
559   //   A glvalue of a non-function, non-array type T can be
560   //   converted to a prvalue.
561   if (!E->isGLValue()) return E;
562 
563   QualType T = E->getType();
564   assert(!T.isNull() && "r-value conversion on typeless expression?");
565 
566   // We don't want to throw lvalue-to-rvalue casts on top of
567   // expressions of certain types in C++.
568   if (getLangOpts().CPlusPlus &&
569       (E->getType() == Context.OverloadTy ||
570        T->isDependentType() ||
571        T->isRecordType()))
572     return E;
573 
574   // The C standard is actually really unclear on this point, and
575   // DR106 tells us what the result should be but not why.  It's
576   // generally best to say that void types just doesn't undergo
577   // lvalue-to-rvalue at all.  Note that expressions of unqualified
578   // 'void' type are never l-values, but qualified void can be.
579   if (T->isVoidType())
580     return E;
581 
582   // OpenCL usually rejects direct accesses to values of 'half' type.
583   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
584       T->isHalfType()) {
585     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
586       << 0 << T;
587     return ExprError();
588   }
589 
590   CheckForNullPointerDereference(*this, E);
591   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
592     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
593                                      &Context.Idents.get("object_getClass"),
594                                      SourceLocation(), LookupOrdinaryName);
595     if (ObjectGetClass)
596       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
597         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
598         FixItHint::CreateReplacement(
599                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
600     else
601       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
602   }
603   else if (const ObjCIvarRefExpr *OIRE =
604             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
605     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
606 
607   // C++ [conv.lval]p1:
608   //   [...] If T is a non-class type, the type of the prvalue is the
609   //   cv-unqualified version of T. Otherwise, the type of the
610   //   rvalue is T.
611   //
612   // C99 6.3.2.1p2:
613   //   If the lvalue has qualified type, the value has the unqualified
614   //   version of the type of the lvalue; otherwise, the value has the
615   //   type of the lvalue.
616   if (T.hasQualifiers())
617     T = T.getUnqualifiedType();
618 
619   UpdateMarkingForLValueToRValue(E);
620 
621   // Loading a __weak object implicitly retains the value, so we need a cleanup to
622   // balance that.
623   if (getLangOpts().ObjCAutoRefCount &&
624       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
625     ExprNeedsCleanups = true;
626 
627   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
628                                             nullptr, VK_RValue);
629 
630   // C11 6.3.2.1p2:
631   //   ... if the lvalue has atomic type, the value has the non-atomic version
632   //   of the type of the lvalue ...
633   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
634     T = Atomic->getValueType().getUnqualifiedType();
635     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
636                                    nullptr, VK_RValue);
637   }
638 
639   return Res;
640 }
641 
642 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
643   ExprResult Res = DefaultFunctionArrayConversion(E);
644   if (Res.isInvalid())
645     return ExprError();
646   Res = DefaultLvalueConversion(Res.get());
647   if (Res.isInvalid())
648     return ExprError();
649   return Res;
650 }
651 
652 /// CallExprUnaryConversions - a special case of an unary conversion
653 /// performed on a function designator of a call expression.
654 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
655   QualType Ty = E->getType();
656   ExprResult Res = E;
657   // Only do implicit cast for a function type, but not for a pointer
658   // to function type.
659   if (Ty->isFunctionType()) {
660     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
661                             CK_FunctionToPointerDecay).get();
662     if (Res.isInvalid())
663       return ExprError();
664   }
665   Res = DefaultLvalueConversion(Res.get());
666   if (Res.isInvalid())
667     return ExprError();
668   return Res.get();
669 }
670 
671 /// UsualUnaryConversions - Performs various conversions that are common to most
672 /// operators (C99 6.3). The conversions of array and function types are
673 /// sometimes suppressed. For example, the array->pointer conversion doesn't
674 /// apply if the array is an argument to the sizeof or address (&) operators.
675 /// In these instances, this routine should *not* be called.
676 ExprResult Sema::UsualUnaryConversions(Expr *E) {
677   // First, convert to an r-value.
678   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
679   if (Res.isInvalid())
680     return ExprError();
681   E = Res.get();
682 
683   QualType Ty = E->getType();
684   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
685 
686   // Half FP have to be promoted to float unless it is natively supported
687   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
688     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
689 
690   // Try to perform integral promotions if the object has a theoretically
691   // promotable type.
692   if (Ty->isIntegralOrUnscopedEnumerationType()) {
693     // C99 6.3.1.1p2:
694     //
695     //   The following may be used in an expression wherever an int or
696     //   unsigned int may be used:
697     //     - an object or expression with an integer type whose integer
698     //       conversion rank is less than or equal to the rank of int
699     //       and unsigned int.
700     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
701     //
702     //   If an int can represent all values of the original type, the
703     //   value is converted to an int; otherwise, it is converted to an
704     //   unsigned int. These are called the integer promotions. All
705     //   other types are unchanged by the integer promotions.
706 
707     QualType PTy = Context.isPromotableBitField(E);
708     if (!PTy.isNull()) {
709       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
710       return E;
711     }
712     if (Ty->isPromotableIntegerType()) {
713       QualType PT = Context.getPromotedIntegerType(Ty);
714       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
715       return E;
716     }
717   }
718   return E;
719 }
720 
721 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
722 /// do not have a prototype. Arguments that have type float or __fp16
723 /// are promoted to double. All other argument types are converted by
724 /// UsualUnaryConversions().
725 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
726   QualType Ty = E->getType();
727   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
728 
729   ExprResult Res = UsualUnaryConversions(E);
730   if (Res.isInvalid())
731     return ExprError();
732   E = Res.get();
733 
734   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
735   // double.
736   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
737   if (BTy && (BTy->getKind() == BuiltinType::Half ||
738               BTy->getKind() == BuiltinType::Float))
739     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
740 
741   // C++ performs lvalue-to-rvalue conversion as a default argument
742   // promotion, even on class types, but note:
743   //   C++11 [conv.lval]p2:
744   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
745   //     operand or a subexpression thereof the value contained in the
746   //     referenced object is not accessed. Otherwise, if the glvalue
747   //     has a class type, the conversion copy-initializes a temporary
748   //     of type T from the glvalue and the result of the conversion
749   //     is a prvalue for the temporary.
750   // FIXME: add some way to gate this entire thing for correctness in
751   // potentially potentially evaluated contexts.
752   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
753     ExprResult Temp = PerformCopyInitialization(
754                        InitializedEntity::InitializeTemporary(E->getType()),
755                                                 E->getExprLoc(), E);
756     if (Temp.isInvalid())
757       return ExprError();
758     E = Temp.get();
759   }
760 
761   return E;
762 }
763 
764 /// Determine the degree of POD-ness for an expression.
765 /// Incomplete types are considered POD, since this check can be performed
766 /// when we're in an unevaluated context.
767 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
768   if (Ty->isIncompleteType()) {
769     // C++11 [expr.call]p7:
770     //   After these conversions, if the argument does not have arithmetic,
771     //   enumeration, pointer, pointer to member, or class type, the program
772     //   is ill-formed.
773     //
774     // Since we've already performed array-to-pointer and function-to-pointer
775     // decay, the only such type in C++ is cv void. This also handles
776     // initializer lists as variadic arguments.
777     if (Ty->isVoidType())
778       return VAK_Invalid;
779 
780     if (Ty->isObjCObjectType())
781       return VAK_Invalid;
782     return VAK_Valid;
783   }
784 
785   if (Ty.isCXX98PODType(Context))
786     return VAK_Valid;
787 
788   // C++11 [expr.call]p7:
789   //   Passing a potentially-evaluated argument of class type (Clause 9)
790   //   having a non-trivial copy constructor, a non-trivial move constructor,
791   //   or a non-trivial destructor, with no corresponding parameter,
792   //   is conditionally-supported with implementation-defined semantics.
793   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
794     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
795       if (!Record->hasNonTrivialCopyConstructor() &&
796           !Record->hasNonTrivialMoveConstructor() &&
797           !Record->hasNonTrivialDestructor())
798         return VAK_ValidInCXX11;
799 
800   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
801     return VAK_Valid;
802 
803   if (Ty->isObjCObjectType())
804     return VAK_Invalid;
805 
806   if (getLangOpts().MSVCCompat)
807     return VAK_MSVCUndefined;
808 
809   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
810   // permitted to reject them. We should consider doing so.
811   return VAK_Undefined;
812 }
813 
814 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
815   // Don't allow one to pass an Objective-C interface to a vararg.
816   const QualType &Ty = E->getType();
817   VarArgKind VAK = isValidVarArgType(Ty);
818 
819   // Complain about passing non-POD types through varargs.
820   switch (VAK) {
821   case VAK_ValidInCXX11:
822     DiagRuntimeBehavior(
823         E->getLocStart(), nullptr,
824         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
825           << Ty << CT);
826     // Fall through.
827   case VAK_Valid:
828     if (Ty->isRecordType()) {
829       // This is unlikely to be what the user intended. If the class has a
830       // 'c_str' member function, the user probably meant to call that.
831       DiagRuntimeBehavior(E->getLocStart(), nullptr,
832                           PDiag(diag::warn_pass_class_arg_to_vararg)
833                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
834     }
835     break;
836 
837   case VAK_Undefined:
838   case VAK_MSVCUndefined:
839     DiagRuntimeBehavior(
840         E->getLocStart(), nullptr,
841         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
842           << getLangOpts().CPlusPlus11 << Ty << CT);
843     break;
844 
845   case VAK_Invalid:
846     if (Ty->isObjCObjectType())
847       DiagRuntimeBehavior(
848           E->getLocStart(), nullptr,
849           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
850             << Ty << CT);
851     else
852       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
853         << isa<InitListExpr>(E) << Ty << CT;
854     break;
855   }
856 }
857 
858 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
859 /// will create a trap if the resulting type is not a POD type.
860 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
861                                                   FunctionDecl *FDecl) {
862   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
863     // Strip the unbridged-cast placeholder expression off, if applicable.
864     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
865         (CT == VariadicMethod ||
866          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
867       E = stripARCUnbridgedCast(E);
868 
869     // Otherwise, do normal placeholder checking.
870     } else {
871       ExprResult ExprRes = CheckPlaceholderExpr(E);
872       if (ExprRes.isInvalid())
873         return ExprError();
874       E = ExprRes.get();
875     }
876   }
877 
878   ExprResult ExprRes = DefaultArgumentPromotion(E);
879   if (ExprRes.isInvalid())
880     return ExprError();
881   E = ExprRes.get();
882 
883   // Diagnostics regarding non-POD argument types are
884   // emitted along with format string checking in Sema::CheckFunctionCall().
885   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
886     // Turn this into a trap.
887     CXXScopeSpec SS;
888     SourceLocation TemplateKWLoc;
889     UnqualifiedId Name;
890     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
891                        E->getLocStart());
892     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
893                                           Name, true, false);
894     if (TrapFn.isInvalid())
895       return ExprError();
896 
897     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
898                                     E->getLocStart(), None,
899                                     E->getLocEnd());
900     if (Call.isInvalid())
901       return ExprError();
902 
903     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
904                                   Call.get(), E);
905     if (Comma.isInvalid())
906       return ExprError();
907     return Comma.get();
908   }
909 
910   if (!getLangOpts().CPlusPlus &&
911       RequireCompleteType(E->getExprLoc(), E->getType(),
912                           diag::err_call_incomplete_argument))
913     return ExprError();
914 
915   return E;
916 }
917 
918 /// \brief Converts an integer to complex float type.  Helper function of
919 /// UsualArithmeticConversions()
920 ///
921 /// \return false if the integer expression is an integer type and is
922 /// successfully converted to the complex type.
923 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
924                                                   ExprResult &ComplexExpr,
925                                                   QualType IntTy,
926                                                   QualType ComplexTy,
927                                                   bool SkipCast) {
928   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
929   if (SkipCast) return false;
930   if (IntTy->isIntegerType()) {
931     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
932     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
933     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
934                                   CK_FloatingRealToComplex);
935   } else {
936     assert(IntTy->isComplexIntegerType());
937     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
938                                   CK_IntegralComplexToFloatingComplex);
939   }
940   return false;
941 }
942 
943 /// \brief Handle arithmetic conversion with complex types.  Helper function of
944 /// UsualArithmeticConversions()
945 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
946                                              ExprResult &RHS, QualType LHSType,
947                                              QualType RHSType,
948                                              bool IsCompAssign) {
949   // if we have an integer operand, the result is the complex type.
950   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
951                                              /*skipCast*/false))
952     return LHSType;
953   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
954                                              /*skipCast*/IsCompAssign))
955     return RHSType;
956 
957   // This handles complex/complex, complex/float, or float/complex.
958   // When both operands are complex, the shorter operand is converted to the
959   // type of the longer, and that is the type of the result. This corresponds
960   // to what is done when combining two real floating-point operands.
961   // The fun begins when size promotion occur across type domains.
962   // From H&S 6.3.4: When one operand is complex and the other is a real
963   // floating-point type, the less precise type is converted, within it's
964   // real or complex domain, to the precision of the other type. For example,
965   // when combining a "long double" with a "double _Complex", the
966   // "double _Complex" is promoted to "long double _Complex".
967 
968   // Compute the rank of the two types, regardless of whether they are complex.
969   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
970 
971   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
972   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
973   QualType LHSElementType =
974       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
975   QualType RHSElementType =
976       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
977 
978   QualType ResultType = S.Context.getComplexType(LHSElementType);
979   if (Order < 0) {
980     // Promote the precision of the LHS if not an assignment.
981     ResultType = S.Context.getComplexType(RHSElementType);
982     if (!IsCompAssign) {
983       if (LHSComplexType)
984         LHS =
985             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
986       else
987         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
988     }
989   } else if (Order > 0) {
990     // Promote the precision of the RHS.
991     if (RHSComplexType)
992       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
993     else
994       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
995   }
996   return ResultType;
997 }
998 
999 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1000 /// of UsualArithmeticConversions()
1001 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1002                                            ExprResult &IntExpr,
1003                                            QualType FloatTy, QualType IntTy,
1004                                            bool ConvertFloat, bool ConvertInt) {
1005   if (IntTy->isIntegerType()) {
1006     if (ConvertInt)
1007       // Convert intExpr to the lhs floating point type.
1008       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1009                                     CK_IntegralToFloating);
1010     return FloatTy;
1011   }
1012 
1013   // Convert both sides to the appropriate complex float.
1014   assert(IntTy->isComplexIntegerType());
1015   QualType result = S.Context.getComplexType(FloatTy);
1016 
1017   // _Complex int -> _Complex float
1018   if (ConvertInt)
1019     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1020                                   CK_IntegralComplexToFloatingComplex);
1021 
1022   // float -> _Complex float
1023   if (ConvertFloat)
1024     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1025                                     CK_FloatingRealToComplex);
1026 
1027   return result;
1028 }
1029 
1030 /// \brief Handle arithmethic conversion with floating point types.  Helper
1031 /// function of UsualArithmeticConversions()
1032 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1033                                       ExprResult &RHS, QualType LHSType,
1034                                       QualType RHSType, bool IsCompAssign) {
1035   bool LHSFloat = LHSType->isRealFloatingType();
1036   bool RHSFloat = RHSType->isRealFloatingType();
1037 
1038   // If we have two real floating types, convert the smaller operand
1039   // to the bigger result.
1040   if (LHSFloat && RHSFloat) {
1041     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1042     if (order > 0) {
1043       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1044       return LHSType;
1045     }
1046 
1047     assert(order < 0 && "illegal float comparison");
1048     if (!IsCompAssign)
1049       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1050     return RHSType;
1051   }
1052 
1053   if (LHSFloat)
1054     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1055                                       /*convertFloat=*/!IsCompAssign,
1056                                       /*convertInt=*/ true);
1057   assert(RHSFloat);
1058   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1059                                     /*convertInt=*/ true,
1060                                     /*convertFloat=*/!IsCompAssign);
1061 }
1062 
1063 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1064 
1065 namespace {
1066 /// These helper callbacks are placed in an anonymous namespace to
1067 /// permit their use as function template parameters.
1068 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1069   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1070 }
1071 
1072 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1073   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1074                              CK_IntegralComplexCast);
1075 }
1076 }
1077 
1078 /// \brief Handle integer arithmetic conversions.  Helper function of
1079 /// UsualArithmeticConversions()
1080 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1081 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1082                                         ExprResult &RHS, QualType LHSType,
1083                                         QualType RHSType, bool IsCompAssign) {
1084   // The rules for this case are in C99 6.3.1.8
1085   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1086   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1087   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1088   if (LHSSigned == RHSSigned) {
1089     // Same signedness; use the higher-ranked type
1090     if (order >= 0) {
1091       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1092       return LHSType;
1093     } else if (!IsCompAssign)
1094       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1095     return RHSType;
1096   } else if (order != (LHSSigned ? 1 : -1)) {
1097     // The unsigned type has greater than or equal rank to the
1098     // signed type, so use the unsigned type
1099     if (RHSSigned) {
1100       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1101       return LHSType;
1102     } else if (!IsCompAssign)
1103       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1104     return RHSType;
1105   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1106     // The two types are different widths; if we are here, that
1107     // means the signed type is larger than the unsigned type, so
1108     // use the signed type.
1109     if (LHSSigned) {
1110       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1111       return LHSType;
1112     } else if (!IsCompAssign)
1113       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1114     return RHSType;
1115   } else {
1116     // The signed type is higher-ranked than the unsigned type,
1117     // but isn't actually any bigger (like unsigned int and long
1118     // on most 32-bit systems).  Use the unsigned type corresponding
1119     // to the signed type.
1120     QualType result =
1121       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1122     RHS = (*doRHSCast)(S, RHS.get(), result);
1123     if (!IsCompAssign)
1124       LHS = (*doLHSCast)(S, LHS.get(), result);
1125     return result;
1126   }
1127 }
1128 
1129 /// \brief Handle conversions with GCC complex int extension.  Helper function
1130 /// of UsualArithmeticConversions()
1131 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1132                                            ExprResult &RHS, QualType LHSType,
1133                                            QualType RHSType,
1134                                            bool IsCompAssign) {
1135   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1136   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1137 
1138   if (LHSComplexInt && RHSComplexInt) {
1139     QualType LHSEltType = LHSComplexInt->getElementType();
1140     QualType RHSEltType = RHSComplexInt->getElementType();
1141     QualType ScalarType =
1142       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1143         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1144 
1145     return S.Context.getComplexType(ScalarType);
1146   }
1147 
1148   if (LHSComplexInt) {
1149     QualType LHSEltType = LHSComplexInt->getElementType();
1150     QualType ScalarType =
1151       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1152         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1153     QualType ComplexType = S.Context.getComplexType(ScalarType);
1154     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1155                               CK_IntegralRealToComplex);
1156 
1157     return ComplexType;
1158   }
1159 
1160   assert(RHSComplexInt);
1161 
1162   QualType RHSEltType = RHSComplexInt->getElementType();
1163   QualType ScalarType =
1164     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1165       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1166   QualType ComplexType = S.Context.getComplexType(ScalarType);
1167 
1168   if (!IsCompAssign)
1169     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1170                               CK_IntegralRealToComplex);
1171   return ComplexType;
1172 }
1173 
1174 /// UsualArithmeticConversions - Performs various conversions that are common to
1175 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1176 /// routine returns the first non-arithmetic type found. The client is
1177 /// responsible for emitting appropriate error diagnostics.
1178 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1179                                           bool IsCompAssign) {
1180   if (!IsCompAssign) {
1181     LHS = UsualUnaryConversions(LHS.get());
1182     if (LHS.isInvalid())
1183       return QualType();
1184   }
1185 
1186   RHS = UsualUnaryConversions(RHS.get());
1187   if (RHS.isInvalid())
1188     return QualType();
1189 
1190   // For conversion purposes, we ignore any qualifiers.
1191   // For example, "const float" and "float" are equivalent.
1192   QualType LHSType =
1193     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1194   QualType RHSType =
1195     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1196 
1197   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1198   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1199     LHSType = AtomicLHS->getValueType();
1200 
1201   // If both types are identical, no conversion is needed.
1202   if (LHSType == RHSType)
1203     return LHSType;
1204 
1205   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1206   // The caller can deal with this (e.g. pointer + int).
1207   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1208     return QualType();
1209 
1210   // Apply unary and bitfield promotions to the LHS's type.
1211   QualType LHSUnpromotedType = LHSType;
1212   if (LHSType->isPromotableIntegerType())
1213     LHSType = Context.getPromotedIntegerType(LHSType);
1214   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1215   if (!LHSBitfieldPromoteTy.isNull())
1216     LHSType = LHSBitfieldPromoteTy;
1217   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1218     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1219 
1220   // If both types are identical, no conversion is needed.
1221   if (LHSType == RHSType)
1222     return LHSType;
1223 
1224   // At this point, we have two different arithmetic types.
1225 
1226   // Handle complex types first (C99 6.3.1.8p1).
1227   if (LHSType->isComplexType() || RHSType->isComplexType())
1228     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1229                                         IsCompAssign);
1230 
1231   // Now handle "real" floating types (i.e. float, double, long double).
1232   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1233     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1234                                  IsCompAssign);
1235 
1236   // Handle GCC complex int extension.
1237   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1238     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1239                                       IsCompAssign);
1240 
1241   // Finally, we have two differing integer types.
1242   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1243            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1244 }
1245 
1246 
1247 //===----------------------------------------------------------------------===//
1248 //  Semantic Analysis for various Expression Types
1249 //===----------------------------------------------------------------------===//
1250 
1251 
1252 ExprResult
1253 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1254                                 SourceLocation DefaultLoc,
1255                                 SourceLocation RParenLoc,
1256                                 Expr *ControllingExpr,
1257                                 ArrayRef<ParsedType> ArgTypes,
1258                                 ArrayRef<Expr *> ArgExprs) {
1259   unsigned NumAssocs = ArgTypes.size();
1260   assert(NumAssocs == ArgExprs.size());
1261 
1262   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1263   for (unsigned i = 0; i < NumAssocs; ++i) {
1264     if (ArgTypes[i])
1265       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1266     else
1267       Types[i] = nullptr;
1268   }
1269 
1270   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1271                                              ControllingExpr,
1272                                              llvm::makeArrayRef(Types, NumAssocs),
1273                                              ArgExprs);
1274   delete [] Types;
1275   return ER;
1276 }
1277 
1278 ExprResult
1279 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1280                                  SourceLocation DefaultLoc,
1281                                  SourceLocation RParenLoc,
1282                                  Expr *ControllingExpr,
1283                                  ArrayRef<TypeSourceInfo *> Types,
1284                                  ArrayRef<Expr *> Exprs) {
1285   unsigned NumAssocs = Types.size();
1286   assert(NumAssocs == Exprs.size());
1287   if (ControllingExpr->getType()->isPlaceholderType()) {
1288     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1289     if (result.isInvalid()) return ExprError();
1290     ControllingExpr = result.get();
1291   }
1292 
1293   bool TypeErrorFound = false,
1294        IsResultDependent = ControllingExpr->isTypeDependent(),
1295        ContainsUnexpandedParameterPack
1296          = ControllingExpr->containsUnexpandedParameterPack();
1297 
1298   for (unsigned i = 0; i < NumAssocs; ++i) {
1299     if (Exprs[i]->containsUnexpandedParameterPack())
1300       ContainsUnexpandedParameterPack = true;
1301 
1302     if (Types[i]) {
1303       if (Types[i]->getType()->containsUnexpandedParameterPack())
1304         ContainsUnexpandedParameterPack = true;
1305 
1306       if (Types[i]->getType()->isDependentType()) {
1307         IsResultDependent = true;
1308       } else {
1309         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1310         // complete object type other than a variably modified type."
1311         unsigned D = 0;
1312         if (Types[i]->getType()->isIncompleteType())
1313           D = diag::err_assoc_type_incomplete;
1314         else if (!Types[i]->getType()->isObjectType())
1315           D = diag::err_assoc_type_nonobject;
1316         else if (Types[i]->getType()->isVariablyModifiedType())
1317           D = diag::err_assoc_type_variably_modified;
1318 
1319         if (D != 0) {
1320           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1321             << Types[i]->getTypeLoc().getSourceRange()
1322             << Types[i]->getType();
1323           TypeErrorFound = true;
1324         }
1325 
1326         // C11 6.5.1.1p2 "No two generic associations in the same generic
1327         // selection shall specify compatible types."
1328         for (unsigned j = i+1; j < NumAssocs; ++j)
1329           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1330               Context.typesAreCompatible(Types[i]->getType(),
1331                                          Types[j]->getType())) {
1332             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1333                  diag::err_assoc_compatible_types)
1334               << Types[j]->getTypeLoc().getSourceRange()
1335               << Types[j]->getType()
1336               << Types[i]->getType();
1337             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1338                  diag::note_compat_assoc)
1339               << Types[i]->getTypeLoc().getSourceRange()
1340               << Types[i]->getType();
1341             TypeErrorFound = true;
1342           }
1343       }
1344     }
1345   }
1346   if (TypeErrorFound)
1347     return ExprError();
1348 
1349   // If we determined that the generic selection is result-dependent, don't
1350   // try to compute the result expression.
1351   if (IsResultDependent)
1352     return new (Context) GenericSelectionExpr(
1353         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1354         ContainsUnexpandedParameterPack);
1355 
1356   SmallVector<unsigned, 1> CompatIndices;
1357   unsigned DefaultIndex = -1U;
1358   for (unsigned i = 0; i < NumAssocs; ++i) {
1359     if (!Types[i])
1360       DefaultIndex = i;
1361     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1362                                         Types[i]->getType()))
1363       CompatIndices.push_back(i);
1364   }
1365 
1366   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1367   // type compatible with at most one of the types named in its generic
1368   // association list."
1369   if (CompatIndices.size() > 1) {
1370     // We strip parens here because the controlling expression is typically
1371     // parenthesized in macro definitions.
1372     ControllingExpr = ControllingExpr->IgnoreParens();
1373     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1374       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1375       << (unsigned) CompatIndices.size();
1376     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1377          E = CompatIndices.end(); I != E; ++I) {
1378       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1379            diag::note_compat_assoc)
1380         << Types[*I]->getTypeLoc().getSourceRange()
1381         << Types[*I]->getType();
1382     }
1383     return ExprError();
1384   }
1385 
1386   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1387   // its controlling expression shall have type compatible with exactly one of
1388   // the types named in its generic association list."
1389   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1390     // We strip parens here because the controlling expression is typically
1391     // parenthesized in macro definitions.
1392     ControllingExpr = ControllingExpr->IgnoreParens();
1393     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1394       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1395     return ExprError();
1396   }
1397 
1398   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1399   // type name that is compatible with the type of the controlling expression,
1400   // then the result expression of the generic selection is the expression
1401   // in that generic association. Otherwise, the result expression of the
1402   // generic selection is the expression in the default generic association."
1403   unsigned ResultIndex =
1404     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1405 
1406   return new (Context) GenericSelectionExpr(
1407       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1408       ContainsUnexpandedParameterPack, ResultIndex);
1409 }
1410 
1411 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1412 /// location of the token and the offset of the ud-suffix within it.
1413 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1414                                      unsigned Offset) {
1415   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1416                                         S.getLangOpts());
1417 }
1418 
1419 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1420 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1421 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1422                                                  IdentifierInfo *UDSuffix,
1423                                                  SourceLocation UDSuffixLoc,
1424                                                  ArrayRef<Expr*> Args,
1425                                                  SourceLocation LitEndLoc) {
1426   assert(Args.size() <= 2 && "too many arguments for literal operator");
1427 
1428   QualType ArgTy[2];
1429   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1430     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1431     if (ArgTy[ArgIdx]->isArrayType())
1432       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1433   }
1434 
1435   DeclarationName OpName =
1436     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1437   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1438   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1439 
1440   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1441   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1442                               /*AllowRaw*/false, /*AllowTemplate*/false,
1443                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1444     return ExprError();
1445 
1446   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1447 }
1448 
1449 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1450 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1451 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1452 /// multiple tokens.  However, the common case is that StringToks points to one
1453 /// string.
1454 ///
1455 ExprResult
1456 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1457   assert(!StringToks.empty() && "Must have at least one string!");
1458 
1459   StringLiteralParser Literal(StringToks, PP);
1460   if (Literal.hadError)
1461     return ExprError();
1462 
1463   SmallVector<SourceLocation, 4> StringTokLocs;
1464   for (unsigned i = 0; i != StringToks.size(); ++i)
1465     StringTokLocs.push_back(StringToks[i].getLocation());
1466 
1467   QualType CharTy = Context.CharTy;
1468   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1469   if (Literal.isWide()) {
1470     CharTy = Context.getWideCharType();
1471     Kind = StringLiteral::Wide;
1472   } else if (Literal.isUTF8()) {
1473     Kind = StringLiteral::UTF8;
1474   } else if (Literal.isUTF16()) {
1475     CharTy = Context.Char16Ty;
1476     Kind = StringLiteral::UTF16;
1477   } else if (Literal.isUTF32()) {
1478     CharTy = Context.Char32Ty;
1479     Kind = StringLiteral::UTF32;
1480   } else if (Literal.isPascal()) {
1481     CharTy = Context.UnsignedCharTy;
1482   }
1483 
1484   QualType CharTyConst = CharTy;
1485   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1486   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1487     CharTyConst.addConst();
1488 
1489   // Get an array type for the string, according to C99 6.4.5.  This includes
1490   // the nul terminator character as well as the string length for pascal
1491   // strings.
1492   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1493                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1494                                  ArrayType::Normal, 0);
1495 
1496   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1497   if (getLangOpts().OpenCL) {
1498     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1499   }
1500 
1501   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1502   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1503                                              Kind, Literal.Pascal, StrTy,
1504                                              &StringTokLocs[0],
1505                                              StringTokLocs.size());
1506   if (Literal.getUDSuffix().empty())
1507     return Lit;
1508 
1509   // We're building a user-defined literal.
1510   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1511   SourceLocation UDSuffixLoc =
1512     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1513                    Literal.getUDSuffixOffset());
1514 
1515   // Make sure we're allowed user-defined literals here.
1516   if (!UDLScope)
1517     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1518 
1519   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1520   //   operator "" X (str, len)
1521   QualType SizeType = Context.getSizeType();
1522 
1523   DeclarationName OpName =
1524     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1525   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1526   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1527 
1528   QualType ArgTy[] = {
1529     Context.getArrayDecayedType(StrTy), SizeType
1530   };
1531 
1532   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1533   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1534                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1535                                 /*AllowStringTemplate*/true)) {
1536 
1537   case LOLR_Cooked: {
1538     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1539     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1540                                                     StringTokLocs[0]);
1541     Expr *Args[] = { Lit, LenArg };
1542 
1543     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1544   }
1545 
1546   case LOLR_StringTemplate: {
1547     TemplateArgumentListInfo ExplicitArgs;
1548 
1549     unsigned CharBits = Context.getIntWidth(CharTy);
1550     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1551     llvm::APSInt Value(CharBits, CharIsUnsigned);
1552 
1553     TemplateArgument TypeArg(CharTy);
1554     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1555     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1556 
1557     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1558       Value = Lit->getCodeUnit(I);
1559       TemplateArgument Arg(Context, Value, CharTy);
1560       TemplateArgumentLocInfo ArgInfo;
1561       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1562     }
1563     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1564                                     &ExplicitArgs);
1565   }
1566   case LOLR_Raw:
1567   case LOLR_Template:
1568     llvm_unreachable("unexpected literal operator lookup result");
1569   case LOLR_Error:
1570     return ExprError();
1571   }
1572   llvm_unreachable("unexpected literal operator lookup result");
1573 }
1574 
1575 ExprResult
1576 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1577                        SourceLocation Loc,
1578                        const CXXScopeSpec *SS) {
1579   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1580   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1581 }
1582 
1583 /// BuildDeclRefExpr - Build an expression that references a
1584 /// declaration that does not require a closure capture.
1585 ExprResult
1586 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1587                        const DeclarationNameInfo &NameInfo,
1588                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1589                        const TemplateArgumentListInfo *TemplateArgs) {
1590   if (getLangOpts().CUDA)
1591     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1592       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1593         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1594                            CalleeTarget = IdentifyCUDATarget(Callee);
1595         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1596           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1597             << CalleeTarget << D->getIdentifier() << CallerTarget;
1598           Diag(D->getLocation(), diag::note_previous_decl)
1599             << D->getIdentifier();
1600           return ExprError();
1601         }
1602       }
1603 
1604   bool refersToEnclosingScope =
1605     (CurContext != D->getDeclContext() &&
1606      D->getDeclContext()->isFunctionOrMethod()) ||
1607     (isa<VarDecl>(D) &&
1608      cast<VarDecl>(D)->isInitCapture());
1609 
1610   DeclRefExpr *E;
1611   if (isa<VarTemplateSpecializationDecl>(D)) {
1612     VarTemplateSpecializationDecl *VarSpec =
1613         cast<VarTemplateSpecializationDecl>(D);
1614 
1615     E = DeclRefExpr::Create(
1616         Context,
1617         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1618         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1619         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1620   } else {
1621     assert(!TemplateArgs && "No template arguments for non-variable"
1622                             " template specialization references");
1623     E = DeclRefExpr::Create(
1624         Context,
1625         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1626         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1627   }
1628 
1629   MarkDeclRefReferenced(E);
1630 
1631   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1632       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1633       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1634       recordUseOfEvaluatedWeak(E);
1635 
1636   // Just in case we're building an illegal pointer-to-member.
1637   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1638   if (FD && FD->isBitField())
1639     E->setObjectKind(OK_BitField);
1640 
1641   return E;
1642 }
1643 
1644 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1645 /// possibly a list of template arguments.
1646 ///
1647 /// If this produces template arguments, it is permitted to call
1648 /// DecomposeTemplateName.
1649 ///
1650 /// This actually loses a lot of source location information for
1651 /// non-standard name kinds; we should consider preserving that in
1652 /// some way.
1653 void
1654 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1655                              TemplateArgumentListInfo &Buffer,
1656                              DeclarationNameInfo &NameInfo,
1657                              const TemplateArgumentListInfo *&TemplateArgs) {
1658   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1659     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1660     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1661 
1662     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1663                                        Id.TemplateId->NumArgs);
1664     translateTemplateArguments(TemplateArgsPtr, Buffer);
1665 
1666     TemplateName TName = Id.TemplateId->Template.get();
1667     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1668     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1669     TemplateArgs = &Buffer;
1670   } else {
1671     NameInfo = GetNameFromUnqualifiedId(Id);
1672     TemplateArgs = nullptr;
1673   }
1674 }
1675 
1676 static void emitEmptyLookupTypoDiagnostic(
1677     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1678     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1679     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1680   DeclContext *Ctx =
1681       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1682   if (!TC) {
1683     // Emit a special diagnostic for failed member lookups.
1684     // FIXME: computing the declaration context might fail here (?)
1685     if (Ctx)
1686       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1687                                                  << SS.getRange();
1688     else
1689       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1690     return;
1691   }
1692 
1693   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1694   bool DroppedSpecifier =
1695       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1696   unsigned NoteID =
1697       (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1698           ? diag::note_implicit_param_decl
1699           : diag::note_previous_decl;
1700   if (!Ctx)
1701     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1702                          SemaRef.PDiag(NoteID));
1703   else
1704     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1705                                  << Typo << Ctx << DroppedSpecifier
1706                                  << SS.getRange(),
1707                          SemaRef.PDiag(NoteID));
1708 }
1709 
1710 /// Diagnose an empty lookup.
1711 ///
1712 /// \return false if new lookup candidates were found
1713 bool
1714 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1715                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1716                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1717                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1718   DeclarationName Name = R.getLookupName();
1719 
1720   unsigned diagnostic = diag::err_undeclared_var_use;
1721   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1722   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1723       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1724       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1725     diagnostic = diag::err_undeclared_use;
1726     diagnostic_suggest = diag::err_undeclared_use_suggest;
1727   }
1728 
1729   // If the original lookup was an unqualified lookup, fake an
1730   // unqualified lookup.  This is useful when (for example) the
1731   // original lookup would not have found something because it was a
1732   // dependent name.
1733   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1734     ? CurContext : nullptr;
1735   while (DC) {
1736     if (isa<CXXRecordDecl>(DC)) {
1737       LookupQualifiedName(R, DC);
1738 
1739       if (!R.empty()) {
1740         // Don't give errors about ambiguities in this lookup.
1741         R.suppressDiagnostics();
1742 
1743         // During a default argument instantiation the CurContext points
1744         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1745         // function parameter list, hence add an explicit check.
1746         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1747                               ActiveTemplateInstantiations.back().Kind ==
1748             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1749         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1750         bool isInstance = CurMethod &&
1751                           CurMethod->isInstance() &&
1752                           DC == CurMethod->getParent() && !isDefaultArgument;
1753 
1754 
1755         // Give a code modification hint to insert 'this->'.
1756         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1757         // Actually quite difficult!
1758         if (getLangOpts().MSVCCompat)
1759           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1760         if (isInstance) {
1761           Diag(R.getNameLoc(), diagnostic) << Name
1762             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1763           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1764               CallsUndergoingInstantiation.back()->getCallee());
1765 
1766           CXXMethodDecl *DepMethod;
1767           if (CurMethod->isDependentContext())
1768             DepMethod = CurMethod;
1769           else if (CurMethod->getTemplatedKind() ==
1770               FunctionDecl::TK_FunctionTemplateSpecialization)
1771             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1772                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1773           else
1774             DepMethod = cast<CXXMethodDecl>(
1775                 CurMethod->getInstantiatedFromMemberFunction());
1776           assert(DepMethod && "No template pattern found");
1777 
1778           QualType DepThisType = DepMethod->getThisType(Context);
1779           CheckCXXThisCapture(R.getNameLoc());
1780           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1781                                      R.getNameLoc(), DepThisType, false);
1782           TemplateArgumentListInfo TList;
1783           if (ULE->hasExplicitTemplateArgs())
1784             ULE->copyTemplateArgumentsInto(TList);
1785 
1786           CXXScopeSpec SS;
1787           SS.Adopt(ULE->getQualifierLoc());
1788           CXXDependentScopeMemberExpr *DepExpr =
1789               CXXDependentScopeMemberExpr::Create(
1790                   Context, DepThis, DepThisType, true, SourceLocation(),
1791                   SS.getWithLocInContext(Context),
1792                   ULE->getTemplateKeywordLoc(), nullptr,
1793                   R.getLookupNameInfo(),
1794                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1795           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1796         } else {
1797           Diag(R.getNameLoc(), diagnostic) << Name;
1798         }
1799 
1800         // Do we really want to note all of these?
1801         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1802           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1803 
1804         // Return true if we are inside a default argument instantiation
1805         // and the found name refers to an instance member function, otherwise
1806         // the function calling DiagnoseEmptyLookup will try to create an
1807         // implicit member call and this is wrong for default argument.
1808         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1809           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1810           return true;
1811         }
1812 
1813         // Tell the callee to try to recover.
1814         return false;
1815       }
1816 
1817       R.clear();
1818     }
1819 
1820     // In Microsoft mode, if we are performing lookup from within a friend
1821     // function definition declared at class scope then we must set
1822     // DC to the lexical parent to be able to search into the parent
1823     // class.
1824     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1825         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1826         DC->getLexicalParent()->isRecord())
1827       DC = DC->getLexicalParent();
1828     else
1829       DC = DC->getParent();
1830   }
1831 
1832   // We didn't find anything, so try to correct for a typo.
1833   TypoCorrection Corrected;
1834   if (S && Out) {
1835     SourceLocation TypoLoc = R.getNameLoc();
1836     assert(!ExplicitTemplateArgs &&
1837            "Diagnosing an empty lookup with explicit template args!");
1838     *Out = CorrectTypoDelayed(
1839         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1840         [=](const TypoCorrection &TC) {
1841           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1842                                         diagnostic, diagnostic_suggest);
1843         },
1844         nullptr, CTK_ErrorRecovery);
1845     if (*Out)
1846       return true;
1847   } else if (S && (Corrected =
1848                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1849                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1850     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1851     bool DroppedSpecifier =
1852         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1853     R.setLookupName(Corrected.getCorrection());
1854 
1855     bool AcceptableWithRecovery = false;
1856     bool AcceptableWithoutRecovery = false;
1857     NamedDecl *ND = Corrected.getCorrectionDecl();
1858     if (ND) {
1859       if (Corrected.isOverloaded()) {
1860         OverloadCandidateSet OCS(R.getNameLoc(),
1861                                  OverloadCandidateSet::CSK_Normal);
1862         OverloadCandidateSet::iterator Best;
1863         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1864                                         CDEnd = Corrected.end();
1865              CD != CDEnd; ++CD) {
1866           if (FunctionTemplateDecl *FTD =
1867                    dyn_cast<FunctionTemplateDecl>(*CD))
1868             AddTemplateOverloadCandidate(
1869                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1870                 Args, OCS);
1871           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1872             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1873               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1874                                    Args, OCS);
1875         }
1876         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1877         case OR_Success:
1878           ND = Best->Function;
1879           Corrected.setCorrectionDecl(ND);
1880           break;
1881         default:
1882           // FIXME: Arbitrarily pick the first declaration for the note.
1883           Corrected.setCorrectionDecl(ND);
1884           break;
1885         }
1886       }
1887       R.addDecl(ND);
1888       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1889         CXXRecordDecl *Record = nullptr;
1890         if (Corrected.getCorrectionSpecifier()) {
1891           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1892           Record = Ty->getAsCXXRecordDecl();
1893         }
1894         if (!Record)
1895           Record = cast<CXXRecordDecl>(
1896               ND->getDeclContext()->getRedeclContext());
1897         R.setNamingClass(Record);
1898       }
1899 
1900       AcceptableWithRecovery =
1901           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1902       // FIXME: If we ended up with a typo for a type name or
1903       // Objective-C class name, we're in trouble because the parser
1904       // is in the wrong place to recover. Suggest the typo
1905       // correction, but don't make it a fix-it since we're not going
1906       // to recover well anyway.
1907       AcceptableWithoutRecovery =
1908           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1909     } else {
1910       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1911       // because we aren't able to recover.
1912       AcceptableWithoutRecovery = true;
1913     }
1914 
1915     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1916       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1917                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1918                             ? diag::note_implicit_param_decl
1919                             : diag::note_previous_decl;
1920       if (SS.isEmpty())
1921         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1922                      PDiag(NoteID), AcceptableWithRecovery);
1923       else
1924         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1925                                   << Name << computeDeclContext(SS, false)
1926                                   << DroppedSpecifier << SS.getRange(),
1927                      PDiag(NoteID), AcceptableWithRecovery);
1928 
1929       // Tell the callee whether to try to recover.
1930       return !AcceptableWithRecovery;
1931     }
1932   }
1933   R.clear();
1934 
1935   // Emit a special diagnostic for failed member lookups.
1936   // FIXME: computing the declaration context might fail here (?)
1937   if (!SS.isEmpty()) {
1938     Diag(R.getNameLoc(), diag::err_no_member)
1939       << Name << computeDeclContext(SS, false)
1940       << SS.getRange();
1941     return true;
1942   }
1943 
1944   // Give up, we can't recover.
1945   Diag(R.getNameLoc(), diagnostic) << Name;
1946   return true;
1947 }
1948 
1949 /// In Microsoft mode, if we are inside a template class whose parent class has
1950 /// dependent base classes, and we can't resolve an unqualified identifier, then
1951 /// assume the identifier is a member of a dependent base class.  We can only
1952 /// recover successfully in static methods, instance methods, and other contexts
1953 /// where 'this' is available.  This doesn't precisely match MSVC's
1954 /// instantiation model, but it's close enough.
1955 static Expr *
1956 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1957                                DeclarationNameInfo &NameInfo,
1958                                SourceLocation TemplateKWLoc,
1959                                const TemplateArgumentListInfo *TemplateArgs) {
1960   // Only try to recover from lookup into dependent bases in static methods or
1961   // contexts where 'this' is available.
1962   QualType ThisType = S.getCurrentThisType();
1963   const CXXRecordDecl *RD = nullptr;
1964   if (!ThisType.isNull())
1965     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1966   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1967     RD = MD->getParent();
1968   if (!RD || !RD->hasAnyDependentBases())
1969     return nullptr;
1970 
1971   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1972   // is available, suggest inserting 'this->' as a fixit.
1973   SourceLocation Loc = NameInfo.getLoc();
1974   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1975   DB << NameInfo.getName() << RD;
1976 
1977   if (!ThisType.isNull()) {
1978     DB << FixItHint::CreateInsertion(Loc, "this->");
1979     return CXXDependentScopeMemberExpr::Create(
1980         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1981         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1982         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1983   }
1984 
1985   // Synthesize a fake NNS that points to the derived class.  This will
1986   // perform name lookup during template instantiation.
1987   CXXScopeSpec SS;
1988   auto *NNS =
1989       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1990   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1991   return DependentScopeDeclRefExpr::Create(
1992       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1993       TemplateArgs);
1994 }
1995 
1996 ExprResult
1997 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
1998                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
1999                         bool HasTrailingLParen, bool IsAddressOfOperand,
2000                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2001                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2002   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2003          "cannot be direct & operand and have a trailing lparen");
2004   if (SS.isInvalid())
2005     return ExprError();
2006 
2007   TemplateArgumentListInfo TemplateArgsBuffer;
2008 
2009   // Decompose the UnqualifiedId into the following data.
2010   DeclarationNameInfo NameInfo;
2011   const TemplateArgumentListInfo *TemplateArgs;
2012   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2013 
2014   DeclarationName Name = NameInfo.getName();
2015   IdentifierInfo *II = Name.getAsIdentifierInfo();
2016   SourceLocation NameLoc = NameInfo.getLoc();
2017 
2018   // C++ [temp.dep.expr]p3:
2019   //   An id-expression is type-dependent if it contains:
2020   //     -- an identifier that was declared with a dependent type,
2021   //        (note: handled after lookup)
2022   //     -- a template-id that is dependent,
2023   //        (note: handled in BuildTemplateIdExpr)
2024   //     -- a conversion-function-id that specifies a dependent type,
2025   //     -- a nested-name-specifier that contains a class-name that
2026   //        names a dependent type.
2027   // Determine whether this is a member of an unknown specialization;
2028   // we need to handle these differently.
2029   bool DependentID = false;
2030   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2031       Name.getCXXNameType()->isDependentType()) {
2032     DependentID = true;
2033   } else if (SS.isSet()) {
2034     if (DeclContext *DC = computeDeclContext(SS, false)) {
2035       if (RequireCompleteDeclContext(SS, DC))
2036         return ExprError();
2037     } else {
2038       DependentID = true;
2039     }
2040   }
2041 
2042   if (DependentID)
2043     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2044                                       IsAddressOfOperand, TemplateArgs);
2045 
2046   // Perform the required lookup.
2047   LookupResult R(*this, NameInfo,
2048                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2049                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2050   if (TemplateArgs) {
2051     // Lookup the template name again to correctly establish the context in
2052     // which it was found. This is really unfortunate as we already did the
2053     // lookup to determine that it was a template name in the first place. If
2054     // this becomes a performance hit, we can work harder to preserve those
2055     // results until we get here but it's likely not worth it.
2056     bool MemberOfUnknownSpecialization;
2057     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2058                        MemberOfUnknownSpecialization);
2059 
2060     if (MemberOfUnknownSpecialization ||
2061         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2062       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2063                                         IsAddressOfOperand, TemplateArgs);
2064   } else {
2065     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2066     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2067 
2068     // If the result might be in a dependent base class, this is a dependent
2069     // id-expression.
2070     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2071       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2072                                         IsAddressOfOperand, TemplateArgs);
2073 
2074     // If this reference is in an Objective-C method, then we need to do
2075     // some special Objective-C lookup, too.
2076     if (IvarLookupFollowUp) {
2077       ExprResult E(LookupInObjCMethod(R, S, II, true));
2078       if (E.isInvalid())
2079         return ExprError();
2080 
2081       if (Expr *Ex = E.getAs<Expr>())
2082         return Ex;
2083     }
2084   }
2085 
2086   if (R.isAmbiguous())
2087     return ExprError();
2088 
2089   // This could be an implicitly declared function reference (legal in C90,
2090   // extension in C99, forbidden in C++).
2091   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2092     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2093     if (D) R.addDecl(D);
2094   }
2095 
2096   // Determine whether this name might be a candidate for
2097   // argument-dependent lookup.
2098   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2099 
2100   if (R.empty() && !ADL) {
2101     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2102       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2103                                                    TemplateKWLoc, TemplateArgs))
2104         return E;
2105     }
2106 
2107     // Don't diagnose an empty lookup for inline assembly.
2108     if (IsInlineAsmIdentifier)
2109       return ExprError();
2110 
2111     // If this name wasn't predeclared and if this is not a function
2112     // call, diagnose the problem.
2113     TypoExpr *TE = nullptr;
2114     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2115         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2116     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2117     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2118            "Typo correction callback misconfigured");
2119     if (CCC) {
2120       // Make sure the callback knows what the typo being diagnosed is.
2121       CCC->setTypoName(II);
2122       if (SS.isValid())
2123         CCC->setTypoNNS(SS.getScopeRep());
2124     }
2125     if (DiagnoseEmptyLookup(
2126             S, SS, R, CCC ? std::move(CCC) : std::move(DefaultValidator),
2127             nullptr, None, getLangOpts().CPlusPlus ? &TE : nullptr)) {
2128       if (TE && KeywordReplacement) {
2129         auto &State = getTypoExprState(TE);
2130         auto BestTC = State.Consumer->getNextCorrection();
2131         if (BestTC.isKeyword()) {
2132           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2133           if (State.DiagHandler)
2134             State.DiagHandler(BestTC);
2135           KeywordReplacement->startToken();
2136           KeywordReplacement->setKind(II->getTokenID());
2137           KeywordReplacement->setIdentifierInfo(II);
2138           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2139           // Clean up the state associated with the TypoExpr, since it has
2140           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2141           clearDelayedTypo(TE);
2142           // Signal that a correction to a keyword was performed by returning a
2143           // valid-but-null ExprResult.
2144           return (Expr*)nullptr;
2145         }
2146         State.Consumer->resetCorrectionStream();
2147       }
2148       return TE ? TE : ExprError();
2149     }
2150 
2151     assert(!R.empty() &&
2152            "DiagnoseEmptyLookup returned false but added no results");
2153 
2154     // If we found an Objective-C instance variable, let
2155     // LookupInObjCMethod build the appropriate expression to
2156     // reference the ivar.
2157     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2158       R.clear();
2159       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2160       // In a hopelessly buggy code, Objective-C instance variable
2161       // lookup fails and no expression will be built to reference it.
2162       if (!E.isInvalid() && !E.get())
2163         return ExprError();
2164       return E;
2165     }
2166   }
2167 
2168   // This is guaranteed from this point on.
2169   assert(!R.empty() || ADL);
2170 
2171   // Check whether this might be a C++ implicit instance member access.
2172   // C++ [class.mfct.non-static]p3:
2173   //   When an id-expression that is not part of a class member access
2174   //   syntax and not used to form a pointer to member is used in the
2175   //   body of a non-static member function of class X, if name lookup
2176   //   resolves the name in the id-expression to a non-static non-type
2177   //   member of some class C, the id-expression is transformed into a
2178   //   class member access expression using (*this) as the
2179   //   postfix-expression to the left of the . operator.
2180   //
2181   // But we don't actually need to do this for '&' operands if R
2182   // resolved to a function or overloaded function set, because the
2183   // expression is ill-formed if it actually works out to be a
2184   // non-static member function:
2185   //
2186   // C++ [expr.ref]p4:
2187   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2188   //   [t]he expression can be used only as the left-hand operand of a
2189   //   member function call.
2190   //
2191   // There are other safeguards against such uses, but it's important
2192   // to get this right here so that we don't end up making a
2193   // spuriously dependent expression if we're inside a dependent
2194   // instance method.
2195   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2196     bool MightBeImplicitMember;
2197     if (!IsAddressOfOperand)
2198       MightBeImplicitMember = true;
2199     else if (!SS.isEmpty())
2200       MightBeImplicitMember = false;
2201     else if (R.isOverloadedResult())
2202       MightBeImplicitMember = false;
2203     else if (R.isUnresolvableResult())
2204       MightBeImplicitMember = true;
2205     else
2206       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2207                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2208                               isa<MSPropertyDecl>(R.getFoundDecl());
2209 
2210     if (MightBeImplicitMember)
2211       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2212                                              R, TemplateArgs);
2213   }
2214 
2215   if (TemplateArgs || TemplateKWLoc.isValid()) {
2216 
2217     // In C++1y, if this is a variable template id, then check it
2218     // in BuildTemplateIdExpr().
2219     // The single lookup result must be a variable template declaration.
2220     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2221         Id.TemplateId->Kind == TNK_Var_template) {
2222       assert(R.getAsSingle<VarTemplateDecl>() &&
2223              "There should only be one declaration found.");
2224     }
2225 
2226     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2227   }
2228 
2229   return BuildDeclarationNameExpr(SS, R, ADL);
2230 }
2231 
2232 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2233 /// declaration name, generally during template instantiation.
2234 /// There's a large number of things which don't need to be done along
2235 /// this path.
2236 ExprResult
2237 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2238                                         const DeclarationNameInfo &NameInfo,
2239                                         bool IsAddressOfOperand,
2240                                         TypeSourceInfo **RecoveryTSI) {
2241   DeclContext *DC = computeDeclContext(SS, false);
2242   if (!DC)
2243     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2244                                      NameInfo, /*TemplateArgs=*/nullptr);
2245 
2246   if (RequireCompleteDeclContext(SS, DC))
2247     return ExprError();
2248 
2249   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2250   LookupQualifiedName(R, DC);
2251 
2252   if (R.isAmbiguous())
2253     return ExprError();
2254 
2255   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2256     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2257                                      NameInfo, /*TemplateArgs=*/nullptr);
2258 
2259   if (R.empty()) {
2260     Diag(NameInfo.getLoc(), diag::err_no_member)
2261       << NameInfo.getName() << DC << SS.getRange();
2262     return ExprError();
2263   }
2264 
2265   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2266     // Diagnose a missing typename if this resolved unambiguously to a type in
2267     // a dependent context.  If we can recover with a type, downgrade this to
2268     // a warning in Microsoft compatibility mode.
2269     unsigned DiagID = diag::err_typename_missing;
2270     if (RecoveryTSI && getLangOpts().MSVCCompat)
2271       DiagID = diag::ext_typename_missing;
2272     SourceLocation Loc = SS.getBeginLoc();
2273     auto D = Diag(Loc, DiagID);
2274     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2275       << SourceRange(Loc, NameInfo.getEndLoc());
2276 
2277     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2278     // context.
2279     if (!RecoveryTSI)
2280       return ExprError();
2281 
2282     // Only issue the fixit if we're prepared to recover.
2283     D << FixItHint::CreateInsertion(Loc, "typename ");
2284 
2285     // Recover by pretending this was an elaborated type.
2286     QualType Ty = Context.getTypeDeclType(TD);
2287     TypeLocBuilder TLB;
2288     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2289 
2290     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2291     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2292     QTL.setElaboratedKeywordLoc(SourceLocation());
2293     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2294 
2295     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2296 
2297     return ExprEmpty();
2298   }
2299 
2300   // Defend against this resolving to an implicit member access. We usually
2301   // won't get here if this might be a legitimate a class member (we end up in
2302   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2303   // a pointer-to-member or in an unevaluated context in C++11.
2304   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2305     return BuildPossibleImplicitMemberExpr(SS,
2306                                            /*TemplateKWLoc=*/SourceLocation(),
2307                                            R, /*TemplateArgs=*/nullptr);
2308 
2309   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2310 }
2311 
2312 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2313 /// detected that we're currently inside an ObjC method.  Perform some
2314 /// additional lookup.
2315 ///
2316 /// Ideally, most of this would be done by lookup, but there's
2317 /// actually quite a lot of extra work involved.
2318 ///
2319 /// Returns a null sentinel to indicate trivial success.
2320 ExprResult
2321 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2322                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2323   SourceLocation Loc = Lookup.getNameLoc();
2324   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2325 
2326   // Check for error condition which is already reported.
2327   if (!CurMethod)
2328     return ExprError();
2329 
2330   // There are two cases to handle here.  1) scoped lookup could have failed,
2331   // in which case we should look for an ivar.  2) scoped lookup could have
2332   // found a decl, but that decl is outside the current instance method (i.e.
2333   // a global variable).  In these two cases, we do a lookup for an ivar with
2334   // this name, if the lookup sucedes, we replace it our current decl.
2335 
2336   // If we're in a class method, we don't normally want to look for
2337   // ivars.  But if we don't find anything else, and there's an
2338   // ivar, that's an error.
2339   bool IsClassMethod = CurMethod->isClassMethod();
2340 
2341   bool LookForIvars;
2342   if (Lookup.empty())
2343     LookForIvars = true;
2344   else if (IsClassMethod)
2345     LookForIvars = false;
2346   else
2347     LookForIvars = (Lookup.isSingleResult() &&
2348                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2349   ObjCInterfaceDecl *IFace = nullptr;
2350   if (LookForIvars) {
2351     IFace = CurMethod->getClassInterface();
2352     ObjCInterfaceDecl *ClassDeclared;
2353     ObjCIvarDecl *IV = nullptr;
2354     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2355       // Diagnose using an ivar in a class method.
2356       if (IsClassMethod)
2357         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2358                          << IV->getDeclName());
2359 
2360       // If we're referencing an invalid decl, just return this as a silent
2361       // error node.  The error diagnostic was already emitted on the decl.
2362       if (IV->isInvalidDecl())
2363         return ExprError();
2364 
2365       // Check if referencing a field with __attribute__((deprecated)).
2366       if (DiagnoseUseOfDecl(IV, Loc))
2367         return ExprError();
2368 
2369       // Diagnose the use of an ivar outside of the declaring class.
2370       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2371           !declaresSameEntity(ClassDeclared, IFace) &&
2372           !getLangOpts().DebuggerSupport)
2373         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2374 
2375       // FIXME: This should use a new expr for a direct reference, don't
2376       // turn this into Self->ivar, just return a BareIVarExpr or something.
2377       IdentifierInfo &II = Context.Idents.get("self");
2378       UnqualifiedId SelfName;
2379       SelfName.setIdentifier(&II, SourceLocation());
2380       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2381       CXXScopeSpec SelfScopeSpec;
2382       SourceLocation TemplateKWLoc;
2383       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2384                                               SelfName, false, false);
2385       if (SelfExpr.isInvalid())
2386         return ExprError();
2387 
2388       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2389       if (SelfExpr.isInvalid())
2390         return ExprError();
2391 
2392       MarkAnyDeclReferenced(Loc, IV, true);
2393 
2394       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2395       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2396           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2397         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2398 
2399       ObjCIvarRefExpr *Result = new (Context)
2400           ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
2401                           SelfExpr.get(), true, true);
2402 
2403       if (getLangOpts().ObjCAutoRefCount) {
2404         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2405           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2406             recordUseOfEvaluatedWeak(Result);
2407         }
2408         if (CurContext->isClosure())
2409           Diag(Loc, diag::warn_implicitly_retains_self)
2410             << FixItHint::CreateInsertion(Loc, "self->");
2411       }
2412 
2413       return Result;
2414     }
2415   } else if (CurMethod->isInstanceMethod()) {
2416     // We should warn if a local variable hides an ivar.
2417     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2418       ObjCInterfaceDecl *ClassDeclared;
2419       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2420         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2421             declaresSameEntity(IFace, ClassDeclared))
2422           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2423       }
2424     }
2425   } else if (Lookup.isSingleResult() &&
2426              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2427     // If accessing a stand-alone ivar in a class method, this is an error.
2428     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2429       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2430                        << IV->getDeclName());
2431   }
2432 
2433   if (Lookup.empty() && II && AllowBuiltinCreation) {
2434     // FIXME. Consolidate this with similar code in LookupName.
2435     if (unsigned BuiltinID = II->getBuiltinID()) {
2436       if (!(getLangOpts().CPlusPlus &&
2437             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2438         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2439                                            S, Lookup.isForRedeclaration(),
2440                                            Lookup.getNameLoc());
2441         if (D) Lookup.addDecl(D);
2442       }
2443     }
2444   }
2445   // Sentinel value saying that we didn't do anything special.
2446   return ExprResult((Expr *)nullptr);
2447 }
2448 
2449 /// \brief Cast a base object to a member's actual type.
2450 ///
2451 /// Logically this happens in three phases:
2452 ///
2453 /// * First we cast from the base type to the naming class.
2454 ///   The naming class is the class into which we were looking
2455 ///   when we found the member;  it's the qualifier type if a
2456 ///   qualifier was provided, and otherwise it's the base type.
2457 ///
2458 /// * Next we cast from the naming class to the declaring class.
2459 ///   If the member we found was brought into a class's scope by
2460 ///   a using declaration, this is that class;  otherwise it's
2461 ///   the class declaring the member.
2462 ///
2463 /// * Finally we cast from the declaring class to the "true"
2464 ///   declaring class of the member.  This conversion does not
2465 ///   obey access control.
2466 ExprResult
2467 Sema::PerformObjectMemberConversion(Expr *From,
2468                                     NestedNameSpecifier *Qualifier,
2469                                     NamedDecl *FoundDecl,
2470                                     NamedDecl *Member) {
2471   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2472   if (!RD)
2473     return From;
2474 
2475   QualType DestRecordType;
2476   QualType DestType;
2477   QualType FromRecordType;
2478   QualType FromType = From->getType();
2479   bool PointerConversions = false;
2480   if (isa<FieldDecl>(Member)) {
2481     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2482 
2483     if (FromType->getAs<PointerType>()) {
2484       DestType = Context.getPointerType(DestRecordType);
2485       FromRecordType = FromType->getPointeeType();
2486       PointerConversions = true;
2487     } else {
2488       DestType = DestRecordType;
2489       FromRecordType = FromType;
2490     }
2491   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2492     if (Method->isStatic())
2493       return From;
2494 
2495     DestType = Method->getThisType(Context);
2496     DestRecordType = DestType->getPointeeType();
2497 
2498     if (FromType->getAs<PointerType>()) {
2499       FromRecordType = FromType->getPointeeType();
2500       PointerConversions = true;
2501     } else {
2502       FromRecordType = FromType;
2503       DestType = DestRecordType;
2504     }
2505   } else {
2506     // No conversion necessary.
2507     return From;
2508   }
2509 
2510   if (DestType->isDependentType() || FromType->isDependentType())
2511     return From;
2512 
2513   // If the unqualified types are the same, no conversion is necessary.
2514   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2515     return From;
2516 
2517   SourceRange FromRange = From->getSourceRange();
2518   SourceLocation FromLoc = FromRange.getBegin();
2519 
2520   ExprValueKind VK = From->getValueKind();
2521 
2522   // C++ [class.member.lookup]p8:
2523   //   [...] Ambiguities can often be resolved by qualifying a name with its
2524   //   class name.
2525   //
2526   // If the member was a qualified name and the qualified referred to a
2527   // specific base subobject type, we'll cast to that intermediate type
2528   // first and then to the object in which the member is declared. That allows
2529   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2530   //
2531   //   class Base { public: int x; };
2532   //   class Derived1 : public Base { };
2533   //   class Derived2 : public Base { };
2534   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2535   //
2536   //   void VeryDerived::f() {
2537   //     x = 17; // error: ambiguous base subobjects
2538   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2539   //   }
2540   if (Qualifier && Qualifier->getAsType()) {
2541     QualType QType = QualType(Qualifier->getAsType(), 0);
2542     assert(QType->isRecordType() && "lookup done with non-record type");
2543 
2544     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2545 
2546     // In C++98, the qualifier type doesn't actually have to be a base
2547     // type of the object type, in which case we just ignore it.
2548     // Otherwise build the appropriate casts.
2549     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2550       CXXCastPath BasePath;
2551       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2552                                        FromLoc, FromRange, &BasePath))
2553         return ExprError();
2554 
2555       if (PointerConversions)
2556         QType = Context.getPointerType(QType);
2557       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2558                                VK, &BasePath).get();
2559 
2560       FromType = QType;
2561       FromRecordType = QRecordType;
2562 
2563       // If the qualifier type was the same as the destination type,
2564       // we're done.
2565       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2566         return From;
2567     }
2568   }
2569 
2570   bool IgnoreAccess = false;
2571 
2572   // If we actually found the member through a using declaration, cast
2573   // down to the using declaration's type.
2574   //
2575   // Pointer equality is fine here because only one declaration of a
2576   // class ever has member declarations.
2577   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2578     assert(isa<UsingShadowDecl>(FoundDecl));
2579     QualType URecordType = Context.getTypeDeclType(
2580                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2581 
2582     // We only need to do this if the naming-class to declaring-class
2583     // conversion is non-trivial.
2584     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2585       assert(IsDerivedFrom(FromRecordType, URecordType));
2586       CXXCastPath BasePath;
2587       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2588                                        FromLoc, FromRange, &BasePath))
2589         return ExprError();
2590 
2591       QualType UType = URecordType;
2592       if (PointerConversions)
2593         UType = Context.getPointerType(UType);
2594       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2595                                VK, &BasePath).get();
2596       FromType = UType;
2597       FromRecordType = URecordType;
2598     }
2599 
2600     // We don't do access control for the conversion from the
2601     // declaring class to the true declaring class.
2602     IgnoreAccess = true;
2603   }
2604 
2605   CXXCastPath BasePath;
2606   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2607                                    FromLoc, FromRange, &BasePath,
2608                                    IgnoreAccess))
2609     return ExprError();
2610 
2611   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2612                            VK, &BasePath);
2613 }
2614 
2615 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2616                                       const LookupResult &R,
2617                                       bool HasTrailingLParen) {
2618   // Only when used directly as the postfix-expression of a call.
2619   if (!HasTrailingLParen)
2620     return false;
2621 
2622   // Never if a scope specifier was provided.
2623   if (SS.isSet())
2624     return false;
2625 
2626   // Only in C++ or ObjC++.
2627   if (!getLangOpts().CPlusPlus)
2628     return false;
2629 
2630   // Turn off ADL when we find certain kinds of declarations during
2631   // normal lookup:
2632   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2633     NamedDecl *D = *I;
2634 
2635     // C++0x [basic.lookup.argdep]p3:
2636     //     -- a declaration of a class member
2637     // Since using decls preserve this property, we check this on the
2638     // original decl.
2639     if (D->isCXXClassMember())
2640       return false;
2641 
2642     // C++0x [basic.lookup.argdep]p3:
2643     //     -- a block-scope function declaration that is not a
2644     //        using-declaration
2645     // NOTE: we also trigger this for function templates (in fact, we
2646     // don't check the decl type at all, since all other decl types
2647     // turn off ADL anyway).
2648     if (isa<UsingShadowDecl>(D))
2649       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2650     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2651       return false;
2652 
2653     // C++0x [basic.lookup.argdep]p3:
2654     //     -- a declaration that is neither a function or a function
2655     //        template
2656     // And also for builtin functions.
2657     if (isa<FunctionDecl>(D)) {
2658       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2659 
2660       // But also builtin functions.
2661       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2662         return false;
2663     } else if (!isa<FunctionTemplateDecl>(D))
2664       return false;
2665   }
2666 
2667   return true;
2668 }
2669 
2670 
2671 /// Diagnoses obvious problems with the use of the given declaration
2672 /// as an expression.  This is only actually called for lookups that
2673 /// were not overloaded, and it doesn't promise that the declaration
2674 /// will in fact be used.
2675 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2676   if (isa<TypedefNameDecl>(D)) {
2677     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2678     return true;
2679   }
2680 
2681   if (isa<ObjCInterfaceDecl>(D)) {
2682     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2683     return true;
2684   }
2685 
2686   if (isa<NamespaceDecl>(D)) {
2687     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2688     return true;
2689   }
2690 
2691   return false;
2692 }
2693 
2694 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2695                                           LookupResult &R, bool NeedsADL,
2696                                           bool AcceptInvalidDecl) {
2697   // If this is a single, fully-resolved result and we don't need ADL,
2698   // just build an ordinary singleton decl ref.
2699   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2700     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2701                                     R.getRepresentativeDecl(), nullptr,
2702                                     AcceptInvalidDecl);
2703 
2704   // We only need to check the declaration if there's exactly one
2705   // result, because in the overloaded case the results can only be
2706   // functions and function templates.
2707   if (R.isSingleResult() &&
2708       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2709     return ExprError();
2710 
2711   // Otherwise, just build an unresolved lookup expression.  Suppress
2712   // any lookup-related diagnostics; we'll hash these out later, when
2713   // we've picked a target.
2714   R.suppressDiagnostics();
2715 
2716   UnresolvedLookupExpr *ULE
2717     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2718                                    SS.getWithLocInContext(Context),
2719                                    R.getLookupNameInfo(),
2720                                    NeedsADL, R.isOverloadedResult(),
2721                                    R.begin(), R.end());
2722 
2723   return ULE;
2724 }
2725 
2726 /// \brief Complete semantic analysis for a reference to the given declaration.
2727 ExprResult Sema::BuildDeclarationNameExpr(
2728     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2729     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2730     bool AcceptInvalidDecl) {
2731   assert(D && "Cannot refer to a NULL declaration");
2732   assert(!isa<FunctionTemplateDecl>(D) &&
2733          "Cannot refer unambiguously to a function template");
2734 
2735   SourceLocation Loc = NameInfo.getLoc();
2736   if (CheckDeclInExpr(*this, Loc, D))
2737     return ExprError();
2738 
2739   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2740     // Specifically diagnose references to class templates that are missing
2741     // a template argument list.
2742     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2743                                            << Template << SS.getRange();
2744     Diag(Template->getLocation(), diag::note_template_decl_here);
2745     return ExprError();
2746   }
2747 
2748   // Make sure that we're referring to a value.
2749   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2750   if (!VD) {
2751     Diag(Loc, diag::err_ref_non_value)
2752       << D << SS.getRange();
2753     Diag(D->getLocation(), diag::note_declared_at);
2754     return ExprError();
2755   }
2756 
2757   // Check whether this declaration can be used. Note that we suppress
2758   // this check when we're going to perform argument-dependent lookup
2759   // on this function name, because this might not be the function
2760   // that overload resolution actually selects.
2761   if (DiagnoseUseOfDecl(VD, Loc))
2762     return ExprError();
2763 
2764   // Only create DeclRefExpr's for valid Decl's.
2765   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2766     return ExprError();
2767 
2768   // Handle members of anonymous structs and unions.  If we got here,
2769   // and the reference is to a class member indirect field, then this
2770   // must be the subject of a pointer-to-member expression.
2771   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2772     if (!indirectField->isCXXClassMember())
2773       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2774                                                       indirectField);
2775 
2776   {
2777     QualType type = VD->getType();
2778     ExprValueKind valueKind = VK_RValue;
2779 
2780     switch (D->getKind()) {
2781     // Ignore all the non-ValueDecl kinds.
2782 #define ABSTRACT_DECL(kind)
2783 #define VALUE(type, base)
2784 #define DECL(type, base) \
2785     case Decl::type:
2786 #include "clang/AST/DeclNodes.inc"
2787       llvm_unreachable("invalid value decl kind");
2788 
2789     // These shouldn't make it here.
2790     case Decl::ObjCAtDefsField:
2791     case Decl::ObjCIvar:
2792       llvm_unreachable("forming non-member reference to ivar?");
2793 
2794     // Enum constants are always r-values and never references.
2795     // Unresolved using declarations are dependent.
2796     case Decl::EnumConstant:
2797     case Decl::UnresolvedUsingValue:
2798       valueKind = VK_RValue;
2799       break;
2800 
2801     // Fields and indirect fields that got here must be for
2802     // pointer-to-member expressions; we just call them l-values for
2803     // internal consistency, because this subexpression doesn't really
2804     // exist in the high-level semantics.
2805     case Decl::Field:
2806     case Decl::IndirectField:
2807       assert(getLangOpts().CPlusPlus &&
2808              "building reference to field in C?");
2809 
2810       // These can't have reference type in well-formed programs, but
2811       // for internal consistency we do this anyway.
2812       type = type.getNonReferenceType();
2813       valueKind = VK_LValue;
2814       break;
2815 
2816     // Non-type template parameters are either l-values or r-values
2817     // depending on the type.
2818     case Decl::NonTypeTemplateParm: {
2819       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2820         type = reftype->getPointeeType();
2821         valueKind = VK_LValue; // even if the parameter is an r-value reference
2822         break;
2823       }
2824 
2825       // For non-references, we need to strip qualifiers just in case
2826       // the template parameter was declared as 'const int' or whatever.
2827       valueKind = VK_RValue;
2828       type = type.getUnqualifiedType();
2829       break;
2830     }
2831 
2832     case Decl::Var:
2833     case Decl::VarTemplateSpecialization:
2834     case Decl::VarTemplatePartialSpecialization:
2835       // In C, "extern void blah;" is valid and is an r-value.
2836       if (!getLangOpts().CPlusPlus &&
2837           !type.hasQualifiers() &&
2838           type->isVoidType()) {
2839         valueKind = VK_RValue;
2840         break;
2841       }
2842       // fallthrough
2843 
2844     case Decl::ImplicitParam:
2845     case Decl::ParmVar: {
2846       // These are always l-values.
2847       valueKind = VK_LValue;
2848       type = type.getNonReferenceType();
2849 
2850       // FIXME: Does the addition of const really only apply in
2851       // potentially-evaluated contexts? Since the variable isn't actually
2852       // captured in an unevaluated context, it seems that the answer is no.
2853       if (!isUnevaluatedContext()) {
2854         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2855         if (!CapturedType.isNull())
2856           type = CapturedType;
2857       }
2858 
2859       break;
2860     }
2861 
2862     case Decl::Function: {
2863       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2864         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2865           type = Context.BuiltinFnTy;
2866           valueKind = VK_RValue;
2867           break;
2868         }
2869       }
2870 
2871       const FunctionType *fty = type->castAs<FunctionType>();
2872 
2873       // If we're referring to a function with an __unknown_anytype
2874       // result type, make the entire expression __unknown_anytype.
2875       if (fty->getReturnType() == Context.UnknownAnyTy) {
2876         type = Context.UnknownAnyTy;
2877         valueKind = VK_RValue;
2878         break;
2879       }
2880 
2881       // Functions are l-values in C++.
2882       if (getLangOpts().CPlusPlus) {
2883         valueKind = VK_LValue;
2884         break;
2885       }
2886 
2887       // C99 DR 316 says that, if a function type comes from a
2888       // function definition (without a prototype), that type is only
2889       // used for checking compatibility. Therefore, when referencing
2890       // the function, we pretend that we don't have the full function
2891       // type.
2892       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2893           isa<FunctionProtoType>(fty))
2894         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2895                                               fty->getExtInfo());
2896 
2897       // Functions are r-values in C.
2898       valueKind = VK_RValue;
2899       break;
2900     }
2901 
2902     case Decl::MSProperty:
2903       valueKind = VK_LValue;
2904       break;
2905 
2906     case Decl::CXXMethod:
2907       // If we're referring to a method with an __unknown_anytype
2908       // result type, make the entire expression __unknown_anytype.
2909       // This should only be possible with a type written directly.
2910       if (const FunctionProtoType *proto
2911             = dyn_cast<FunctionProtoType>(VD->getType()))
2912         if (proto->getReturnType() == Context.UnknownAnyTy) {
2913           type = Context.UnknownAnyTy;
2914           valueKind = VK_RValue;
2915           break;
2916         }
2917 
2918       // C++ methods are l-values if static, r-values if non-static.
2919       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2920         valueKind = VK_LValue;
2921         break;
2922       }
2923       // fallthrough
2924 
2925     case Decl::CXXConversion:
2926     case Decl::CXXDestructor:
2927     case Decl::CXXConstructor:
2928       valueKind = VK_RValue;
2929       break;
2930     }
2931 
2932     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2933                             TemplateArgs);
2934   }
2935 }
2936 
2937 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2938                                     SmallString<32> &Target) {
2939   Target.resize(CharByteWidth * (Source.size() + 1));
2940   char *ResultPtr = &Target[0];
2941   const UTF8 *ErrorPtr;
2942   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2943   (void)success;
2944   assert(success);
2945   Target.resize(ResultPtr - &Target[0]);
2946 }
2947 
2948 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2949                                      PredefinedExpr::IdentType IT) {
2950   // Pick the current block, lambda, captured statement or function.
2951   Decl *currentDecl = nullptr;
2952   if (const BlockScopeInfo *BSI = getCurBlock())
2953     currentDecl = BSI->TheDecl;
2954   else if (const LambdaScopeInfo *LSI = getCurLambda())
2955     currentDecl = LSI->CallOperator;
2956   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2957     currentDecl = CSI->TheCapturedDecl;
2958   else
2959     currentDecl = getCurFunctionOrMethodDecl();
2960 
2961   if (!currentDecl) {
2962     Diag(Loc, diag::ext_predef_outside_function);
2963     currentDecl = Context.getTranslationUnitDecl();
2964   }
2965 
2966   QualType ResTy;
2967   StringLiteral *SL = nullptr;
2968   if (cast<DeclContext>(currentDecl)->isDependentContext())
2969     ResTy = Context.DependentTy;
2970   else {
2971     // Pre-defined identifiers are of type char[x], where x is the length of
2972     // the string.
2973     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
2974     unsigned Length = Str.length();
2975 
2976     llvm::APInt LengthI(32, Length + 1);
2977     if (IT == PredefinedExpr::LFunction) {
2978       ResTy = Context.WideCharTy.withConst();
2979       SmallString<32> RawChars;
2980       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
2981                               Str, RawChars);
2982       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
2983                                            /*IndexTypeQuals*/ 0);
2984       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
2985                                  /*Pascal*/ false, ResTy, Loc);
2986     } else {
2987       ResTy = Context.CharTy.withConst();
2988       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
2989                                            /*IndexTypeQuals*/ 0);
2990       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
2991                                  /*Pascal*/ false, ResTy, Loc);
2992     }
2993   }
2994 
2995   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
2996 }
2997 
2998 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2999   PredefinedExpr::IdentType IT;
3000 
3001   switch (Kind) {
3002   default: llvm_unreachable("Unknown simple primary expr!");
3003   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3004   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3005   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3006   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3007   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3008   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3009   }
3010 
3011   return BuildPredefinedExpr(Loc, IT);
3012 }
3013 
3014 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3015   SmallString<16> CharBuffer;
3016   bool Invalid = false;
3017   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3018   if (Invalid)
3019     return ExprError();
3020 
3021   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3022                             PP, Tok.getKind());
3023   if (Literal.hadError())
3024     return ExprError();
3025 
3026   QualType Ty;
3027   if (Literal.isWide())
3028     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3029   else if (Literal.isUTF16())
3030     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3031   else if (Literal.isUTF32())
3032     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3033   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3034     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3035   else
3036     Ty = Context.CharTy;  // 'x' -> char in C++
3037 
3038   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3039   if (Literal.isWide())
3040     Kind = CharacterLiteral::Wide;
3041   else if (Literal.isUTF16())
3042     Kind = CharacterLiteral::UTF16;
3043   else if (Literal.isUTF32())
3044     Kind = CharacterLiteral::UTF32;
3045 
3046   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3047                                              Tok.getLocation());
3048 
3049   if (Literal.getUDSuffix().empty())
3050     return Lit;
3051 
3052   // We're building a user-defined literal.
3053   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3054   SourceLocation UDSuffixLoc =
3055     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3056 
3057   // Make sure we're allowed user-defined literals here.
3058   if (!UDLScope)
3059     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3060 
3061   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3062   //   operator "" X (ch)
3063   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3064                                         Lit, Tok.getLocation());
3065 }
3066 
3067 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3068   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3069   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3070                                 Context.IntTy, Loc);
3071 }
3072 
3073 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3074                                   QualType Ty, SourceLocation Loc) {
3075   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3076 
3077   using llvm::APFloat;
3078   APFloat Val(Format);
3079 
3080   APFloat::opStatus result = Literal.GetFloatValue(Val);
3081 
3082   // Overflow is always an error, but underflow is only an error if
3083   // we underflowed to zero (APFloat reports denormals as underflow).
3084   if ((result & APFloat::opOverflow) ||
3085       ((result & APFloat::opUnderflow) && Val.isZero())) {
3086     unsigned diagnostic;
3087     SmallString<20> buffer;
3088     if (result & APFloat::opOverflow) {
3089       diagnostic = diag::warn_float_overflow;
3090       APFloat::getLargest(Format).toString(buffer);
3091     } else {
3092       diagnostic = diag::warn_float_underflow;
3093       APFloat::getSmallest(Format).toString(buffer);
3094     }
3095 
3096     S.Diag(Loc, diagnostic)
3097       << Ty
3098       << StringRef(buffer.data(), buffer.size());
3099   }
3100 
3101   bool isExact = (result == APFloat::opOK);
3102   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3103 }
3104 
3105 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3106   assert(E && "Invalid expression");
3107 
3108   if (E->isValueDependent())
3109     return false;
3110 
3111   QualType QT = E->getType();
3112   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3113     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3114     return true;
3115   }
3116 
3117   llvm::APSInt ValueAPS;
3118   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3119 
3120   if (R.isInvalid())
3121     return true;
3122 
3123   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3124   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3125     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3126         << ValueAPS.toString(10) << ValueIsPositive;
3127     return true;
3128   }
3129 
3130   return false;
3131 }
3132 
3133 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3134   // Fast path for a single digit (which is quite common).  A single digit
3135   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3136   if (Tok.getLength() == 1) {
3137     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3138     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3139   }
3140 
3141   SmallString<128> SpellingBuffer;
3142   // NumericLiteralParser wants to overread by one character.  Add padding to
3143   // the buffer in case the token is copied to the buffer.  If getSpelling()
3144   // returns a StringRef to the memory buffer, it should have a null char at
3145   // the EOF, so it is also safe.
3146   SpellingBuffer.resize(Tok.getLength() + 1);
3147 
3148   // Get the spelling of the token, which eliminates trigraphs, etc.
3149   bool Invalid = false;
3150   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3151   if (Invalid)
3152     return ExprError();
3153 
3154   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3155   if (Literal.hadError)
3156     return ExprError();
3157 
3158   if (Literal.hasUDSuffix()) {
3159     // We're building a user-defined literal.
3160     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3161     SourceLocation UDSuffixLoc =
3162       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3163 
3164     // Make sure we're allowed user-defined literals here.
3165     if (!UDLScope)
3166       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3167 
3168     QualType CookedTy;
3169     if (Literal.isFloatingLiteral()) {
3170       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3171       // long double, the literal is treated as a call of the form
3172       //   operator "" X (f L)
3173       CookedTy = Context.LongDoubleTy;
3174     } else {
3175       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3176       // unsigned long long, the literal is treated as a call of the form
3177       //   operator "" X (n ULL)
3178       CookedTy = Context.UnsignedLongLongTy;
3179     }
3180 
3181     DeclarationName OpName =
3182       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3183     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3184     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3185 
3186     SourceLocation TokLoc = Tok.getLocation();
3187 
3188     // Perform literal operator lookup to determine if we're building a raw
3189     // literal or a cooked one.
3190     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3191     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3192                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3193                                   /*AllowStringTemplate*/false)) {
3194     case LOLR_Error:
3195       return ExprError();
3196 
3197     case LOLR_Cooked: {
3198       Expr *Lit;
3199       if (Literal.isFloatingLiteral()) {
3200         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3201       } else {
3202         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3203         if (Literal.GetIntegerValue(ResultVal))
3204           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3205               << /* Unsigned */ 1;
3206         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3207                                      Tok.getLocation());
3208       }
3209       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3210     }
3211 
3212     case LOLR_Raw: {
3213       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3214       // literal is treated as a call of the form
3215       //   operator "" X ("n")
3216       unsigned Length = Literal.getUDSuffixOffset();
3217       QualType StrTy = Context.getConstantArrayType(
3218           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3219           ArrayType::Normal, 0);
3220       Expr *Lit = StringLiteral::Create(
3221           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3222           /*Pascal*/false, StrTy, &TokLoc, 1);
3223       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3224     }
3225 
3226     case LOLR_Template: {
3227       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3228       // template), L is treated as a call fo the form
3229       //   operator "" X <'c1', 'c2', ... 'ck'>()
3230       // where n is the source character sequence c1 c2 ... ck.
3231       TemplateArgumentListInfo ExplicitArgs;
3232       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3233       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3234       llvm::APSInt Value(CharBits, CharIsUnsigned);
3235       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3236         Value = TokSpelling[I];
3237         TemplateArgument Arg(Context, Value, Context.CharTy);
3238         TemplateArgumentLocInfo ArgInfo;
3239         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3240       }
3241       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3242                                       &ExplicitArgs);
3243     }
3244     case LOLR_StringTemplate:
3245       llvm_unreachable("unexpected literal operator lookup result");
3246     }
3247   }
3248 
3249   Expr *Res;
3250 
3251   if (Literal.isFloatingLiteral()) {
3252     QualType Ty;
3253     if (Literal.isFloat)
3254       Ty = Context.FloatTy;
3255     else if (!Literal.isLong)
3256       Ty = Context.DoubleTy;
3257     else
3258       Ty = Context.LongDoubleTy;
3259 
3260     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3261 
3262     if (Ty == Context.DoubleTy) {
3263       if (getLangOpts().SinglePrecisionConstants) {
3264         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3265       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3266         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3267         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3268       }
3269     }
3270   } else if (!Literal.isIntegerLiteral()) {
3271     return ExprError();
3272   } else {
3273     QualType Ty;
3274 
3275     // 'long long' is a C99 or C++11 feature.
3276     if (!getLangOpts().C99 && Literal.isLongLong) {
3277       if (getLangOpts().CPlusPlus)
3278         Diag(Tok.getLocation(),
3279              getLangOpts().CPlusPlus11 ?
3280              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3281       else
3282         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3283     }
3284 
3285     // Get the value in the widest-possible width.
3286     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3287     // The microsoft literal suffix extensions support 128-bit literals, which
3288     // may be wider than [u]intmax_t.
3289     // FIXME: Actually, they don't. We seem to have accidentally invented the
3290     //        i128 suffix.
3291     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3292         Context.getTargetInfo().hasInt128Type())
3293       MaxWidth = 128;
3294     llvm::APInt ResultVal(MaxWidth, 0);
3295 
3296     if (Literal.GetIntegerValue(ResultVal)) {
3297       // If this value didn't fit into uintmax_t, error and force to ull.
3298       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3299           << /* Unsigned */ 1;
3300       Ty = Context.UnsignedLongLongTy;
3301       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3302              "long long is not intmax_t?");
3303     } else {
3304       // If this value fits into a ULL, try to figure out what else it fits into
3305       // according to the rules of C99 6.4.4.1p5.
3306 
3307       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3308       // be an unsigned int.
3309       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3310 
3311       // Check from smallest to largest, picking the smallest type we can.
3312       unsigned Width = 0;
3313 
3314       // Microsoft specific integer suffixes are explicitly sized.
3315       if (Literal.MicrosoftInteger) {
3316         if (Literal.MicrosoftInteger > MaxWidth) {
3317           // If this target doesn't support __int128, error and force to ull.
3318           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3319           Width = MaxWidth;
3320           Ty = Context.getIntMaxType();
3321         } else {
3322           Width = Literal.MicrosoftInteger;
3323           Ty = Context.getIntTypeForBitwidth(Width,
3324                                              /*Signed=*/!Literal.isUnsigned);
3325         }
3326       }
3327 
3328       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3329         // Are int/unsigned possibilities?
3330         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3331 
3332         // Does it fit in a unsigned int?
3333         if (ResultVal.isIntN(IntSize)) {
3334           // Does it fit in a signed int?
3335           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3336             Ty = Context.IntTy;
3337           else if (AllowUnsigned)
3338             Ty = Context.UnsignedIntTy;
3339           Width = IntSize;
3340         }
3341       }
3342 
3343       // Are long/unsigned long possibilities?
3344       if (Ty.isNull() && !Literal.isLongLong) {
3345         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3346 
3347         // Does it fit in a unsigned long?
3348         if (ResultVal.isIntN(LongSize)) {
3349           // Does it fit in a signed long?
3350           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3351             Ty = Context.LongTy;
3352           else if (AllowUnsigned)
3353             Ty = Context.UnsignedLongTy;
3354           Width = LongSize;
3355         }
3356       }
3357 
3358       // Check long long if needed.
3359       if (Ty.isNull()) {
3360         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3361 
3362         // Does it fit in a unsigned long long?
3363         if (ResultVal.isIntN(LongLongSize)) {
3364           // Does it fit in a signed long long?
3365           // To be compatible with MSVC, hex integer literals ending with the
3366           // LL or i64 suffix are always signed in Microsoft mode.
3367           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3368               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3369             Ty = Context.LongLongTy;
3370           else if (AllowUnsigned)
3371             Ty = Context.UnsignedLongLongTy;
3372           Width = LongLongSize;
3373         }
3374       }
3375 
3376       // If we still couldn't decide a type, we probably have something that
3377       // does not fit in a signed long long, but has no U suffix.
3378       if (Ty.isNull()) {
3379         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3380         Ty = Context.UnsignedLongLongTy;
3381         Width = Context.getTargetInfo().getLongLongWidth();
3382       }
3383 
3384       if (ResultVal.getBitWidth() != Width)
3385         ResultVal = ResultVal.trunc(Width);
3386     }
3387     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3388   }
3389 
3390   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3391   if (Literal.isImaginary)
3392     Res = new (Context) ImaginaryLiteral(Res,
3393                                         Context.getComplexType(Res->getType()));
3394 
3395   return Res;
3396 }
3397 
3398 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3399   assert(E && "ActOnParenExpr() missing expr");
3400   return new (Context) ParenExpr(L, R, E);
3401 }
3402 
3403 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3404                                          SourceLocation Loc,
3405                                          SourceRange ArgRange) {
3406   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3407   // scalar or vector data type argument..."
3408   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3409   // type (C99 6.2.5p18) or void.
3410   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3411     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3412       << T << ArgRange;
3413     return true;
3414   }
3415 
3416   assert((T->isVoidType() || !T->isIncompleteType()) &&
3417          "Scalar types should always be complete");
3418   return false;
3419 }
3420 
3421 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3422                                            SourceLocation Loc,
3423                                            SourceRange ArgRange,
3424                                            UnaryExprOrTypeTrait TraitKind) {
3425   // Invalid types must be hard errors for SFINAE in C++.
3426   if (S.LangOpts.CPlusPlus)
3427     return true;
3428 
3429   // C99 6.5.3.4p1:
3430   if (T->isFunctionType() &&
3431       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3432     // sizeof(function)/alignof(function) is allowed as an extension.
3433     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3434       << TraitKind << ArgRange;
3435     return false;
3436   }
3437 
3438   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3439   // this is an error (OpenCL v1.1 s6.3.k)
3440   if (T->isVoidType()) {
3441     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3442                                         : diag::ext_sizeof_alignof_void_type;
3443     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3444     return false;
3445   }
3446 
3447   return true;
3448 }
3449 
3450 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3451                                              SourceLocation Loc,
3452                                              SourceRange ArgRange,
3453                                              UnaryExprOrTypeTrait TraitKind) {
3454   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3455   // runtime doesn't allow it.
3456   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3457     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3458       << T << (TraitKind == UETT_SizeOf)
3459       << ArgRange;
3460     return true;
3461   }
3462 
3463   return false;
3464 }
3465 
3466 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3467 /// pointer type is equal to T) and emit a warning if it is.
3468 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3469                                      Expr *E) {
3470   // Don't warn if the operation changed the type.
3471   if (T != E->getType())
3472     return;
3473 
3474   // Now look for array decays.
3475   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3476   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3477     return;
3478 
3479   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3480                                              << ICE->getType()
3481                                              << ICE->getSubExpr()->getType();
3482 }
3483 
3484 /// \brief Check the constraints on expression operands to unary type expression
3485 /// and type traits.
3486 ///
3487 /// Completes any types necessary and validates the constraints on the operand
3488 /// expression. The logic mostly mirrors the type-based overload, but may modify
3489 /// the expression as it completes the type for that expression through template
3490 /// instantiation, etc.
3491 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3492                                             UnaryExprOrTypeTrait ExprKind) {
3493   QualType ExprTy = E->getType();
3494   assert(!ExprTy->isReferenceType());
3495 
3496   if (ExprKind == UETT_VecStep)
3497     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3498                                         E->getSourceRange());
3499 
3500   // Whitelist some types as extensions
3501   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3502                                       E->getSourceRange(), ExprKind))
3503     return false;
3504 
3505   // 'alignof' applied to an expression only requires the base element type of
3506   // the expression to be complete. 'sizeof' requires the expression's type to
3507   // be complete (and will attempt to complete it if it's an array of unknown
3508   // bound).
3509   if (ExprKind == UETT_AlignOf) {
3510     if (RequireCompleteType(E->getExprLoc(),
3511                             Context.getBaseElementType(E->getType()),
3512                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3513                             E->getSourceRange()))
3514       return true;
3515   } else {
3516     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3517                                 ExprKind, E->getSourceRange()))
3518       return true;
3519   }
3520 
3521   // Completing the expression's type may have changed it.
3522   ExprTy = E->getType();
3523   assert(!ExprTy->isReferenceType());
3524 
3525   if (ExprTy->isFunctionType()) {
3526     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3527       << ExprKind << E->getSourceRange();
3528     return true;
3529   }
3530 
3531   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3532                                        E->getSourceRange(), ExprKind))
3533     return true;
3534 
3535   if (ExprKind == UETT_SizeOf) {
3536     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3537       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3538         QualType OType = PVD->getOriginalType();
3539         QualType Type = PVD->getType();
3540         if (Type->isPointerType() && OType->isArrayType()) {
3541           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3542             << Type << OType;
3543           Diag(PVD->getLocation(), diag::note_declared_at);
3544         }
3545       }
3546     }
3547 
3548     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3549     // decays into a pointer and returns an unintended result. This is most
3550     // likely a typo for "sizeof(array) op x".
3551     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3552       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3553                                BO->getLHS());
3554       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3555                                BO->getRHS());
3556     }
3557   }
3558 
3559   return false;
3560 }
3561 
3562 /// \brief Check the constraints on operands to unary expression and type
3563 /// traits.
3564 ///
3565 /// This will complete any types necessary, and validate the various constraints
3566 /// on those operands.
3567 ///
3568 /// The UsualUnaryConversions() function is *not* called by this routine.
3569 /// C99 6.3.2.1p[2-4] all state:
3570 ///   Except when it is the operand of the sizeof operator ...
3571 ///
3572 /// C++ [expr.sizeof]p4
3573 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3574 ///   standard conversions are not applied to the operand of sizeof.
3575 ///
3576 /// This policy is followed for all of the unary trait expressions.
3577 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3578                                             SourceLocation OpLoc,
3579                                             SourceRange ExprRange,
3580                                             UnaryExprOrTypeTrait ExprKind) {
3581   if (ExprType->isDependentType())
3582     return false;
3583 
3584   // C++ [expr.sizeof]p2:
3585   //     When applied to a reference or a reference type, the result
3586   //     is the size of the referenced type.
3587   // C++11 [expr.alignof]p3:
3588   //     When alignof is applied to a reference type, the result
3589   //     shall be the alignment of the referenced type.
3590   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3591     ExprType = Ref->getPointeeType();
3592 
3593   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3594   //   When alignof or _Alignof is applied to an array type, the result
3595   //   is the alignment of the element type.
3596   if (ExprKind == UETT_AlignOf)
3597     ExprType = Context.getBaseElementType(ExprType);
3598 
3599   if (ExprKind == UETT_VecStep)
3600     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3601 
3602   // Whitelist some types as extensions
3603   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3604                                       ExprKind))
3605     return false;
3606 
3607   if (RequireCompleteType(OpLoc, ExprType,
3608                           diag::err_sizeof_alignof_incomplete_type,
3609                           ExprKind, ExprRange))
3610     return true;
3611 
3612   if (ExprType->isFunctionType()) {
3613     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3614       << ExprKind << ExprRange;
3615     return true;
3616   }
3617 
3618   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3619                                        ExprKind))
3620     return true;
3621 
3622   return false;
3623 }
3624 
3625 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3626   E = E->IgnoreParens();
3627 
3628   // Cannot know anything else if the expression is dependent.
3629   if (E->isTypeDependent())
3630     return false;
3631 
3632   if (E->getObjectKind() == OK_BitField) {
3633     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3634        << 1 << E->getSourceRange();
3635     return true;
3636   }
3637 
3638   ValueDecl *D = nullptr;
3639   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3640     D = DRE->getDecl();
3641   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3642     D = ME->getMemberDecl();
3643   }
3644 
3645   // If it's a field, require the containing struct to have a
3646   // complete definition so that we can compute the layout.
3647   //
3648   // This can happen in C++11 onwards, either by naming the member
3649   // in a way that is not transformed into a member access expression
3650   // (in an unevaluated operand, for instance), or by naming the member
3651   // in a trailing-return-type.
3652   //
3653   // For the record, since __alignof__ on expressions is a GCC
3654   // extension, GCC seems to permit this but always gives the
3655   // nonsensical answer 0.
3656   //
3657   // We don't really need the layout here --- we could instead just
3658   // directly check for all the appropriate alignment-lowing
3659   // attributes --- but that would require duplicating a lot of
3660   // logic that just isn't worth duplicating for such a marginal
3661   // use-case.
3662   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3663     // Fast path this check, since we at least know the record has a
3664     // definition if we can find a member of it.
3665     if (!FD->getParent()->isCompleteDefinition()) {
3666       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3667         << E->getSourceRange();
3668       return true;
3669     }
3670 
3671     // Otherwise, if it's a field, and the field doesn't have
3672     // reference type, then it must have a complete type (or be a
3673     // flexible array member, which we explicitly want to
3674     // white-list anyway), which makes the following checks trivial.
3675     if (!FD->getType()->isReferenceType())
3676       return false;
3677   }
3678 
3679   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3680 }
3681 
3682 bool Sema::CheckVecStepExpr(Expr *E) {
3683   E = E->IgnoreParens();
3684 
3685   // Cannot know anything else if the expression is dependent.
3686   if (E->isTypeDependent())
3687     return false;
3688 
3689   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3690 }
3691 
3692 /// \brief Build a sizeof or alignof expression given a type operand.
3693 ExprResult
3694 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3695                                      SourceLocation OpLoc,
3696                                      UnaryExprOrTypeTrait ExprKind,
3697                                      SourceRange R) {
3698   if (!TInfo)
3699     return ExprError();
3700 
3701   QualType T = TInfo->getType();
3702 
3703   if (!T->isDependentType() &&
3704       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3705     return ExprError();
3706 
3707   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3708   return new (Context) UnaryExprOrTypeTraitExpr(
3709       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3710 }
3711 
3712 /// \brief Build a sizeof or alignof expression given an expression
3713 /// operand.
3714 ExprResult
3715 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3716                                      UnaryExprOrTypeTrait ExprKind) {
3717   ExprResult PE = CheckPlaceholderExpr(E);
3718   if (PE.isInvalid())
3719     return ExprError();
3720 
3721   E = PE.get();
3722 
3723   // Verify that the operand is valid.
3724   bool isInvalid = false;
3725   if (E->isTypeDependent()) {
3726     // Delay type-checking for type-dependent expressions.
3727   } else if (ExprKind == UETT_AlignOf) {
3728     isInvalid = CheckAlignOfExpr(*this, E);
3729   } else if (ExprKind == UETT_VecStep) {
3730     isInvalid = CheckVecStepExpr(E);
3731   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3732     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3733     isInvalid = true;
3734   } else {
3735     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3736   }
3737 
3738   if (isInvalid)
3739     return ExprError();
3740 
3741   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3742     PE = TransformToPotentiallyEvaluated(E);
3743     if (PE.isInvalid()) return ExprError();
3744     E = PE.get();
3745   }
3746 
3747   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3748   return new (Context) UnaryExprOrTypeTraitExpr(
3749       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3750 }
3751 
3752 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3753 /// expr and the same for @c alignof and @c __alignof
3754 /// Note that the ArgRange is invalid if isType is false.
3755 ExprResult
3756 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3757                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3758                                     void *TyOrEx, const SourceRange &ArgRange) {
3759   // If error parsing type, ignore.
3760   if (!TyOrEx) return ExprError();
3761 
3762   if (IsType) {
3763     TypeSourceInfo *TInfo;
3764     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3765     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3766   }
3767 
3768   Expr *ArgEx = (Expr *)TyOrEx;
3769   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3770   return Result;
3771 }
3772 
3773 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3774                                      bool IsReal) {
3775   if (V.get()->isTypeDependent())
3776     return S.Context.DependentTy;
3777 
3778   // _Real and _Imag are only l-values for normal l-values.
3779   if (V.get()->getObjectKind() != OK_Ordinary) {
3780     V = S.DefaultLvalueConversion(V.get());
3781     if (V.isInvalid())
3782       return QualType();
3783   }
3784 
3785   // These operators return the element type of a complex type.
3786   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3787     return CT->getElementType();
3788 
3789   // Otherwise they pass through real integer and floating point types here.
3790   if (V.get()->getType()->isArithmeticType())
3791     return V.get()->getType();
3792 
3793   // Test for placeholders.
3794   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3795   if (PR.isInvalid()) return QualType();
3796   if (PR.get() != V.get()) {
3797     V = PR;
3798     return CheckRealImagOperand(S, V, Loc, IsReal);
3799   }
3800 
3801   // Reject anything else.
3802   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3803     << (IsReal ? "__real" : "__imag");
3804   return QualType();
3805 }
3806 
3807 
3808 
3809 ExprResult
3810 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3811                           tok::TokenKind Kind, Expr *Input) {
3812   UnaryOperatorKind Opc;
3813   switch (Kind) {
3814   default: llvm_unreachable("Unknown unary op!");
3815   case tok::plusplus:   Opc = UO_PostInc; break;
3816   case tok::minusminus: Opc = UO_PostDec; break;
3817   }
3818 
3819   // Since this might is a postfix expression, get rid of ParenListExprs.
3820   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3821   if (Result.isInvalid()) return ExprError();
3822   Input = Result.get();
3823 
3824   return BuildUnaryOp(S, OpLoc, Opc, Input);
3825 }
3826 
3827 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3828 ///
3829 /// \return true on error
3830 static bool checkArithmeticOnObjCPointer(Sema &S,
3831                                          SourceLocation opLoc,
3832                                          Expr *op) {
3833   assert(op->getType()->isObjCObjectPointerType());
3834   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3835       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3836     return false;
3837 
3838   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3839     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3840     << op->getSourceRange();
3841   return true;
3842 }
3843 
3844 ExprResult
3845 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3846                               Expr *idx, SourceLocation rbLoc) {
3847   // Since this might be a postfix expression, get rid of ParenListExprs.
3848   if (isa<ParenListExpr>(base)) {
3849     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3850     if (result.isInvalid()) return ExprError();
3851     base = result.get();
3852   }
3853 
3854   // Handle any non-overload placeholder types in the base and index
3855   // expressions.  We can't handle overloads here because the other
3856   // operand might be an overloadable type, in which case the overload
3857   // resolution for the operator overload should get the first crack
3858   // at the overload.
3859   if (base->getType()->isNonOverloadPlaceholderType()) {
3860     ExprResult result = CheckPlaceholderExpr(base);
3861     if (result.isInvalid()) return ExprError();
3862     base = result.get();
3863   }
3864   if (idx->getType()->isNonOverloadPlaceholderType()) {
3865     ExprResult result = CheckPlaceholderExpr(idx);
3866     if (result.isInvalid()) return ExprError();
3867     idx = result.get();
3868   }
3869 
3870   // Build an unanalyzed expression if either operand is type-dependent.
3871   if (getLangOpts().CPlusPlus &&
3872       (base->isTypeDependent() || idx->isTypeDependent())) {
3873     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3874                                             VK_LValue, OK_Ordinary, rbLoc);
3875   }
3876 
3877   // Use C++ overloaded-operator rules if either operand has record
3878   // type.  The spec says to do this if either type is *overloadable*,
3879   // but enum types can't declare subscript operators or conversion
3880   // operators, so there's nothing interesting for overload resolution
3881   // to do if there aren't any record types involved.
3882   //
3883   // ObjC pointers have their own subscripting logic that is not tied
3884   // to overload resolution and so should not take this path.
3885   if (getLangOpts().CPlusPlus &&
3886       (base->getType()->isRecordType() ||
3887        (!base->getType()->isObjCObjectPointerType() &&
3888         idx->getType()->isRecordType()))) {
3889     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3890   }
3891 
3892   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3893 }
3894 
3895 ExprResult
3896 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3897                                       Expr *Idx, SourceLocation RLoc) {
3898   Expr *LHSExp = Base;
3899   Expr *RHSExp = Idx;
3900 
3901   // Perform default conversions.
3902   if (!LHSExp->getType()->getAs<VectorType>()) {
3903     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3904     if (Result.isInvalid())
3905       return ExprError();
3906     LHSExp = Result.get();
3907   }
3908   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3909   if (Result.isInvalid())
3910     return ExprError();
3911   RHSExp = Result.get();
3912 
3913   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3914   ExprValueKind VK = VK_LValue;
3915   ExprObjectKind OK = OK_Ordinary;
3916 
3917   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3918   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3919   // in the subscript position. As a result, we need to derive the array base
3920   // and index from the expression types.
3921   Expr *BaseExpr, *IndexExpr;
3922   QualType ResultType;
3923   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3924     BaseExpr = LHSExp;
3925     IndexExpr = RHSExp;
3926     ResultType = Context.DependentTy;
3927   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3928     BaseExpr = LHSExp;
3929     IndexExpr = RHSExp;
3930     ResultType = PTy->getPointeeType();
3931   } else if (const ObjCObjectPointerType *PTy =
3932                LHSTy->getAs<ObjCObjectPointerType>()) {
3933     BaseExpr = LHSExp;
3934     IndexExpr = RHSExp;
3935 
3936     // Use custom logic if this should be the pseudo-object subscript
3937     // expression.
3938     if (!LangOpts.isSubscriptPointerArithmetic())
3939       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3940                                           nullptr);
3941 
3942     ResultType = PTy->getPointeeType();
3943   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3944      // Handle the uncommon case of "123[Ptr]".
3945     BaseExpr = RHSExp;
3946     IndexExpr = LHSExp;
3947     ResultType = PTy->getPointeeType();
3948   } else if (const ObjCObjectPointerType *PTy =
3949                RHSTy->getAs<ObjCObjectPointerType>()) {
3950      // Handle the uncommon case of "123[Ptr]".
3951     BaseExpr = RHSExp;
3952     IndexExpr = LHSExp;
3953     ResultType = PTy->getPointeeType();
3954     if (!LangOpts.isSubscriptPointerArithmetic()) {
3955       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3956         << ResultType << BaseExpr->getSourceRange();
3957       return ExprError();
3958     }
3959   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3960     BaseExpr = LHSExp;    // vectors: V[123]
3961     IndexExpr = RHSExp;
3962     VK = LHSExp->getValueKind();
3963     if (VK != VK_RValue)
3964       OK = OK_VectorComponent;
3965 
3966     // FIXME: need to deal with const...
3967     ResultType = VTy->getElementType();
3968   } else if (LHSTy->isArrayType()) {
3969     // If we see an array that wasn't promoted by
3970     // DefaultFunctionArrayLvalueConversion, it must be an array that
3971     // wasn't promoted because of the C90 rule that doesn't
3972     // allow promoting non-lvalue arrays.  Warn, then
3973     // force the promotion here.
3974     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3975         LHSExp->getSourceRange();
3976     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3977                                CK_ArrayToPointerDecay).get();
3978     LHSTy = LHSExp->getType();
3979 
3980     BaseExpr = LHSExp;
3981     IndexExpr = RHSExp;
3982     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3983   } else if (RHSTy->isArrayType()) {
3984     // Same as previous, except for 123[f().a] case
3985     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3986         RHSExp->getSourceRange();
3987     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3988                                CK_ArrayToPointerDecay).get();
3989     RHSTy = RHSExp->getType();
3990 
3991     BaseExpr = RHSExp;
3992     IndexExpr = LHSExp;
3993     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3994   } else {
3995     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3996        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3997   }
3998   // C99 6.5.2.1p1
3999   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4000     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4001                      << IndexExpr->getSourceRange());
4002 
4003   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4004        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4005          && !IndexExpr->isTypeDependent())
4006     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4007 
4008   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4009   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4010   // type. Note that Functions are not objects, and that (in C99 parlance)
4011   // incomplete types are not object types.
4012   if (ResultType->isFunctionType()) {
4013     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4014       << ResultType << BaseExpr->getSourceRange();
4015     return ExprError();
4016   }
4017 
4018   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4019     // GNU extension: subscripting on pointer to void
4020     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4021       << BaseExpr->getSourceRange();
4022 
4023     // C forbids expressions of unqualified void type from being l-values.
4024     // See IsCForbiddenLValueType.
4025     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4026   } else if (!ResultType->isDependentType() &&
4027       RequireCompleteType(LLoc, ResultType,
4028                           diag::err_subscript_incomplete_type, BaseExpr))
4029     return ExprError();
4030 
4031   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4032          !ResultType.isCForbiddenLValueType());
4033 
4034   return new (Context)
4035       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4036 }
4037 
4038 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4039                                         FunctionDecl *FD,
4040                                         ParmVarDecl *Param) {
4041   if (Param->hasUnparsedDefaultArg()) {
4042     Diag(CallLoc,
4043          diag::err_use_of_default_argument_to_function_declared_later) <<
4044       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4045     Diag(UnparsedDefaultArgLocs[Param],
4046          diag::note_default_argument_declared_here);
4047     return ExprError();
4048   }
4049 
4050   if (Param->hasUninstantiatedDefaultArg()) {
4051     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4052 
4053     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4054                                                  Param);
4055 
4056     // Instantiate the expression.
4057     MultiLevelTemplateArgumentList MutiLevelArgList
4058       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4059 
4060     InstantiatingTemplate Inst(*this, CallLoc, Param,
4061                                MutiLevelArgList.getInnermost());
4062     if (Inst.isInvalid())
4063       return ExprError();
4064 
4065     ExprResult Result;
4066     {
4067       // C++ [dcl.fct.default]p5:
4068       //   The names in the [default argument] expression are bound, and
4069       //   the semantic constraints are checked, at the point where the
4070       //   default argument expression appears.
4071       ContextRAII SavedContext(*this, FD);
4072       LocalInstantiationScope Local(*this);
4073       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4074     }
4075     if (Result.isInvalid())
4076       return ExprError();
4077 
4078     // Check the expression as an initializer for the parameter.
4079     InitializedEntity Entity
4080       = InitializedEntity::InitializeParameter(Context, Param);
4081     InitializationKind Kind
4082       = InitializationKind::CreateCopy(Param->getLocation(),
4083              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4084     Expr *ResultE = Result.getAs<Expr>();
4085 
4086     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4087     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4088     if (Result.isInvalid())
4089       return ExprError();
4090 
4091     Expr *Arg = Result.getAs<Expr>();
4092     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4093     // Build the default argument expression.
4094     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4095   }
4096 
4097   // If the default expression creates temporaries, we need to
4098   // push them to the current stack of expression temporaries so they'll
4099   // be properly destroyed.
4100   // FIXME: We should really be rebuilding the default argument with new
4101   // bound temporaries; see the comment in PR5810.
4102   // We don't need to do that with block decls, though, because
4103   // blocks in default argument expression can never capture anything.
4104   if (isa<ExprWithCleanups>(Param->getInit())) {
4105     // Set the "needs cleanups" bit regardless of whether there are
4106     // any explicit objects.
4107     ExprNeedsCleanups = true;
4108 
4109     // Append all the objects to the cleanup list.  Right now, this
4110     // should always be a no-op, because blocks in default argument
4111     // expressions should never be able to capture anything.
4112     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4113            "default argument expression has capturing blocks?");
4114   }
4115 
4116   // We already type-checked the argument, so we know it works.
4117   // Just mark all of the declarations in this potentially-evaluated expression
4118   // as being "referenced".
4119   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4120                                    /*SkipLocalVariables=*/true);
4121   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4122 }
4123 
4124 
4125 Sema::VariadicCallType
4126 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4127                           Expr *Fn) {
4128   if (Proto && Proto->isVariadic()) {
4129     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4130       return VariadicConstructor;
4131     else if (Fn && Fn->getType()->isBlockPointerType())
4132       return VariadicBlock;
4133     else if (FDecl) {
4134       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4135         if (Method->isInstance())
4136           return VariadicMethod;
4137     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4138       return VariadicMethod;
4139     return VariadicFunction;
4140   }
4141   return VariadicDoesNotApply;
4142 }
4143 
4144 namespace {
4145 class FunctionCallCCC : public FunctionCallFilterCCC {
4146 public:
4147   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4148                   unsigned NumArgs, MemberExpr *ME)
4149       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4150         FunctionName(FuncName) {}
4151 
4152   bool ValidateCandidate(const TypoCorrection &candidate) override {
4153     if (!candidate.getCorrectionSpecifier() ||
4154         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4155       return false;
4156     }
4157 
4158     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4159   }
4160 
4161 private:
4162   const IdentifierInfo *const FunctionName;
4163 };
4164 }
4165 
4166 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4167                                                FunctionDecl *FDecl,
4168                                                ArrayRef<Expr *> Args) {
4169   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4170   DeclarationName FuncName = FDecl->getDeclName();
4171   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4172 
4173   if (TypoCorrection Corrected = S.CorrectTypo(
4174           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4175           S.getScopeForContext(S.CurContext), nullptr,
4176           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4177                                              Args.size(), ME),
4178           Sema::CTK_ErrorRecovery)) {
4179     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4180       if (Corrected.isOverloaded()) {
4181         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4182         OverloadCandidateSet::iterator Best;
4183         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4184                                            CDEnd = Corrected.end();
4185              CD != CDEnd; ++CD) {
4186           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4187             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4188                                    OCS);
4189         }
4190         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4191         case OR_Success:
4192           ND = Best->Function;
4193           Corrected.setCorrectionDecl(ND);
4194           break;
4195         default:
4196           break;
4197         }
4198       }
4199       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4200         return Corrected;
4201       }
4202     }
4203   }
4204   return TypoCorrection();
4205 }
4206 
4207 /// ConvertArgumentsForCall - Converts the arguments specified in
4208 /// Args/NumArgs to the parameter types of the function FDecl with
4209 /// function prototype Proto. Call is the call expression itself, and
4210 /// Fn is the function expression. For a C++ member function, this
4211 /// routine does not attempt to convert the object argument. Returns
4212 /// true if the call is ill-formed.
4213 bool
4214 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4215                               FunctionDecl *FDecl,
4216                               const FunctionProtoType *Proto,
4217                               ArrayRef<Expr *> Args,
4218                               SourceLocation RParenLoc,
4219                               bool IsExecConfig) {
4220   // Bail out early if calling a builtin with custom typechecking.
4221   // We don't need to do this in the
4222   if (FDecl)
4223     if (unsigned ID = FDecl->getBuiltinID())
4224       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4225         return false;
4226 
4227   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4228   // assignment, to the types of the corresponding parameter, ...
4229   unsigned NumParams = Proto->getNumParams();
4230   bool Invalid = false;
4231   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4232   unsigned FnKind = Fn->getType()->isBlockPointerType()
4233                        ? 1 /* block */
4234                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4235                                        : 0 /* function */);
4236 
4237   // If too few arguments are available (and we don't have default
4238   // arguments for the remaining parameters), don't make the call.
4239   if (Args.size() < NumParams) {
4240     if (Args.size() < MinArgs) {
4241       TypoCorrection TC;
4242       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4243         unsigned diag_id =
4244             MinArgs == NumParams && !Proto->isVariadic()
4245                 ? diag::err_typecheck_call_too_few_args_suggest
4246                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4247         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4248                                         << static_cast<unsigned>(Args.size())
4249                                         << TC.getCorrectionRange());
4250       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4251         Diag(RParenLoc,
4252              MinArgs == NumParams && !Proto->isVariadic()
4253                  ? diag::err_typecheck_call_too_few_args_one
4254                  : diag::err_typecheck_call_too_few_args_at_least_one)
4255             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4256       else
4257         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4258                             ? diag::err_typecheck_call_too_few_args
4259                             : diag::err_typecheck_call_too_few_args_at_least)
4260             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4261             << Fn->getSourceRange();
4262 
4263       // Emit the location of the prototype.
4264       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4265         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4266           << FDecl;
4267 
4268       return true;
4269     }
4270     Call->setNumArgs(Context, NumParams);
4271   }
4272 
4273   // If too many are passed and not variadic, error on the extras and drop
4274   // them.
4275   if (Args.size() > NumParams) {
4276     if (!Proto->isVariadic()) {
4277       TypoCorrection TC;
4278       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4279         unsigned diag_id =
4280             MinArgs == NumParams && !Proto->isVariadic()
4281                 ? diag::err_typecheck_call_too_many_args_suggest
4282                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4283         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4284                                         << static_cast<unsigned>(Args.size())
4285                                         << TC.getCorrectionRange());
4286       } else if (NumParams == 1 && FDecl &&
4287                  FDecl->getParamDecl(0)->getDeclName())
4288         Diag(Args[NumParams]->getLocStart(),
4289              MinArgs == NumParams
4290                  ? diag::err_typecheck_call_too_many_args_one
4291                  : diag::err_typecheck_call_too_many_args_at_most_one)
4292             << FnKind << FDecl->getParamDecl(0)
4293             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4294             << SourceRange(Args[NumParams]->getLocStart(),
4295                            Args.back()->getLocEnd());
4296       else
4297         Diag(Args[NumParams]->getLocStart(),
4298              MinArgs == NumParams
4299                  ? diag::err_typecheck_call_too_many_args
4300                  : diag::err_typecheck_call_too_many_args_at_most)
4301             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4302             << Fn->getSourceRange()
4303             << SourceRange(Args[NumParams]->getLocStart(),
4304                            Args.back()->getLocEnd());
4305 
4306       // Emit the location of the prototype.
4307       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4308         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4309           << FDecl;
4310 
4311       // This deletes the extra arguments.
4312       Call->setNumArgs(Context, NumParams);
4313       return true;
4314     }
4315   }
4316   SmallVector<Expr *, 8> AllArgs;
4317   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4318 
4319   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4320                                    Proto, 0, Args, AllArgs, CallType);
4321   if (Invalid)
4322     return true;
4323   unsigned TotalNumArgs = AllArgs.size();
4324   for (unsigned i = 0; i < TotalNumArgs; ++i)
4325     Call->setArg(i, AllArgs[i]);
4326 
4327   return false;
4328 }
4329 
4330 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4331                                   const FunctionProtoType *Proto,
4332                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4333                                   SmallVectorImpl<Expr *> &AllArgs,
4334                                   VariadicCallType CallType, bool AllowExplicit,
4335                                   bool IsListInitialization) {
4336   unsigned NumParams = Proto->getNumParams();
4337   bool Invalid = false;
4338   unsigned ArgIx = 0;
4339   // Continue to check argument types (even if we have too few/many args).
4340   for (unsigned i = FirstParam; i < NumParams; i++) {
4341     QualType ProtoArgType = Proto->getParamType(i);
4342 
4343     Expr *Arg;
4344     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4345     if (ArgIx < Args.size()) {
4346       Arg = Args[ArgIx++];
4347 
4348       if (RequireCompleteType(Arg->getLocStart(),
4349                               ProtoArgType,
4350                               diag::err_call_incomplete_argument, Arg))
4351         return true;
4352 
4353       // Strip the unbridged-cast placeholder expression off, if applicable.
4354       bool CFAudited = false;
4355       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4356           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4357           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4358         Arg = stripARCUnbridgedCast(Arg);
4359       else if (getLangOpts().ObjCAutoRefCount &&
4360                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4361                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4362         CFAudited = true;
4363 
4364       InitializedEntity Entity =
4365           Param ? InitializedEntity::InitializeParameter(Context, Param,
4366                                                          ProtoArgType)
4367                 : InitializedEntity::InitializeParameter(
4368                       Context, ProtoArgType, Proto->isParamConsumed(i));
4369 
4370       // Remember that parameter belongs to a CF audited API.
4371       if (CFAudited)
4372         Entity.setParameterCFAudited();
4373 
4374       ExprResult ArgE = PerformCopyInitialization(
4375           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4376       if (ArgE.isInvalid())
4377         return true;
4378 
4379       Arg = ArgE.getAs<Expr>();
4380     } else {
4381       assert(Param && "can't use default arguments without a known callee");
4382 
4383       ExprResult ArgExpr =
4384         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4385       if (ArgExpr.isInvalid())
4386         return true;
4387 
4388       Arg = ArgExpr.getAs<Expr>();
4389     }
4390 
4391     // Check for array bounds violations for each argument to the call. This
4392     // check only triggers warnings when the argument isn't a more complex Expr
4393     // with its own checking, such as a BinaryOperator.
4394     CheckArrayAccess(Arg);
4395 
4396     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4397     CheckStaticArrayArgument(CallLoc, Param, Arg);
4398 
4399     AllArgs.push_back(Arg);
4400   }
4401 
4402   // If this is a variadic call, handle args passed through "...".
4403   if (CallType != VariadicDoesNotApply) {
4404     // Assume that extern "C" functions with variadic arguments that
4405     // return __unknown_anytype aren't *really* variadic.
4406     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4407         FDecl->isExternC()) {
4408       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4409         QualType paramType; // ignored
4410         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4411         Invalid |= arg.isInvalid();
4412         AllArgs.push_back(arg.get());
4413       }
4414 
4415     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4416     } else {
4417       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4418         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4419                                                           FDecl);
4420         Invalid |= Arg.isInvalid();
4421         AllArgs.push_back(Arg.get());
4422       }
4423     }
4424 
4425     // Check for array bounds violations.
4426     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4427       CheckArrayAccess(Args[i]);
4428   }
4429   return Invalid;
4430 }
4431 
4432 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4433   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4434   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4435     TL = DTL.getOriginalLoc();
4436   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4437     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4438       << ATL.getLocalSourceRange();
4439 }
4440 
4441 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4442 /// array parameter, check that it is non-null, and that if it is formed by
4443 /// array-to-pointer decay, the underlying array is sufficiently large.
4444 ///
4445 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4446 /// array type derivation, then for each call to the function, the value of the
4447 /// corresponding actual argument shall provide access to the first element of
4448 /// an array with at least as many elements as specified by the size expression.
4449 void
4450 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4451                                ParmVarDecl *Param,
4452                                const Expr *ArgExpr) {
4453   // Static array parameters are not supported in C++.
4454   if (!Param || getLangOpts().CPlusPlus)
4455     return;
4456 
4457   QualType OrigTy = Param->getOriginalType();
4458 
4459   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4460   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4461     return;
4462 
4463   if (ArgExpr->isNullPointerConstant(Context,
4464                                      Expr::NPC_NeverValueDependent)) {
4465     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4466     DiagnoseCalleeStaticArrayParam(*this, Param);
4467     return;
4468   }
4469 
4470   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4471   if (!CAT)
4472     return;
4473 
4474   const ConstantArrayType *ArgCAT =
4475     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4476   if (!ArgCAT)
4477     return;
4478 
4479   if (ArgCAT->getSize().ult(CAT->getSize())) {
4480     Diag(CallLoc, diag::warn_static_array_too_small)
4481       << ArgExpr->getSourceRange()
4482       << (unsigned) ArgCAT->getSize().getZExtValue()
4483       << (unsigned) CAT->getSize().getZExtValue();
4484     DiagnoseCalleeStaticArrayParam(*this, Param);
4485   }
4486 }
4487 
4488 /// Given a function expression of unknown-any type, try to rebuild it
4489 /// to have a function type.
4490 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4491 
4492 /// Is the given type a placeholder that we need to lower out
4493 /// immediately during argument processing?
4494 static bool isPlaceholderToRemoveAsArg(QualType type) {
4495   // Placeholders are never sugared.
4496   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4497   if (!placeholder) return false;
4498 
4499   switch (placeholder->getKind()) {
4500   // Ignore all the non-placeholder types.
4501 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4502 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4503 #include "clang/AST/BuiltinTypes.def"
4504     return false;
4505 
4506   // We cannot lower out overload sets; they might validly be resolved
4507   // by the call machinery.
4508   case BuiltinType::Overload:
4509     return false;
4510 
4511   // Unbridged casts in ARC can be handled in some call positions and
4512   // should be left in place.
4513   case BuiltinType::ARCUnbridgedCast:
4514     return false;
4515 
4516   // Pseudo-objects should be converted as soon as possible.
4517   case BuiltinType::PseudoObject:
4518     return true;
4519 
4520   // The debugger mode could theoretically but currently does not try
4521   // to resolve unknown-typed arguments based on known parameter types.
4522   case BuiltinType::UnknownAny:
4523     return true;
4524 
4525   // These are always invalid as call arguments and should be reported.
4526   case BuiltinType::BoundMember:
4527   case BuiltinType::BuiltinFn:
4528     return true;
4529   }
4530   llvm_unreachable("bad builtin type kind");
4531 }
4532 
4533 /// Check an argument list for placeholders that we won't try to
4534 /// handle later.
4535 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4536   // Apply this processing to all the arguments at once instead of
4537   // dying at the first failure.
4538   bool hasInvalid = false;
4539   for (size_t i = 0, e = args.size(); i != e; i++) {
4540     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4541       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4542       if (result.isInvalid()) hasInvalid = true;
4543       else args[i] = result.get();
4544     }
4545   }
4546   return hasInvalid;
4547 }
4548 
4549 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4550 /// This provides the location of the left/right parens and a list of comma
4551 /// locations.
4552 ExprResult
4553 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4554                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4555                     Expr *ExecConfig, bool IsExecConfig) {
4556   // Since this might be a postfix expression, get rid of ParenListExprs.
4557   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4558   if (Result.isInvalid()) return ExprError();
4559   Fn = Result.get();
4560 
4561   if (checkArgsForPlaceholders(*this, ArgExprs))
4562     return ExprError();
4563 
4564   if (getLangOpts().CPlusPlus) {
4565     // If this is a pseudo-destructor expression, build the call immediately.
4566     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4567       if (!ArgExprs.empty()) {
4568         // Pseudo-destructor calls should not have any arguments.
4569         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4570           << FixItHint::CreateRemoval(
4571                                     SourceRange(ArgExprs[0]->getLocStart(),
4572                                                 ArgExprs.back()->getLocEnd()));
4573       }
4574 
4575       return new (Context)
4576           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4577     }
4578     if (Fn->getType() == Context.PseudoObjectTy) {
4579       ExprResult result = CheckPlaceholderExpr(Fn);
4580       if (result.isInvalid()) return ExprError();
4581       Fn = result.get();
4582     }
4583 
4584     // Determine whether this is a dependent call inside a C++ template,
4585     // in which case we won't do any semantic analysis now.
4586     // FIXME: Will need to cache the results of name lookup (including ADL) in
4587     // Fn.
4588     bool Dependent = false;
4589     if (Fn->isTypeDependent())
4590       Dependent = true;
4591     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4592       Dependent = true;
4593 
4594     if (Dependent) {
4595       if (ExecConfig) {
4596         return new (Context) CUDAKernelCallExpr(
4597             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4598             Context.DependentTy, VK_RValue, RParenLoc);
4599       } else {
4600         return new (Context) CallExpr(
4601             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4602       }
4603     }
4604 
4605     // Determine whether this is a call to an object (C++ [over.call.object]).
4606     if (Fn->getType()->isRecordType())
4607       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4608                                           RParenLoc);
4609 
4610     if (Fn->getType() == Context.UnknownAnyTy) {
4611       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4612       if (result.isInvalid()) return ExprError();
4613       Fn = result.get();
4614     }
4615 
4616     if (Fn->getType() == Context.BoundMemberTy) {
4617       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4618     }
4619   }
4620 
4621   // Check for overloaded calls.  This can happen even in C due to extensions.
4622   if (Fn->getType() == Context.OverloadTy) {
4623     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4624 
4625     // We aren't supposed to apply this logic for if there's an '&' involved.
4626     if (!find.HasFormOfMemberPointer) {
4627       OverloadExpr *ovl = find.Expression;
4628       if (isa<UnresolvedLookupExpr>(ovl)) {
4629         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4630         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4631                                        RParenLoc, ExecConfig);
4632       } else {
4633         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4634                                          RParenLoc);
4635       }
4636     }
4637   }
4638 
4639   // If we're directly calling a function, get the appropriate declaration.
4640   if (Fn->getType() == Context.UnknownAnyTy) {
4641     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4642     if (result.isInvalid()) return ExprError();
4643     Fn = result.get();
4644   }
4645 
4646   Expr *NakedFn = Fn->IgnoreParens();
4647 
4648   NamedDecl *NDecl = nullptr;
4649   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4650     if (UnOp->getOpcode() == UO_AddrOf)
4651       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4652 
4653   if (isa<DeclRefExpr>(NakedFn))
4654     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4655   else if (isa<MemberExpr>(NakedFn))
4656     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4657 
4658   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4659     if (FD->hasAttr<EnableIfAttr>()) {
4660       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4661         Diag(Fn->getLocStart(),
4662              isa<CXXMethodDecl>(FD) ?
4663                  diag::err_ovl_no_viable_member_function_in_call :
4664                  diag::err_ovl_no_viable_function_in_call)
4665           << FD << FD->getSourceRange();
4666         Diag(FD->getLocation(),
4667              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4668             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4669       }
4670     }
4671   }
4672 
4673   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4674                                ExecConfig, IsExecConfig);
4675 }
4676 
4677 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4678 ///
4679 /// __builtin_astype( value, dst type )
4680 ///
4681 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4682                                  SourceLocation BuiltinLoc,
4683                                  SourceLocation RParenLoc) {
4684   ExprValueKind VK = VK_RValue;
4685   ExprObjectKind OK = OK_Ordinary;
4686   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4687   QualType SrcTy = E->getType();
4688   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4689     return ExprError(Diag(BuiltinLoc,
4690                           diag::err_invalid_astype_of_different_size)
4691                      << DstTy
4692                      << SrcTy
4693                      << E->getSourceRange());
4694   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4695 }
4696 
4697 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4698 /// provided arguments.
4699 ///
4700 /// __builtin_convertvector( value, dst type )
4701 ///
4702 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4703                                         SourceLocation BuiltinLoc,
4704                                         SourceLocation RParenLoc) {
4705   TypeSourceInfo *TInfo;
4706   GetTypeFromParser(ParsedDestTy, &TInfo);
4707   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4708 }
4709 
4710 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4711 /// i.e. an expression not of \p OverloadTy.  The expression should
4712 /// unary-convert to an expression of function-pointer or
4713 /// block-pointer type.
4714 ///
4715 /// \param NDecl the declaration being called, if available
4716 ExprResult
4717 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4718                             SourceLocation LParenLoc,
4719                             ArrayRef<Expr *> Args,
4720                             SourceLocation RParenLoc,
4721                             Expr *Config, bool IsExecConfig) {
4722   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4723   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4724 
4725   // Promote the function operand.
4726   // We special-case function promotion here because we only allow promoting
4727   // builtin functions to function pointers in the callee of a call.
4728   ExprResult Result;
4729   if (BuiltinID &&
4730       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4731     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4732                                CK_BuiltinFnToFnPtr).get();
4733   } else {
4734     Result = CallExprUnaryConversions(Fn);
4735   }
4736   if (Result.isInvalid())
4737     return ExprError();
4738   Fn = Result.get();
4739 
4740   // Make the call expr early, before semantic checks.  This guarantees cleanup
4741   // of arguments and function on error.
4742   CallExpr *TheCall;
4743   if (Config)
4744     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4745                                                cast<CallExpr>(Config), Args,
4746                                                Context.BoolTy, VK_RValue,
4747                                                RParenLoc);
4748   else
4749     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4750                                      VK_RValue, RParenLoc);
4751 
4752   // Bail out early if calling a builtin with custom typechecking.
4753   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4754     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4755 
4756  retry:
4757   const FunctionType *FuncT;
4758   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4759     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4760     // have type pointer to function".
4761     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4762     if (!FuncT)
4763       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4764                          << Fn->getType() << Fn->getSourceRange());
4765   } else if (const BlockPointerType *BPT =
4766                Fn->getType()->getAs<BlockPointerType>()) {
4767     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4768   } else {
4769     // Handle calls to expressions of unknown-any type.
4770     if (Fn->getType() == Context.UnknownAnyTy) {
4771       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4772       if (rewrite.isInvalid()) return ExprError();
4773       Fn = rewrite.get();
4774       TheCall->setCallee(Fn);
4775       goto retry;
4776     }
4777 
4778     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4779       << Fn->getType() << Fn->getSourceRange());
4780   }
4781 
4782   if (getLangOpts().CUDA) {
4783     if (Config) {
4784       // CUDA: Kernel calls must be to global functions
4785       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4786         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4787             << FDecl->getName() << Fn->getSourceRange());
4788 
4789       // CUDA: Kernel function must have 'void' return type
4790       if (!FuncT->getReturnType()->isVoidType())
4791         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4792             << Fn->getType() << Fn->getSourceRange());
4793     } else {
4794       // CUDA: Calls to global functions must be configured
4795       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4796         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4797             << FDecl->getName() << Fn->getSourceRange());
4798     }
4799   }
4800 
4801   // Check for a valid return type
4802   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4803                           FDecl))
4804     return ExprError();
4805 
4806   // We know the result type of the call, set it.
4807   TheCall->setType(FuncT->getCallResultType(Context));
4808   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4809 
4810   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4811   if (Proto) {
4812     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4813                                 IsExecConfig))
4814       return ExprError();
4815   } else {
4816     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4817 
4818     if (FDecl) {
4819       // Check if we have too few/too many template arguments, based
4820       // on our knowledge of the function definition.
4821       const FunctionDecl *Def = nullptr;
4822       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4823         Proto = Def->getType()->getAs<FunctionProtoType>();
4824        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4825           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4826           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4827       }
4828 
4829       // If the function we're calling isn't a function prototype, but we have
4830       // a function prototype from a prior declaratiom, use that prototype.
4831       if (!FDecl->hasPrototype())
4832         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4833     }
4834 
4835     // Promote the arguments (C99 6.5.2.2p6).
4836     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4837       Expr *Arg = Args[i];
4838 
4839       if (Proto && i < Proto->getNumParams()) {
4840         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4841             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4842         ExprResult ArgE =
4843             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4844         if (ArgE.isInvalid())
4845           return true;
4846 
4847         Arg = ArgE.getAs<Expr>();
4848 
4849       } else {
4850         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4851 
4852         if (ArgE.isInvalid())
4853           return true;
4854 
4855         Arg = ArgE.getAs<Expr>();
4856       }
4857 
4858       if (RequireCompleteType(Arg->getLocStart(),
4859                               Arg->getType(),
4860                               diag::err_call_incomplete_argument, Arg))
4861         return ExprError();
4862 
4863       TheCall->setArg(i, Arg);
4864     }
4865   }
4866 
4867   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4868     if (!Method->isStatic())
4869       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4870         << Fn->getSourceRange());
4871 
4872   // Check for sentinels
4873   if (NDecl)
4874     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4875 
4876   // Do special checking on direct calls to functions.
4877   if (FDecl) {
4878     if (CheckFunctionCall(FDecl, TheCall, Proto))
4879       return ExprError();
4880 
4881     if (BuiltinID)
4882       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4883   } else if (NDecl) {
4884     if (CheckPointerCall(NDecl, TheCall, Proto))
4885       return ExprError();
4886   } else {
4887     if (CheckOtherCall(TheCall, Proto))
4888       return ExprError();
4889   }
4890 
4891   return MaybeBindToTemporary(TheCall);
4892 }
4893 
4894 ExprResult
4895 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4896                            SourceLocation RParenLoc, Expr *InitExpr) {
4897   assert(Ty && "ActOnCompoundLiteral(): missing type");
4898   // FIXME: put back this assert when initializers are worked out.
4899   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4900 
4901   TypeSourceInfo *TInfo;
4902   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4903   if (!TInfo)
4904     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4905 
4906   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4907 }
4908 
4909 ExprResult
4910 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4911                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4912   QualType literalType = TInfo->getType();
4913 
4914   if (literalType->isArrayType()) {
4915     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4916           diag::err_illegal_decl_array_incomplete_type,
4917           SourceRange(LParenLoc,
4918                       LiteralExpr->getSourceRange().getEnd())))
4919       return ExprError();
4920     if (literalType->isVariableArrayType())
4921       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4922         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4923   } else if (!literalType->isDependentType() &&
4924              RequireCompleteType(LParenLoc, literalType,
4925                diag::err_typecheck_decl_incomplete_type,
4926                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4927     return ExprError();
4928 
4929   InitializedEntity Entity
4930     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4931   InitializationKind Kind
4932     = InitializationKind::CreateCStyleCast(LParenLoc,
4933                                            SourceRange(LParenLoc, RParenLoc),
4934                                            /*InitList=*/true);
4935   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4936   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4937                                       &literalType);
4938   if (Result.isInvalid())
4939     return ExprError();
4940   LiteralExpr = Result.get();
4941 
4942   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4943   if (isFileScope &&
4944       !LiteralExpr->isTypeDependent() &&
4945       !LiteralExpr->isValueDependent() &&
4946       !literalType->isDependentType()) { // 6.5.2.5p3
4947     if (CheckForConstantInitializer(LiteralExpr, literalType))
4948       return ExprError();
4949   }
4950 
4951   // In C, compound literals are l-values for some reason.
4952   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4953 
4954   return MaybeBindToTemporary(
4955            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4956                                              VK, LiteralExpr, isFileScope));
4957 }
4958 
4959 ExprResult
4960 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4961                     SourceLocation RBraceLoc) {
4962   // Immediately handle non-overload placeholders.  Overloads can be
4963   // resolved contextually, but everything else here can't.
4964   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4965     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4966       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4967 
4968       // Ignore failures; dropping the entire initializer list because
4969       // of one failure would be terrible for indexing/etc.
4970       if (result.isInvalid()) continue;
4971 
4972       InitArgList[I] = result.get();
4973     }
4974   }
4975 
4976   // Semantic analysis for initializers is done by ActOnDeclarator() and
4977   // CheckInitializer() - it requires knowledge of the object being intialized.
4978 
4979   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4980                                                RBraceLoc);
4981   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4982   return E;
4983 }
4984 
4985 /// Do an explicit extend of the given block pointer if we're in ARC.
4986 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4987   assert(E.get()->getType()->isBlockPointerType());
4988   assert(E.get()->isRValue());
4989 
4990   // Only do this in an r-value context.
4991   if (!S.getLangOpts().ObjCAutoRefCount) return;
4992 
4993   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4994                                CK_ARCExtendBlockObject, E.get(),
4995                                /*base path*/ nullptr, VK_RValue);
4996   S.ExprNeedsCleanups = true;
4997 }
4998 
4999 /// Prepare a conversion of the given expression to an ObjC object
5000 /// pointer type.
5001 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5002   QualType type = E.get()->getType();
5003   if (type->isObjCObjectPointerType()) {
5004     return CK_BitCast;
5005   } else if (type->isBlockPointerType()) {
5006     maybeExtendBlockObject(*this, E);
5007     return CK_BlockPointerToObjCPointerCast;
5008   } else {
5009     assert(type->isPointerType());
5010     return CK_CPointerToObjCPointerCast;
5011   }
5012 }
5013 
5014 /// Prepares for a scalar cast, performing all the necessary stages
5015 /// except the final cast and returning the kind required.
5016 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5017   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5018   // Also, callers should have filtered out the invalid cases with
5019   // pointers.  Everything else should be possible.
5020 
5021   QualType SrcTy = Src.get()->getType();
5022   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5023     return CK_NoOp;
5024 
5025   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5026   case Type::STK_MemberPointer:
5027     llvm_unreachable("member pointer type in C");
5028 
5029   case Type::STK_CPointer:
5030   case Type::STK_BlockPointer:
5031   case Type::STK_ObjCObjectPointer:
5032     switch (DestTy->getScalarTypeKind()) {
5033     case Type::STK_CPointer: {
5034       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5035       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5036       if (SrcAS != DestAS)
5037         return CK_AddressSpaceConversion;
5038       return CK_BitCast;
5039     }
5040     case Type::STK_BlockPointer:
5041       return (SrcKind == Type::STK_BlockPointer
5042                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5043     case Type::STK_ObjCObjectPointer:
5044       if (SrcKind == Type::STK_ObjCObjectPointer)
5045         return CK_BitCast;
5046       if (SrcKind == Type::STK_CPointer)
5047         return CK_CPointerToObjCPointerCast;
5048       maybeExtendBlockObject(*this, Src);
5049       return CK_BlockPointerToObjCPointerCast;
5050     case Type::STK_Bool:
5051       return CK_PointerToBoolean;
5052     case Type::STK_Integral:
5053       return CK_PointerToIntegral;
5054     case Type::STK_Floating:
5055     case Type::STK_FloatingComplex:
5056     case Type::STK_IntegralComplex:
5057     case Type::STK_MemberPointer:
5058       llvm_unreachable("illegal cast from pointer");
5059     }
5060     llvm_unreachable("Should have returned before this");
5061 
5062   case Type::STK_Bool: // casting from bool is like casting from an integer
5063   case Type::STK_Integral:
5064     switch (DestTy->getScalarTypeKind()) {
5065     case Type::STK_CPointer:
5066     case Type::STK_ObjCObjectPointer:
5067     case Type::STK_BlockPointer:
5068       if (Src.get()->isNullPointerConstant(Context,
5069                                            Expr::NPC_ValueDependentIsNull))
5070         return CK_NullToPointer;
5071       return CK_IntegralToPointer;
5072     case Type::STK_Bool:
5073       return CK_IntegralToBoolean;
5074     case Type::STK_Integral:
5075       return CK_IntegralCast;
5076     case Type::STK_Floating:
5077       return CK_IntegralToFloating;
5078     case Type::STK_IntegralComplex:
5079       Src = ImpCastExprToType(Src.get(),
5080                               DestTy->castAs<ComplexType>()->getElementType(),
5081                               CK_IntegralCast);
5082       return CK_IntegralRealToComplex;
5083     case Type::STK_FloatingComplex:
5084       Src = ImpCastExprToType(Src.get(),
5085                               DestTy->castAs<ComplexType>()->getElementType(),
5086                               CK_IntegralToFloating);
5087       return CK_FloatingRealToComplex;
5088     case Type::STK_MemberPointer:
5089       llvm_unreachable("member pointer type in C");
5090     }
5091     llvm_unreachable("Should have returned before this");
5092 
5093   case Type::STK_Floating:
5094     switch (DestTy->getScalarTypeKind()) {
5095     case Type::STK_Floating:
5096       return CK_FloatingCast;
5097     case Type::STK_Bool:
5098       return CK_FloatingToBoolean;
5099     case Type::STK_Integral:
5100       return CK_FloatingToIntegral;
5101     case Type::STK_FloatingComplex:
5102       Src = ImpCastExprToType(Src.get(),
5103                               DestTy->castAs<ComplexType>()->getElementType(),
5104                               CK_FloatingCast);
5105       return CK_FloatingRealToComplex;
5106     case Type::STK_IntegralComplex:
5107       Src = ImpCastExprToType(Src.get(),
5108                               DestTy->castAs<ComplexType>()->getElementType(),
5109                               CK_FloatingToIntegral);
5110       return CK_IntegralRealToComplex;
5111     case Type::STK_CPointer:
5112     case Type::STK_ObjCObjectPointer:
5113     case Type::STK_BlockPointer:
5114       llvm_unreachable("valid float->pointer cast?");
5115     case Type::STK_MemberPointer:
5116       llvm_unreachable("member pointer type in C");
5117     }
5118     llvm_unreachable("Should have returned before this");
5119 
5120   case Type::STK_FloatingComplex:
5121     switch (DestTy->getScalarTypeKind()) {
5122     case Type::STK_FloatingComplex:
5123       return CK_FloatingComplexCast;
5124     case Type::STK_IntegralComplex:
5125       return CK_FloatingComplexToIntegralComplex;
5126     case Type::STK_Floating: {
5127       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5128       if (Context.hasSameType(ET, DestTy))
5129         return CK_FloatingComplexToReal;
5130       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5131       return CK_FloatingCast;
5132     }
5133     case Type::STK_Bool:
5134       return CK_FloatingComplexToBoolean;
5135     case Type::STK_Integral:
5136       Src = ImpCastExprToType(Src.get(),
5137                               SrcTy->castAs<ComplexType>()->getElementType(),
5138                               CK_FloatingComplexToReal);
5139       return CK_FloatingToIntegral;
5140     case Type::STK_CPointer:
5141     case Type::STK_ObjCObjectPointer:
5142     case Type::STK_BlockPointer:
5143       llvm_unreachable("valid complex float->pointer cast?");
5144     case Type::STK_MemberPointer:
5145       llvm_unreachable("member pointer type in C");
5146     }
5147     llvm_unreachable("Should have returned before this");
5148 
5149   case Type::STK_IntegralComplex:
5150     switch (DestTy->getScalarTypeKind()) {
5151     case Type::STK_FloatingComplex:
5152       return CK_IntegralComplexToFloatingComplex;
5153     case Type::STK_IntegralComplex:
5154       return CK_IntegralComplexCast;
5155     case Type::STK_Integral: {
5156       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5157       if (Context.hasSameType(ET, DestTy))
5158         return CK_IntegralComplexToReal;
5159       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5160       return CK_IntegralCast;
5161     }
5162     case Type::STK_Bool:
5163       return CK_IntegralComplexToBoolean;
5164     case Type::STK_Floating:
5165       Src = ImpCastExprToType(Src.get(),
5166                               SrcTy->castAs<ComplexType>()->getElementType(),
5167                               CK_IntegralComplexToReal);
5168       return CK_IntegralToFloating;
5169     case Type::STK_CPointer:
5170     case Type::STK_ObjCObjectPointer:
5171     case Type::STK_BlockPointer:
5172       llvm_unreachable("valid complex int->pointer cast?");
5173     case Type::STK_MemberPointer:
5174       llvm_unreachable("member pointer type in C");
5175     }
5176     llvm_unreachable("Should have returned before this");
5177   }
5178 
5179   llvm_unreachable("Unhandled scalar cast");
5180 }
5181 
5182 static bool breakDownVectorType(QualType type, uint64_t &len,
5183                                 QualType &eltType) {
5184   // Vectors are simple.
5185   if (const VectorType *vecType = type->getAs<VectorType>()) {
5186     len = vecType->getNumElements();
5187     eltType = vecType->getElementType();
5188     assert(eltType->isScalarType());
5189     return true;
5190   }
5191 
5192   // We allow lax conversion to and from non-vector types, but only if
5193   // they're real types (i.e. non-complex, non-pointer scalar types).
5194   if (!type->isRealType()) return false;
5195 
5196   len = 1;
5197   eltType = type;
5198   return true;
5199 }
5200 
5201 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5202   uint64_t srcLen, destLen;
5203   QualType srcElt, destElt;
5204   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5205   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5206 
5207   // ASTContext::getTypeSize will return the size rounded up to a
5208   // power of 2, so instead of using that, we need to use the raw
5209   // element size multiplied by the element count.
5210   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5211   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5212 
5213   return (srcLen * srcEltSize == destLen * destEltSize);
5214 }
5215 
5216 /// Is this a legal conversion between two known vector types?
5217 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5218   assert(destTy->isVectorType() || srcTy->isVectorType());
5219 
5220   if (!Context.getLangOpts().LaxVectorConversions)
5221     return false;
5222   return VectorTypesMatch(*this, srcTy, destTy);
5223 }
5224 
5225 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5226                            CastKind &Kind) {
5227   assert(VectorTy->isVectorType() && "Not a vector type!");
5228 
5229   if (Ty->isVectorType() || Ty->isIntegerType()) {
5230     if (!VectorTypesMatch(*this, Ty, VectorTy))
5231       return Diag(R.getBegin(),
5232                   Ty->isVectorType() ?
5233                   diag::err_invalid_conversion_between_vectors :
5234                   diag::err_invalid_conversion_between_vector_and_integer)
5235         << VectorTy << Ty << R;
5236   } else
5237     return Diag(R.getBegin(),
5238                 diag::err_invalid_conversion_between_vector_and_scalar)
5239       << VectorTy << Ty << R;
5240 
5241   Kind = CK_BitCast;
5242   return false;
5243 }
5244 
5245 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5246                                     Expr *CastExpr, CastKind &Kind) {
5247   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5248 
5249   QualType SrcTy = CastExpr->getType();
5250 
5251   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5252   // an ExtVectorType.
5253   // In OpenCL, casts between vectors of different types are not allowed.
5254   // (See OpenCL 6.2).
5255   if (SrcTy->isVectorType()) {
5256     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5257         || (getLangOpts().OpenCL &&
5258             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5259       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5260         << DestTy << SrcTy << R;
5261       return ExprError();
5262     }
5263     Kind = CK_BitCast;
5264     return CastExpr;
5265   }
5266 
5267   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5268   // conversion will take place first from scalar to elt type, and then
5269   // splat from elt type to vector.
5270   if (SrcTy->isPointerType())
5271     return Diag(R.getBegin(),
5272                 diag::err_invalid_conversion_between_vector_and_scalar)
5273       << DestTy << SrcTy << R;
5274 
5275   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5276   ExprResult CastExprRes = CastExpr;
5277   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5278   if (CastExprRes.isInvalid())
5279     return ExprError();
5280   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5281 
5282   Kind = CK_VectorSplat;
5283   return CastExpr;
5284 }
5285 
5286 ExprResult
5287 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5288                     Declarator &D, ParsedType &Ty,
5289                     SourceLocation RParenLoc, Expr *CastExpr) {
5290   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5291          "ActOnCastExpr(): missing type or expr");
5292 
5293   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5294   if (D.isInvalidType())
5295     return ExprError();
5296 
5297   if (getLangOpts().CPlusPlus) {
5298     // Check that there are no default arguments (C++ only).
5299     CheckExtraCXXDefaultArguments(D);
5300   }
5301 
5302   checkUnusedDeclAttributes(D);
5303 
5304   QualType castType = castTInfo->getType();
5305   Ty = CreateParsedType(castType, castTInfo);
5306 
5307   bool isVectorLiteral = false;
5308 
5309   // Check for an altivec or OpenCL literal,
5310   // i.e. all the elements are integer constants.
5311   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5312   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5313   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5314        && castType->isVectorType() && (PE || PLE)) {
5315     if (PLE && PLE->getNumExprs() == 0) {
5316       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5317       return ExprError();
5318     }
5319     if (PE || PLE->getNumExprs() == 1) {
5320       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5321       if (!E->getType()->isVectorType())
5322         isVectorLiteral = true;
5323     }
5324     else
5325       isVectorLiteral = true;
5326   }
5327 
5328   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5329   // then handle it as such.
5330   if (isVectorLiteral)
5331     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5332 
5333   // If the Expr being casted is a ParenListExpr, handle it specially.
5334   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5335   // sequence of BinOp comma operators.
5336   if (isa<ParenListExpr>(CastExpr)) {
5337     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5338     if (Result.isInvalid()) return ExprError();
5339     CastExpr = Result.get();
5340   }
5341 
5342   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5343       !getSourceManager().isInSystemMacro(LParenLoc))
5344     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5345 
5346   CheckTollFreeBridgeCast(castType, CastExpr);
5347 
5348   CheckObjCBridgeRelatedCast(castType, CastExpr);
5349 
5350   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5351 }
5352 
5353 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5354                                     SourceLocation RParenLoc, Expr *E,
5355                                     TypeSourceInfo *TInfo) {
5356   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5357          "Expected paren or paren list expression");
5358 
5359   Expr **exprs;
5360   unsigned numExprs;
5361   Expr *subExpr;
5362   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5363   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5364     LiteralLParenLoc = PE->getLParenLoc();
5365     LiteralRParenLoc = PE->getRParenLoc();
5366     exprs = PE->getExprs();
5367     numExprs = PE->getNumExprs();
5368   } else { // isa<ParenExpr> by assertion at function entrance
5369     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5370     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5371     subExpr = cast<ParenExpr>(E)->getSubExpr();
5372     exprs = &subExpr;
5373     numExprs = 1;
5374   }
5375 
5376   QualType Ty = TInfo->getType();
5377   assert(Ty->isVectorType() && "Expected vector type");
5378 
5379   SmallVector<Expr *, 8> initExprs;
5380   const VectorType *VTy = Ty->getAs<VectorType>();
5381   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5382 
5383   // '(...)' form of vector initialization in AltiVec: the number of
5384   // initializers must be one or must match the size of the vector.
5385   // If a single value is specified in the initializer then it will be
5386   // replicated to all the components of the vector
5387   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5388     // The number of initializers must be one or must match the size of the
5389     // vector. If a single value is specified in the initializer then it will
5390     // be replicated to all the components of the vector
5391     if (numExprs == 1) {
5392       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5393       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5394       if (Literal.isInvalid())
5395         return ExprError();
5396       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5397                                   PrepareScalarCast(Literal, ElemTy));
5398       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5399     }
5400     else if (numExprs < numElems) {
5401       Diag(E->getExprLoc(),
5402            diag::err_incorrect_number_of_vector_initializers);
5403       return ExprError();
5404     }
5405     else
5406       initExprs.append(exprs, exprs + numExprs);
5407   }
5408   else {
5409     // For OpenCL, when the number of initializers is a single value,
5410     // it will be replicated to all components of the vector.
5411     if (getLangOpts().OpenCL &&
5412         VTy->getVectorKind() == VectorType::GenericVector &&
5413         numExprs == 1) {
5414         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5415         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5416         if (Literal.isInvalid())
5417           return ExprError();
5418         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5419                                     PrepareScalarCast(Literal, ElemTy));
5420         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5421     }
5422 
5423     initExprs.append(exprs, exprs + numExprs);
5424   }
5425   // FIXME: This means that pretty-printing the final AST will produce curly
5426   // braces instead of the original commas.
5427   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5428                                                    initExprs, LiteralRParenLoc);
5429   initE->setType(Ty);
5430   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5431 }
5432 
5433 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5434 /// the ParenListExpr into a sequence of comma binary operators.
5435 ExprResult
5436 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5437   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5438   if (!E)
5439     return OrigExpr;
5440 
5441   ExprResult Result(E->getExpr(0));
5442 
5443   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5444     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5445                         E->getExpr(i));
5446 
5447   if (Result.isInvalid()) return ExprError();
5448 
5449   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5450 }
5451 
5452 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5453                                     SourceLocation R,
5454                                     MultiExprArg Val) {
5455   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5456   return expr;
5457 }
5458 
5459 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5460 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5461 /// emitted.
5462 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5463                                       SourceLocation QuestionLoc) {
5464   Expr *NullExpr = LHSExpr;
5465   Expr *NonPointerExpr = RHSExpr;
5466   Expr::NullPointerConstantKind NullKind =
5467       NullExpr->isNullPointerConstant(Context,
5468                                       Expr::NPC_ValueDependentIsNotNull);
5469 
5470   if (NullKind == Expr::NPCK_NotNull) {
5471     NullExpr = RHSExpr;
5472     NonPointerExpr = LHSExpr;
5473     NullKind =
5474         NullExpr->isNullPointerConstant(Context,
5475                                         Expr::NPC_ValueDependentIsNotNull);
5476   }
5477 
5478   if (NullKind == Expr::NPCK_NotNull)
5479     return false;
5480 
5481   if (NullKind == Expr::NPCK_ZeroExpression)
5482     return false;
5483 
5484   if (NullKind == Expr::NPCK_ZeroLiteral) {
5485     // In this case, check to make sure that we got here from a "NULL"
5486     // string in the source code.
5487     NullExpr = NullExpr->IgnoreParenImpCasts();
5488     SourceLocation loc = NullExpr->getExprLoc();
5489     if (!findMacroSpelling(loc, "NULL"))
5490       return false;
5491   }
5492 
5493   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5494   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5495       << NonPointerExpr->getType() << DiagType
5496       << NonPointerExpr->getSourceRange();
5497   return true;
5498 }
5499 
5500 /// \brief Return false if the condition expression is valid, true otherwise.
5501 static bool checkCondition(Sema &S, Expr *Cond) {
5502   QualType CondTy = Cond->getType();
5503 
5504   // C99 6.5.15p2
5505   if (CondTy->isScalarType()) return false;
5506 
5507   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5508   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5509     return false;
5510 
5511   // Emit the proper error message.
5512   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5513                               diag::err_typecheck_cond_expect_scalar :
5514                               diag::err_typecheck_cond_expect_scalar_or_vector)
5515     << CondTy;
5516   return true;
5517 }
5518 
5519 /// \brief Return false if the two expressions can be converted to a vector,
5520 /// true otherwise
5521 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5522                                                     ExprResult &RHS,
5523                                                     QualType CondTy) {
5524   // Both operands should be of scalar type.
5525   if (!LHS.get()->getType()->isScalarType()) {
5526     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5527       << CondTy;
5528     return true;
5529   }
5530   if (!RHS.get()->getType()->isScalarType()) {
5531     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5532       << CondTy;
5533     return true;
5534   }
5535 
5536   // Implicity convert these scalars to the type of the condition.
5537   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5538   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5539   return false;
5540 }
5541 
5542 /// \brief Handle when one or both operands are void type.
5543 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5544                                          ExprResult &RHS) {
5545     Expr *LHSExpr = LHS.get();
5546     Expr *RHSExpr = RHS.get();
5547 
5548     if (!LHSExpr->getType()->isVoidType())
5549       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5550         << RHSExpr->getSourceRange();
5551     if (!RHSExpr->getType()->isVoidType())
5552       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5553         << LHSExpr->getSourceRange();
5554     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5555     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5556     return S.Context.VoidTy;
5557 }
5558 
5559 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5560 /// true otherwise.
5561 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5562                                         QualType PointerTy) {
5563   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5564       !NullExpr.get()->isNullPointerConstant(S.Context,
5565                                             Expr::NPC_ValueDependentIsNull))
5566     return true;
5567 
5568   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5569   return false;
5570 }
5571 
5572 /// \brief Checks compatibility between two pointers and return the resulting
5573 /// type.
5574 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5575                                                      ExprResult &RHS,
5576                                                      SourceLocation Loc) {
5577   QualType LHSTy = LHS.get()->getType();
5578   QualType RHSTy = RHS.get()->getType();
5579 
5580   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5581     // Two identical pointers types are always compatible.
5582     return LHSTy;
5583   }
5584 
5585   QualType lhptee, rhptee;
5586 
5587   // Get the pointee types.
5588   bool IsBlockPointer = false;
5589   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5590     lhptee = LHSBTy->getPointeeType();
5591     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5592     IsBlockPointer = true;
5593   } else {
5594     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5595     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5596   }
5597 
5598   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5599   // differently qualified versions of compatible types, the result type is
5600   // a pointer to an appropriately qualified version of the composite
5601   // type.
5602 
5603   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5604   // clause doesn't make sense for our extensions. E.g. address space 2 should
5605   // be incompatible with address space 3: they may live on different devices or
5606   // anything.
5607   Qualifiers lhQual = lhptee.getQualifiers();
5608   Qualifiers rhQual = rhptee.getQualifiers();
5609 
5610   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5611   lhQual.removeCVRQualifiers();
5612   rhQual.removeCVRQualifiers();
5613 
5614   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5615   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5616 
5617   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5618 
5619   if (CompositeTy.isNull()) {
5620     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5621       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5622       << RHS.get()->getSourceRange();
5623     // In this situation, we assume void* type. No especially good
5624     // reason, but this is what gcc does, and we do have to pick
5625     // to get a consistent AST.
5626     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5627     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5628     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5629     return incompatTy;
5630   }
5631 
5632   // The pointer types are compatible.
5633   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5634   if (IsBlockPointer)
5635     ResultTy = S.Context.getBlockPointerType(ResultTy);
5636   else
5637     ResultTy = S.Context.getPointerType(ResultTy);
5638 
5639   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5640   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5641   return ResultTy;
5642 }
5643 
5644 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5645 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5646 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5647 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5648   if (QT->isObjCIdType())
5649     return true;
5650 
5651   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5652   if (!OPT)
5653     return false;
5654 
5655   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5656     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5657       return false;
5658 
5659   ObjCProtocolDecl* PNSCopying =
5660     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5661   ObjCProtocolDecl* PNSObject =
5662     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5663 
5664   for (auto *Proto : OPT->quals()) {
5665     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5666         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5667       ;
5668     else
5669       return false;
5670   }
5671   return true;
5672 }
5673 
5674 /// \brief Return the resulting type when the operands are both block pointers.
5675 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5676                                                           ExprResult &LHS,
5677                                                           ExprResult &RHS,
5678                                                           SourceLocation Loc) {
5679   QualType LHSTy = LHS.get()->getType();
5680   QualType RHSTy = RHS.get()->getType();
5681 
5682   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5683     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5684       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5685       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5686       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5687       return destType;
5688     }
5689     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5690       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5691       << RHS.get()->getSourceRange();
5692     return QualType();
5693   }
5694 
5695   // We have 2 block pointer types.
5696   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5697 }
5698 
5699 /// \brief Return the resulting type when the operands are both pointers.
5700 static QualType
5701 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5702                                             ExprResult &RHS,
5703                                             SourceLocation Loc) {
5704   // get the pointer types
5705   QualType LHSTy = LHS.get()->getType();
5706   QualType RHSTy = RHS.get()->getType();
5707 
5708   // get the "pointed to" types
5709   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5710   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5711 
5712   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5713   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5714     // Figure out necessary qualifiers (C99 6.5.15p6)
5715     QualType destPointee
5716       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5717     QualType destType = S.Context.getPointerType(destPointee);
5718     // Add qualifiers if necessary.
5719     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5720     // Promote to void*.
5721     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5722     return destType;
5723   }
5724   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5725     QualType destPointee
5726       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5727     QualType destType = S.Context.getPointerType(destPointee);
5728     // Add qualifiers if necessary.
5729     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5730     // Promote to void*.
5731     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5732     return destType;
5733   }
5734 
5735   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5736 }
5737 
5738 /// \brief Return false if the first expression is not an integer and the second
5739 /// expression is not a pointer, true otherwise.
5740 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5741                                         Expr* PointerExpr, SourceLocation Loc,
5742                                         bool IsIntFirstExpr) {
5743   if (!PointerExpr->getType()->isPointerType() ||
5744       !Int.get()->getType()->isIntegerType())
5745     return false;
5746 
5747   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5748   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5749 
5750   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
5751     << Expr1->getType() << Expr2->getType()
5752     << Expr1->getSourceRange() << Expr2->getSourceRange();
5753   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5754                             CK_IntegralToPointer);
5755   return true;
5756 }
5757 
5758 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5759 /// In that case, LHS = cond.
5760 /// C99 6.5.15
5761 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5762                                         ExprResult &RHS, ExprValueKind &VK,
5763                                         ExprObjectKind &OK,
5764                                         SourceLocation QuestionLoc) {
5765 
5766   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5767   if (!LHSResult.isUsable()) return QualType();
5768   LHS = LHSResult;
5769 
5770   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5771   if (!RHSResult.isUsable()) return QualType();
5772   RHS = RHSResult;
5773 
5774   // C++ is sufficiently different to merit its own checker.
5775   if (getLangOpts().CPlusPlus)
5776     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5777 
5778   VK = VK_RValue;
5779   OK = OK_Ordinary;
5780 
5781   // First, check the condition.
5782   Cond = UsualUnaryConversions(Cond.get());
5783   if (Cond.isInvalid())
5784     return QualType();
5785   if (checkCondition(*this, Cond.get()))
5786     return QualType();
5787 
5788   // Now check the two expressions.
5789   if (LHS.get()->getType()->isVectorType() ||
5790       RHS.get()->getType()->isVectorType())
5791     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5792 
5793   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5794   if (LHS.isInvalid() || RHS.isInvalid())
5795     return QualType();
5796 
5797   QualType CondTy = Cond.get()->getType();
5798   QualType LHSTy = LHS.get()->getType();
5799   QualType RHSTy = RHS.get()->getType();
5800 
5801   // If the condition is a vector, and both operands are scalar,
5802   // attempt to implicity convert them to the vector type to act like the
5803   // built in select. (OpenCL v1.1 s6.3.i)
5804   if (getLangOpts().OpenCL && CondTy->isVectorType())
5805     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5806       return QualType();
5807 
5808   // If both operands have arithmetic type, do the usual arithmetic conversions
5809   // to find a common type: C99 6.5.15p3,5.
5810   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5811     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5812     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5813 
5814     return ResTy;
5815   }
5816 
5817   // If both operands are the same structure or union type, the result is that
5818   // type.
5819   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5820     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5821       if (LHSRT->getDecl() == RHSRT->getDecl())
5822         // "If both the operands have structure or union type, the result has
5823         // that type."  This implies that CV qualifiers are dropped.
5824         return LHSTy.getUnqualifiedType();
5825     // FIXME: Type of conditional expression must be complete in C mode.
5826   }
5827 
5828   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5829   // The following || allows only one side to be void (a GCC-ism).
5830   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5831     return checkConditionalVoidType(*this, LHS, RHS);
5832   }
5833 
5834   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5835   // the type of the other operand."
5836   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5837   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5838 
5839   // All objective-c pointer type analysis is done here.
5840   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5841                                                         QuestionLoc);
5842   if (LHS.isInvalid() || RHS.isInvalid())
5843     return QualType();
5844   if (!compositeType.isNull())
5845     return compositeType;
5846 
5847 
5848   // Handle block pointer types.
5849   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5850     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5851                                                      QuestionLoc);
5852 
5853   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5854   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5855     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5856                                                        QuestionLoc);
5857 
5858   // GCC compatibility: soften pointer/integer mismatch.  Note that
5859   // null pointers have been filtered out by this point.
5860   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5861       /*isIntFirstExpr=*/true))
5862     return RHSTy;
5863   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5864       /*isIntFirstExpr=*/false))
5865     return LHSTy;
5866 
5867   // Emit a better diagnostic if one of the expressions is a null pointer
5868   // constant and the other is not a pointer type. In this case, the user most
5869   // likely forgot to take the address of the other expression.
5870   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5871     return QualType();
5872 
5873   // Otherwise, the operands are not compatible.
5874   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5875     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5876     << RHS.get()->getSourceRange();
5877   return QualType();
5878 }
5879 
5880 /// FindCompositeObjCPointerType - Helper method to find composite type of
5881 /// two objective-c pointer types of the two input expressions.
5882 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5883                                             SourceLocation QuestionLoc) {
5884   QualType LHSTy = LHS.get()->getType();
5885   QualType RHSTy = RHS.get()->getType();
5886 
5887   // Handle things like Class and struct objc_class*.  Here we case the result
5888   // to the pseudo-builtin, because that will be implicitly cast back to the
5889   // redefinition type if an attempt is made to access its fields.
5890   if (LHSTy->isObjCClassType() &&
5891       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5892     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5893     return LHSTy;
5894   }
5895   if (RHSTy->isObjCClassType() &&
5896       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5897     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5898     return RHSTy;
5899   }
5900   // And the same for struct objc_object* / id
5901   if (LHSTy->isObjCIdType() &&
5902       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5903     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5904     return LHSTy;
5905   }
5906   if (RHSTy->isObjCIdType() &&
5907       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5908     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5909     return RHSTy;
5910   }
5911   // And the same for struct objc_selector* / SEL
5912   if (Context.isObjCSelType(LHSTy) &&
5913       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5914     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5915     return LHSTy;
5916   }
5917   if (Context.isObjCSelType(RHSTy) &&
5918       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5919     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5920     return RHSTy;
5921   }
5922   // Check constraints for Objective-C object pointers types.
5923   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5924 
5925     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5926       // Two identical object pointer types are always compatible.
5927       return LHSTy;
5928     }
5929     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5930     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5931     QualType compositeType = LHSTy;
5932 
5933     // If both operands are interfaces and either operand can be
5934     // assigned to the other, use that type as the composite
5935     // type. This allows
5936     //   xxx ? (A*) a : (B*) b
5937     // where B is a subclass of A.
5938     //
5939     // Additionally, as for assignment, if either type is 'id'
5940     // allow silent coercion. Finally, if the types are
5941     // incompatible then make sure to use 'id' as the composite
5942     // type so the result is acceptable for sending messages to.
5943 
5944     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5945     // It could return the composite type.
5946     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5947       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5948     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5949       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5950     } else if ((LHSTy->isObjCQualifiedIdType() ||
5951                 RHSTy->isObjCQualifiedIdType()) &&
5952                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5953       // Need to handle "id<xx>" explicitly.
5954       // GCC allows qualified id and any Objective-C type to devolve to
5955       // id. Currently localizing to here until clear this should be
5956       // part of ObjCQualifiedIdTypesAreCompatible.
5957       compositeType = Context.getObjCIdType();
5958     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5959       compositeType = Context.getObjCIdType();
5960     } else if (!(compositeType =
5961                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5962       ;
5963     else {
5964       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5965       << LHSTy << RHSTy
5966       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5967       QualType incompatTy = Context.getObjCIdType();
5968       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5969       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5970       return incompatTy;
5971     }
5972     // The object pointer types are compatible.
5973     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5974     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5975     return compositeType;
5976   }
5977   // Check Objective-C object pointer types and 'void *'
5978   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5979     if (getLangOpts().ObjCAutoRefCount) {
5980       // ARC forbids the implicit conversion of object pointers to 'void *',
5981       // so these types are not compatible.
5982       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5983           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5984       LHS = RHS = true;
5985       return QualType();
5986     }
5987     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5988     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5989     QualType destPointee
5990     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5991     QualType destType = Context.getPointerType(destPointee);
5992     // Add qualifiers if necessary.
5993     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5994     // Promote to void*.
5995     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5996     return destType;
5997   }
5998   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5999     if (getLangOpts().ObjCAutoRefCount) {
6000       // ARC forbids the implicit conversion of object pointers to 'void *',
6001       // so these types are not compatible.
6002       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6003           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6004       LHS = RHS = true;
6005       return QualType();
6006     }
6007     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6008     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6009     QualType destPointee
6010     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6011     QualType destType = Context.getPointerType(destPointee);
6012     // Add qualifiers if necessary.
6013     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6014     // Promote to void*.
6015     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6016     return destType;
6017   }
6018   return QualType();
6019 }
6020 
6021 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6022 /// ParenRange in parentheses.
6023 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6024                                const PartialDiagnostic &Note,
6025                                SourceRange ParenRange) {
6026   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6027   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6028       EndLoc.isValid()) {
6029     Self.Diag(Loc, Note)
6030       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6031       << FixItHint::CreateInsertion(EndLoc, ")");
6032   } else {
6033     // We can't display the parentheses, so just show the bare note.
6034     Self.Diag(Loc, Note) << ParenRange;
6035   }
6036 }
6037 
6038 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6039   return Opc >= BO_Mul && Opc <= BO_Shr;
6040 }
6041 
6042 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6043 /// expression, either using a built-in or overloaded operator,
6044 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6045 /// expression.
6046 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6047                                    Expr **RHSExprs) {
6048   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6049   E = E->IgnoreImpCasts();
6050   E = E->IgnoreConversionOperator();
6051   E = E->IgnoreImpCasts();
6052 
6053   // Built-in binary operator.
6054   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6055     if (IsArithmeticOp(OP->getOpcode())) {
6056       *Opcode = OP->getOpcode();
6057       *RHSExprs = OP->getRHS();
6058       return true;
6059     }
6060   }
6061 
6062   // Overloaded operator.
6063   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6064     if (Call->getNumArgs() != 2)
6065       return false;
6066 
6067     // Make sure this is really a binary operator that is safe to pass into
6068     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6069     OverloadedOperatorKind OO = Call->getOperator();
6070     if (OO < OO_Plus || OO > OO_Arrow ||
6071         OO == OO_PlusPlus || OO == OO_MinusMinus)
6072       return false;
6073 
6074     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6075     if (IsArithmeticOp(OpKind)) {
6076       *Opcode = OpKind;
6077       *RHSExprs = Call->getArg(1);
6078       return true;
6079     }
6080   }
6081 
6082   return false;
6083 }
6084 
6085 static bool IsLogicOp(BinaryOperatorKind Opc) {
6086   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6087 }
6088 
6089 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6090 /// or is a logical expression such as (x==y) which has int type, but is
6091 /// commonly interpreted as boolean.
6092 static bool ExprLooksBoolean(Expr *E) {
6093   E = E->IgnoreParenImpCasts();
6094 
6095   if (E->getType()->isBooleanType())
6096     return true;
6097   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6098     return IsLogicOp(OP->getOpcode());
6099   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6100     return OP->getOpcode() == UO_LNot;
6101 
6102   return false;
6103 }
6104 
6105 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6106 /// and binary operator are mixed in a way that suggests the programmer assumed
6107 /// the conditional operator has higher precedence, for example:
6108 /// "int x = a + someBinaryCondition ? 1 : 2".
6109 static void DiagnoseConditionalPrecedence(Sema &Self,
6110                                           SourceLocation OpLoc,
6111                                           Expr *Condition,
6112                                           Expr *LHSExpr,
6113                                           Expr *RHSExpr) {
6114   BinaryOperatorKind CondOpcode;
6115   Expr *CondRHS;
6116 
6117   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6118     return;
6119   if (!ExprLooksBoolean(CondRHS))
6120     return;
6121 
6122   // The condition is an arithmetic binary expression, with a right-
6123   // hand side that looks boolean, so warn.
6124 
6125   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6126       << Condition->getSourceRange()
6127       << BinaryOperator::getOpcodeStr(CondOpcode);
6128 
6129   SuggestParentheses(Self, OpLoc,
6130     Self.PDiag(diag::note_precedence_silence)
6131       << BinaryOperator::getOpcodeStr(CondOpcode),
6132     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6133 
6134   SuggestParentheses(Self, OpLoc,
6135     Self.PDiag(diag::note_precedence_conditional_first),
6136     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6137 }
6138 
6139 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6140 /// in the case of a the GNU conditional expr extension.
6141 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6142                                     SourceLocation ColonLoc,
6143                                     Expr *CondExpr, Expr *LHSExpr,
6144                                     Expr *RHSExpr) {
6145   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6146   // was the condition.
6147   OpaqueValueExpr *opaqueValue = nullptr;
6148   Expr *commonExpr = nullptr;
6149   if (!LHSExpr) {
6150     commonExpr = CondExpr;
6151     // Lower out placeholder types first.  This is important so that we don't
6152     // try to capture a placeholder. This happens in few cases in C++; such
6153     // as Objective-C++'s dictionary subscripting syntax.
6154     if (commonExpr->hasPlaceholderType()) {
6155       ExprResult result = CheckPlaceholderExpr(commonExpr);
6156       if (!result.isUsable()) return ExprError();
6157       commonExpr = result.get();
6158     }
6159     // We usually want to apply unary conversions *before* saving, except
6160     // in the special case of a C++ l-value conditional.
6161     if (!(getLangOpts().CPlusPlus
6162           && !commonExpr->isTypeDependent()
6163           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6164           && commonExpr->isGLValue()
6165           && commonExpr->isOrdinaryOrBitFieldObject()
6166           && RHSExpr->isOrdinaryOrBitFieldObject()
6167           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6168       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6169       if (commonRes.isInvalid())
6170         return ExprError();
6171       commonExpr = commonRes.get();
6172     }
6173 
6174     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6175                                                 commonExpr->getType(),
6176                                                 commonExpr->getValueKind(),
6177                                                 commonExpr->getObjectKind(),
6178                                                 commonExpr);
6179     LHSExpr = CondExpr = opaqueValue;
6180   }
6181 
6182   ExprValueKind VK = VK_RValue;
6183   ExprObjectKind OK = OK_Ordinary;
6184   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6185   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6186                                              VK, OK, QuestionLoc);
6187   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6188       RHS.isInvalid())
6189     return ExprError();
6190 
6191   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6192                                 RHS.get());
6193 
6194   if (!commonExpr)
6195     return new (Context)
6196         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6197                             RHS.get(), result, VK, OK);
6198 
6199   return new (Context) BinaryConditionalOperator(
6200       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6201       ColonLoc, result, VK, OK);
6202 }
6203 
6204 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6205 // being closely modeled after the C99 spec:-). The odd characteristic of this
6206 // routine is it effectively iqnores the qualifiers on the top level pointee.
6207 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6208 // FIXME: add a couple examples in this comment.
6209 static Sema::AssignConvertType
6210 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6211   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6212   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6213 
6214   // get the "pointed to" type (ignoring qualifiers at the top level)
6215   const Type *lhptee, *rhptee;
6216   Qualifiers lhq, rhq;
6217   std::tie(lhptee, lhq) =
6218       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6219   std::tie(rhptee, rhq) =
6220       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6221 
6222   Sema::AssignConvertType ConvTy = Sema::Compatible;
6223 
6224   // C99 6.5.16.1p1: This following citation is common to constraints
6225   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6226   // qualifiers of the type *pointed to* by the right;
6227 
6228   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6229   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6230       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6231     // Ignore lifetime for further calculation.
6232     lhq.removeObjCLifetime();
6233     rhq.removeObjCLifetime();
6234   }
6235 
6236   if (!lhq.compatiblyIncludes(rhq)) {
6237     // Treat address-space mismatches as fatal.  TODO: address subspaces
6238     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6239       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6240 
6241     // It's okay to add or remove GC or lifetime qualifiers when converting to
6242     // and from void*.
6243     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6244                         .compatiblyIncludes(
6245                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6246              && (lhptee->isVoidType() || rhptee->isVoidType()))
6247       ; // keep old
6248 
6249     // Treat lifetime mismatches as fatal.
6250     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6251       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6252 
6253     // For GCC compatibility, other qualifier mismatches are treated
6254     // as still compatible in C.
6255     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6256   }
6257 
6258   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6259   // incomplete type and the other is a pointer to a qualified or unqualified
6260   // version of void...
6261   if (lhptee->isVoidType()) {
6262     if (rhptee->isIncompleteOrObjectType())
6263       return ConvTy;
6264 
6265     // As an extension, we allow cast to/from void* to function pointer.
6266     assert(rhptee->isFunctionType());
6267     return Sema::FunctionVoidPointer;
6268   }
6269 
6270   if (rhptee->isVoidType()) {
6271     if (lhptee->isIncompleteOrObjectType())
6272       return ConvTy;
6273 
6274     // As an extension, we allow cast to/from void* to function pointer.
6275     assert(lhptee->isFunctionType());
6276     return Sema::FunctionVoidPointer;
6277   }
6278 
6279   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6280   // unqualified versions of compatible types, ...
6281   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6282   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6283     // Check if the pointee types are compatible ignoring the sign.
6284     // We explicitly check for char so that we catch "char" vs
6285     // "unsigned char" on systems where "char" is unsigned.
6286     if (lhptee->isCharType())
6287       ltrans = S.Context.UnsignedCharTy;
6288     else if (lhptee->hasSignedIntegerRepresentation())
6289       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6290 
6291     if (rhptee->isCharType())
6292       rtrans = S.Context.UnsignedCharTy;
6293     else if (rhptee->hasSignedIntegerRepresentation())
6294       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6295 
6296     if (ltrans == rtrans) {
6297       // Types are compatible ignoring the sign. Qualifier incompatibility
6298       // takes priority over sign incompatibility because the sign
6299       // warning can be disabled.
6300       if (ConvTy != Sema::Compatible)
6301         return ConvTy;
6302 
6303       return Sema::IncompatiblePointerSign;
6304     }
6305 
6306     // If we are a multi-level pointer, it's possible that our issue is simply
6307     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6308     // the eventual target type is the same and the pointers have the same
6309     // level of indirection, this must be the issue.
6310     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6311       do {
6312         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6313         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6314       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6315 
6316       if (lhptee == rhptee)
6317         return Sema::IncompatibleNestedPointerQualifiers;
6318     }
6319 
6320     // General pointer incompatibility takes priority over qualifiers.
6321     return Sema::IncompatiblePointer;
6322   }
6323   if (!S.getLangOpts().CPlusPlus &&
6324       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6325     return Sema::IncompatiblePointer;
6326   return ConvTy;
6327 }
6328 
6329 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6330 /// block pointer types are compatible or whether a block and normal pointer
6331 /// are compatible. It is more restrict than comparing two function pointer
6332 // types.
6333 static Sema::AssignConvertType
6334 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6335                                     QualType RHSType) {
6336   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6337   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6338 
6339   QualType lhptee, rhptee;
6340 
6341   // get the "pointed to" type (ignoring qualifiers at the top level)
6342   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6343   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6344 
6345   // In C++, the types have to match exactly.
6346   if (S.getLangOpts().CPlusPlus)
6347     return Sema::IncompatibleBlockPointer;
6348 
6349   Sema::AssignConvertType ConvTy = Sema::Compatible;
6350 
6351   // For blocks we enforce that qualifiers are identical.
6352   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6353     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6354 
6355   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6356     return Sema::IncompatibleBlockPointer;
6357 
6358   return ConvTy;
6359 }
6360 
6361 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6362 /// for assignment compatibility.
6363 static Sema::AssignConvertType
6364 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6365                                    QualType RHSType) {
6366   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6367   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6368 
6369   if (LHSType->isObjCBuiltinType()) {
6370     // Class is not compatible with ObjC object pointers.
6371     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6372         !RHSType->isObjCQualifiedClassType())
6373       return Sema::IncompatiblePointer;
6374     return Sema::Compatible;
6375   }
6376   if (RHSType->isObjCBuiltinType()) {
6377     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6378         !LHSType->isObjCQualifiedClassType())
6379       return Sema::IncompatiblePointer;
6380     return Sema::Compatible;
6381   }
6382   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6383   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6384 
6385   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6386       // make an exception for id<P>
6387       !LHSType->isObjCQualifiedIdType())
6388     return Sema::CompatiblePointerDiscardsQualifiers;
6389 
6390   if (S.Context.typesAreCompatible(LHSType, RHSType))
6391     return Sema::Compatible;
6392   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6393     return Sema::IncompatibleObjCQualifiedId;
6394   return Sema::IncompatiblePointer;
6395 }
6396 
6397 Sema::AssignConvertType
6398 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6399                                  QualType LHSType, QualType RHSType) {
6400   // Fake up an opaque expression.  We don't actually care about what
6401   // cast operations are required, so if CheckAssignmentConstraints
6402   // adds casts to this they'll be wasted, but fortunately that doesn't
6403   // usually happen on valid code.
6404   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6405   ExprResult RHSPtr = &RHSExpr;
6406   CastKind K = CK_Invalid;
6407 
6408   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6409 }
6410 
6411 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6412 /// has code to accommodate several GCC extensions when type checking
6413 /// pointers. Here are some objectionable examples that GCC considers warnings:
6414 ///
6415 ///  int a, *pint;
6416 ///  short *pshort;
6417 ///  struct foo *pfoo;
6418 ///
6419 ///  pint = pshort; // warning: assignment from incompatible pointer type
6420 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6421 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6422 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6423 ///
6424 /// As a result, the code for dealing with pointers is more complex than the
6425 /// C99 spec dictates.
6426 ///
6427 /// Sets 'Kind' for any result kind except Incompatible.
6428 Sema::AssignConvertType
6429 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6430                                  CastKind &Kind) {
6431   QualType RHSType = RHS.get()->getType();
6432   QualType OrigLHSType = LHSType;
6433 
6434   // Get canonical types.  We're not formatting these types, just comparing
6435   // them.
6436   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6437   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6438 
6439   // Common case: no conversion required.
6440   if (LHSType == RHSType) {
6441     Kind = CK_NoOp;
6442     return Compatible;
6443   }
6444 
6445   // If we have an atomic type, try a non-atomic assignment, then just add an
6446   // atomic qualification step.
6447   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6448     Sema::AssignConvertType result =
6449       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6450     if (result != Compatible)
6451       return result;
6452     if (Kind != CK_NoOp)
6453       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6454     Kind = CK_NonAtomicToAtomic;
6455     return Compatible;
6456   }
6457 
6458   // If the left-hand side is a reference type, then we are in a
6459   // (rare!) case where we've allowed the use of references in C,
6460   // e.g., as a parameter type in a built-in function. In this case,
6461   // just make sure that the type referenced is compatible with the
6462   // right-hand side type. The caller is responsible for adjusting
6463   // LHSType so that the resulting expression does not have reference
6464   // type.
6465   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6466     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6467       Kind = CK_LValueBitCast;
6468       return Compatible;
6469     }
6470     return Incompatible;
6471   }
6472 
6473   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6474   // to the same ExtVector type.
6475   if (LHSType->isExtVectorType()) {
6476     if (RHSType->isExtVectorType())
6477       return Incompatible;
6478     if (RHSType->isArithmeticType()) {
6479       // CK_VectorSplat does T -> vector T, so first cast to the
6480       // element type.
6481       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6482       if (elType != RHSType) {
6483         Kind = PrepareScalarCast(RHS, elType);
6484         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6485       }
6486       Kind = CK_VectorSplat;
6487       return Compatible;
6488     }
6489   }
6490 
6491   // Conversions to or from vector type.
6492   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6493     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6494       // Allow assignments of an AltiVec vector type to an equivalent GCC
6495       // vector type and vice versa
6496       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6497         Kind = CK_BitCast;
6498         return Compatible;
6499       }
6500 
6501       // If we are allowing lax vector conversions, and LHS and RHS are both
6502       // vectors, the total size only needs to be the same. This is a bitcast;
6503       // no bits are changed but the result type is different.
6504       if (isLaxVectorConversion(RHSType, LHSType)) {
6505         Kind = CK_BitCast;
6506         return IncompatibleVectors;
6507       }
6508     }
6509     return Incompatible;
6510   }
6511 
6512   // Arithmetic conversions.
6513   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6514       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6515     Kind = PrepareScalarCast(RHS, LHSType);
6516     return Compatible;
6517   }
6518 
6519   // Conversions to normal pointers.
6520   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6521     // U* -> T*
6522     if (isa<PointerType>(RHSType)) {
6523       Kind = CK_BitCast;
6524       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6525     }
6526 
6527     // int -> T*
6528     if (RHSType->isIntegerType()) {
6529       Kind = CK_IntegralToPointer; // FIXME: null?
6530       return IntToPointer;
6531     }
6532 
6533     // C pointers are not compatible with ObjC object pointers,
6534     // with two exceptions:
6535     if (isa<ObjCObjectPointerType>(RHSType)) {
6536       //  - conversions to void*
6537       if (LHSPointer->getPointeeType()->isVoidType()) {
6538         Kind = CK_BitCast;
6539         return Compatible;
6540       }
6541 
6542       //  - conversions from 'Class' to the redefinition type
6543       if (RHSType->isObjCClassType() &&
6544           Context.hasSameType(LHSType,
6545                               Context.getObjCClassRedefinitionType())) {
6546         Kind = CK_BitCast;
6547         return Compatible;
6548       }
6549 
6550       Kind = CK_BitCast;
6551       return IncompatiblePointer;
6552     }
6553 
6554     // U^ -> void*
6555     if (RHSType->getAs<BlockPointerType>()) {
6556       if (LHSPointer->getPointeeType()->isVoidType()) {
6557         Kind = CK_BitCast;
6558         return Compatible;
6559       }
6560     }
6561 
6562     return Incompatible;
6563   }
6564 
6565   // Conversions to block pointers.
6566   if (isa<BlockPointerType>(LHSType)) {
6567     // U^ -> T^
6568     if (RHSType->isBlockPointerType()) {
6569       Kind = CK_BitCast;
6570       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6571     }
6572 
6573     // int or null -> T^
6574     if (RHSType->isIntegerType()) {
6575       Kind = CK_IntegralToPointer; // FIXME: null
6576       return IntToBlockPointer;
6577     }
6578 
6579     // id -> T^
6580     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6581       Kind = CK_AnyPointerToBlockPointerCast;
6582       return Compatible;
6583     }
6584 
6585     // void* -> T^
6586     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6587       if (RHSPT->getPointeeType()->isVoidType()) {
6588         Kind = CK_AnyPointerToBlockPointerCast;
6589         return Compatible;
6590       }
6591 
6592     return Incompatible;
6593   }
6594 
6595   // Conversions to Objective-C pointers.
6596   if (isa<ObjCObjectPointerType>(LHSType)) {
6597     // A* -> B*
6598     if (RHSType->isObjCObjectPointerType()) {
6599       Kind = CK_BitCast;
6600       Sema::AssignConvertType result =
6601         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6602       if (getLangOpts().ObjCAutoRefCount &&
6603           result == Compatible &&
6604           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6605         result = IncompatibleObjCWeakRef;
6606       return result;
6607     }
6608 
6609     // int or null -> A*
6610     if (RHSType->isIntegerType()) {
6611       Kind = CK_IntegralToPointer; // FIXME: null
6612       return IntToPointer;
6613     }
6614 
6615     // In general, C pointers are not compatible with ObjC object pointers,
6616     // with two exceptions:
6617     if (isa<PointerType>(RHSType)) {
6618       Kind = CK_CPointerToObjCPointerCast;
6619 
6620       //  - conversions from 'void*'
6621       if (RHSType->isVoidPointerType()) {
6622         return Compatible;
6623       }
6624 
6625       //  - conversions to 'Class' from its redefinition type
6626       if (LHSType->isObjCClassType() &&
6627           Context.hasSameType(RHSType,
6628                               Context.getObjCClassRedefinitionType())) {
6629         return Compatible;
6630       }
6631 
6632       return IncompatiblePointer;
6633     }
6634 
6635     // Only under strict condition T^ is compatible with an Objective-C pointer.
6636     if (RHSType->isBlockPointerType() &&
6637         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6638       maybeExtendBlockObject(*this, RHS);
6639       Kind = CK_BlockPointerToObjCPointerCast;
6640       return Compatible;
6641     }
6642 
6643     return Incompatible;
6644   }
6645 
6646   // Conversions from pointers that are not covered by the above.
6647   if (isa<PointerType>(RHSType)) {
6648     // T* -> _Bool
6649     if (LHSType == Context.BoolTy) {
6650       Kind = CK_PointerToBoolean;
6651       return Compatible;
6652     }
6653 
6654     // T* -> int
6655     if (LHSType->isIntegerType()) {
6656       Kind = CK_PointerToIntegral;
6657       return PointerToInt;
6658     }
6659 
6660     return Incompatible;
6661   }
6662 
6663   // Conversions from Objective-C pointers that are not covered by the above.
6664   if (isa<ObjCObjectPointerType>(RHSType)) {
6665     // T* -> _Bool
6666     if (LHSType == Context.BoolTy) {
6667       Kind = CK_PointerToBoolean;
6668       return Compatible;
6669     }
6670 
6671     // T* -> int
6672     if (LHSType->isIntegerType()) {
6673       Kind = CK_PointerToIntegral;
6674       return PointerToInt;
6675     }
6676 
6677     return Incompatible;
6678   }
6679 
6680   // struct A -> struct B
6681   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6682     if (Context.typesAreCompatible(LHSType, RHSType)) {
6683       Kind = CK_NoOp;
6684       return Compatible;
6685     }
6686   }
6687 
6688   return Incompatible;
6689 }
6690 
6691 /// \brief Constructs a transparent union from an expression that is
6692 /// used to initialize the transparent union.
6693 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6694                                       ExprResult &EResult, QualType UnionType,
6695                                       FieldDecl *Field) {
6696   // Build an initializer list that designates the appropriate member
6697   // of the transparent union.
6698   Expr *E = EResult.get();
6699   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6700                                                    E, SourceLocation());
6701   Initializer->setType(UnionType);
6702   Initializer->setInitializedFieldInUnion(Field);
6703 
6704   // Build a compound literal constructing a value of the transparent
6705   // union type from this initializer list.
6706   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6707   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6708                                         VK_RValue, Initializer, false);
6709 }
6710 
6711 Sema::AssignConvertType
6712 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6713                                                ExprResult &RHS) {
6714   QualType RHSType = RHS.get()->getType();
6715 
6716   // If the ArgType is a Union type, we want to handle a potential
6717   // transparent_union GCC extension.
6718   const RecordType *UT = ArgType->getAsUnionType();
6719   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6720     return Incompatible;
6721 
6722   // The field to initialize within the transparent union.
6723   RecordDecl *UD = UT->getDecl();
6724   FieldDecl *InitField = nullptr;
6725   // It's compatible if the expression matches any of the fields.
6726   for (auto *it : UD->fields()) {
6727     if (it->getType()->isPointerType()) {
6728       // If the transparent union contains a pointer type, we allow:
6729       // 1) void pointer
6730       // 2) null pointer constant
6731       if (RHSType->isPointerType())
6732         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6733           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6734           InitField = it;
6735           break;
6736         }
6737 
6738       if (RHS.get()->isNullPointerConstant(Context,
6739                                            Expr::NPC_ValueDependentIsNull)) {
6740         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6741                                 CK_NullToPointer);
6742         InitField = it;
6743         break;
6744       }
6745     }
6746 
6747     CastKind Kind = CK_Invalid;
6748     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6749           == Compatible) {
6750       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6751       InitField = it;
6752       break;
6753     }
6754   }
6755 
6756   if (!InitField)
6757     return Incompatible;
6758 
6759   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6760   return Compatible;
6761 }
6762 
6763 Sema::AssignConvertType
6764 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6765                                        bool Diagnose,
6766                                        bool DiagnoseCFAudited) {
6767   if (getLangOpts().CPlusPlus) {
6768     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6769       // C++ 5.17p3: If the left operand is not of class type, the
6770       // expression is implicitly converted (C++ 4) to the
6771       // cv-unqualified type of the left operand.
6772       ExprResult Res;
6773       if (Diagnose) {
6774         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6775                                         AA_Assigning);
6776       } else {
6777         ImplicitConversionSequence ICS =
6778             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6779                                   /*SuppressUserConversions=*/false,
6780                                   /*AllowExplicit=*/false,
6781                                   /*InOverloadResolution=*/false,
6782                                   /*CStyle=*/false,
6783                                   /*AllowObjCWritebackConversion=*/false);
6784         if (ICS.isFailure())
6785           return Incompatible;
6786         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6787                                         ICS, AA_Assigning);
6788       }
6789       if (Res.isInvalid())
6790         return Incompatible;
6791       Sema::AssignConvertType result = Compatible;
6792       if (getLangOpts().ObjCAutoRefCount &&
6793           !CheckObjCARCUnavailableWeakConversion(LHSType,
6794                                                  RHS.get()->getType()))
6795         result = IncompatibleObjCWeakRef;
6796       RHS = Res;
6797       return result;
6798     }
6799 
6800     // FIXME: Currently, we fall through and treat C++ classes like C
6801     // structures.
6802     // FIXME: We also fall through for atomics; not sure what should
6803     // happen there, though.
6804   }
6805 
6806   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6807   // a null pointer constant.
6808   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6809        LHSType->isBlockPointerType()) &&
6810       RHS.get()->isNullPointerConstant(Context,
6811                                        Expr::NPC_ValueDependentIsNull)) {
6812     CastKind Kind;
6813     CXXCastPath Path;
6814     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6815     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6816     return Compatible;
6817   }
6818 
6819   // This check seems unnatural, however it is necessary to ensure the proper
6820   // conversion of functions/arrays. If the conversion were done for all
6821   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6822   // expressions that suppress this implicit conversion (&, sizeof).
6823   //
6824   // Suppress this for references: C++ 8.5.3p5.
6825   if (!LHSType->isReferenceType()) {
6826     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6827     if (RHS.isInvalid())
6828       return Incompatible;
6829   }
6830 
6831   Expr *PRE = RHS.get()->IgnoreParenCasts();
6832   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
6833     ObjCProtocolDecl *PDecl = OPE->getProtocol();
6834     if (PDecl && !PDecl->hasDefinition()) {
6835       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
6836       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
6837     }
6838   }
6839 
6840   CastKind Kind = CK_Invalid;
6841   Sema::AssignConvertType result =
6842     CheckAssignmentConstraints(LHSType, RHS, Kind);
6843 
6844   // C99 6.5.16.1p2: The value of the right operand is converted to the
6845   // type of the assignment expression.
6846   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6847   // so that we can use references in built-in functions even in C.
6848   // The getNonReferenceType() call makes sure that the resulting expression
6849   // does not have reference type.
6850   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6851     QualType Ty = LHSType.getNonLValueExprType(Context);
6852     Expr *E = RHS.get();
6853     if (getLangOpts().ObjCAutoRefCount)
6854       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6855                              DiagnoseCFAudited);
6856     if (getLangOpts().ObjC1 &&
6857         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6858                                           LHSType, E->getType(), E) ||
6859          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6860       RHS = E;
6861       return Compatible;
6862     }
6863 
6864     RHS = ImpCastExprToType(E, Ty, Kind);
6865   }
6866   return result;
6867 }
6868 
6869 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6870                                ExprResult &RHS) {
6871   Diag(Loc, diag::err_typecheck_invalid_operands)
6872     << LHS.get()->getType() << RHS.get()->getType()
6873     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6874   return QualType();
6875 }
6876 
6877 /// Try to convert a value of non-vector type to a vector type by converting
6878 /// the type to the element type of the vector and then performing a splat.
6879 /// If the language is OpenCL, we only use conversions that promote scalar
6880 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6881 /// for float->int.
6882 ///
6883 /// \param scalar - if non-null, actually perform the conversions
6884 /// \return true if the operation fails (but without diagnosing the failure)
6885 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6886                                      QualType scalarTy,
6887                                      QualType vectorEltTy,
6888                                      QualType vectorTy) {
6889   // The conversion to apply to the scalar before splatting it,
6890   // if necessary.
6891   CastKind scalarCast = CK_Invalid;
6892 
6893   if (vectorEltTy->isIntegralType(S.Context)) {
6894     if (!scalarTy->isIntegralType(S.Context))
6895       return true;
6896     if (S.getLangOpts().OpenCL &&
6897         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6898       return true;
6899     scalarCast = CK_IntegralCast;
6900   } else if (vectorEltTy->isRealFloatingType()) {
6901     if (scalarTy->isRealFloatingType()) {
6902       if (S.getLangOpts().OpenCL &&
6903           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6904         return true;
6905       scalarCast = CK_FloatingCast;
6906     }
6907     else if (scalarTy->isIntegralType(S.Context))
6908       scalarCast = CK_IntegralToFloating;
6909     else
6910       return true;
6911   } else {
6912     return true;
6913   }
6914 
6915   // Adjust scalar if desired.
6916   if (scalar) {
6917     if (scalarCast != CK_Invalid)
6918       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6919     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6920   }
6921   return false;
6922 }
6923 
6924 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6925                                    SourceLocation Loc, bool IsCompAssign) {
6926   if (!IsCompAssign) {
6927     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6928     if (LHS.isInvalid())
6929       return QualType();
6930   }
6931   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6932   if (RHS.isInvalid())
6933     return QualType();
6934 
6935   // For conversion purposes, we ignore any qualifiers.
6936   // For example, "const float" and "float" are equivalent.
6937   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6938   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6939 
6940   // If the vector types are identical, return.
6941   if (Context.hasSameType(LHSType, RHSType))
6942     return LHSType;
6943 
6944   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6945   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6946   assert(LHSVecType || RHSVecType);
6947 
6948   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6949   if (LHSVecType && RHSVecType &&
6950       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6951     if (isa<ExtVectorType>(LHSVecType)) {
6952       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6953       return LHSType;
6954     }
6955 
6956     if (!IsCompAssign)
6957       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6958     return RHSType;
6959   }
6960 
6961   // If there's an ext-vector type and a scalar, try to convert the scalar to
6962   // the vector element type and splat.
6963   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6964     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6965                                   LHSVecType->getElementType(), LHSType))
6966       return LHSType;
6967   }
6968   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6969     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6970                                   LHSType, RHSVecType->getElementType(),
6971                                   RHSType))
6972       return RHSType;
6973   }
6974 
6975   // If we're allowing lax vector conversions, only the total (data) size
6976   // needs to be the same.
6977   // FIXME: Should we really be allowing this?
6978   // FIXME: We really just pick the LHS type arbitrarily?
6979   if (isLaxVectorConversion(RHSType, LHSType)) {
6980     QualType resultType = LHSType;
6981     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
6982     return resultType;
6983   }
6984 
6985   // Okay, the expression is invalid.
6986 
6987   // If there's a non-vector, non-real operand, diagnose that.
6988   if ((!RHSVecType && !RHSType->isRealType()) ||
6989       (!LHSVecType && !LHSType->isRealType())) {
6990     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6991       << LHSType << RHSType
6992       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6993     return QualType();
6994   }
6995 
6996   // Otherwise, use the generic diagnostic.
6997   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6998     << LHSType << RHSType
6999     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7000   return QualType();
7001 }
7002 
7003 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7004 // expression.  These are mainly cases where the null pointer is used as an
7005 // integer instead of a pointer.
7006 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7007                                 SourceLocation Loc, bool IsCompare) {
7008   // The canonical way to check for a GNU null is with isNullPointerConstant,
7009   // but we use a bit of a hack here for speed; this is a relatively
7010   // hot path, and isNullPointerConstant is slow.
7011   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7012   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7013 
7014   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7015 
7016   // Avoid analyzing cases where the result will either be invalid (and
7017   // diagnosed as such) or entirely valid and not something to warn about.
7018   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7019       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7020     return;
7021 
7022   // Comparison operations would not make sense with a null pointer no matter
7023   // what the other expression is.
7024   if (!IsCompare) {
7025     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7026         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7027         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7028     return;
7029   }
7030 
7031   // The rest of the operations only make sense with a null pointer
7032   // if the other expression is a pointer.
7033   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7034       NonNullType->canDecayToPointerType())
7035     return;
7036 
7037   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7038       << LHSNull /* LHS is NULL */ << NonNullType
7039       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7040 }
7041 
7042 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7043                                            SourceLocation Loc,
7044                                            bool IsCompAssign, bool IsDiv) {
7045   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7046 
7047   if (LHS.get()->getType()->isVectorType() ||
7048       RHS.get()->getType()->isVectorType())
7049     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7050 
7051   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7052   if (LHS.isInvalid() || RHS.isInvalid())
7053     return QualType();
7054 
7055 
7056   if (compType.isNull() || !compType->isArithmeticType())
7057     return InvalidOperands(Loc, LHS, RHS);
7058 
7059   // Check for division by zero.
7060   llvm::APSInt RHSValue;
7061   if (IsDiv && !RHS.get()->isValueDependent() &&
7062       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7063     DiagRuntimeBehavior(Loc, RHS.get(),
7064                         PDiag(diag::warn_division_by_zero)
7065                           << RHS.get()->getSourceRange());
7066 
7067   return compType;
7068 }
7069 
7070 QualType Sema::CheckRemainderOperands(
7071   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7072   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7073 
7074   if (LHS.get()->getType()->isVectorType() ||
7075       RHS.get()->getType()->isVectorType()) {
7076     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7077         RHS.get()->getType()->hasIntegerRepresentation())
7078       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7079     return InvalidOperands(Loc, LHS, RHS);
7080   }
7081 
7082   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7083   if (LHS.isInvalid() || RHS.isInvalid())
7084     return QualType();
7085 
7086   if (compType.isNull() || !compType->isIntegerType())
7087     return InvalidOperands(Loc, LHS, RHS);
7088 
7089   // Check for remainder by zero.
7090   llvm::APSInt RHSValue;
7091   if (!RHS.get()->isValueDependent() &&
7092       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7093     DiagRuntimeBehavior(Loc, RHS.get(),
7094                         PDiag(diag::warn_remainder_by_zero)
7095                           << RHS.get()->getSourceRange());
7096 
7097   return compType;
7098 }
7099 
7100 /// \brief Diagnose invalid arithmetic on two void pointers.
7101 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7102                                                 Expr *LHSExpr, Expr *RHSExpr) {
7103   S.Diag(Loc, S.getLangOpts().CPlusPlus
7104                 ? diag::err_typecheck_pointer_arith_void_type
7105                 : diag::ext_gnu_void_ptr)
7106     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7107                             << RHSExpr->getSourceRange();
7108 }
7109 
7110 /// \brief Diagnose invalid arithmetic on a void pointer.
7111 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7112                                             Expr *Pointer) {
7113   S.Diag(Loc, S.getLangOpts().CPlusPlus
7114                 ? diag::err_typecheck_pointer_arith_void_type
7115                 : diag::ext_gnu_void_ptr)
7116     << 0 /* one pointer */ << Pointer->getSourceRange();
7117 }
7118 
7119 /// \brief Diagnose invalid arithmetic on two function pointers.
7120 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7121                                                     Expr *LHS, Expr *RHS) {
7122   assert(LHS->getType()->isAnyPointerType());
7123   assert(RHS->getType()->isAnyPointerType());
7124   S.Diag(Loc, S.getLangOpts().CPlusPlus
7125                 ? diag::err_typecheck_pointer_arith_function_type
7126                 : diag::ext_gnu_ptr_func_arith)
7127     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7128     // We only show the second type if it differs from the first.
7129     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7130                                                    RHS->getType())
7131     << RHS->getType()->getPointeeType()
7132     << LHS->getSourceRange() << RHS->getSourceRange();
7133 }
7134 
7135 /// \brief Diagnose invalid arithmetic on a function pointer.
7136 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7137                                                 Expr *Pointer) {
7138   assert(Pointer->getType()->isAnyPointerType());
7139   S.Diag(Loc, S.getLangOpts().CPlusPlus
7140                 ? diag::err_typecheck_pointer_arith_function_type
7141                 : diag::ext_gnu_ptr_func_arith)
7142     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7143     << 0 /* one pointer, so only one type */
7144     << Pointer->getSourceRange();
7145 }
7146 
7147 /// \brief Emit error if Operand is incomplete pointer type
7148 ///
7149 /// \returns True if pointer has incomplete type
7150 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7151                                                  Expr *Operand) {
7152   assert(Operand->getType()->isAnyPointerType() &&
7153          !Operand->getType()->isDependentType());
7154   QualType PointeeTy = Operand->getType()->getPointeeType();
7155   return S.RequireCompleteType(Loc, PointeeTy,
7156                                diag::err_typecheck_arithmetic_incomplete_type,
7157                                PointeeTy, Operand->getSourceRange());
7158 }
7159 
7160 /// \brief Check the validity of an arithmetic pointer operand.
7161 ///
7162 /// If the operand has pointer type, this code will check for pointer types
7163 /// which are invalid in arithmetic operations. These will be diagnosed
7164 /// appropriately, including whether or not the use is supported as an
7165 /// extension.
7166 ///
7167 /// \returns True when the operand is valid to use (even if as an extension).
7168 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7169                                             Expr *Operand) {
7170   if (!Operand->getType()->isAnyPointerType()) return true;
7171 
7172   QualType PointeeTy = Operand->getType()->getPointeeType();
7173   if (PointeeTy->isVoidType()) {
7174     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7175     return !S.getLangOpts().CPlusPlus;
7176   }
7177   if (PointeeTy->isFunctionType()) {
7178     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7179     return !S.getLangOpts().CPlusPlus;
7180   }
7181 
7182   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7183 
7184   return true;
7185 }
7186 
7187 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7188 /// operands.
7189 ///
7190 /// This routine will diagnose any invalid arithmetic on pointer operands much
7191 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7192 /// for emitting a single diagnostic even for operations where both LHS and RHS
7193 /// are (potentially problematic) pointers.
7194 ///
7195 /// \returns True when the operand is valid to use (even if as an extension).
7196 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7197                                                 Expr *LHSExpr, Expr *RHSExpr) {
7198   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7199   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7200   if (!isLHSPointer && !isRHSPointer) return true;
7201 
7202   QualType LHSPointeeTy, RHSPointeeTy;
7203   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7204   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7205 
7206   // Check for arithmetic on pointers to incomplete types.
7207   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7208   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7209   if (isLHSVoidPtr || isRHSVoidPtr) {
7210     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7211     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7212     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7213 
7214     return !S.getLangOpts().CPlusPlus;
7215   }
7216 
7217   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7218   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7219   if (isLHSFuncPtr || isRHSFuncPtr) {
7220     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7221     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7222                                                                 RHSExpr);
7223     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7224 
7225     return !S.getLangOpts().CPlusPlus;
7226   }
7227 
7228   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7229     return false;
7230   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7231     return false;
7232 
7233   return true;
7234 }
7235 
7236 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7237 /// literal.
7238 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7239                                   Expr *LHSExpr, Expr *RHSExpr) {
7240   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7241   Expr* IndexExpr = RHSExpr;
7242   if (!StrExpr) {
7243     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7244     IndexExpr = LHSExpr;
7245   }
7246 
7247   bool IsStringPlusInt = StrExpr &&
7248       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7249   if (!IsStringPlusInt)
7250     return;
7251 
7252   llvm::APSInt index;
7253   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7254     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7255     if (index.isNonNegative() &&
7256         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7257                               index.isUnsigned()))
7258       return;
7259   }
7260 
7261   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7262   Self.Diag(OpLoc, diag::warn_string_plus_int)
7263       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7264 
7265   // Only print a fixit for "str" + int, not for int + "str".
7266   if (IndexExpr == RHSExpr) {
7267     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7268     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7269         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7270         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7271         << FixItHint::CreateInsertion(EndLoc, "]");
7272   } else
7273     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7274 }
7275 
7276 /// \brief Emit a warning when adding a char literal to a string.
7277 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7278                                    Expr *LHSExpr, Expr *RHSExpr) {
7279   const DeclRefExpr *StringRefExpr =
7280       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7281   const CharacterLiteral *CharExpr =
7282       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7283   if (!StringRefExpr) {
7284     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7285     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7286   }
7287 
7288   if (!CharExpr || !StringRefExpr)
7289     return;
7290 
7291   const QualType StringType = StringRefExpr->getType();
7292 
7293   // Return if not a PointerType.
7294   if (!StringType->isAnyPointerType())
7295     return;
7296 
7297   // Return if not a CharacterType.
7298   if (!StringType->getPointeeType()->isAnyCharacterType())
7299     return;
7300 
7301   ASTContext &Ctx = Self.getASTContext();
7302   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7303 
7304   const QualType CharType = CharExpr->getType();
7305   if (!CharType->isAnyCharacterType() &&
7306       CharType->isIntegerType() &&
7307       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7308     Self.Diag(OpLoc, diag::warn_string_plus_char)
7309         << DiagRange << Ctx.CharTy;
7310   } else {
7311     Self.Diag(OpLoc, diag::warn_string_plus_char)
7312         << DiagRange << CharExpr->getType();
7313   }
7314 
7315   // Only print a fixit for str + char, not for char + str.
7316   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7317     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7318     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7319         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7320         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7321         << FixItHint::CreateInsertion(EndLoc, "]");
7322   } else {
7323     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7324   }
7325 }
7326 
7327 /// \brief Emit error when two pointers are incompatible.
7328 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7329                                            Expr *LHSExpr, Expr *RHSExpr) {
7330   assert(LHSExpr->getType()->isAnyPointerType());
7331   assert(RHSExpr->getType()->isAnyPointerType());
7332   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7333     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7334     << RHSExpr->getSourceRange();
7335 }
7336 
7337 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7338     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7339     QualType* CompLHSTy) {
7340   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7341 
7342   if (LHS.get()->getType()->isVectorType() ||
7343       RHS.get()->getType()->isVectorType()) {
7344     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7345     if (CompLHSTy) *CompLHSTy = compType;
7346     return compType;
7347   }
7348 
7349   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7350   if (LHS.isInvalid() || RHS.isInvalid())
7351     return QualType();
7352 
7353   // Diagnose "string literal" '+' int and string '+' "char literal".
7354   if (Opc == BO_Add) {
7355     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7356     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7357   }
7358 
7359   // handle the common case first (both operands are arithmetic).
7360   if (!compType.isNull() && compType->isArithmeticType()) {
7361     if (CompLHSTy) *CompLHSTy = compType;
7362     return compType;
7363   }
7364 
7365   // Type-checking.  Ultimately the pointer's going to be in PExp;
7366   // note that we bias towards the LHS being the pointer.
7367   Expr *PExp = LHS.get(), *IExp = RHS.get();
7368 
7369   bool isObjCPointer;
7370   if (PExp->getType()->isPointerType()) {
7371     isObjCPointer = false;
7372   } else if (PExp->getType()->isObjCObjectPointerType()) {
7373     isObjCPointer = true;
7374   } else {
7375     std::swap(PExp, IExp);
7376     if (PExp->getType()->isPointerType()) {
7377       isObjCPointer = false;
7378     } else if (PExp->getType()->isObjCObjectPointerType()) {
7379       isObjCPointer = true;
7380     } else {
7381       return InvalidOperands(Loc, LHS, RHS);
7382     }
7383   }
7384   assert(PExp->getType()->isAnyPointerType());
7385 
7386   if (!IExp->getType()->isIntegerType())
7387     return InvalidOperands(Loc, LHS, RHS);
7388 
7389   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7390     return QualType();
7391 
7392   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7393     return QualType();
7394 
7395   // Check array bounds for pointer arithemtic
7396   CheckArrayAccess(PExp, IExp);
7397 
7398   if (CompLHSTy) {
7399     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7400     if (LHSTy.isNull()) {
7401       LHSTy = LHS.get()->getType();
7402       if (LHSTy->isPromotableIntegerType())
7403         LHSTy = Context.getPromotedIntegerType(LHSTy);
7404     }
7405     *CompLHSTy = LHSTy;
7406   }
7407 
7408   return PExp->getType();
7409 }
7410 
7411 // C99 6.5.6
7412 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7413                                         SourceLocation Loc,
7414                                         QualType* CompLHSTy) {
7415   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7416 
7417   if (LHS.get()->getType()->isVectorType() ||
7418       RHS.get()->getType()->isVectorType()) {
7419     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7420     if (CompLHSTy) *CompLHSTy = compType;
7421     return compType;
7422   }
7423 
7424   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7425   if (LHS.isInvalid() || RHS.isInvalid())
7426     return QualType();
7427 
7428   // Enforce type constraints: C99 6.5.6p3.
7429 
7430   // Handle the common case first (both operands are arithmetic).
7431   if (!compType.isNull() && compType->isArithmeticType()) {
7432     if (CompLHSTy) *CompLHSTy = compType;
7433     return compType;
7434   }
7435 
7436   // Either ptr - int   or   ptr - ptr.
7437   if (LHS.get()->getType()->isAnyPointerType()) {
7438     QualType lpointee = LHS.get()->getType()->getPointeeType();
7439 
7440     // Diagnose bad cases where we step over interface counts.
7441     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7442         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7443       return QualType();
7444 
7445     // The result type of a pointer-int computation is the pointer type.
7446     if (RHS.get()->getType()->isIntegerType()) {
7447       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7448         return QualType();
7449 
7450       // Check array bounds for pointer arithemtic
7451       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7452                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7453 
7454       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7455       return LHS.get()->getType();
7456     }
7457 
7458     // Handle pointer-pointer subtractions.
7459     if (const PointerType *RHSPTy
7460           = RHS.get()->getType()->getAs<PointerType>()) {
7461       QualType rpointee = RHSPTy->getPointeeType();
7462 
7463       if (getLangOpts().CPlusPlus) {
7464         // Pointee types must be the same: C++ [expr.add]
7465         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7466           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7467         }
7468       } else {
7469         // Pointee types must be compatible C99 6.5.6p3
7470         if (!Context.typesAreCompatible(
7471                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7472                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7473           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7474           return QualType();
7475         }
7476       }
7477 
7478       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7479                                                LHS.get(), RHS.get()))
7480         return QualType();
7481 
7482       // The pointee type may have zero size.  As an extension, a structure or
7483       // union may have zero size or an array may have zero length.  In this
7484       // case subtraction does not make sense.
7485       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7486         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7487         if (ElementSize.isZero()) {
7488           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7489             << rpointee.getUnqualifiedType()
7490             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7491         }
7492       }
7493 
7494       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7495       return Context.getPointerDiffType();
7496     }
7497   }
7498 
7499   return InvalidOperands(Loc, LHS, RHS);
7500 }
7501 
7502 static bool isScopedEnumerationType(QualType T) {
7503   if (const EnumType *ET = dyn_cast<EnumType>(T))
7504     return ET->getDecl()->isScoped();
7505   return false;
7506 }
7507 
7508 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7509                                    SourceLocation Loc, unsigned Opc,
7510                                    QualType LHSType) {
7511   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7512   // so skip remaining warnings as we don't want to modify values within Sema.
7513   if (S.getLangOpts().OpenCL)
7514     return;
7515 
7516   llvm::APSInt Right;
7517   // Check right/shifter operand
7518   if (RHS.get()->isValueDependent() ||
7519       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7520     return;
7521 
7522   if (Right.isNegative()) {
7523     S.DiagRuntimeBehavior(Loc, RHS.get(),
7524                           S.PDiag(diag::warn_shift_negative)
7525                             << RHS.get()->getSourceRange());
7526     return;
7527   }
7528   llvm::APInt LeftBits(Right.getBitWidth(),
7529                        S.Context.getTypeSize(LHS.get()->getType()));
7530   if (Right.uge(LeftBits)) {
7531     S.DiagRuntimeBehavior(Loc, RHS.get(),
7532                           S.PDiag(diag::warn_shift_gt_typewidth)
7533                             << RHS.get()->getSourceRange());
7534     return;
7535   }
7536   if (Opc != BO_Shl)
7537     return;
7538 
7539   // When left shifting an ICE which is signed, we can check for overflow which
7540   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7541   // integers have defined behavior modulo one more than the maximum value
7542   // representable in the result type, so never warn for those.
7543   llvm::APSInt Left;
7544   if (LHS.get()->isValueDependent() ||
7545       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7546       LHSType->hasUnsignedIntegerRepresentation())
7547     return;
7548   llvm::APInt ResultBits =
7549       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7550   if (LeftBits.uge(ResultBits))
7551     return;
7552   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7553   Result = Result.shl(Right);
7554 
7555   // Print the bit representation of the signed integer as an unsigned
7556   // hexadecimal number.
7557   SmallString<40> HexResult;
7558   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7559 
7560   // If we are only missing a sign bit, this is less likely to result in actual
7561   // bugs -- if the result is cast back to an unsigned type, it will have the
7562   // expected value. Thus we place this behind a different warning that can be
7563   // turned off separately if needed.
7564   if (LeftBits == ResultBits - 1) {
7565     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7566         << HexResult.str() << LHSType
7567         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7568     return;
7569   }
7570 
7571   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7572     << HexResult.str() << Result.getMinSignedBits() << LHSType
7573     << Left.getBitWidth() << LHS.get()->getSourceRange()
7574     << RHS.get()->getSourceRange();
7575 }
7576 
7577 // C99 6.5.7
7578 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7579                                   SourceLocation Loc, unsigned Opc,
7580                                   bool IsCompAssign) {
7581   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7582 
7583   // Vector shifts promote their scalar inputs to vector type.
7584   if (LHS.get()->getType()->isVectorType() ||
7585       RHS.get()->getType()->isVectorType())
7586     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7587 
7588   // Shifts don't perform usual arithmetic conversions, they just do integer
7589   // promotions on each operand. C99 6.5.7p3
7590 
7591   // For the LHS, do usual unary conversions, but then reset them away
7592   // if this is a compound assignment.
7593   ExprResult OldLHS = LHS;
7594   LHS = UsualUnaryConversions(LHS.get());
7595   if (LHS.isInvalid())
7596     return QualType();
7597   QualType LHSType = LHS.get()->getType();
7598   if (IsCompAssign) LHS = OldLHS;
7599 
7600   // The RHS is simpler.
7601   RHS = UsualUnaryConversions(RHS.get());
7602   if (RHS.isInvalid())
7603     return QualType();
7604   QualType RHSType = RHS.get()->getType();
7605 
7606   // C99 6.5.7p2: Each of the operands shall have integer type.
7607   if (!LHSType->hasIntegerRepresentation() ||
7608       !RHSType->hasIntegerRepresentation())
7609     return InvalidOperands(Loc, LHS, RHS);
7610 
7611   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7612   // hasIntegerRepresentation() above instead of this.
7613   if (isScopedEnumerationType(LHSType) ||
7614       isScopedEnumerationType(RHSType)) {
7615     return InvalidOperands(Loc, LHS, RHS);
7616   }
7617   // Sanity-check shift operands
7618   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7619 
7620   // "The type of the result is that of the promoted left operand."
7621   return LHSType;
7622 }
7623 
7624 static bool IsWithinTemplateSpecialization(Decl *D) {
7625   if (DeclContext *DC = D->getDeclContext()) {
7626     if (isa<ClassTemplateSpecializationDecl>(DC))
7627       return true;
7628     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7629       return FD->isFunctionTemplateSpecialization();
7630   }
7631   return false;
7632 }
7633 
7634 /// If two different enums are compared, raise a warning.
7635 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7636                                 Expr *RHS) {
7637   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7638   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7639 
7640   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7641   if (!LHSEnumType)
7642     return;
7643   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7644   if (!RHSEnumType)
7645     return;
7646 
7647   // Ignore anonymous enums.
7648   if (!LHSEnumType->getDecl()->getIdentifier())
7649     return;
7650   if (!RHSEnumType->getDecl()->getIdentifier())
7651     return;
7652 
7653   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7654     return;
7655 
7656   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7657       << LHSStrippedType << RHSStrippedType
7658       << LHS->getSourceRange() << RHS->getSourceRange();
7659 }
7660 
7661 /// \brief Diagnose bad pointer comparisons.
7662 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7663                                               ExprResult &LHS, ExprResult &RHS,
7664                                               bool IsError) {
7665   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7666                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7667     << LHS.get()->getType() << RHS.get()->getType()
7668     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7669 }
7670 
7671 /// \brief Returns false if the pointers are converted to a composite type,
7672 /// true otherwise.
7673 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7674                                            ExprResult &LHS, ExprResult &RHS) {
7675   // C++ [expr.rel]p2:
7676   //   [...] Pointer conversions (4.10) and qualification
7677   //   conversions (4.4) are performed on pointer operands (or on
7678   //   a pointer operand and a null pointer constant) to bring
7679   //   them to their composite pointer type. [...]
7680   //
7681   // C++ [expr.eq]p1 uses the same notion for (in)equality
7682   // comparisons of pointers.
7683 
7684   // C++ [expr.eq]p2:
7685   //   In addition, pointers to members can be compared, or a pointer to
7686   //   member and a null pointer constant. Pointer to member conversions
7687   //   (4.11) and qualification conversions (4.4) are performed to bring
7688   //   them to a common type. If one operand is a null pointer constant,
7689   //   the common type is the type of the other operand. Otherwise, the
7690   //   common type is a pointer to member type similar (4.4) to the type
7691   //   of one of the operands, with a cv-qualification signature (4.4)
7692   //   that is the union of the cv-qualification signatures of the operand
7693   //   types.
7694 
7695   QualType LHSType = LHS.get()->getType();
7696   QualType RHSType = RHS.get()->getType();
7697   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7698          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7699 
7700   bool NonStandardCompositeType = false;
7701   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7702   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7703   if (T.isNull()) {
7704     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7705     return true;
7706   }
7707 
7708   if (NonStandardCompositeType)
7709     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7710       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7711       << RHS.get()->getSourceRange();
7712 
7713   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7714   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7715   return false;
7716 }
7717 
7718 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7719                                                     ExprResult &LHS,
7720                                                     ExprResult &RHS,
7721                                                     bool IsError) {
7722   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7723                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7724     << LHS.get()->getType() << RHS.get()->getType()
7725     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7726 }
7727 
7728 static bool isObjCObjectLiteral(ExprResult &E) {
7729   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7730   case Stmt::ObjCArrayLiteralClass:
7731   case Stmt::ObjCDictionaryLiteralClass:
7732   case Stmt::ObjCStringLiteralClass:
7733   case Stmt::ObjCBoxedExprClass:
7734     return true;
7735   default:
7736     // Note that ObjCBoolLiteral is NOT an object literal!
7737     return false;
7738   }
7739 }
7740 
7741 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7742   const ObjCObjectPointerType *Type =
7743     LHS->getType()->getAs<ObjCObjectPointerType>();
7744 
7745   // If this is not actually an Objective-C object, bail out.
7746   if (!Type)
7747     return false;
7748 
7749   // Get the LHS object's interface type.
7750   QualType InterfaceType = Type->getPointeeType();
7751   if (const ObjCObjectType *iQFaceTy =
7752       InterfaceType->getAsObjCQualifiedInterfaceType())
7753     InterfaceType = iQFaceTy->getBaseType();
7754 
7755   // If the RHS isn't an Objective-C object, bail out.
7756   if (!RHS->getType()->isObjCObjectPointerType())
7757     return false;
7758 
7759   // Try to find the -isEqual: method.
7760   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7761   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7762                                                       InterfaceType,
7763                                                       /*instance=*/true);
7764   if (!Method) {
7765     if (Type->isObjCIdType()) {
7766       // For 'id', just check the global pool.
7767       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7768                                                   /*receiverId=*/true,
7769                                                   /*warn=*/false);
7770     } else {
7771       // Check protocols.
7772       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7773                                              /*instance=*/true);
7774     }
7775   }
7776 
7777   if (!Method)
7778     return false;
7779 
7780   QualType T = Method->parameters()[0]->getType();
7781   if (!T->isObjCObjectPointerType())
7782     return false;
7783 
7784   QualType R = Method->getReturnType();
7785   if (!R->isScalarType())
7786     return false;
7787 
7788   return true;
7789 }
7790 
7791 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7792   FromE = FromE->IgnoreParenImpCasts();
7793   switch (FromE->getStmtClass()) {
7794     default:
7795       break;
7796     case Stmt::ObjCStringLiteralClass:
7797       // "string literal"
7798       return LK_String;
7799     case Stmt::ObjCArrayLiteralClass:
7800       // "array literal"
7801       return LK_Array;
7802     case Stmt::ObjCDictionaryLiteralClass:
7803       // "dictionary literal"
7804       return LK_Dictionary;
7805     case Stmt::BlockExprClass:
7806       return LK_Block;
7807     case Stmt::ObjCBoxedExprClass: {
7808       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7809       switch (Inner->getStmtClass()) {
7810         case Stmt::IntegerLiteralClass:
7811         case Stmt::FloatingLiteralClass:
7812         case Stmt::CharacterLiteralClass:
7813         case Stmt::ObjCBoolLiteralExprClass:
7814         case Stmt::CXXBoolLiteralExprClass:
7815           // "numeric literal"
7816           return LK_Numeric;
7817         case Stmt::ImplicitCastExprClass: {
7818           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7819           // Boolean literals can be represented by implicit casts.
7820           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7821             return LK_Numeric;
7822           break;
7823         }
7824         default:
7825           break;
7826       }
7827       return LK_Boxed;
7828     }
7829   }
7830   return LK_None;
7831 }
7832 
7833 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7834                                           ExprResult &LHS, ExprResult &RHS,
7835                                           BinaryOperator::Opcode Opc){
7836   Expr *Literal;
7837   Expr *Other;
7838   if (isObjCObjectLiteral(LHS)) {
7839     Literal = LHS.get();
7840     Other = RHS.get();
7841   } else {
7842     Literal = RHS.get();
7843     Other = LHS.get();
7844   }
7845 
7846   // Don't warn on comparisons against nil.
7847   Other = Other->IgnoreParenCasts();
7848   if (Other->isNullPointerConstant(S.getASTContext(),
7849                                    Expr::NPC_ValueDependentIsNotNull))
7850     return;
7851 
7852   // This should be kept in sync with warn_objc_literal_comparison.
7853   // LK_String should always be after the other literals, since it has its own
7854   // warning flag.
7855   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7856   assert(LiteralKind != Sema::LK_Block);
7857   if (LiteralKind == Sema::LK_None) {
7858     llvm_unreachable("Unknown Objective-C object literal kind");
7859   }
7860 
7861   if (LiteralKind == Sema::LK_String)
7862     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7863       << Literal->getSourceRange();
7864   else
7865     S.Diag(Loc, diag::warn_objc_literal_comparison)
7866       << LiteralKind << Literal->getSourceRange();
7867 
7868   if (BinaryOperator::isEqualityOp(Opc) &&
7869       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7870     SourceLocation Start = LHS.get()->getLocStart();
7871     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7872     CharSourceRange OpRange =
7873       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7874 
7875     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7876       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7877       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7878       << FixItHint::CreateInsertion(End, "]");
7879   }
7880 }
7881 
7882 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7883                                                 ExprResult &RHS,
7884                                                 SourceLocation Loc,
7885                                                 unsigned OpaqueOpc) {
7886   // This checking requires bools.
7887   if (!S.getLangOpts().Bool) return;
7888 
7889   // Check that left hand side is !something.
7890   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7891   if (!UO || UO->getOpcode() != UO_LNot) return;
7892 
7893   // Only check if the right hand side is non-bool arithmetic type.
7894   if (RHS.get()->getType()->isBooleanType()) return;
7895 
7896   // Make sure that the something in !something is not bool.
7897   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7898   if (SubExpr->getType()->isBooleanType()) return;
7899 
7900   // Emit warning.
7901   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7902       << Loc;
7903 
7904   // First note suggest !(x < y)
7905   SourceLocation FirstOpen = SubExpr->getLocStart();
7906   SourceLocation FirstClose = RHS.get()->getLocEnd();
7907   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7908   if (FirstClose.isInvalid())
7909     FirstOpen = SourceLocation();
7910   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7911       << FixItHint::CreateInsertion(FirstOpen, "(")
7912       << FixItHint::CreateInsertion(FirstClose, ")");
7913 
7914   // Second note suggests (!x) < y
7915   SourceLocation SecondOpen = LHS.get()->getLocStart();
7916   SourceLocation SecondClose = LHS.get()->getLocEnd();
7917   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7918   if (SecondClose.isInvalid())
7919     SecondOpen = SourceLocation();
7920   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7921       << FixItHint::CreateInsertion(SecondOpen, "(")
7922       << FixItHint::CreateInsertion(SecondClose, ")");
7923 }
7924 
7925 // Get the decl for a simple expression: a reference to a variable,
7926 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7927 static ValueDecl *getCompareDecl(Expr *E) {
7928   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7929     return DR->getDecl();
7930   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7931     if (Ivar->isFreeIvar())
7932       return Ivar->getDecl();
7933   }
7934   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7935     if (Mem->isImplicitAccess())
7936       return Mem->getMemberDecl();
7937   }
7938   return nullptr;
7939 }
7940 
7941 // C99 6.5.8, C++ [expr.rel]
7942 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7943                                     SourceLocation Loc, unsigned OpaqueOpc,
7944                                     bool IsRelational) {
7945   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7946 
7947   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7948 
7949   // Handle vector comparisons separately.
7950   if (LHS.get()->getType()->isVectorType() ||
7951       RHS.get()->getType()->isVectorType())
7952     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7953 
7954   QualType LHSType = LHS.get()->getType();
7955   QualType RHSType = RHS.get()->getType();
7956 
7957   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7958   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7959 
7960   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7961   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7962 
7963   if (!LHSType->hasFloatingRepresentation() &&
7964       !(LHSType->isBlockPointerType() && IsRelational) &&
7965       !LHS.get()->getLocStart().isMacroID() &&
7966       !RHS.get()->getLocStart().isMacroID() &&
7967       ActiveTemplateInstantiations.empty()) {
7968     // For non-floating point types, check for self-comparisons of the form
7969     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7970     // often indicate logic errors in the program.
7971     //
7972     // NOTE: Don't warn about comparison expressions resulting from macro
7973     // expansion. Also don't warn about comparisons which are only self
7974     // comparisons within a template specialization. The warnings should catch
7975     // obvious cases in the definition of the template anyways. The idea is to
7976     // warn when the typed comparison operator will always evaluate to the same
7977     // result.
7978     ValueDecl *DL = getCompareDecl(LHSStripped);
7979     ValueDecl *DR = getCompareDecl(RHSStripped);
7980     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7981       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7982                           << 0 // self-
7983                           << (Opc == BO_EQ
7984                               || Opc == BO_LE
7985                               || Opc == BO_GE));
7986     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7987                !DL->getType()->isReferenceType() &&
7988                !DR->getType()->isReferenceType()) {
7989         // what is it always going to eval to?
7990         char always_evals_to;
7991         switch(Opc) {
7992         case BO_EQ: // e.g. array1 == array2
7993           always_evals_to = 0; // false
7994           break;
7995         case BO_NE: // e.g. array1 != array2
7996           always_evals_to = 1; // true
7997           break;
7998         default:
7999           // best we can say is 'a constant'
8000           always_evals_to = 2; // e.g. array1 <= array2
8001           break;
8002         }
8003         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8004                             << 1 // array
8005                             << always_evals_to);
8006     }
8007 
8008     if (isa<CastExpr>(LHSStripped))
8009       LHSStripped = LHSStripped->IgnoreParenCasts();
8010     if (isa<CastExpr>(RHSStripped))
8011       RHSStripped = RHSStripped->IgnoreParenCasts();
8012 
8013     // Warn about comparisons against a string constant (unless the other
8014     // operand is null), the user probably wants strcmp.
8015     Expr *literalString = nullptr;
8016     Expr *literalStringStripped = nullptr;
8017     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8018         !RHSStripped->isNullPointerConstant(Context,
8019                                             Expr::NPC_ValueDependentIsNull)) {
8020       literalString = LHS.get();
8021       literalStringStripped = LHSStripped;
8022     } else if ((isa<StringLiteral>(RHSStripped) ||
8023                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8024                !LHSStripped->isNullPointerConstant(Context,
8025                                             Expr::NPC_ValueDependentIsNull)) {
8026       literalString = RHS.get();
8027       literalStringStripped = RHSStripped;
8028     }
8029 
8030     if (literalString) {
8031       DiagRuntimeBehavior(Loc, nullptr,
8032         PDiag(diag::warn_stringcompare)
8033           << isa<ObjCEncodeExpr>(literalStringStripped)
8034           << literalString->getSourceRange());
8035     }
8036   }
8037 
8038   // C99 6.5.8p3 / C99 6.5.9p4
8039   UsualArithmeticConversions(LHS, RHS);
8040   if (LHS.isInvalid() || RHS.isInvalid())
8041     return QualType();
8042 
8043   LHSType = LHS.get()->getType();
8044   RHSType = RHS.get()->getType();
8045 
8046   // The result of comparisons is 'bool' in C++, 'int' in C.
8047   QualType ResultTy = Context.getLogicalOperationType();
8048 
8049   if (IsRelational) {
8050     if (LHSType->isRealType() && RHSType->isRealType())
8051       return ResultTy;
8052   } else {
8053     // Check for comparisons of floating point operands using != and ==.
8054     if (LHSType->hasFloatingRepresentation())
8055       CheckFloatComparison(Loc, LHS.get(), RHS.get());
8056 
8057     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8058       return ResultTy;
8059   }
8060 
8061   const Expr::NullPointerConstantKind LHSNullKind =
8062       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8063   const Expr::NullPointerConstantKind RHSNullKind =
8064       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8065   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8066   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8067 
8068   if (!IsRelational && LHSIsNull != RHSIsNull) {
8069     bool IsEquality = Opc == BO_EQ;
8070     if (RHSIsNull)
8071       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8072                                    RHS.get()->getSourceRange());
8073     else
8074       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8075                                    LHS.get()->getSourceRange());
8076   }
8077 
8078   // All of the following pointer-related warnings are GCC extensions, except
8079   // when handling null pointer constants.
8080   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8081     QualType LCanPointeeTy =
8082       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8083     QualType RCanPointeeTy =
8084       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8085 
8086     if (getLangOpts().CPlusPlus) {
8087       if (LCanPointeeTy == RCanPointeeTy)
8088         return ResultTy;
8089       if (!IsRelational &&
8090           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8091         // Valid unless comparison between non-null pointer and function pointer
8092         // This is a gcc extension compatibility comparison.
8093         // In a SFINAE context, we treat this as a hard error to maintain
8094         // conformance with the C++ standard.
8095         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8096             && !LHSIsNull && !RHSIsNull) {
8097           diagnoseFunctionPointerToVoidComparison(
8098               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8099 
8100           if (isSFINAEContext())
8101             return QualType();
8102 
8103           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8104           return ResultTy;
8105         }
8106       }
8107 
8108       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8109         return QualType();
8110       else
8111         return ResultTy;
8112     }
8113     // C99 6.5.9p2 and C99 6.5.8p2
8114     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8115                                    RCanPointeeTy.getUnqualifiedType())) {
8116       // Valid unless a relational comparison of function pointers
8117       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8118         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8119           << LHSType << RHSType << LHS.get()->getSourceRange()
8120           << RHS.get()->getSourceRange();
8121       }
8122     } else if (!IsRelational &&
8123                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8124       // Valid unless comparison between non-null pointer and function pointer
8125       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8126           && !LHSIsNull && !RHSIsNull)
8127         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8128                                                 /*isError*/false);
8129     } else {
8130       // Invalid
8131       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8132     }
8133     if (LCanPointeeTy != RCanPointeeTy) {
8134       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8135       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8136       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8137                                                : CK_BitCast;
8138       if (LHSIsNull && !RHSIsNull)
8139         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8140       else
8141         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8142     }
8143     return ResultTy;
8144   }
8145 
8146   if (getLangOpts().CPlusPlus) {
8147     // Comparison of nullptr_t with itself.
8148     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8149       return ResultTy;
8150 
8151     // Comparison of pointers with null pointer constants and equality
8152     // comparisons of member pointers to null pointer constants.
8153     if (RHSIsNull &&
8154         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8155          (!IsRelational &&
8156           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8157       RHS = ImpCastExprToType(RHS.get(), LHSType,
8158                         LHSType->isMemberPointerType()
8159                           ? CK_NullToMemberPointer
8160                           : CK_NullToPointer);
8161       return ResultTy;
8162     }
8163     if (LHSIsNull &&
8164         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8165          (!IsRelational &&
8166           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8167       LHS = ImpCastExprToType(LHS.get(), RHSType,
8168                         RHSType->isMemberPointerType()
8169                           ? CK_NullToMemberPointer
8170                           : CK_NullToPointer);
8171       return ResultTy;
8172     }
8173 
8174     // Comparison of member pointers.
8175     if (!IsRelational &&
8176         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8177       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8178         return QualType();
8179       else
8180         return ResultTy;
8181     }
8182 
8183     // Handle scoped enumeration types specifically, since they don't promote
8184     // to integers.
8185     if (LHS.get()->getType()->isEnumeralType() &&
8186         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8187                                        RHS.get()->getType()))
8188       return ResultTy;
8189   }
8190 
8191   // Handle block pointer types.
8192   if (!IsRelational && LHSType->isBlockPointerType() &&
8193       RHSType->isBlockPointerType()) {
8194     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8195     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8196 
8197     if (!LHSIsNull && !RHSIsNull &&
8198         !Context.typesAreCompatible(lpointee, rpointee)) {
8199       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8200         << LHSType << RHSType << LHS.get()->getSourceRange()
8201         << RHS.get()->getSourceRange();
8202     }
8203     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8204     return ResultTy;
8205   }
8206 
8207   // Allow block pointers to be compared with null pointer constants.
8208   if (!IsRelational
8209       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8210           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8211     if (!LHSIsNull && !RHSIsNull) {
8212       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8213              ->getPointeeType()->isVoidType())
8214             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8215                 ->getPointeeType()->isVoidType())))
8216         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8217           << LHSType << RHSType << LHS.get()->getSourceRange()
8218           << RHS.get()->getSourceRange();
8219     }
8220     if (LHSIsNull && !RHSIsNull)
8221       LHS = ImpCastExprToType(LHS.get(), RHSType,
8222                               RHSType->isPointerType() ? CK_BitCast
8223                                 : CK_AnyPointerToBlockPointerCast);
8224     else
8225       RHS = ImpCastExprToType(RHS.get(), LHSType,
8226                               LHSType->isPointerType() ? CK_BitCast
8227                                 : CK_AnyPointerToBlockPointerCast);
8228     return ResultTy;
8229   }
8230 
8231   if (LHSType->isObjCObjectPointerType() ||
8232       RHSType->isObjCObjectPointerType()) {
8233     const PointerType *LPT = LHSType->getAs<PointerType>();
8234     const PointerType *RPT = RHSType->getAs<PointerType>();
8235     if (LPT || RPT) {
8236       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8237       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8238 
8239       if (!LPtrToVoid && !RPtrToVoid &&
8240           !Context.typesAreCompatible(LHSType, RHSType)) {
8241         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8242                                           /*isError*/false);
8243       }
8244       if (LHSIsNull && !RHSIsNull) {
8245         Expr *E = LHS.get();
8246         if (getLangOpts().ObjCAutoRefCount)
8247           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8248         LHS = ImpCastExprToType(E, RHSType,
8249                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8250       }
8251       else {
8252         Expr *E = RHS.get();
8253         if (getLangOpts().ObjCAutoRefCount)
8254           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8255                                  Opc);
8256         RHS = ImpCastExprToType(E, LHSType,
8257                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8258       }
8259       return ResultTy;
8260     }
8261     if (LHSType->isObjCObjectPointerType() &&
8262         RHSType->isObjCObjectPointerType()) {
8263       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8264         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8265                                           /*isError*/false);
8266       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8267         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8268 
8269       if (LHSIsNull && !RHSIsNull)
8270         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8271       else
8272         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8273       return ResultTy;
8274     }
8275   }
8276   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8277       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8278     unsigned DiagID = 0;
8279     bool isError = false;
8280     if (LangOpts.DebuggerSupport) {
8281       // Under a debugger, allow the comparison of pointers to integers,
8282       // since users tend to want to compare addresses.
8283     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8284         (RHSIsNull && RHSType->isIntegerType())) {
8285       if (IsRelational && !getLangOpts().CPlusPlus)
8286         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8287     } else if (IsRelational && !getLangOpts().CPlusPlus)
8288       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8289     else if (getLangOpts().CPlusPlus) {
8290       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8291       isError = true;
8292     } else
8293       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8294 
8295     if (DiagID) {
8296       Diag(Loc, DiagID)
8297         << LHSType << RHSType << LHS.get()->getSourceRange()
8298         << RHS.get()->getSourceRange();
8299       if (isError)
8300         return QualType();
8301     }
8302 
8303     if (LHSType->isIntegerType())
8304       LHS = ImpCastExprToType(LHS.get(), RHSType,
8305                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8306     else
8307       RHS = ImpCastExprToType(RHS.get(), LHSType,
8308                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8309     return ResultTy;
8310   }
8311 
8312   // Handle block pointers.
8313   if (!IsRelational && RHSIsNull
8314       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8315     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8316     return ResultTy;
8317   }
8318   if (!IsRelational && LHSIsNull
8319       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8320     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8321     return ResultTy;
8322   }
8323 
8324   return InvalidOperands(Loc, LHS, RHS);
8325 }
8326 
8327 
8328 // Return a signed type that is of identical size and number of elements.
8329 // For floating point vectors, return an integer type of identical size
8330 // and number of elements.
8331 QualType Sema::GetSignedVectorType(QualType V) {
8332   const VectorType *VTy = V->getAs<VectorType>();
8333   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8334   if (TypeSize == Context.getTypeSize(Context.CharTy))
8335     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8336   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8337     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8338   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8339     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8340   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8341     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8342   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8343          "Unhandled vector element size in vector compare");
8344   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8345 }
8346 
8347 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8348 /// operates on extended vector types.  Instead of producing an IntTy result,
8349 /// like a scalar comparison, a vector comparison produces a vector of integer
8350 /// types.
8351 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8352                                           SourceLocation Loc,
8353                                           bool IsRelational) {
8354   // Check to make sure we're operating on vectors of the same type and width,
8355   // Allowing one side to be a scalar of element type.
8356   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8357   if (vType.isNull())
8358     return vType;
8359 
8360   QualType LHSType = LHS.get()->getType();
8361 
8362   // If AltiVec, the comparison results in a numeric type, i.e.
8363   // bool for C++, int for C
8364   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8365     return Context.getLogicalOperationType();
8366 
8367   // For non-floating point types, check for self-comparisons of the form
8368   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8369   // often indicate logic errors in the program.
8370   if (!LHSType->hasFloatingRepresentation() &&
8371       ActiveTemplateInstantiations.empty()) {
8372     if (DeclRefExpr* DRL
8373           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8374       if (DeclRefExpr* DRR
8375             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8376         if (DRL->getDecl() == DRR->getDecl())
8377           DiagRuntimeBehavior(Loc, nullptr,
8378                               PDiag(diag::warn_comparison_always)
8379                                 << 0 // self-
8380                                 << 2 // "a constant"
8381                               );
8382   }
8383 
8384   // Check for comparisons of floating point operands using != and ==.
8385   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8386     assert (RHS.get()->getType()->hasFloatingRepresentation());
8387     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8388   }
8389 
8390   // Return a signed type for the vector.
8391   return GetSignedVectorType(LHSType);
8392 }
8393 
8394 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8395                                           SourceLocation Loc) {
8396   // Ensure that either both operands are of the same vector type, or
8397   // one operand is of a vector type and the other is of its element type.
8398   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8399   if (vType.isNull())
8400     return InvalidOperands(Loc, LHS, RHS);
8401   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8402       vType->hasFloatingRepresentation())
8403     return InvalidOperands(Loc, LHS, RHS);
8404 
8405   return GetSignedVectorType(LHS.get()->getType());
8406 }
8407 
8408 inline QualType Sema::CheckBitwiseOperands(
8409   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8410   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8411 
8412   if (LHS.get()->getType()->isVectorType() ||
8413       RHS.get()->getType()->isVectorType()) {
8414     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8415         RHS.get()->getType()->hasIntegerRepresentation())
8416       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8417 
8418     return InvalidOperands(Loc, LHS, RHS);
8419   }
8420 
8421   ExprResult LHSResult = LHS, RHSResult = RHS;
8422   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8423                                                  IsCompAssign);
8424   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8425     return QualType();
8426   LHS = LHSResult.get();
8427   RHS = RHSResult.get();
8428 
8429   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8430     return compType;
8431   return InvalidOperands(Loc, LHS, RHS);
8432 }
8433 
8434 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8435   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8436 
8437   // Check vector operands differently.
8438   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8439     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8440 
8441   // Diagnose cases where the user write a logical and/or but probably meant a
8442   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8443   // is a constant.
8444   if (LHS.get()->getType()->isIntegerType() &&
8445       !LHS.get()->getType()->isBooleanType() &&
8446       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8447       // Don't warn in macros or template instantiations.
8448       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8449     // If the RHS can be constant folded, and if it constant folds to something
8450     // that isn't 0 or 1 (which indicate a potential logical operation that
8451     // happened to fold to true/false) then warn.
8452     // Parens on the RHS are ignored.
8453     llvm::APSInt Result;
8454     if (RHS.get()->EvaluateAsInt(Result, Context))
8455       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8456            !RHS.get()->getExprLoc().isMacroID()) ||
8457           (Result != 0 && Result != 1)) {
8458         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8459           << RHS.get()->getSourceRange()
8460           << (Opc == BO_LAnd ? "&&" : "||");
8461         // Suggest replacing the logical operator with the bitwise version
8462         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8463             << (Opc == BO_LAnd ? "&" : "|")
8464             << FixItHint::CreateReplacement(SourceRange(
8465                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8466                                                 getLangOpts())),
8467                                             Opc == BO_LAnd ? "&" : "|");
8468         if (Opc == BO_LAnd)
8469           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8470           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8471               << FixItHint::CreateRemoval(
8472                   SourceRange(
8473                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8474                                                  0, getSourceManager(),
8475                                                  getLangOpts()),
8476                       RHS.get()->getLocEnd()));
8477       }
8478   }
8479 
8480   if (!Context.getLangOpts().CPlusPlus) {
8481     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8482     // not operate on the built-in scalar and vector float types.
8483     if (Context.getLangOpts().OpenCL &&
8484         Context.getLangOpts().OpenCLVersion < 120) {
8485       if (LHS.get()->getType()->isFloatingType() ||
8486           RHS.get()->getType()->isFloatingType())
8487         return InvalidOperands(Loc, LHS, RHS);
8488     }
8489 
8490     LHS = UsualUnaryConversions(LHS.get());
8491     if (LHS.isInvalid())
8492       return QualType();
8493 
8494     RHS = UsualUnaryConversions(RHS.get());
8495     if (RHS.isInvalid())
8496       return QualType();
8497 
8498     if (!LHS.get()->getType()->isScalarType() ||
8499         !RHS.get()->getType()->isScalarType())
8500       return InvalidOperands(Loc, LHS, RHS);
8501 
8502     return Context.IntTy;
8503   }
8504 
8505   // The following is safe because we only use this method for
8506   // non-overloadable operands.
8507 
8508   // C++ [expr.log.and]p1
8509   // C++ [expr.log.or]p1
8510   // The operands are both contextually converted to type bool.
8511   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8512   if (LHSRes.isInvalid())
8513     return InvalidOperands(Loc, LHS, RHS);
8514   LHS = LHSRes;
8515 
8516   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8517   if (RHSRes.isInvalid())
8518     return InvalidOperands(Loc, LHS, RHS);
8519   RHS = RHSRes;
8520 
8521   // C++ [expr.log.and]p2
8522   // C++ [expr.log.or]p2
8523   // The result is a bool.
8524   return Context.BoolTy;
8525 }
8526 
8527 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8528   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8529   if (!ME) return false;
8530   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8531   ObjCMessageExpr *Base =
8532     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8533   if (!Base) return false;
8534   return Base->getMethodDecl() != nullptr;
8535 }
8536 
8537 /// Is the given expression (which must be 'const') a reference to a
8538 /// variable which was originally non-const, but which has become
8539 /// 'const' due to being captured within a block?
8540 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8541 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8542   assert(E->isLValue() && E->getType().isConstQualified());
8543   E = E->IgnoreParens();
8544 
8545   // Must be a reference to a declaration from an enclosing scope.
8546   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8547   if (!DRE) return NCCK_None;
8548   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8549 
8550   // The declaration must be a variable which is not declared 'const'.
8551   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8552   if (!var) return NCCK_None;
8553   if (var->getType().isConstQualified()) return NCCK_None;
8554   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8555 
8556   // Decide whether the first capture was for a block or a lambda.
8557   DeclContext *DC = S.CurContext, *Prev = nullptr;
8558   while (DC != var->getDeclContext()) {
8559     Prev = DC;
8560     DC = DC->getParent();
8561   }
8562   // Unless we have an init-capture, we've gone one step too far.
8563   if (!var->isInitCapture())
8564     DC = Prev;
8565   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8566 }
8567 
8568 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8569 /// emit an error and return true.  If so, return false.
8570 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8571   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8572   SourceLocation OrigLoc = Loc;
8573   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8574                                                               &Loc);
8575   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8576     IsLV = Expr::MLV_InvalidMessageExpression;
8577   if (IsLV == Expr::MLV_Valid)
8578     return false;
8579 
8580   unsigned Diag = 0;
8581   bool NeedType = false;
8582   switch (IsLV) { // C99 6.5.16p2
8583   case Expr::MLV_ConstQualified:
8584     Diag = diag::err_typecheck_assign_const;
8585 
8586     // Use a specialized diagnostic when we're assigning to an object
8587     // from an enclosing function or block.
8588     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8589       if (NCCK == NCCK_Block)
8590         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8591       else
8592         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8593       break;
8594     }
8595 
8596     // In ARC, use some specialized diagnostics for occasions where we
8597     // infer 'const'.  These are always pseudo-strong variables.
8598     if (S.getLangOpts().ObjCAutoRefCount) {
8599       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8600       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8601         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8602 
8603         // Use the normal diagnostic if it's pseudo-__strong but the
8604         // user actually wrote 'const'.
8605         if (var->isARCPseudoStrong() &&
8606             (!var->getTypeSourceInfo() ||
8607              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8608           // There are two pseudo-strong cases:
8609           //  - self
8610           ObjCMethodDecl *method = S.getCurMethodDecl();
8611           if (method && var == method->getSelfDecl())
8612             Diag = method->isClassMethod()
8613               ? diag::err_typecheck_arc_assign_self_class_method
8614               : diag::err_typecheck_arc_assign_self;
8615 
8616           //  - fast enumeration variables
8617           else
8618             Diag = diag::err_typecheck_arr_assign_enumeration;
8619 
8620           SourceRange Assign;
8621           if (Loc != OrigLoc)
8622             Assign = SourceRange(OrigLoc, OrigLoc);
8623           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8624           // We need to preserve the AST regardless, so migration tool
8625           // can do its job.
8626           return false;
8627         }
8628       }
8629     }
8630 
8631     break;
8632   case Expr::MLV_ArrayType:
8633   case Expr::MLV_ArrayTemporary:
8634     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8635     NeedType = true;
8636     break;
8637   case Expr::MLV_NotObjectType:
8638     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8639     NeedType = true;
8640     break;
8641   case Expr::MLV_LValueCast:
8642     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8643     break;
8644   case Expr::MLV_Valid:
8645     llvm_unreachable("did not take early return for MLV_Valid");
8646   case Expr::MLV_InvalidExpression:
8647   case Expr::MLV_MemberFunction:
8648   case Expr::MLV_ClassTemporary:
8649     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8650     break;
8651   case Expr::MLV_IncompleteType:
8652   case Expr::MLV_IncompleteVoidType:
8653     return S.RequireCompleteType(Loc, E->getType(),
8654              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8655   case Expr::MLV_DuplicateVectorComponents:
8656     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8657     break;
8658   case Expr::MLV_NoSetterProperty:
8659     llvm_unreachable("readonly properties should be processed differently");
8660   case Expr::MLV_InvalidMessageExpression:
8661     Diag = diag::error_readonly_message_assignment;
8662     break;
8663   case Expr::MLV_SubObjCPropertySetting:
8664     Diag = diag::error_no_subobject_property_setting;
8665     break;
8666   }
8667 
8668   SourceRange Assign;
8669   if (Loc != OrigLoc)
8670     Assign = SourceRange(OrigLoc, OrigLoc);
8671   if (NeedType)
8672     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8673   else
8674     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8675   return true;
8676 }
8677 
8678 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8679                                          SourceLocation Loc,
8680                                          Sema &Sema) {
8681   // C / C++ fields
8682   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8683   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8684   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8685     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8686       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8687   }
8688 
8689   // Objective-C instance variables
8690   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8691   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8692   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8693     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8694     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8695     if (RL && RR && RL->getDecl() == RR->getDecl())
8696       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8697   }
8698 }
8699 
8700 // C99 6.5.16.1
8701 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8702                                        SourceLocation Loc,
8703                                        QualType CompoundType) {
8704   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8705 
8706   if (!getLangOpts().CPlusPlus) {
8707     // C cannot handle TypoExpr nodes on either side of n assignment because it
8708     // doesn't handle dependent types properly, so make sure any TypoExprs have
8709     // been dealt with before checking the operands.
8710     ExprResult Res = CorrectDelayedTyposInExpr(LHSExpr);
8711     Expr *NewLHS = Res.isInvalid() ? LHSExpr : Res.get();
8712     Res = CorrectDelayedTyposInExpr(RHS);
8713     if (!Res.isInvalid() && (Res.get() != RHS.get() || NewLHS != LHSExpr))
8714       return CheckAssignmentOperands(NewLHS, Res, Loc, CompoundType);
8715   }
8716 
8717   // Verify that LHS is a modifiable lvalue, and emit error if not.
8718   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8719     return QualType();
8720 
8721   QualType LHSType = LHSExpr->getType();
8722   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8723                                              CompoundType;
8724   AssignConvertType ConvTy;
8725   if (CompoundType.isNull()) {
8726     Expr *RHSCheck = RHS.get();
8727 
8728     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8729 
8730     QualType LHSTy(LHSType);
8731     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8732     if (RHS.isInvalid())
8733       return QualType();
8734     // Special case of NSObject attributes on c-style pointer types.
8735     if (ConvTy == IncompatiblePointer &&
8736         ((Context.isObjCNSObjectType(LHSType) &&
8737           RHSType->isObjCObjectPointerType()) ||
8738          (Context.isObjCNSObjectType(RHSType) &&
8739           LHSType->isObjCObjectPointerType())))
8740       ConvTy = Compatible;
8741 
8742     if (ConvTy == Compatible &&
8743         LHSType->isObjCObjectType())
8744         Diag(Loc, diag::err_objc_object_assignment)
8745           << LHSType;
8746 
8747     // If the RHS is a unary plus or minus, check to see if they = and + are
8748     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8749     // instead of "x += 4".
8750     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8751       RHSCheck = ICE->getSubExpr();
8752     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8753       if ((UO->getOpcode() == UO_Plus ||
8754            UO->getOpcode() == UO_Minus) &&
8755           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8756           // Only if the two operators are exactly adjacent.
8757           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8758           // And there is a space or other character before the subexpr of the
8759           // unary +/-.  We don't want to warn on "x=-1".
8760           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8761           UO->getSubExpr()->getLocStart().isFileID()) {
8762         Diag(Loc, diag::warn_not_compound_assign)
8763           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8764           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8765       }
8766     }
8767 
8768     if (ConvTy == Compatible) {
8769       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8770         // Warn about retain cycles where a block captures the LHS, but
8771         // not if the LHS is a simple variable into which the block is
8772         // being stored...unless that variable can be captured by reference!
8773         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8774         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8775         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8776           checkRetainCycles(LHSExpr, RHS.get());
8777 
8778         // It is safe to assign a weak reference into a strong variable.
8779         // Although this code can still have problems:
8780         //   id x = self.weakProp;
8781         //   id y = self.weakProp;
8782         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8783         // paths through the function. This should be revisited if
8784         // -Wrepeated-use-of-weak is made flow-sensitive.
8785         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8786                              RHS.get()->getLocStart()))
8787           getCurFunction()->markSafeWeakUse(RHS.get());
8788 
8789       } else if (getLangOpts().ObjCAutoRefCount) {
8790         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8791       }
8792     }
8793   } else {
8794     // Compound assignment "x += y"
8795     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8796   }
8797 
8798   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8799                                RHS.get(), AA_Assigning))
8800     return QualType();
8801 
8802   CheckForNullPointerDereference(*this, LHSExpr);
8803 
8804   // C99 6.5.16p3: The type of an assignment expression is the type of the
8805   // left operand unless the left operand has qualified type, in which case
8806   // it is the unqualified version of the type of the left operand.
8807   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8808   // is converted to the type of the assignment expression (above).
8809   // C++ 5.17p1: the type of the assignment expression is that of its left
8810   // operand.
8811   return (getLangOpts().CPlusPlus
8812           ? LHSType : LHSType.getUnqualifiedType());
8813 }
8814 
8815 // C99 6.5.17
8816 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8817                                    SourceLocation Loc) {
8818   LHS = S.CheckPlaceholderExpr(LHS.get());
8819   RHS = S.CheckPlaceholderExpr(RHS.get());
8820   if (LHS.isInvalid() || RHS.isInvalid())
8821     return QualType();
8822 
8823   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8824   // operands, but not unary promotions.
8825   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8826 
8827   // So we treat the LHS as a ignored value, and in C++ we allow the
8828   // containing site to determine what should be done with the RHS.
8829   LHS = S.IgnoredValueConversions(LHS.get());
8830   if (LHS.isInvalid())
8831     return QualType();
8832 
8833   S.DiagnoseUnusedExprResult(LHS.get());
8834 
8835   if (!S.getLangOpts().CPlusPlus) {
8836     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8837     if (RHS.isInvalid())
8838       return QualType();
8839     if (!RHS.get()->getType()->isVoidType())
8840       S.RequireCompleteType(Loc, RHS.get()->getType(),
8841                             diag::err_incomplete_type);
8842   }
8843 
8844   return RHS.get()->getType();
8845 }
8846 
8847 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8848 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8849 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8850                                                ExprValueKind &VK,
8851                                                ExprObjectKind &OK,
8852                                                SourceLocation OpLoc,
8853                                                bool IsInc, bool IsPrefix) {
8854   if (Op->isTypeDependent())
8855     return S.Context.DependentTy;
8856 
8857   QualType ResType = Op->getType();
8858   // Atomic types can be used for increment / decrement where the non-atomic
8859   // versions can, so ignore the _Atomic() specifier for the purpose of
8860   // checking.
8861   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8862     ResType = ResAtomicType->getValueType();
8863 
8864   assert(!ResType.isNull() && "no type for increment/decrement expression");
8865 
8866   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8867     // Decrement of bool is not allowed.
8868     if (!IsInc) {
8869       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8870       return QualType();
8871     }
8872     // Increment of bool sets it to true, but is deprecated.
8873     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8874   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8875     // Error on enum increments and decrements in C++ mode
8876     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8877     return QualType();
8878   } else if (ResType->isRealType()) {
8879     // OK!
8880   } else if (ResType->isPointerType()) {
8881     // C99 6.5.2.4p2, 6.5.6p2
8882     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8883       return QualType();
8884   } else if (ResType->isObjCObjectPointerType()) {
8885     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8886     // Otherwise, we just need a complete type.
8887     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8888         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8889       return QualType();
8890   } else if (ResType->isAnyComplexType()) {
8891     // C99 does not support ++/-- on complex types, we allow as an extension.
8892     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8893       << ResType << Op->getSourceRange();
8894   } else if (ResType->isPlaceholderType()) {
8895     ExprResult PR = S.CheckPlaceholderExpr(Op);
8896     if (PR.isInvalid()) return QualType();
8897     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
8898                                           IsInc, IsPrefix);
8899   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8900     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8901   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8902             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8903     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8904   } else {
8905     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8906       << ResType << int(IsInc) << Op->getSourceRange();
8907     return QualType();
8908   }
8909   // At this point, we know we have a real, complex or pointer type.
8910   // Now make sure the operand is a modifiable lvalue.
8911   if (CheckForModifiableLvalue(Op, OpLoc, S))
8912     return QualType();
8913   // In C++, a prefix increment is the same type as the operand. Otherwise
8914   // (in C or with postfix), the increment is the unqualified type of the
8915   // operand.
8916   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8917     VK = VK_LValue;
8918     OK = Op->getObjectKind();
8919     return ResType;
8920   } else {
8921     VK = VK_RValue;
8922     return ResType.getUnqualifiedType();
8923   }
8924 }
8925 
8926 
8927 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8928 /// This routine allows us to typecheck complex/recursive expressions
8929 /// where the declaration is needed for type checking. We only need to
8930 /// handle cases when the expression references a function designator
8931 /// or is an lvalue. Here are some examples:
8932 ///  - &(x) => x
8933 ///  - &*****f => f for f a function designator.
8934 ///  - &s.xx => s
8935 ///  - &s.zz[1].yy -> s, if zz is an array
8936 ///  - *(x + 1) -> x, if x is an array
8937 ///  - &"123"[2] -> 0
8938 ///  - & __real__ x -> x
8939 static ValueDecl *getPrimaryDecl(Expr *E) {
8940   switch (E->getStmtClass()) {
8941   case Stmt::DeclRefExprClass:
8942     return cast<DeclRefExpr>(E)->getDecl();
8943   case Stmt::MemberExprClass:
8944     // If this is an arrow operator, the address is an offset from
8945     // the base's value, so the object the base refers to is
8946     // irrelevant.
8947     if (cast<MemberExpr>(E)->isArrow())
8948       return nullptr;
8949     // Otherwise, the expression refers to a part of the base
8950     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8951   case Stmt::ArraySubscriptExprClass: {
8952     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8953     // promotion of register arrays earlier.
8954     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8955     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8956       if (ICE->getSubExpr()->getType()->isArrayType())
8957         return getPrimaryDecl(ICE->getSubExpr());
8958     }
8959     return nullptr;
8960   }
8961   case Stmt::UnaryOperatorClass: {
8962     UnaryOperator *UO = cast<UnaryOperator>(E);
8963 
8964     switch(UO->getOpcode()) {
8965     case UO_Real:
8966     case UO_Imag:
8967     case UO_Extension:
8968       return getPrimaryDecl(UO->getSubExpr());
8969     default:
8970       return nullptr;
8971     }
8972   }
8973   case Stmt::ParenExprClass:
8974     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8975   case Stmt::ImplicitCastExprClass:
8976     // If the result of an implicit cast is an l-value, we care about
8977     // the sub-expression; otherwise, the result here doesn't matter.
8978     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8979   default:
8980     return nullptr;
8981   }
8982 }
8983 
8984 namespace {
8985   enum {
8986     AO_Bit_Field = 0,
8987     AO_Vector_Element = 1,
8988     AO_Property_Expansion = 2,
8989     AO_Register_Variable = 3,
8990     AO_No_Error = 4
8991   };
8992 }
8993 /// \brief Diagnose invalid operand for address of operations.
8994 ///
8995 /// \param Type The type of operand which cannot have its address taken.
8996 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8997                                          Expr *E, unsigned Type) {
8998   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8999 }
9000 
9001 /// CheckAddressOfOperand - The operand of & must be either a function
9002 /// designator or an lvalue designating an object. If it is an lvalue, the
9003 /// object cannot be declared with storage class register or be a bit field.
9004 /// Note: The usual conversions are *not* applied to the operand of the &
9005 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9006 /// In C++, the operand might be an overloaded function name, in which case
9007 /// we allow the '&' but retain the overloaded-function type.
9008 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
9009   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9010     if (PTy->getKind() == BuiltinType::Overload) {
9011       Expr *E = OrigOp.get()->IgnoreParens();
9012       if (!isa<OverloadExpr>(E)) {
9013         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
9014         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
9015           << OrigOp.get()->getSourceRange();
9016         return QualType();
9017       }
9018 
9019       OverloadExpr *Ovl = cast<OverloadExpr>(E);
9020       if (isa<UnresolvedMemberExpr>(Ovl))
9021         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9022           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9023             << OrigOp.get()->getSourceRange();
9024           return QualType();
9025         }
9026 
9027       return Context.OverloadTy;
9028     }
9029 
9030     if (PTy->getKind() == BuiltinType::UnknownAny)
9031       return Context.UnknownAnyTy;
9032 
9033     if (PTy->getKind() == BuiltinType::BoundMember) {
9034       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9035         << OrigOp.get()->getSourceRange();
9036       return QualType();
9037     }
9038 
9039     OrigOp = CheckPlaceholderExpr(OrigOp.get());
9040     if (OrigOp.isInvalid()) return QualType();
9041   }
9042 
9043   if (OrigOp.get()->isTypeDependent())
9044     return Context.DependentTy;
9045 
9046   assert(!OrigOp.get()->getType()->isPlaceholderType());
9047 
9048   // Make sure to ignore parentheses in subsequent checks
9049   Expr *op = OrigOp.get()->IgnoreParens();
9050 
9051   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9052   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9053     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9054     return QualType();
9055   }
9056 
9057   if (getLangOpts().C99) {
9058     // Implement C99-only parts of addressof rules.
9059     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
9060       if (uOp->getOpcode() == UO_Deref)
9061         // Per C99 6.5.3.2, the address of a deref always returns a valid result
9062         // (assuming the deref expression is valid).
9063         return uOp->getSubExpr()->getType();
9064     }
9065     // Technically, there should be a check for array subscript
9066     // expressions here, but the result of one is always an lvalue anyway.
9067   }
9068   ValueDecl *dcl = getPrimaryDecl(op);
9069   Expr::LValueClassification lval = op->ClassifyLValue(Context);
9070   unsigned AddressOfError = AO_No_Error;
9071 
9072   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
9073     bool sfinae = (bool)isSFINAEContext();
9074     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9075                                   : diag::ext_typecheck_addrof_temporary)
9076       << op->getType() << op->getSourceRange();
9077     if (sfinae)
9078       return QualType();
9079     // Materialize the temporary as an lvalue so that we can take its address.
9080     OrigOp = op = new (Context)
9081         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
9082   } else if (isa<ObjCSelectorExpr>(op)) {
9083     return Context.getPointerType(op->getType());
9084   } else if (lval == Expr::LV_MemberFunction) {
9085     // If it's an instance method, make a member pointer.
9086     // The expression must have exactly the form &A::foo.
9087 
9088     // If the underlying expression isn't a decl ref, give up.
9089     if (!isa<DeclRefExpr>(op)) {
9090       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9091         << OrigOp.get()->getSourceRange();
9092       return QualType();
9093     }
9094     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9095     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9096 
9097     // The id-expression was parenthesized.
9098     if (OrigOp.get() != DRE) {
9099       Diag(OpLoc, diag::err_parens_pointer_member_function)
9100         << OrigOp.get()->getSourceRange();
9101 
9102     // The method was named without a qualifier.
9103     } else if (!DRE->getQualifier()) {
9104       if (MD->getParent()->getName().empty())
9105         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9106           << op->getSourceRange();
9107       else {
9108         SmallString<32> Str;
9109         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9110         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9111           << op->getSourceRange()
9112           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9113       }
9114     }
9115 
9116     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9117     if (isa<CXXDestructorDecl>(MD))
9118       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9119 
9120     QualType MPTy = Context.getMemberPointerType(
9121         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9122     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9123       RequireCompleteType(OpLoc, MPTy, 0);
9124     return MPTy;
9125   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9126     // C99 6.5.3.2p1
9127     // The operand must be either an l-value or a function designator
9128     if (!op->getType()->isFunctionType()) {
9129       // Use a special diagnostic for loads from property references.
9130       if (isa<PseudoObjectExpr>(op)) {
9131         AddressOfError = AO_Property_Expansion;
9132       } else {
9133         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9134           << op->getType() << op->getSourceRange();
9135         return QualType();
9136       }
9137     }
9138   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9139     // The operand cannot be a bit-field
9140     AddressOfError = AO_Bit_Field;
9141   } else if (op->getObjectKind() == OK_VectorComponent) {
9142     // The operand cannot be an element of a vector
9143     AddressOfError = AO_Vector_Element;
9144   } else if (dcl) { // C99 6.5.3.2p1
9145     // We have an lvalue with a decl. Make sure the decl is not declared
9146     // with the register storage-class specifier.
9147     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9148       // in C++ it is not error to take address of a register
9149       // variable (c++03 7.1.1P3)
9150       if (vd->getStorageClass() == SC_Register &&
9151           !getLangOpts().CPlusPlus) {
9152         AddressOfError = AO_Register_Variable;
9153       }
9154     } else if (isa<FunctionTemplateDecl>(dcl)) {
9155       return Context.OverloadTy;
9156     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9157       // Okay: we can take the address of a field.
9158       // Could be a pointer to member, though, if there is an explicit
9159       // scope qualifier for the class.
9160       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9161         DeclContext *Ctx = dcl->getDeclContext();
9162         if (Ctx && Ctx->isRecord()) {
9163           if (dcl->getType()->isReferenceType()) {
9164             Diag(OpLoc,
9165                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9166               << dcl->getDeclName() << dcl->getType();
9167             return QualType();
9168           }
9169 
9170           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9171             Ctx = Ctx->getParent();
9172 
9173           QualType MPTy = Context.getMemberPointerType(
9174               op->getType(),
9175               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9176           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9177             RequireCompleteType(OpLoc, MPTy, 0);
9178           return MPTy;
9179         }
9180       }
9181     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9182       llvm_unreachable("Unknown/unexpected decl type");
9183   }
9184 
9185   if (AddressOfError != AO_No_Error) {
9186     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9187     return QualType();
9188   }
9189 
9190   if (lval == Expr::LV_IncompleteVoidType) {
9191     // Taking the address of a void variable is technically illegal, but we
9192     // allow it in cases which are otherwise valid.
9193     // Example: "extern void x; void* y = &x;".
9194     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9195   }
9196 
9197   // If the operand has type "type", the result has type "pointer to type".
9198   if (op->getType()->isObjCObjectType())
9199     return Context.getObjCObjectPointerType(op->getType());
9200   return Context.getPointerType(op->getType());
9201 }
9202 
9203 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
9204   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
9205   if (!DRE)
9206     return;
9207   const Decl *D = DRE->getDecl();
9208   if (!D)
9209     return;
9210   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
9211   if (!Param)
9212     return;
9213   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
9214     if (!FD->hasAttr<NonNullAttr>())
9215       return;
9216   if (FunctionScopeInfo *FD = S.getCurFunction())
9217     if (!FD->ModifiedNonNullParams.count(Param))
9218       FD->ModifiedNonNullParams.insert(Param);
9219 }
9220 
9221 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9222 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9223                                         SourceLocation OpLoc) {
9224   if (Op->isTypeDependent())
9225     return S.Context.DependentTy;
9226 
9227   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9228   if (ConvResult.isInvalid())
9229     return QualType();
9230   Op = ConvResult.get();
9231   QualType OpTy = Op->getType();
9232   QualType Result;
9233 
9234   if (isa<CXXReinterpretCastExpr>(Op)) {
9235     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9236     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9237                                      Op->getSourceRange());
9238   }
9239 
9240   if (const PointerType *PT = OpTy->getAs<PointerType>())
9241     Result = PT->getPointeeType();
9242   else if (const ObjCObjectPointerType *OPT =
9243              OpTy->getAs<ObjCObjectPointerType>())
9244     Result = OPT->getPointeeType();
9245   else {
9246     ExprResult PR = S.CheckPlaceholderExpr(Op);
9247     if (PR.isInvalid()) return QualType();
9248     if (PR.get() != Op)
9249       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9250   }
9251 
9252   if (Result.isNull()) {
9253     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9254       << OpTy << Op->getSourceRange();
9255     return QualType();
9256   }
9257 
9258   // Note that per both C89 and C99, indirection is always legal, even if Result
9259   // is an incomplete type or void.  It would be possible to warn about
9260   // dereferencing a void pointer, but it's completely well-defined, and such a
9261   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9262   // for pointers to 'void' but is fine for any other pointer type:
9263   //
9264   // C++ [expr.unary.op]p1:
9265   //   [...] the expression to which [the unary * operator] is applied shall
9266   //   be a pointer to an object type, or a pointer to a function type
9267   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9268     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9269       << OpTy << Op->getSourceRange();
9270 
9271   // Dereferences are usually l-values...
9272   VK = VK_LValue;
9273 
9274   // ...except that certain expressions are never l-values in C.
9275   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9276     VK = VK_RValue;
9277 
9278   return Result;
9279 }
9280 
9281 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
9282   BinaryOperatorKind Opc;
9283   switch (Kind) {
9284   default: llvm_unreachable("Unknown binop!");
9285   case tok::periodstar:           Opc = BO_PtrMemD; break;
9286   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9287   case tok::star:                 Opc = BO_Mul; break;
9288   case tok::slash:                Opc = BO_Div; break;
9289   case tok::percent:              Opc = BO_Rem; break;
9290   case tok::plus:                 Opc = BO_Add; break;
9291   case tok::minus:                Opc = BO_Sub; break;
9292   case tok::lessless:             Opc = BO_Shl; break;
9293   case tok::greatergreater:       Opc = BO_Shr; break;
9294   case tok::lessequal:            Opc = BO_LE; break;
9295   case tok::less:                 Opc = BO_LT; break;
9296   case tok::greaterequal:         Opc = BO_GE; break;
9297   case tok::greater:              Opc = BO_GT; break;
9298   case tok::exclaimequal:         Opc = BO_NE; break;
9299   case tok::equalequal:           Opc = BO_EQ; break;
9300   case tok::amp:                  Opc = BO_And; break;
9301   case tok::caret:                Opc = BO_Xor; break;
9302   case tok::pipe:                 Opc = BO_Or; break;
9303   case tok::ampamp:               Opc = BO_LAnd; break;
9304   case tok::pipepipe:             Opc = BO_LOr; break;
9305   case tok::equal:                Opc = BO_Assign; break;
9306   case tok::starequal:            Opc = BO_MulAssign; break;
9307   case tok::slashequal:           Opc = BO_DivAssign; break;
9308   case tok::percentequal:         Opc = BO_RemAssign; break;
9309   case tok::plusequal:            Opc = BO_AddAssign; break;
9310   case tok::minusequal:           Opc = BO_SubAssign; break;
9311   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9312   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9313   case tok::ampequal:             Opc = BO_AndAssign; break;
9314   case tok::caretequal:           Opc = BO_XorAssign; break;
9315   case tok::pipeequal:            Opc = BO_OrAssign; break;
9316   case tok::comma:                Opc = BO_Comma; break;
9317   }
9318   return Opc;
9319 }
9320 
9321 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9322   tok::TokenKind Kind) {
9323   UnaryOperatorKind Opc;
9324   switch (Kind) {
9325   default: llvm_unreachable("Unknown unary op!");
9326   case tok::plusplus:     Opc = UO_PreInc; break;
9327   case tok::minusminus:   Opc = UO_PreDec; break;
9328   case tok::amp:          Opc = UO_AddrOf; break;
9329   case tok::star:         Opc = UO_Deref; break;
9330   case tok::plus:         Opc = UO_Plus; break;
9331   case tok::minus:        Opc = UO_Minus; break;
9332   case tok::tilde:        Opc = UO_Not; break;
9333   case tok::exclaim:      Opc = UO_LNot; break;
9334   case tok::kw___real:    Opc = UO_Real; break;
9335   case tok::kw___imag:    Opc = UO_Imag; break;
9336   case tok::kw___extension__: Opc = UO_Extension; break;
9337   }
9338   return Opc;
9339 }
9340 
9341 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9342 /// This warning is only emitted for builtin assignment operations. It is also
9343 /// suppressed in the event of macro expansions.
9344 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9345                                    SourceLocation OpLoc) {
9346   if (!S.ActiveTemplateInstantiations.empty())
9347     return;
9348   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9349     return;
9350   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9351   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9352   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9353   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9354   if (!LHSDeclRef || !RHSDeclRef ||
9355       LHSDeclRef->getLocation().isMacroID() ||
9356       RHSDeclRef->getLocation().isMacroID())
9357     return;
9358   const ValueDecl *LHSDecl =
9359     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9360   const ValueDecl *RHSDecl =
9361     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9362   if (LHSDecl != RHSDecl)
9363     return;
9364   if (LHSDecl->getType().isVolatileQualified())
9365     return;
9366   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9367     if (RefTy->getPointeeType().isVolatileQualified())
9368       return;
9369 
9370   S.Diag(OpLoc, diag::warn_self_assignment)
9371       << LHSDeclRef->getType()
9372       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9373 }
9374 
9375 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9376 /// is usually indicative of introspection within the Objective-C pointer.
9377 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9378                                           SourceLocation OpLoc) {
9379   if (!S.getLangOpts().ObjC1)
9380     return;
9381 
9382   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9383   const Expr *LHS = L.get();
9384   const Expr *RHS = R.get();
9385 
9386   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9387     ObjCPointerExpr = LHS;
9388     OtherExpr = RHS;
9389   }
9390   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9391     ObjCPointerExpr = RHS;
9392     OtherExpr = LHS;
9393   }
9394 
9395   // This warning is deliberately made very specific to reduce false
9396   // positives with logic that uses '&' for hashing.  This logic mainly
9397   // looks for code trying to introspect into tagged pointers, which
9398   // code should generally never do.
9399   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9400     unsigned Diag = diag::warn_objc_pointer_masking;
9401     // Determine if we are introspecting the result of performSelectorXXX.
9402     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9403     // Special case messages to -performSelector and friends, which
9404     // can return non-pointer values boxed in a pointer value.
9405     // Some clients may wish to silence warnings in this subcase.
9406     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9407       Selector S = ME->getSelector();
9408       StringRef SelArg0 = S.getNameForSlot(0);
9409       if (SelArg0.startswith("performSelector"))
9410         Diag = diag::warn_objc_pointer_masking_performSelector;
9411     }
9412 
9413     S.Diag(OpLoc, Diag)
9414       << ObjCPointerExpr->getSourceRange();
9415   }
9416 }
9417 
9418 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9419 /// operator @p Opc at location @c TokLoc. This routine only supports
9420 /// built-in operations; ActOnBinOp handles overloaded operators.
9421 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9422                                     BinaryOperatorKind Opc,
9423                                     Expr *LHSExpr, Expr *RHSExpr) {
9424   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9425     // The syntax only allows initializer lists on the RHS of assignment,
9426     // so we don't need to worry about accepting invalid code for
9427     // non-assignment operators.
9428     // C++11 5.17p9:
9429     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9430     //   of x = {} is x = T().
9431     InitializationKind Kind =
9432         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9433     InitializedEntity Entity =
9434         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9435     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9436     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9437     if (Init.isInvalid())
9438       return Init;
9439     RHSExpr = Init.get();
9440   }
9441 
9442   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9443   QualType ResultTy;     // Result type of the binary operator.
9444   // The following two variables are used for compound assignment operators
9445   QualType CompLHSTy;    // Type of LHS after promotions for computation
9446   QualType CompResultTy; // Type of computation result
9447   ExprValueKind VK = VK_RValue;
9448   ExprObjectKind OK = OK_Ordinary;
9449 
9450   switch (Opc) {
9451   case BO_Assign:
9452     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9453     if (getLangOpts().CPlusPlus &&
9454         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9455       VK = LHS.get()->getValueKind();
9456       OK = LHS.get()->getObjectKind();
9457     }
9458     if (!ResultTy.isNull())
9459       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9460     RecordModifiableNonNullParam(*this, LHS.get());
9461     break;
9462   case BO_PtrMemD:
9463   case BO_PtrMemI:
9464     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9465                                             Opc == BO_PtrMemI);
9466     break;
9467   case BO_Mul:
9468   case BO_Div:
9469     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9470                                            Opc == BO_Div);
9471     break;
9472   case BO_Rem:
9473     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9474     break;
9475   case BO_Add:
9476     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9477     break;
9478   case BO_Sub:
9479     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9480     break;
9481   case BO_Shl:
9482   case BO_Shr:
9483     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9484     break;
9485   case BO_LE:
9486   case BO_LT:
9487   case BO_GE:
9488   case BO_GT:
9489     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9490     break;
9491   case BO_EQ:
9492   case BO_NE:
9493     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9494     break;
9495   case BO_And:
9496     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9497   case BO_Xor:
9498   case BO_Or:
9499     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9500     break;
9501   case BO_LAnd:
9502   case BO_LOr:
9503     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9504     break;
9505   case BO_MulAssign:
9506   case BO_DivAssign:
9507     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9508                                                Opc == BO_DivAssign);
9509     CompLHSTy = CompResultTy;
9510     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9511       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9512     break;
9513   case BO_RemAssign:
9514     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9515     CompLHSTy = CompResultTy;
9516     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9517       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9518     break;
9519   case BO_AddAssign:
9520     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9521     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9522       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9523     break;
9524   case BO_SubAssign:
9525     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9526     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9527       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9528     break;
9529   case BO_ShlAssign:
9530   case BO_ShrAssign:
9531     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9532     CompLHSTy = CompResultTy;
9533     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9534       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9535     break;
9536   case BO_AndAssign:
9537   case BO_OrAssign: // fallthrough
9538 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9539   case BO_XorAssign:
9540     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9541     CompLHSTy = CompResultTy;
9542     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9543       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9544     break;
9545   case BO_Comma:
9546     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9547     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9548       VK = RHS.get()->getValueKind();
9549       OK = RHS.get()->getObjectKind();
9550     }
9551     break;
9552   }
9553   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9554     return ExprError();
9555 
9556   // Check for array bounds violations for both sides of the BinaryOperator
9557   CheckArrayAccess(LHS.get());
9558   CheckArrayAccess(RHS.get());
9559 
9560   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9561     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9562                                                  &Context.Idents.get("object_setClass"),
9563                                                  SourceLocation(), LookupOrdinaryName);
9564     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9565       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9566       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9567       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9568       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9569       FixItHint::CreateInsertion(RHSLocEnd, ")");
9570     }
9571     else
9572       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9573   }
9574   else if (const ObjCIvarRefExpr *OIRE =
9575            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9576     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9577 
9578   if (CompResultTy.isNull())
9579     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9580                                         OK, OpLoc, FPFeatures.fp_contract);
9581   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9582       OK_ObjCProperty) {
9583     VK = VK_LValue;
9584     OK = LHS.get()->getObjectKind();
9585   }
9586   return new (Context) CompoundAssignOperator(
9587       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9588       OpLoc, FPFeatures.fp_contract);
9589 }
9590 
9591 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9592 /// operators are mixed in a way that suggests that the programmer forgot that
9593 /// comparison operators have higher precedence. The most typical example of
9594 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9595 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9596                                       SourceLocation OpLoc, Expr *LHSExpr,
9597                                       Expr *RHSExpr) {
9598   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9599   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9600 
9601   // Check that one of the sides is a comparison operator.
9602   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9603   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9604   if (!isLeftComp && !isRightComp)
9605     return;
9606 
9607   // Bitwise operations are sometimes used as eager logical ops.
9608   // Don't diagnose this.
9609   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9610   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9611   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9612     return;
9613 
9614   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9615                                                    OpLoc)
9616                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9617   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9618   SourceRange ParensRange = isLeftComp ?
9619       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9620     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
9621 
9622   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9623     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9624   SuggestParentheses(Self, OpLoc,
9625     Self.PDiag(diag::note_precedence_silence) << OpStr,
9626     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9627   SuggestParentheses(Self, OpLoc,
9628     Self.PDiag(diag::note_precedence_bitwise_first)
9629       << BinaryOperator::getOpcodeStr(Opc),
9630     ParensRange);
9631 }
9632 
9633 /// \brief It accepts a '&' expr that is inside a '|' one.
9634 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9635 /// in parentheses.
9636 static void
9637 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9638                                        BinaryOperator *Bop) {
9639   assert(Bop->getOpcode() == BO_And);
9640   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9641       << Bop->getSourceRange() << OpLoc;
9642   SuggestParentheses(Self, Bop->getOperatorLoc(),
9643     Self.PDiag(diag::note_precedence_silence)
9644       << Bop->getOpcodeStr(),
9645     Bop->getSourceRange());
9646 }
9647 
9648 /// \brief It accepts a '&&' expr that is inside a '||' one.
9649 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9650 /// in parentheses.
9651 static void
9652 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9653                                        BinaryOperator *Bop) {
9654   assert(Bop->getOpcode() == BO_LAnd);
9655   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9656       << Bop->getSourceRange() << OpLoc;
9657   SuggestParentheses(Self, Bop->getOperatorLoc(),
9658     Self.PDiag(diag::note_precedence_silence)
9659       << Bop->getOpcodeStr(),
9660     Bop->getSourceRange());
9661 }
9662 
9663 /// \brief Returns true if the given expression can be evaluated as a constant
9664 /// 'true'.
9665 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9666   bool Res;
9667   return !E->isValueDependent() &&
9668          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9669 }
9670 
9671 /// \brief Returns true if the given expression can be evaluated as a constant
9672 /// 'false'.
9673 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9674   bool Res;
9675   return !E->isValueDependent() &&
9676          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9677 }
9678 
9679 /// \brief Look for '&&' in the left hand of a '||' expr.
9680 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9681                                              Expr *LHSExpr, Expr *RHSExpr) {
9682   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9683     if (Bop->getOpcode() == BO_LAnd) {
9684       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9685       if (EvaluatesAsFalse(S, RHSExpr))
9686         return;
9687       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9688       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9689         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9690     } else if (Bop->getOpcode() == BO_LOr) {
9691       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9692         // If it's "a || b && 1 || c" we didn't warn earlier for
9693         // "a || b && 1", but warn now.
9694         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9695           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9696       }
9697     }
9698   }
9699 }
9700 
9701 /// \brief Look for '&&' in the right hand of a '||' expr.
9702 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9703                                              Expr *LHSExpr, Expr *RHSExpr) {
9704   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9705     if (Bop->getOpcode() == BO_LAnd) {
9706       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9707       if (EvaluatesAsFalse(S, LHSExpr))
9708         return;
9709       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9710       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9711         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9712     }
9713   }
9714 }
9715 
9716 /// \brief Look for '&' in the left or right hand of a '|' expr.
9717 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9718                                              Expr *OrArg) {
9719   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9720     if (Bop->getOpcode() == BO_And)
9721       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9722   }
9723 }
9724 
9725 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9726                                     Expr *SubExpr, StringRef Shift) {
9727   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9728     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9729       StringRef Op = Bop->getOpcodeStr();
9730       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9731           << Bop->getSourceRange() << OpLoc << Shift << Op;
9732       SuggestParentheses(S, Bop->getOperatorLoc(),
9733           S.PDiag(diag::note_precedence_silence) << Op,
9734           Bop->getSourceRange());
9735     }
9736   }
9737 }
9738 
9739 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9740                                  Expr *LHSExpr, Expr *RHSExpr) {
9741   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9742   if (!OCE)
9743     return;
9744 
9745   FunctionDecl *FD = OCE->getDirectCallee();
9746   if (!FD || !FD->isOverloadedOperator())
9747     return;
9748 
9749   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9750   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9751     return;
9752 
9753   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9754       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9755       << (Kind == OO_LessLess);
9756   SuggestParentheses(S, OCE->getOperatorLoc(),
9757                      S.PDiag(diag::note_precedence_silence)
9758                          << (Kind == OO_LessLess ? "<<" : ">>"),
9759                      OCE->getSourceRange());
9760   SuggestParentheses(S, OpLoc,
9761                      S.PDiag(diag::note_evaluate_comparison_first),
9762                      SourceRange(OCE->getArg(1)->getLocStart(),
9763                                  RHSExpr->getLocEnd()));
9764 }
9765 
9766 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9767 /// precedence.
9768 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9769                                     SourceLocation OpLoc, Expr *LHSExpr,
9770                                     Expr *RHSExpr){
9771   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9772   if (BinaryOperator::isBitwiseOp(Opc))
9773     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9774 
9775   // Diagnose "arg1 & arg2 | arg3"
9776   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9777     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9778     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9779   }
9780 
9781   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9782   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9783   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9784     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9785     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9786   }
9787 
9788   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9789       || Opc == BO_Shr) {
9790     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9791     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9792     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9793   }
9794 
9795   // Warn on overloaded shift operators and comparisons, such as:
9796   // cout << 5 == 4;
9797   if (BinaryOperator::isComparisonOp(Opc))
9798     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9799 }
9800 
9801 // Binary Operators.  'Tok' is the token for the operator.
9802 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9803                             tok::TokenKind Kind,
9804                             Expr *LHSExpr, Expr *RHSExpr) {
9805   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9806   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9807   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9808 
9809   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9810   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9811 
9812   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9813 }
9814 
9815 /// Build an overloaded binary operator expression in the given scope.
9816 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9817                                        BinaryOperatorKind Opc,
9818                                        Expr *LHS, Expr *RHS) {
9819   // Find all of the overloaded operators visible from this
9820   // point. We perform both an operator-name lookup from the local
9821   // scope and an argument-dependent lookup based on the types of
9822   // the arguments.
9823   UnresolvedSet<16> Functions;
9824   OverloadedOperatorKind OverOp
9825     = BinaryOperator::getOverloadedOperator(Opc);
9826   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
9827     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9828                                    RHS->getType(), Functions);
9829 
9830   // Build the (potentially-overloaded, potentially-dependent)
9831   // binary operation.
9832   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9833 }
9834 
9835 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9836                             BinaryOperatorKind Opc,
9837                             Expr *LHSExpr, Expr *RHSExpr) {
9838   // We want to end up calling one of checkPseudoObjectAssignment
9839   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9840   // both expressions are overloadable or either is type-dependent),
9841   // or CreateBuiltinBinOp (in any other case).  We also want to get
9842   // any placeholder types out of the way.
9843 
9844   // Handle pseudo-objects in the LHS.
9845   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9846     // Assignments with a pseudo-object l-value need special analysis.
9847     if (pty->getKind() == BuiltinType::PseudoObject &&
9848         BinaryOperator::isAssignmentOp(Opc))
9849       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9850 
9851     // Don't resolve overloads if the other type is overloadable.
9852     if (pty->getKind() == BuiltinType::Overload) {
9853       // We can't actually test that if we still have a placeholder,
9854       // though.  Fortunately, none of the exceptions we see in that
9855       // code below are valid when the LHS is an overload set.  Note
9856       // that an overload set can be dependently-typed, but it never
9857       // instantiates to having an overloadable type.
9858       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9859       if (resolvedRHS.isInvalid()) return ExprError();
9860       RHSExpr = resolvedRHS.get();
9861 
9862       if (RHSExpr->isTypeDependent() ||
9863           RHSExpr->getType()->isOverloadableType())
9864         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9865     }
9866 
9867     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9868     if (LHS.isInvalid()) return ExprError();
9869     LHSExpr = LHS.get();
9870   }
9871 
9872   // Handle pseudo-objects in the RHS.
9873   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9874     // An overload in the RHS can potentially be resolved by the type
9875     // being assigned to.
9876     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9877       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9878         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9879 
9880       if (LHSExpr->getType()->isOverloadableType())
9881         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9882 
9883       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9884     }
9885 
9886     // Don't resolve overloads if the other type is overloadable.
9887     if (pty->getKind() == BuiltinType::Overload &&
9888         LHSExpr->getType()->isOverloadableType())
9889       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9890 
9891     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9892     if (!resolvedRHS.isUsable()) return ExprError();
9893     RHSExpr = resolvedRHS.get();
9894   }
9895 
9896   if (getLangOpts().CPlusPlus) {
9897     // If either expression is type-dependent, always build an
9898     // overloaded op.
9899     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9900       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9901 
9902     // Otherwise, build an overloaded op if either expression has an
9903     // overloadable type.
9904     if (LHSExpr->getType()->isOverloadableType() ||
9905         RHSExpr->getType()->isOverloadableType())
9906       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9907   }
9908 
9909   // Build a built-in binary operation.
9910   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9911 }
9912 
9913 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9914                                       UnaryOperatorKind Opc,
9915                                       Expr *InputExpr) {
9916   ExprResult Input = InputExpr;
9917   ExprValueKind VK = VK_RValue;
9918   ExprObjectKind OK = OK_Ordinary;
9919   QualType resultType;
9920   switch (Opc) {
9921   case UO_PreInc:
9922   case UO_PreDec:
9923   case UO_PostInc:
9924   case UO_PostDec:
9925     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
9926                                                 OpLoc,
9927                                                 Opc == UO_PreInc ||
9928                                                 Opc == UO_PostInc,
9929                                                 Opc == UO_PreInc ||
9930                                                 Opc == UO_PreDec);
9931     break;
9932   case UO_AddrOf:
9933     resultType = CheckAddressOfOperand(Input, OpLoc);
9934     RecordModifiableNonNullParam(*this, InputExpr);
9935     break;
9936   case UO_Deref: {
9937     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9938     if (Input.isInvalid()) return ExprError();
9939     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9940     break;
9941   }
9942   case UO_Plus:
9943   case UO_Minus:
9944     Input = UsualUnaryConversions(Input.get());
9945     if (Input.isInvalid()) return ExprError();
9946     resultType = Input.get()->getType();
9947     if (resultType->isDependentType())
9948       break;
9949     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9950         resultType->isVectorType())
9951       break;
9952     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9953              Opc == UO_Plus &&
9954              resultType->isPointerType())
9955       break;
9956 
9957     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9958       << resultType << Input.get()->getSourceRange());
9959 
9960   case UO_Not: // bitwise complement
9961     Input = UsualUnaryConversions(Input.get());
9962     if (Input.isInvalid())
9963       return ExprError();
9964     resultType = Input.get()->getType();
9965     if (resultType->isDependentType())
9966       break;
9967     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9968     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9969       // C99 does not support '~' for complex conjugation.
9970       Diag(OpLoc, diag::ext_integer_complement_complex)
9971           << resultType << Input.get()->getSourceRange();
9972     else if (resultType->hasIntegerRepresentation())
9973       break;
9974     else if (resultType->isExtVectorType()) {
9975       if (Context.getLangOpts().OpenCL) {
9976         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9977         // on vector float types.
9978         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9979         if (!T->isIntegerType())
9980           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9981                            << resultType << Input.get()->getSourceRange());
9982       }
9983       break;
9984     } else {
9985       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9986                        << resultType << Input.get()->getSourceRange());
9987     }
9988     break;
9989 
9990   case UO_LNot: // logical negation
9991     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9992     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9993     if (Input.isInvalid()) return ExprError();
9994     resultType = Input.get()->getType();
9995 
9996     // Though we still have to promote half FP to float...
9997     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9998       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9999       resultType = Context.FloatTy;
10000     }
10001 
10002     if (resultType->isDependentType())
10003       break;
10004     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
10005       // C99 6.5.3.3p1: ok, fallthrough;
10006       if (Context.getLangOpts().CPlusPlus) {
10007         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10008         // operand contextually converted to bool.
10009         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
10010                                   ScalarTypeToBooleanCastKind(resultType));
10011       } else if (Context.getLangOpts().OpenCL &&
10012                  Context.getLangOpts().OpenCLVersion < 120) {
10013         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10014         // operate on scalar float types.
10015         if (!resultType->isIntegerType())
10016           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10017                            << resultType << Input.get()->getSourceRange());
10018       }
10019     } else if (resultType->isExtVectorType()) {
10020       if (Context.getLangOpts().OpenCL &&
10021           Context.getLangOpts().OpenCLVersion < 120) {
10022         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10023         // operate on vector float types.
10024         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10025         if (!T->isIntegerType())
10026           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10027                            << resultType << Input.get()->getSourceRange());
10028       }
10029       // Vector logical not returns the signed variant of the operand type.
10030       resultType = GetSignedVectorType(resultType);
10031       break;
10032     } else {
10033       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10034         << resultType << Input.get()->getSourceRange());
10035     }
10036 
10037     // LNot always has type int. C99 6.5.3.3p5.
10038     // In C++, it's bool. C++ 5.3.1p8
10039     resultType = Context.getLogicalOperationType();
10040     break;
10041   case UO_Real:
10042   case UO_Imag:
10043     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
10044     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10045     // complex l-values to ordinary l-values and all other values to r-values.
10046     if (Input.isInvalid()) return ExprError();
10047     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10048       if (Input.get()->getValueKind() != VK_RValue &&
10049           Input.get()->getObjectKind() == OK_Ordinary)
10050         VK = Input.get()->getValueKind();
10051     } else if (!getLangOpts().CPlusPlus) {
10052       // In C, a volatile scalar is read by __imag. In C++, it is not.
10053       Input = DefaultLvalueConversion(Input.get());
10054     }
10055     break;
10056   case UO_Extension:
10057     resultType = Input.get()->getType();
10058     VK = Input.get()->getValueKind();
10059     OK = Input.get()->getObjectKind();
10060     break;
10061   }
10062   if (resultType.isNull() || Input.isInvalid())
10063     return ExprError();
10064 
10065   // Check for array bounds violations in the operand of the UnaryOperator,
10066   // except for the '*' and '&' operators that have to be handled specially
10067   // by CheckArrayAccess (as there are special cases like &array[arraysize]
10068   // that are explicitly defined as valid by the standard).
10069   if (Opc != UO_AddrOf && Opc != UO_Deref)
10070     CheckArrayAccess(Input.get());
10071 
10072   return new (Context)
10073       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
10074 }
10075 
10076 /// \brief Determine whether the given expression is a qualified member
10077 /// access expression, of a form that could be turned into a pointer to member
10078 /// with the address-of operator.
10079 static bool isQualifiedMemberAccess(Expr *E) {
10080   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10081     if (!DRE->getQualifier())
10082       return false;
10083 
10084     ValueDecl *VD = DRE->getDecl();
10085     if (!VD->isCXXClassMember())
10086       return false;
10087 
10088     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10089       return true;
10090     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10091       return Method->isInstance();
10092 
10093     return false;
10094   }
10095 
10096   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10097     if (!ULE->getQualifier())
10098       return false;
10099 
10100     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10101                                            DEnd = ULE->decls_end();
10102          D != DEnd; ++D) {
10103       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10104         if (Method->isInstance())
10105           return true;
10106       } else {
10107         // Overload set does not contain methods.
10108         break;
10109       }
10110     }
10111 
10112     return false;
10113   }
10114 
10115   return false;
10116 }
10117 
10118 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10119                               UnaryOperatorKind Opc, Expr *Input) {
10120   // First things first: handle placeholders so that the
10121   // overloaded-operator check considers the right type.
10122   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10123     // Increment and decrement of pseudo-object references.
10124     if (pty->getKind() == BuiltinType::PseudoObject &&
10125         UnaryOperator::isIncrementDecrementOp(Opc))
10126       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10127 
10128     // extension is always a builtin operator.
10129     if (Opc == UO_Extension)
10130       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10131 
10132     // & gets special logic for several kinds of placeholder.
10133     // The builtin code knows what to do.
10134     if (Opc == UO_AddrOf &&
10135         (pty->getKind() == BuiltinType::Overload ||
10136          pty->getKind() == BuiltinType::UnknownAny ||
10137          pty->getKind() == BuiltinType::BoundMember))
10138       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10139 
10140     // Anything else needs to be handled now.
10141     ExprResult Result = CheckPlaceholderExpr(Input);
10142     if (Result.isInvalid()) return ExprError();
10143     Input = Result.get();
10144   }
10145 
10146   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10147       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10148       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10149     // Find all of the overloaded operators visible from this
10150     // point. We perform both an operator-name lookup from the local
10151     // scope and an argument-dependent lookup based on the types of
10152     // the arguments.
10153     UnresolvedSet<16> Functions;
10154     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10155     if (S && OverOp != OO_None)
10156       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10157                                    Functions);
10158 
10159     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10160   }
10161 
10162   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10163 }
10164 
10165 // Unary Operators.  'Tok' is the token for the operator.
10166 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10167                               tok::TokenKind Op, Expr *Input) {
10168   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10169 }
10170 
10171 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10172 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10173                                 LabelDecl *TheDecl) {
10174   TheDecl->markUsed(Context);
10175   // Create the AST node.  The address of a label always has type 'void*'.
10176   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10177                                      Context.getPointerType(Context.VoidTy));
10178 }
10179 
10180 /// Given the last statement in a statement-expression, check whether
10181 /// the result is a producing expression (like a call to an
10182 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10183 /// release out of the full-expression.  Otherwise, return null.
10184 /// Cannot fail.
10185 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10186   // Should always be wrapped with one of these.
10187   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10188   if (!cleanups) return nullptr;
10189 
10190   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10191   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10192     return nullptr;
10193 
10194   // Splice out the cast.  This shouldn't modify any interesting
10195   // features of the statement.
10196   Expr *producer = cast->getSubExpr();
10197   assert(producer->getType() == cast->getType());
10198   assert(producer->getValueKind() == cast->getValueKind());
10199   cleanups->setSubExpr(producer);
10200   return cleanups;
10201 }
10202 
10203 void Sema::ActOnStartStmtExpr() {
10204   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10205 }
10206 
10207 void Sema::ActOnStmtExprError() {
10208   // Note that function is also called by TreeTransform when leaving a
10209   // StmtExpr scope without rebuilding anything.
10210 
10211   DiscardCleanupsInEvaluationContext();
10212   PopExpressionEvaluationContext();
10213 }
10214 
10215 ExprResult
10216 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10217                     SourceLocation RPLoc) { // "({..})"
10218   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10219   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10220 
10221   if (hasAnyUnrecoverableErrorsInThisFunction())
10222     DiscardCleanupsInEvaluationContext();
10223   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10224   PopExpressionEvaluationContext();
10225 
10226   bool isFileScope
10227     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10228   if (isFileScope)
10229     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10230 
10231   // FIXME: there are a variety of strange constraints to enforce here, for
10232   // example, it is not possible to goto into a stmt expression apparently.
10233   // More semantic analysis is needed.
10234 
10235   // If there are sub-stmts in the compound stmt, take the type of the last one
10236   // as the type of the stmtexpr.
10237   QualType Ty = Context.VoidTy;
10238   bool StmtExprMayBindToTemp = false;
10239   if (!Compound->body_empty()) {
10240     Stmt *LastStmt = Compound->body_back();
10241     LabelStmt *LastLabelStmt = nullptr;
10242     // If LastStmt is a label, skip down through into the body.
10243     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10244       LastLabelStmt = Label;
10245       LastStmt = Label->getSubStmt();
10246     }
10247 
10248     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10249       // Do function/array conversion on the last expression, but not
10250       // lvalue-to-rvalue.  However, initialize an unqualified type.
10251       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10252       if (LastExpr.isInvalid())
10253         return ExprError();
10254       Ty = LastExpr.get()->getType().getUnqualifiedType();
10255 
10256       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10257         // In ARC, if the final expression ends in a consume, splice
10258         // the consume out and bind it later.  In the alternate case
10259         // (when dealing with a retainable type), the result
10260         // initialization will create a produce.  In both cases the
10261         // result will be +1, and we'll need to balance that out with
10262         // a bind.
10263         if (Expr *rebuiltLastStmt
10264               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10265           LastExpr = rebuiltLastStmt;
10266         } else {
10267           LastExpr = PerformCopyInitialization(
10268                             InitializedEntity::InitializeResult(LPLoc,
10269                                                                 Ty,
10270                                                                 false),
10271                                                    SourceLocation(),
10272                                                LastExpr);
10273         }
10274 
10275         if (LastExpr.isInvalid())
10276           return ExprError();
10277         if (LastExpr.get() != nullptr) {
10278           if (!LastLabelStmt)
10279             Compound->setLastStmt(LastExpr.get());
10280           else
10281             LastLabelStmt->setSubStmt(LastExpr.get());
10282           StmtExprMayBindToTemp = true;
10283         }
10284       }
10285     }
10286   }
10287 
10288   // FIXME: Check that expression type is complete/non-abstract; statement
10289   // expressions are not lvalues.
10290   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10291   if (StmtExprMayBindToTemp)
10292     return MaybeBindToTemporary(ResStmtExpr);
10293   return ResStmtExpr;
10294 }
10295 
10296 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10297                                       TypeSourceInfo *TInfo,
10298                                       OffsetOfComponent *CompPtr,
10299                                       unsigned NumComponents,
10300                                       SourceLocation RParenLoc) {
10301   QualType ArgTy = TInfo->getType();
10302   bool Dependent = ArgTy->isDependentType();
10303   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10304 
10305   // We must have at least one component that refers to the type, and the first
10306   // one is known to be a field designator.  Verify that the ArgTy represents
10307   // a struct/union/class.
10308   if (!Dependent && !ArgTy->isRecordType())
10309     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10310                        << ArgTy << TypeRange);
10311 
10312   // Type must be complete per C99 7.17p3 because a declaring a variable
10313   // with an incomplete type would be ill-formed.
10314   if (!Dependent
10315       && RequireCompleteType(BuiltinLoc, ArgTy,
10316                              diag::err_offsetof_incomplete_type, TypeRange))
10317     return ExprError();
10318 
10319   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10320   // GCC extension, diagnose them.
10321   // FIXME: This diagnostic isn't actually visible because the location is in
10322   // a system header!
10323   if (NumComponents != 1)
10324     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10325       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10326 
10327   bool DidWarnAboutNonPOD = false;
10328   QualType CurrentType = ArgTy;
10329   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10330   SmallVector<OffsetOfNode, 4> Comps;
10331   SmallVector<Expr*, 4> Exprs;
10332   for (unsigned i = 0; i != NumComponents; ++i) {
10333     const OffsetOfComponent &OC = CompPtr[i];
10334     if (OC.isBrackets) {
10335       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10336       if (!CurrentType->isDependentType()) {
10337         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10338         if(!AT)
10339           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10340                            << CurrentType);
10341         CurrentType = AT->getElementType();
10342       } else
10343         CurrentType = Context.DependentTy;
10344 
10345       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10346       if (IdxRval.isInvalid())
10347         return ExprError();
10348       Expr *Idx = IdxRval.get();
10349 
10350       // The expression must be an integral expression.
10351       // FIXME: An integral constant expression?
10352       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10353           !Idx->getType()->isIntegerType())
10354         return ExprError(Diag(Idx->getLocStart(),
10355                               diag::err_typecheck_subscript_not_integer)
10356                          << Idx->getSourceRange());
10357 
10358       // Record this array index.
10359       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10360       Exprs.push_back(Idx);
10361       continue;
10362     }
10363 
10364     // Offset of a field.
10365     if (CurrentType->isDependentType()) {
10366       // We have the offset of a field, but we can't look into the dependent
10367       // type. Just record the identifier of the field.
10368       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10369       CurrentType = Context.DependentTy;
10370       continue;
10371     }
10372 
10373     // We need to have a complete type to look into.
10374     if (RequireCompleteType(OC.LocStart, CurrentType,
10375                             diag::err_offsetof_incomplete_type))
10376       return ExprError();
10377 
10378     // Look for the designated field.
10379     const RecordType *RC = CurrentType->getAs<RecordType>();
10380     if (!RC)
10381       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10382                        << CurrentType);
10383     RecordDecl *RD = RC->getDecl();
10384 
10385     // C++ [lib.support.types]p5:
10386     //   The macro offsetof accepts a restricted set of type arguments in this
10387     //   International Standard. type shall be a POD structure or a POD union
10388     //   (clause 9).
10389     // C++11 [support.types]p4:
10390     //   If type is not a standard-layout class (Clause 9), the results are
10391     //   undefined.
10392     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10393       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10394       unsigned DiagID =
10395         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10396                             : diag::ext_offsetof_non_pod_type;
10397 
10398       if (!IsSafe && !DidWarnAboutNonPOD &&
10399           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10400                               PDiag(DiagID)
10401                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10402                               << CurrentType))
10403         DidWarnAboutNonPOD = true;
10404     }
10405 
10406     // Look for the field.
10407     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10408     LookupQualifiedName(R, RD);
10409     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10410     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10411     if (!MemberDecl) {
10412       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10413         MemberDecl = IndirectMemberDecl->getAnonField();
10414     }
10415 
10416     if (!MemberDecl)
10417       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10418                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10419                                                               OC.LocEnd));
10420 
10421     // C99 7.17p3:
10422     //   (If the specified member is a bit-field, the behavior is undefined.)
10423     //
10424     // We diagnose this as an error.
10425     if (MemberDecl->isBitField()) {
10426       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10427         << MemberDecl->getDeclName()
10428         << SourceRange(BuiltinLoc, RParenLoc);
10429       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10430       return ExprError();
10431     }
10432 
10433     RecordDecl *Parent = MemberDecl->getParent();
10434     if (IndirectMemberDecl)
10435       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10436 
10437     // If the member was found in a base class, introduce OffsetOfNodes for
10438     // the base class indirections.
10439     CXXBasePaths Paths;
10440     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10441       if (Paths.getDetectedVirtual()) {
10442         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10443           << MemberDecl->getDeclName()
10444           << SourceRange(BuiltinLoc, RParenLoc);
10445         return ExprError();
10446       }
10447 
10448       CXXBasePath &Path = Paths.front();
10449       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10450            B != BEnd; ++B)
10451         Comps.push_back(OffsetOfNode(B->Base));
10452     }
10453 
10454     if (IndirectMemberDecl) {
10455       for (auto *FI : IndirectMemberDecl->chain()) {
10456         assert(isa<FieldDecl>(FI));
10457         Comps.push_back(OffsetOfNode(OC.LocStart,
10458                                      cast<FieldDecl>(FI), OC.LocEnd));
10459       }
10460     } else
10461       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10462 
10463     CurrentType = MemberDecl->getType().getNonReferenceType();
10464   }
10465 
10466   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10467                               Comps, Exprs, RParenLoc);
10468 }
10469 
10470 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10471                                       SourceLocation BuiltinLoc,
10472                                       SourceLocation TypeLoc,
10473                                       ParsedType ParsedArgTy,
10474                                       OffsetOfComponent *CompPtr,
10475                                       unsigned NumComponents,
10476                                       SourceLocation RParenLoc) {
10477 
10478   TypeSourceInfo *ArgTInfo;
10479   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10480   if (ArgTy.isNull())
10481     return ExprError();
10482 
10483   if (!ArgTInfo)
10484     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10485 
10486   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10487                               RParenLoc);
10488 }
10489 
10490 
10491 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10492                                  Expr *CondExpr,
10493                                  Expr *LHSExpr, Expr *RHSExpr,
10494                                  SourceLocation RPLoc) {
10495   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10496 
10497   ExprValueKind VK = VK_RValue;
10498   ExprObjectKind OK = OK_Ordinary;
10499   QualType resType;
10500   bool ValueDependent = false;
10501   bool CondIsTrue = false;
10502   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10503     resType = Context.DependentTy;
10504     ValueDependent = true;
10505   } else {
10506     // The conditional expression is required to be a constant expression.
10507     llvm::APSInt condEval(32);
10508     ExprResult CondICE
10509       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10510           diag::err_typecheck_choose_expr_requires_constant, false);
10511     if (CondICE.isInvalid())
10512       return ExprError();
10513     CondExpr = CondICE.get();
10514     CondIsTrue = condEval.getZExtValue();
10515 
10516     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10517     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10518 
10519     resType = ActiveExpr->getType();
10520     ValueDependent = ActiveExpr->isValueDependent();
10521     VK = ActiveExpr->getValueKind();
10522     OK = ActiveExpr->getObjectKind();
10523   }
10524 
10525   return new (Context)
10526       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10527                  CondIsTrue, resType->isDependentType(), ValueDependent);
10528 }
10529 
10530 //===----------------------------------------------------------------------===//
10531 // Clang Extensions.
10532 //===----------------------------------------------------------------------===//
10533 
10534 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10535 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10536   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10537 
10538   if (LangOpts.CPlusPlus) {
10539     Decl *ManglingContextDecl;
10540     if (MangleNumberingContext *MCtx =
10541             getCurrentMangleNumberContext(Block->getDeclContext(),
10542                                           ManglingContextDecl)) {
10543       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10544       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10545     }
10546   }
10547 
10548   PushBlockScope(CurScope, Block);
10549   CurContext->addDecl(Block);
10550   if (CurScope)
10551     PushDeclContext(CurScope, Block);
10552   else
10553     CurContext = Block;
10554 
10555   getCurBlock()->HasImplicitReturnType = true;
10556 
10557   // Enter a new evaluation context to insulate the block from any
10558   // cleanups from the enclosing full-expression.
10559   PushExpressionEvaluationContext(PotentiallyEvaluated);
10560 }
10561 
10562 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10563                                Scope *CurScope) {
10564   assert(ParamInfo.getIdentifier() == nullptr &&
10565          "block-id should have no identifier!");
10566   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10567   BlockScopeInfo *CurBlock = getCurBlock();
10568 
10569   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10570   QualType T = Sig->getType();
10571 
10572   // FIXME: We should allow unexpanded parameter packs here, but that would,
10573   // in turn, make the block expression contain unexpanded parameter packs.
10574   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10575     // Drop the parameters.
10576     FunctionProtoType::ExtProtoInfo EPI;
10577     EPI.HasTrailingReturn = false;
10578     EPI.TypeQuals |= DeclSpec::TQ_const;
10579     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10580     Sig = Context.getTrivialTypeSourceInfo(T);
10581   }
10582 
10583   // GetTypeForDeclarator always produces a function type for a block
10584   // literal signature.  Furthermore, it is always a FunctionProtoType
10585   // unless the function was written with a typedef.
10586   assert(T->isFunctionType() &&
10587          "GetTypeForDeclarator made a non-function block signature");
10588 
10589   // Look for an explicit signature in that function type.
10590   FunctionProtoTypeLoc ExplicitSignature;
10591 
10592   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10593   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10594 
10595     // Check whether that explicit signature was synthesized by
10596     // GetTypeForDeclarator.  If so, don't save that as part of the
10597     // written signature.
10598     if (ExplicitSignature.getLocalRangeBegin() ==
10599         ExplicitSignature.getLocalRangeEnd()) {
10600       // This would be much cheaper if we stored TypeLocs instead of
10601       // TypeSourceInfos.
10602       TypeLoc Result = ExplicitSignature.getReturnLoc();
10603       unsigned Size = Result.getFullDataSize();
10604       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10605       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10606 
10607       ExplicitSignature = FunctionProtoTypeLoc();
10608     }
10609   }
10610 
10611   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10612   CurBlock->FunctionType = T;
10613 
10614   const FunctionType *Fn = T->getAs<FunctionType>();
10615   QualType RetTy = Fn->getReturnType();
10616   bool isVariadic =
10617     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10618 
10619   CurBlock->TheDecl->setIsVariadic(isVariadic);
10620 
10621   // Context.DependentTy is used as a placeholder for a missing block
10622   // return type.  TODO:  what should we do with declarators like:
10623   //   ^ * { ... }
10624   // If the answer is "apply template argument deduction"....
10625   if (RetTy != Context.DependentTy) {
10626     CurBlock->ReturnType = RetTy;
10627     CurBlock->TheDecl->setBlockMissingReturnType(false);
10628     CurBlock->HasImplicitReturnType = false;
10629   }
10630 
10631   // Push block parameters from the declarator if we had them.
10632   SmallVector<ParmVarDecl*, 8> Params;
10633   if (ExplicitSignature) {
10634     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10635       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10636       if (Param->getIdentifier() == nullptr &&
10637           !Param->isImplicit() &&
10638           !Param->isInvalidDecl() &&
10639           !getLangOpts().CPlusPlus)
10640         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10641       Params.push_back(Param);
10642     }
10643 
10644   // Fake up parameter variables if we have a typedef, like
10645   //   ^ fntype { ... }
10646   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10647     for (const auto &I : Fn->param_types()) {
10648       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10649           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10650       Params.push_back(Param);
10651     }
10652   }
10653 
10654   // Set the parameters on the block decl.
10655   if (!Params.empty()) {
10656     CurBlock->TheDecl->setParams(Params);
10657     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10658                              CurBlock->TheDecl->param_end(),
10659                              /*CheckParameterNames=*/false);
10660   }
10661 
10662   // Finally we can process decl attributes.
10663   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10664 
10665   // Put the parameter variables in scope.
10666   for (auto AI : CurBlock->TheDecl->params()) {
10667     AI->setOwningFunction(CurBlock->TheDecl);
10668 
10669     // If this has an identifier, add it to the scope stack.
10670     if (AI->getIdentifier()) {
10671       CheckShadow(CurBlock->TheScope, AI);
10672 
10673       PushOnScopeChains(AI, CurBlock->TheScope);
10674     }
10675   }
10676 }
10677 
10678 /// ActOnBlockError - If there is an error parsing a block, this callback
10679 /// is invoked to pop the information about the block from the action impl.
10680 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10681   // Leave the expression-evaluation context.
10682   DiscardCleanupsInEvaluationContext();
10683   PopExpressionEvaluationContext();
10684 
10685   // Pop off CurBlock, handle nested blocks.
10686   PopDeclContext();
10687   PopFunctionScopeInfo();
10688 }
10689 
10690 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10691 /// literal was successfully completed.  ^(int x){...}
10692 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10693                                     Stmt *Body, Scope *CurScope) {
10694   // If blocks are disabled, emit an error.
10695   if (!LangOpts.Blocks)
10696     Diag(CaretLoc, diag::err_blocks_disable);
10697 
10698   // Leave the expression-evaluation context.
10699   if (hasAnyUnrecoverableErrorsInThisFunction())
10700     DiscardCleanupsInEvaluationContext();
10701   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10702   PopExpressionEvaluationContext();
10703 
10704   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10705 
10706   if (BSI->HasImplicitReturnType)
10707     deduceClosureReturnType(*BSI);
10708 
10709   PopDeclContext();
10710 
10711   QualType RetTy = Context.VoidTy;
10712   if (!BSI->ReturnType.isNull())
10713     RetTy = BSI->ReturnType;
10714 
10715   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10716   QualType BlockTy;
10717 
10718   // Set the captured variables on the block.
10719   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10720   SmallVector<BlockDecl::Capture, 4> Captures;
10721   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10722     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10723     if (Cap.isThisCapture())
10724       continue;
10725     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10726                               Cap.isNested(), Cap.getInitExpr());
10727     Captures.push_back(NewCap);
10728   }
10729   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10730                             BSI->CXXThisCaptureIndex != 0);
10731 
10732   // If the user wrote a function type in some form, try to use that.
10733   if (!BSI->FunctionType.isNull()) {
10734     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10735 
10736     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10737     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10738 
10739     // Turn protoless block types into nullary block types.
10740     if (isa<FunctionNoProtoType>(FTy)) {
10741       FunctionProtoType::ExtProtoInfo EPI;
10742       EPI.ExtInfo = Ext;
10743       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10744 
10745     // Otherwise, if we don't need to change anything about the function type,
10746     // preserve its sugar structure.
10747     } else if (FTy->getReturnType() == RetTy &&
10748                (!NoReturn || FTy->getNoReturnAttr())) {
10749       BlockTy = BSI->FunctionType;
10750 
10751     // Otherwise, make the minimal modifications to the function type.
10752     } else {
10753       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10754       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10755       EPI.TypeQuals = 0; // FIXME: silently?
10756       EPI.ExtInfo = Ext;
10757       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10758     }
10759 
10760   // If we don't have a function type, just build one from nothing.
10761   } else {
10762     FunctionProtoType::ExtProtoInfo EPI;
10763     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10764     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10765   }
10766 
10767   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10768                            BSI->TheDecl->param_end());
10769   BlockTy = Context.getBlockPointerType(BlockTy);
10770 
10771   // If needed, diagnose invalid gotos and switches in the block.
10772   if (getCurFunction()->NeedsScopeChecking() &&
10773       !PP.isCodeCompletionEnabled())
10774     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10775 
10776   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10777 
10778   // Try to apply the named return value optimization. We have to check again
10779   // if we can do this, though, because blocks keep return statements around
10780   // to deduce an implicit return type.
10781   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10782       !BSI->TheDecl->isDependentContext())
10783     computeNRVO(Body, BSI);
10784 
10785   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10786   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10787   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10788 
10789   // If the block isn't obviously global, i.e. it captures anything at
10790   // all, then we need to do a few things in the surrounding context:
10791   if (Result->getBlockDecl()->hasCaptures()) {
10792     // First, this expression has a new cleanup object.
10793     ExprCleanupObjects.push_back(Result->getBlockDecl());
10794     ExprNeedsCleanups = true;
10795 
10796     // It also gets a branch-protected scope if any of the captured
10797     // variables needs destruction.
10798     for (const auto &CI : Result->getBlockDecl()->captures()) {
10799       const VarDecl *var = CI.getVariable();
10800       if (var->getType().isDestructedType() != QualType::DK_none) {
10801         getCurFunction()->setHasBranchProtectedScope();
10802         break;
10803       }
10804     }
10805   }
10806 
10807   return Result;
10808 }
10809 
10810 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10811                                         Expr *E, ParsedType Ty,
10812                                         SourceLocation RPLoc) {
10813   TypeSourceInfo *TInfo;
10814   GetTypeFromParser(Ty, &TInfo);
10815   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10816 }
10817 
10818 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10819                                 Expr *E, TypeSourceInfo *TInfo,
10820                                 SourceLocation RPLoc) {
10821   Expr *OrigExpr = E;
10822 
10823   // Get the va_list type
10824   QualType VaListType = Context.getBuiltinVaListType();
10825   if (VaListType->isArrayType()) {
10826     // Deal with implicit array decay; for example, on x86-64,
10827     // va_list is an array, but it's supposed to decay to
10828     // a pointer for va_arg.
10829     VaListType = Context.getArrayDecayedType(VaListType);
10830     // Make sure the input expression also decays appropriately.
10831     ExprResult Result = UsualUnaryConversions(E);
10832     if (Result.isInvalid())
10833       return ExprError();
10834     E = Result.get();
10835   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10836     // If va_list is a record type and we are compiling in C++ mode,
10837     // check the argument using reference binding.
10838     InitializedEntity Entity
10839       = InitializedEntity::InitializeParameter(Context,
10840           Context.getLValueReferenceType(VaListType), false);
10841     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10842     if (Init.isInvalid())
10843       return ExprError();
10844     E = Init.getAs<Expr>();
10845   } else {
10846     // Otherwise, the va_list argument must be an l-value because
10847     // it is modified by va_arg.
10848     if (!E->isTypeDependent() &&
10849         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10850       return ExprError();
10851   }
10852 
10853   if (!E->isTypeDependent() &&
10854       !Context.hasSameType(VaListType, E->getType())) {
10855     return ExprError(Diag(E->getLocStart(),
10856                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10857       << OrigExpr->getType() << E->getSourceRange());
10858   }
10859 
10860   if (!TInfo->getType()->isDependentType()) {
10861     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10862                             diag::err_second_parameter_to_va_arg_incomplete,
10863                             TInfo->getTypeLoc()))
10864       return ExprError();
10865 
10866     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10867                                TInfo->getType(),
10868                                diag::err_second_parameter_to_va_arg_abstract,
10869                                TInfo->getTypeLoc()))
10870       return ExprError();
10871 
10872     if (!TInfo->getType().isPODType(Context)) {
10873       Diag(TInfo->getTypeLoc().getBeginLoc(),
10874            TInfo->getType()->isObjCLifetimeType()
10875              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10876              : diag::warn_second_parameter_to_va_arg_not_pod)
10877         << TInfo->getType()
10878         << TInfo->getTypeLoc().getSourceRange();
10879     }
10880 
10881     // Check for va_arg where arguments of the given type will be promoted
10882     // (i.e. this va_arg is guaranteed to have undefined behavior).
10883     QualType PromoteType;
10884     if (TInfo->getType()->isPromotableIntegerType()) {
10885       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10886       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10887         PromoteType = QualType();
10888     }
10889     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10890       PromoteType = Context.DoubleTy;
10891     if (!PromoteType.isNull())
10892       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10893                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10894                           << TInfo->getType()
10895                           << PromoteType
10896                           << TInfo->getTypeLoc().getSourceRange());
10897   }
10898 
10899   QualType T = TInfo->getType().getNonLValueExprType(Context);
10900   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10901 }
10902 
10903 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10904   // The type of __null will be int or long, depending on the size of
10905   // pointers on the target.
10906   QualType Ty;
10907   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10908   if (pw == Context.getTargetInfo().getIntWidth())
10909     Ty = Context.IntTy;
10910   else if (pw == Context.getTargetInfo().getLongWidth())
10911     Ty = Context.LongTy;
10912   else if (pw == Context.getTargetInfo().getLongLongWidth())
10913     Ty = Context.LongLongTy;
10914   else {
10915     llvm_unreachable("I don't know size of pointer!");
10916   }
10917 
10918   return new (Context) GNUNullExpr(Ty, TokenLoc);
10919 }
10920 
10921 bool
10922 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10923   if (!getLangOpts().ObjC1)
10924     return false;
10925 
10926   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10927   if (!PT)
10928     return false;
10929 
10930   if (!PT->isObjCIdType()) {
10931     // Check if the destination is the 'NSString' interface.
10932     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10933     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10934       return false;
10935   }
10936 
10937   // Ignore any parens, implicit casts (should only be
10938   // array-to-pointer decays), and not-so-opaque values.  The last is
10939   // important for making this trigger for property assignments.
10940   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10941   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10942     if (OV->getSourceExpr())
10943       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10944 
10945   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10946   if (!SL || !SL->isAscii())
10947     return false;
10948   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10949     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10950   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10951   return true;
10952 }
10953 
10954 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10955                                     SourceLocation Loc,
10956                                     QualType DstType, QualType SrcType,
10957                                     Expr *SrcExpr, AssignmentAction Action,
10958                                     bool *Complained) {
10959   if (Complained)
10960     *Complained = false;
10961 
10962   // Decode the result (notice that AST's are still created for extensions).
10963   bool CheckInferredResultType = false;
10964   bool isInvalid = false;
10965   unsigned DiagKind = 0;
10966   FixItHint Hint;
10967   ConversionFixItGenerator ConvHints;
10968   bool MayHaveConvFixit = false;
10969   bool MayHaveFunctionDiff = false;
10970   const ObjCInterfaceDecl *IFace = nullptr;
10971   const ObjCProtocolDecl *PDecl = nullptr;
10972 
10973   switch (ConvTy) {
10974   case Compatible:
10975       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10976       return false;
10977 
10978   case PointerToInt:
10979     DiagKind = diag::ext_typecheck_convert_pointer_int;
10980     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10981     MayHaveConvFixit = true;
10982     break;
10983   case IntToPointer:
10984     DiagKind = diag::ext_typecheck_convert_int_pointer;
10985     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10986     MayHaveConvFixit = true;
10987     break;
10988   case IncompatiblePointer:
10989       DiagKind =
10990         (Action == AA_Passing_CFAudited ?
10991           diag::err_arc_typecheck_convert_incompatible_pointer :
10992           diag::ext_typecheck_convert_incompatible_pointer);
10993     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10994       SrcType->isObjCObjectPointerType();
10995     if (Hint.isNull() && !CheckInferredResultType) {
10996       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10997     }
10998     else if (CheckInferredResultType) {
10999       SrcType = SrcType.getUnqualifiedType();
11000       DstType = DstType.getUnqualifiedType();
11001     }
11002     MayHaveConvFixit = true;
11003     break;
11004   case IncompatiblePointerSign:
11005     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11006     break;
11007   case FunctionVoidPointer:
11008     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11009     break;
11010   case IncompatiblePointerDiscardsQualifiers: {
11011     // Perform array-to-pointer decay if necessary.
11012     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11013 
11014     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11015     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11016     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11017       DiagKind = diag::err_typecheck_incompatible_address_space;
11018       break;
11019 
11020 
11021     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
11022       DiagKind = diag::err_typecheck_incompatible_ownership;
11023       break;
11024     }
11025 
11026     llvm_unreachable("unknown error case for discarding qualifiers!");
11027     // fallthrough
11028   }
11029   case CompatiblePointerDiscardsQualifiers:
11030     // If the qualifiers lost were because we were applying the
11031     // (deprecated) C++ conversion from a string literal to a char*
11032     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
11033     // Ideally, this check would be performed in
11034     // checkPointerTypesForAssignment. However, that would require a
11035     // bit of refactoring (so that the second argument is an
11036     // expression, rather than a type), which should be done as part
11037     // of a larger effort to fix checkPointerTypesForAssignment for
11038     // C++ semantics.
11039     if (getLangOpts().CPlusPlus &&
11040         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11041       return false;
11042     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11043     break;
11044   case IncompatibleNestedPointerQualifiers:
11045     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
11046     break;
11047   case IntToBlockPointer:
11048     DiagKind = diag::err_int_to_block_pointer;
11049     break;
11050   case IncompatibleBlockPointer:
11051     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
11052     break;
11053   case IncompatibleObjCQualifiedId: {
11054     if (SrcType->isObjCQualifiedIdType()) {
11055       const ObjCObjectPointerType *srcOPT =
11056                 SrcType->getAs<ObjCObjectPointerType>();
11057       for (auto *srcProto : srcOPT->quals()) {
11058         PDecl = srcProto;
11059         break;
11060       }
11061       if (const ObjCInterfaceType *IFaceT =
11062             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11063         IFace = IFaceT->getDecl();
11064     }
11065     else if (DstType->isObjCQualifiedIdType()) {
11066       const ObjCObjectPointerType *dstOPT =
11067         DstType->getAs<ObjCObjectPointerType>();
11068       for (auto *dstProto : dstOPT->quals()) {
11069         PDecl = dstProto;
11070         break;
11071       }
11072       if (const ObjCInterfaceType *IFaceT =
11073             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11074         IFace = IFaceT->getDecl();
11075     }
11076     DiagKind = diag::warn_incompatible_qualified_id;
11077     break;
11078   }
11079   case IncompatibleVectors:
11080     DiagKind = diag::warn_incompatible_vectors;
11081     break;
11082   case IncompatibleObjCWeakRef:
11083     DiagKind = diag::err_arc_weak_unavailable_assign;
11084     break;
11085   case Incompatible:
11086     DiagKind = diag::err_typecheck_convert_incompatible;
11087     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11088     MayHaveConvFixit = true;
11089     isInvalid = true;
11090     MayHaveFunctionDiff = true;
11091     break;
11092   }
11093 
11094   QualType FirstType, SecondType;
11095   switch (Action) {
11096   case AA_Assigning:
11097   case AA_Initializing:
11098     // The destination type comes first.
11099     FirstType = DstType;
11100     SecondType = SrcType;
11101     break;
11102 
11103   case AA_Returning:
11104   case AA_Passing:
11105   case AA_Passing_CFAudited:
11106   case AA_Converting:
11107   case AA_Sending:
11108   case AA_Casting:
11109     // The source type comes first.
11110     FirstType = SrcType;
11111     SecondType = DstType;
11112     break;
11113   }
11114 
11115   PartialDiagnostic FDiag = PDiag(DiagKind);
11116   if (Action == AA_Passing_CFAudited)
11117     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11118   else
11119     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11120 
11121   // If we can fix the conversion, suggest the FixIts.
11122   assert(ConvHints.isNull() || Hint.isNull());
11123   if (!ConvHints.isNull()) {
11124     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11125          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11126       FDiag << *HI;
11127   } else {
11128     FDiag << Hint;
11129   }
11130   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11131 
11132   if (MayHaveFunctionDiff)
11133     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11134 
11135   Diag(Loc, FDiag);
11136   if (DiagKind == diag::warn_incompatible_qualified_id &&
11137       PDecl && IFace && !IFace->hasDefinition())
11138       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11139         << IFace->getName() << PDecl->getName();
11140 
11141   if (SecondType == Context.OverloadTy)
11142     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11143                               FirstType);
11144 
11145   if (CheckInferredResultType)
11146     EmitRelatedResultTypeNote(SrcExpr);
11147 
11148   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11149     EmitRelatedResultTypeNoteForReturn(DstType);
11150 
11151   if (Complained)
11152     *Complained = true;
11153   return isInvalid;
11154 }
11155 
11156 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11157                                                  llvm::APSInt *Result) {
11158   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11159   public:
11160     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11161       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11162     }
11163   } Diagnoser;
11164 
11165   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11166 }
11167 
11168 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11169                                                  llvm::APSInt *Result,
11170                                                  unsigned DiagID,
11171                                                  bool AllowFold) {
11172   class IDDiagnoser : public VerifyICEDiagnoser {
11173     unsigned DiagID;
11174 
11175   public:
11176     IDDiagnoser(unsigned DiagID)
11177       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11178 
11179     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11180       S.Diag(Loc, DiagID) << SR;
11181     }
11182   } Diagnoser(DiagID);
11183 
11184   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11185 }
11186 
11187 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11188                                             SourceRange SR) {
11189   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11190 }
11191 
11192 ExprResult
11193 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11194                                       VerifyICEDiagnoser &Diagnoser,
11195                                       bool AllowFold) {
11196   SourceLocation DiagLoc = E->getLocStart();
11197 
11198   if (getLangOpts().CPlusPlus11) {
11199     // C++11 [expr.const]p5:
11200     //   If an expression of literal class type is used in a context where an
11201     //   integral constant expression is required, then that class type shall
11202     //   have a single non-explicit conversion function to an integral or
11203     //   unscoped enumeration type
11204     ExprResult Converted;
11205     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11206     public:
11207       CXX11ConvertDiagnoser(bool Silent)
11208           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11209                                 Silent, true) {}
11210 
11211       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11212                                            QualType T) override {
11213         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11214       }
11215 
11216       SemaDiagnosticBuilder diagnoseIncomplete(
11217           Sema &S, SourceLocation Loc, QualType T) override {
11218         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11219       }
11220 
11221       SemaDiagnosticBuilder diagnoseExplicitConv(
11222           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11223         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11224       }
11225 
11226       SemaDiagnosticBuilder noteExplicitConv(
11227           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11228         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11229                  << ConvTy->isEnumeralType() << ConvTy;
11230       }
11231 
11232       SemaDiagnosticBuilder diagnoseAmbiguous(
11233           Sema &S, SourceLocation Loc, QualType T) override {
11234         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11235       }
11236 
11237       SemaDiagnosticBuilder noteAmbiguous(
11238           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11239         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11240                  << ConvTy->isEnumeralType() << ConvTy;
11241       }
11242 
11243       SemaDiagnosticBuilder diagnoseConversion(
11244           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11245         llvm_unreachable("conversion functions are permitted");
11246       }
11247     } ConvertDiagnoser(Diagnoser.Suppress);
11248 
11249     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11250                                                     ConvertDiagnoser);
11251     if (Converted.isInvalid())
11252       return Converted;
11253     E = Converted.get();
11254     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11255       return ExprError();
11256   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11257     // An ICE must be of integral or unscoped enumeration type.
11258     if (!Diagnoser.Suppress)
11259       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11260     return ExprError();
11261   }
11262 
11263   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11264   // in the non-ICE case.
11265   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11266     if (Result)
11267       *Result = E->EvaluateKnownConstInt(Context);
11268     return E;
11269   }
11270 
11271   Expr::EvalResult EvalResult;
11272   SmallVector<PartialDiagnosticAt, 8> Notes;
11273   EvalResult.Diag = &Notes;
11274 
11275   // Try to evaluate the expression, and produce diagnostics explaining why it's
11276   // not a constant expression as a side-effect.
11277   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11278                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11279 
11280   // In C++11, we can rely on diagnostics being produced for any expression
11281   // which is not a constant expression. If no diagnostics were produced, then
11282   // this is a constant expression.
11283   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11284     if (Result)
11285       *Result = EvalResult.Val.getInt();
11286     return E;
11287   }
11288 
11289   // If our only note is the usual "invalid subexpression" note, just point
11290   // the caret at its location rather than producing an essentially
11291   // redundant note.
11292   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11293         diag::note_invalid_subexpr_in_const_expr) {
11294     DiagLoc = Notes[0].first;
11295     Notes.clear();
11296   }
11297 
11298   if (!Folded || !AllowFold) {
11299     if (!Diagnoser.Suppress) {
11300       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11301       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11302         Diag(Notes[I].first, Notes[I].second);
11303     }
11304 
11305     return ExprError();
11306   }
11307 
11308   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11309   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11310     Diag(Notes[I].first, Notes[I].second);
11311 
11312   if (Result)
11313     *Result = EvalResult.Val.getInt();
11314   return E;
11315 }
11316 
11317 namespace {
11318   // Handle the case where we conclude a expression which we speculatively
11319   // considered to be unevaluated is actually evaluated.
11320   class TransformToPE : public TreeTransform<TransformToPE> {
11321     typedef TreeTransform<TransformToPE> BaseTransform;
11322 
11323   public:
11324     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11325 
11326     // Make sure we redo semantic analysis
11327     bool AlwaysRebuild() { return true; }
11328 
11329     // Make sure we handle LabelStmts correctly.
11330     // FIXME: This does the right thing, but maybe we need a more general
11331     // fix to TreeTransform?
11332     StmtResult TransformLabelStmt(LabelStmt *S) {
11333       S->getDecl()->setStmt(nullptr);
11334       return BaseTransform::TransformLabelStmt(S);
11335     }
11336 
11337     // We need to special-case DeclRefExprs referring to FieldDecls which
11338     // are not part of a member pointer formation; normal TreeTransforming
11339     // doesn't catch this case because of the way we represent them in the AST.
11340     // FIXME: This is a bit ugly; is it really the best way to handle this
11341     // case?
11342     //
11343     // Error on DeclRefExprs referring to FieldDecls.
11344     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11345       if (isa<FieldDecl>(E->getDecl()) &&
11346           !SemaRef.isUnevaluatedContext())
11347         return SemaRef.Diag(E->getLocation(),
11348                             diag::err_invalid_non_static_member_use)
11349             << E->getDecl() << E->getSourceRange();
11350 
11351       return BaseTransform::TransformDeclRefExpr(E);
11352     }
11353 
11354     // Exception: filter out member pointer formation
11355     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11356       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11357         return E;
11358 
11359       return BaseTransform::TransformUnaryOperator(E);
11360     }
11361 
11362     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11363       // Lambdas never need to be transformed.
11364       return E;
11365     }
11366   };
11367 }
11368 
11369 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11370   assert(isUnevaluatedContext() &&
11371          "Should only transform unevaluated expressions");
11372   ExprEvalContexts.back().Context =
11373       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11374   if (isUnevaluatedContext())
11375     return E;
11376   return TransformToPE(*this).TransformExpr(E);
11377 }
11378 
11379 void
11380 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11381                                       Decl *LambdaContextDecl,
11382                                       bool IsDecltype) {
11383   ExprEvalContexts.push_back(
11384              ExpressionEvaluationContextRecord(NewContext,
11385                                                ExprCleanupObjects.size(),
11386                                                ExprNeedsCleanups,
11387                                                LambdaContextDecl,
11388                                                IsDecltype));
11389   ExprNeedsCleanups = false;
11390   if (!MaybeODRUseExprs.empty())
11391     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11392 }
11393 
11394 void
11395 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11396                                       ReuseLambdaContextDecl_t,
11397                                       bool IsDecltype) {
11398   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11399   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11400 }
11401 
11402 void Sema::PopExpressionEvaluationContext() {
11403   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11404   unsigned NumTypos = Rec.NumTypos;
11405 
11406   if (!Rec.Lambdas.empty()) {
11407     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11408       unsigned D;
11409       if (Rec.isUnevaluated()) {
11410         // C++11 [expr.prim.lambda]p2:
11411         //   A lambda-expression shall not appear in an unevaluated operand
11412         //   (Clause 5).
11413         D = diag::err_lambda_unevaluated_operand;
11414       } else {
11415         // C++1y [expr.const]p2:
11416         //   A conditional-expression e is a core constant expression unless the
11417         //   evaluation of e, following the rules of the abstract machine, would
11418         //   evaluate [...] a lambda-expression.
11419         D = diag::err_lambda_in_constant_expression;
11420       }
11421       for (const auto *L : Rec.Lambdas)
11422         Diag(L->getLocStart(), D);
11423     } else {
11424       // Mark the capture expressions odr-used. This was deferred
11425       // during lambda expression creation.
11426       for (auto *Lambda : Rec.Lambdas) {
11427         for (auto *C : Lambda->capture_inits())
11428           MarkDeclarationsReferencedInExpr(C);
11429       }
11430     }
11431   }
11432 
11433   // When are coming out of an unevaluated context, clear out any
11434   // temporaries that we may have created as part of the evaluation of
11435   // the expression in that context: they aren't relevant because they
11436   // will never be constructed.
11437   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11438     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11439                              ExprCleanupObjects.end());
11440     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11441     CleanupVarDeclMarking();
11442     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11443   // Otherwise, merge the contexts together.
11444   } else {
11445     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11446     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11447                             Rec.SavedMaybeODRUseExprs.end());
11448   }
11449 
11450   // Pop the current expression evaluation context off the stack.
11451   ExprEvalContexts.pop_back();
11452 
11453   if (!ExprEvalContexts.empty())
11454     ExprEvalContexts.back().NumTypos += NumTypos;
11455   else
11456     assert(NumTypos == 0 && "There are outstanding typos after popping the "
11457                             "last ExpressionEvaluationContextRecord");
11458 }
11459 
11460 void Sema::DiscardCleanupsInEvaluationContext() {
11461   ExprCleanupObjects.erase(
11462          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11463          ExprCleanupObjects.end());
11464   ExprNeedsCleanups = false;
11465   MaybeODRUseExprs.clear();
11466 }
11467 
11468 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11469   if (!E->getType()->isVariablyModifiedType())
11470     return E;
11471   return TransformToPotentiallyEvaluated(E);
11472 }
11473 
11474 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11475   // Do not mark anything as "used" within a dependent context; wait for
11476   // an instantiation.
11477   if (SemaRef.CurContext->isDependentContext())
11478     return false;
11479 
11480   switch (SemaRef.ExprEvalContexts.back().Context) {
11481     case Sema::Unevaluated:
11482     case Sema::UnevaluatedAbstract:
11483       // We are in an expression that is not potentially evaluated; do nothing.
11484       // (Depending on how you read the standard, we actually do need to do
11485       // something here for null pointer constants, but the standard's
11486       // definition of a null pointer constant is completely crazy.)
11487       return false;
11488 
11489     case Sema::ConstantEvaluated:
11490     case Sema::PotentiallyEvaluated:
11491       // We are in a potentially evaluated expression (or a constant-expression
11492       // in C++03); we need to do implicit template instantiation, implicitly
11493       // define class members, and mark most declarations as used.
11494       return true;
11495 
11496     case Sema::PotentiallyEvaluatedIfUsed:
11497       // Referenced declarations will only be used if the construct in the
11498       // containing expression is used.
11499       return false;
11500   }
11501   llvm_unreachable("Invalid context");
11502 }
11503 
11504 /// \brief Mark a function referenced, and check whether it is odr-used
11505 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11506 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
11507                                   bool OdrUse) {
11508   assert(Func && "No function?");
11509 
11510   Func->setReferenced();
11511 
11512   // C++11 [basic.def.odr]p3:
11513   //   A function whose name appears as a potentially-evaluated expression is
11514   //   odr-used if it is the unique lookup result or the selected member of a
11515   //   set of overloaded functions [...].
11516   //
11517   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11518   // can just check that here. Skip the rest of this function if we've already
11519   // marked the function as used.
11520   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11521     // C++11 [temp.inst]p3:
11522     //   Unless a function template specialization has been explicitly
11523     //   instantiated or explicitly specialized, the function template
11524     //   specialization is implicitly instantiated when the specialization is
11525     //   referenced in a context that requires a function definition to exist.
11526     //
11527     // We consider constexpr function templates to be referenced in a context
11528     // that requires a definition to exist whenever they are referenced.
11529     //
11530     // FIXME: This instantiates constexpr functions too frequently. If this is
11531     // really an unevaluated context (and we're not just in the definition of a
11532     // function template or overload resolution or other cases which we
11533     // incorrectly consider to be unevaluated contexts), and we're not in a
11534     // subexpression which we actually need to evaluate (for instance, a
11535     // template argument, array bound or an expression in a braced-init-list),
11536     // we are not permitted to instantiate this constexpr function definition.
11537     //
11538     // FIXME: This also implicitly defines special members too frequently. They
11539     // are only supposed to be implicitly defined if they are odr-used, but they
11540     // are not odr-used from constant expressions in unevaluated contexts.
11541     // However, they cannot be referenced if they are deleted, and they are
11542     // deleted whenever the implicit definition of the special member would
11543     // fail.
11544     if (!Func->isConstexpr() || Func->getBody())
11545       return;
11546     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11547     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11548       return;
11549   }
11550 
11551   // Note that this declaration has been used.
11552   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11553     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11554     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11555       if (Constructor->isDefaultConstructor()) {
11556         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11557           return;
11558         DefineImplicitDefaultConstructor(Loc, Constructor);
11559       } else if (Constructor->isCopyConstructor()) {
11560         DefineImplicitCopyConstructor(Loc, Constructor);
11561       } else if (Constructor->isMoveConstructor()) {
11562         DefineImplicitMoveConstructor(Loc, Constructor);
11563       }
11564     } else if (Constructor->getInheritedConstructor()) {
11565       DefineInheritingConstructor(Loc, Constructor);
11566     }
11567   } else if (CXXDestructorDecl *Destructor =
11568                  dyn_cast<CXXDestructorDecl>(Func)) {
11569     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11570     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11571       DefineImplicitDestructor(Loc, Destructor);
11572     if (Destructor->isVirtual())
11573       MarkVTableUsed(Loc, Destructor->getParent());
11574   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11575     if (MethodDecl->isOverloadedOperator() &&
11576         MethodDecl->getOverloadedOperator() == OO_Equal) {
11577       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11578       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11579         if (MethodDecl->isCopyAssignmentOperator())
11580           DefineImplicitCopyAssignment(Loc, MethodDecl);
11581         else
11582           DefineImplicitMoveAssignment(Loc, MethodDecl);
11583       }
11584     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11585                MethodDecl->getParent()->isLambda()) {
11586       CXXConversionDecl *Conversion =
11587           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11588       if (Conversion->isLambdaToBlockPointerConversion())
11589         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11590       else
11591         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11592     } else if (MethodDecl->isVirtual())
11593       MarkVTableUsed(Loc, MethodDecl->getParent());
11594   }
11595 
11596   // Recursive functions should be marked when used from another function.
11597   // FIXME: Is this really right?
11598   if (CurContext == Func) return;
11599 
11600   // Resolve the exception specification for any function which is
11601   // used: CodeGen will need it.
11602   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11603   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11604     ResolveExceptionSpec(Loc, FPT);
11605 
11606   if (!OdrUse) return;
11607 
11608   // Implicit instantiation of function templates and member functions of
11609   // class templates.
11610   if (Func->isImplicitlyInstantiable()) {
11611     bool AlreadyInstantiated = false;
11612     SourceLocation PointOfInstantiation = Loc;
11613     if (FunctionTemplateSpecializationInfo *SpecInfo
11614                               = Func->getTemplateSpecializationInfo()) {
11615       if (SpecInfo->getPointOfInstantiation().isInvalid())
11616         SpecInfo->setPointOfInstantiation(Loc);
11617       else if (SpecInfo->getTemplateSpecializationKind()
11618                  == TSK_ImplicitInstantiation) {
11619         AlreadyInstantiated = true;
11620         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11621       }
11622     } else if (MemberSpecializationInfo *MSInfo
11623                                 = Func->getMemberSpecializationInfo()) {
11624       if (MSInfo->getPointOfInstantiation().isInvalid())
11625         MSInfo->setPointOfInstantiation(Loc);
11626       else if (MSInfo->getTemplateSpecializationKind()
11627                  == TSK_ImplicitInstantiation) {
11628         AlreadyInstantiated = true;
11629         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11630       }
11631     }
11632 
11633     if (!AlreadyInstantiated || Func->isConstexpr()) {
11634       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11635           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11636           ActiveTemplateInstantiations.size())
11637         PendingLocalImplicitInstantiations.push_back(
11638             std::make_pair(Func, PointOfInstantiation));
11639       else if (Func->isConstexpr())
11640         // Do not defer instantiations of constexpr functions, to avoid the
11641         // expression evaluator needing to call back into Sema if it sees a
11642         // call to such a function.
11643         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11644       else {
11645         PendingInstantiations.push_back(std::make_pair(Func,
11646                                                        PointOfInstantiation));
11647         // Notify the consumer that a function was implicitly instantiated.
11648         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11649       }
11650     }
11651   } else {
11652     // Walk redefinitions, as some of them may be instantiable.
11653     for (auto i : Func->redecls()) {
11654       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11655         MarkFunctionReferenced(Loc, i);
11656     }
11657   }
11658 
11659   // Keep track of used but undefined functions.
11660   if (!Func->isDefined()) {
11661     if (mightHaveNonExternalLinkage(Func))
11662       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11663     else if (Func->getMostRecentDecl()->isInlined() &&
11664              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11665              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11666       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11667   }
11668 
11669   // Normally the most current decl is marked used while processing the use and
11670   // any subsequent decls are marked used by decl merging. This fails with
11671   // template instantiation since marking can happen at the end of the file
11672   // and, because of the two phase lookup, this function is called with at
11673   // decl in the middle of a decl chain. We loop to maintain the invariant
11674   // that once a decl is used, all decls after it are also used.
11675   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11676     F->markUsed(Context);
11677     if (F == Func)
11678       break;
11679   }
11680 }
11681 
11682 static void
11683 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11684                                    VarDecl *var, DeclContext *DC) {
11685   DeclContext *VarDC = var->getDeclContext();
11686 
11687   //  If the parameter still belongs to the translation unit, then
11688   //  we're actually just using one parameter in the declaration of
11689   //  the next.
11690   if (isa<ParmVarDecl>(var) &&
11691       isa<TranslationUnitDecl>(VarDC))
11692     return;
11693 
11694   // For C code, don't diagnose about capture if we're not actually in code
11695   // right now; it's impossible to write a non-constant expression outside of
11696   // function context, so we'll get other (more useful) diagnostics later.
11697   //
11698   // For C++, things get a bit more nasty... it would be nice to suppress this
11699   // diagnostic for certain cases like using a local variable in an array bound
11700   // for a member of a local class, but the correct predicate is not obvious.
11701   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11702     return;
11703 
11704   if (isa<CXXMethodDecl>(VarDC) &&
11705       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11706     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11707       << var->getIdentifier();
11708   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11709     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11710       << var->getIdentifier() << fn->getDeclName();
11711   } else if (isa<BlockDecl>(VarDC)) {
11712     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11713       << var->getIdentifier();
11714   } else {
11715     // FIXME: Is there any other context where a local variable can be
11716     // declared?
11717     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11718       << var->getIdentifier();
11719   }
11720 
11721   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11722       << var->getIdentifier();
11723 
11724   // FIXME: Add additional diagnostic info about class etc. which prevents
11725   // capture.
11726 }
11727 
11728 
11729 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11730                                       bool &SubCapturesAreNested,
11731                                       QualType &CaptureType,
11732                                       QualType &DeclRefType) {
11733    // Check whether we've already captured it.
11734   if (CSI->CaptureMap.count(Var)) {
11735     // If we found a capture, any subcaptures are nested.
11736     SubCapturesAreNested = true;
11737 
11738     // Retrieve the capture type for this variable.
11739     CaptureType = CSI->getCapture(Var).getCaptureType();
11740 
11741     // Compute the type of an expression that refers to this variable.
11742     DeclRefType = CaptureType.getNonReferenceType();
11743 
11744     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11745     if (Cap.isCopyCapture() &&
11746         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11747       DeclRefType.addConst();
11748     return true;
11749   }
11750   return false;
11751 }
11752 
11753 // Only block literals, captured statements, and lambda expressions can
11754 // capture; other scopes don't work.
11755 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11756                                  SourceLocation Loc,
11757                                  const bool Diagnose, Sema &S) {
11758   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11759     return getLambdaAwareParentOfDeclContext(DC);
11760   else {
11761     if (Diagnose)
11762        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11763   }
11764   return nullptr;
11765 }
11766 
11767 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11768 // certain types of variables (unnamed, variably modified types etc.)
11769 // so check for eligibility.
11770 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11771                                  SourceLocation Loc,
11772                                  const bool Diagnose, Sema &S) {
11773 
11774   bool IsBlock = isa<BlockScopeInfo>(CSI);
11775   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11776 
11777   // Lambdas are not allowed to capture unnamed variables
11778   // (e.g. anonymous unions).
11779   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11780   // assuming that's the intent.
11781   if (IsLambda && !Var->getDeclName()) {
11782     if (Diagnose) {
11783       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11784       S.Diag(Var->getLocation(), diag::note_declared_at);
11785     }
11786     return false;
11787   }
11788 
11789   // Prohibit variably-modified types in blocks; they're difficult to deal with.
11790   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
11791     if (Diagnose) {
11792       S.Diag(Loc, diag::err_ref_vm_type);
11793       S.Diag(Var->getLocation(), diag::note_previous_decl)
11794         << Var->getDeclName();
11795     }
11796     return false;
11797   }
11798   // Prohibit structs with flexible array members too.
11799   // We cannot capture what is in the tail end of the struct.
11800   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11801     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11802       if (Diagnose) {
11803         if (IsBlock)
11804           S.Diag(Loc, diag::err_ref_flexarray_type);
11805         else
11806           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11807             << Var->getDeclName();
11808         S.Diag(Var->getLocation(), diag::note_previous_decl)
11809           << Var->getDeclName();
11810       }
11811       return false;
11812     }
11813   }
11814   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11815   // Lambdas and captured statements are not allowed to capture __block
11816   // variables; they don't support the expected semantics.
11817   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11818     if (Diagnose) {
11819       S.Diag(Loc, diag::err_capture_block_variable)
11820         << Var->getDeclName() << !IsLambda;
11821       S.Diag(Var->getLocation(), diag::note_previous_decl)
11822         << Var->getDeclName();
11823     }
11824     return false;
11825   }
11826 
11827   return true;
11828 }
11829 
11830 // Returns true if the capture by block was successful.
11831 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11832                                  SourceLocation Loc,
11833                                  const bool BuildAndDiagnose,
11834                                  QualType &CaptureType,
11835                                  QualType &DeclRefType,
11836                                  const bool Nested,
11837                                  Sema &S) {
11838   Expr *CopyExpr = nullptr;
11839   bool ByRef = false;
11840 
11841   // Blocks are not allowed to capture arrays.
11842   if (CaptureType->isArrayType()) {
11843     if (BuildAndDiagnose) {
11844       S.Diag(Loc, diag::err_ref_array_type);
11845       S.Diag(Var->getLocation(), diag::note_previous_decl)
11846       << Var->getDeclName();
11847     }
11848     return false;
11849   }
11850 
11851   // Forbid the block-capture of autoreleasing variables.
11852   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11853     if (BuildAndDiagnose) {
11854       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11855         << /*block*/ 0;
11856       S.Diag(Var->getLocation(), diag::note_previous_decl)
11857         << Var->getDeclName();
11858     }
11859     return false;
11860   }
11861   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11862   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11863     // Block capture by reference does not change the capture or
11864     // declaration reference types.
11865     ByRef = true;
11866   } else {
11867     // Block capture by copy introduces 'const'.
11868     CaptureType = CaptureType.getNonReferenceType().withConst();
11869     DeclRefType = CaptureType;
11870 
11871     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11872       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11873         // The capture logic needs the destructor, so make sure we mark it.
11874         // Usually this is unnecessary because most local variables have
11875         // their destructors marked at declaration time, but parameters are
11876         // an exception because it's technically only the call site that
11877         // actually requires the destructor.
11878         if (isa<ParmVarDecl>(Var))
11879           S.FinalizeVarWithDestructor(Var, Record);
11880 
11881         // Enter a new evaluation context to insulate the copy
11882         // full-expression.
11883         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11884 
11885         // According to the blocks spec, the capture of a variable from
11886         // the stack requires a const copy constructor.  This is not true
11887         // of the copy/move done to move a __block variable to the heap.
11888         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11889                                                   DeclRefType.withConst(),
11890                                                   VK_LValue, Loc);
11891 
11892         ExprResult Result
11893           = S.PerformCopyInitialization(
11894               InitializedEntity::InitializeBlock(Var->getLocation(),
11895                                                   CaptureType, false),
11896               Loc, DeclRef);
11897 
11898         // Build a full-expression copy expression if initialization
11899         // succeeded and used a non-trivial constructor.  Recover from
11900         // errors by pretending that the copy isn't necessary.
11901         if (!Result.isInvalid() &&
11902             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11903                 ->isTrivial()) {
11904           Result = S.MaybeCreateExprWithCleanups(Result);
11905           CopyExpr = Result.get();
11906         }
11907       }
11908     }
11909   }
11910 
11911   // Actually capture the variable.
11912   if (BuildAndDiagnose)
11913     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11914                     SourceLocation(), CaptureType, CopyExpr);
11915 
11916   return true;
11917 
11918 }
11919 
11920 
11921 /// \brief Capture the given variable in the captured region.
11922 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11923                                     VarDecl *Var,
11924                                     SourceLocation Loc,
11925                                     const bool BuildAndDiagnose,
11926                                     QualType &CaptureType,
11927                                     QualType &DeclRefType,
11928                                     const bool RefersToEnclosingLocal,
11929                                     Sema &S) {
11930 
11931   // By default, capture variables by reference.
11932   bool ByRef = true;
11933   // Using an LValue reference type is consistent with Lambdas (see below).
11934   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11935   Expr *CopyExpr = nullptr;
11936   if (BuildAndDiagnose) {
11937     // The current implementation assumes that all variables are captured
11938     // by references. Since there is no capture by copy, no expression
11939     // evaluation will be needed.
11940     RecordDecl *RD = RSI->TheRecordDecl;
11941 
11942     FieldDecl *Field
11943       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11944                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11945                           nullptr, false, ICIS_NoInit);
11946     Field->setImplicit(true);
11947     Field->setAccess(AS_private);
11948     RD->addDecl(Field);
11949 
11950     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11951                                             DeclRefType, VK_LValue, Loc);
11952     Var->setReferenced(true);
11953     Var->markUsed(S.Context);
11954   }
11955 
11956   // Actually capture the variable.
11957   if (BuildAndDiagnose)
11958     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11959                     SourceLocation(), CaptureType, CopyExpr);
11960 
11961 
11962   return true;
11963 }
11964 
11965 /// \brief Create a field within the lambda class for the variable
11966 ///  being captured.  Handle Array captures.
11967 static ExprResult addAsFieldToClosureType(Sema &S,
11968                                  LambdaScopeInfo *LSI,
11969                                   VarDecl *Var, QualType FieldType,
11970                                   QualType DeclRefType,
11971                                   SourceLocation Loc,
11972                                   bool RefersToEnclosingLocal) {
11973   CXXRecordDecl *Lambda = LSI->Lambda;
11974 
11975   // Build the non-static data member.
11976   FieldDecl *Field
11977     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11978                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11979                         nullptr, false, ICIS_NoInit);
11980   Field->setImplicit(true);
11981   Field->setAccess(AS_private);
11982   Lambda->addDecl(Field);
11983 
11984   // C++11 [expr.prim.lambda]p21:
11985   //   When the lambda-expression is evaluated, the entities that
11986   //   are captured by copy are used to direct-initialize each
11987   //   corresponding non-static data member of the resulting closure
11988   //   object. (For array members, the array elements are
11989   //   direct-initialized in increasing subscript order.) These
11990   //   initializations are performed in the (unspecified) order in
11991   //   which the non-static data members are declared.
11992 
11993   // Introduce a new evaluation context for the initialization, so
11994   // that temporaries introduced as part of the capture are retained
11995   // to be re-"exported" from the lambda expression itself.
11996   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11997 
11998   // C++ [expr.prim.labda]p12:
11999   //   An entity captured by a lambda-expression is odr-used (3.2) in
12000   //   the scope containing the lambda-expression.
12001   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
12002                                           DeclRefType, VK_LValue, Loc);
12003   Var->setReferenced(true);
12004   Var->markUsed(S.Context);
12005 
12006   // When the field has array type, create index variables for each
12007   // dimension of the array. We use these index variables to subscript
12008   // the source array, and other clients (e.g., CodeGen) will perform
12009   // the necessary iteration with these index variables.
12010   SmallVector<VarDecl *, 4> IndexVariables;
12011   QualType BaseType = FieldType;
12012   QualType SizeType = S.Context.getSizeType();
12013   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
12014   while (const ConstantArrayType *Array
12015                         = S.Context.getAsConstantArrayType(BaseType)) {
12016     // Create the iteration variable for this array index.
12017     IdentifierInfo *IterationVarName = nullptr;
12018     {
12019       SmallString<8> Str;
12020       llvm::raw_svector_ostream OS(Str);
12021       OS << "__i" << IndexVariables.size();
12022       IterationVarName = &S.Context.Idents.get(OS.str());
12023     }
12024     VarDecl *IterationVar
12025       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
12026                         IterationVarName, SizeType,
12027                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
12028                         SC_None);
12029     IndexVariables.push_back(IterationVar);
12030     LSI->ArrayIndexVars.push_back(IterationVar);
12031 
12032     // Create a reference to the iteration variable.
12033     ExprResult IterationVarRef
12034       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
12035     assert(!IterationVarRef.isInvalid() &&
12036            "Reference to invented variable cannot fail!");
12037     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
12038     assert(!IterationVarRef.isInvalid() &&
12039            "Conversion of invented variable cannot fail!");
12040 
12041     // Subscript the array with this iteration variable.
12042     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
12043                              Ref, Loc, IterationVarRef.get(), Loc);
12044     if (Subscript.isInvalid()) {
12045       S.CleanupVarDeclMarking();
12046       S.DiscardCleanupsInEvaluationContext();
12047       return ExprError();
12048     }
12049 
12050     Ref = Subscript.get();
12051     BaseType = Array->getElementType();
12052   }
12053 
12054   // Construct the entity that we will be initializing. For an array, this
12055   // will be first element in the array, which may require several levels
12056   // of array-subscript entities.
12057   SmallVector<InitializedEntity, 4> Entities;
12058   Entities.reserve(1 + IndexVariables.size());
12059   Entities.push_back(
12060     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
12061         Field->getType(), Loc));
12062   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
12063     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
12064                                                             0,
12065                                                             Entities.back()));
12066 
12067   InitializationKind InitKind
12068     = InitializationKind::CreateDirect(Loc, Loc, Loc);
12069   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
12070   ExprResult Result(true);
12071   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
12072     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
12073 
12074   // If this initialization requires any cleanups (e.g., due to a
12075   // default argument to a copy constructor), note that for the
12076   // lambda.
12077   if (S.ExprNeedsCleanups)
12078     LSI->ExprNeedsCleanups = true;
12079 
12080   // Exit the expression evaluation context used for the capture.
12081   S.CleanupVarDeclMarking();
12082   S.DiscardCleanupsInEvaluationContext();
12083   return Result;
12084 }
12085 
12086 
12087 
12088 /// \brief Capture the given variable in the lambda.
12089 static bool captureInLambda(LambdaScopeInfo *LSI,
12090                             VarDecl *Var,
12091                             SourceLocation Loc,
12092                             const bool BuildAndDiagnose,
12093                             QualType &CaptureType,
12094                             QualType &DeclRefType,
12095                             const bool RefersToEnclosingLocal,
12096                             const Sema::TryCaptureKind Kind,
12097                             SourceLocation EllipsisLoc,
12098                             const bool IsTopScope,
12099                             Sema &S) {
12100 
12101   // Determine whether we are capturing by reference or by value.
12102   bool ByRef = false;
12103   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12104     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12105   } else {
12106     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12107   }
12108 
12109   // Compute the type of the field that will capture this variable.
12110   if (ByRef) {
12111     // C++11 [expr.prim.lambda]p15:
12112     //   An entity is captured by reference if it is implicitly or
12113     //   explicitly captured but not captured by copy. It is
12114     //   unspecified whether additional unnamed non-static data
12115     //   members are declared in the closure type for entities
12116     //   captured by reference.
12117     //
12118     // FIXME: It is not clear whether we want to build an lvalue reference
12119     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12120     // to do the former, while EDG does the latter. Core issue 1249 will
12121     // clarify, but for now we follow GCC because it's a more permissive and
12122     // easily defensible position.
12123     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12124   } else {
12125     // C++11 [expr.prim.lambda]p14:
12126     //   For each entity captured by copy, an unnamed non-static
12127     //   data member is declared in the closure type. The
12128     //   declaration order of these members is unspecified. The type
12129     //   of such a data member is the type of the corresponding
12130     //   captured entity if the entity is not a reference to an
12131     //   object, or the referenced type otherwise. [Note: If the
12132     //   captured entity is a reference to a function, the
12133     //   corresponding data member is also a reference to a
12134     //   function. - end note ]
12135     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12136       if (!RefType->getPointeeType()->isFunctionType())
12137         CaptureType = RefType->getPointeeType();
12138     }
12139 
12140     // Forbid the lambda copy-capture of autoreleasing variables.
12141     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12142       if (BuildAndDiagnose) {
12143         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12144         S.Diag(Var->getLocation(), diag::note_previous_decl)
12145           << Var->getDeclName();
12146       }
12147       return false;
12148     }
12149 
12150     // Make sure that by-copy captures are of a complete and non-abstract type.
12151     if (BuildAndDiagnose) {
12152       if (!CaptureType->isDependentType() &&
12153           S.RequireCompleteType(Loc, CaptureType,
12154                                 diag::err_capture_of_incomplete_type,
12155                                 Var->getDeclName()))
12156         return false;
12157 
12158       if (S.RequireNonAbstractType(Loc, CaptureType,
12159                                    diag::err_capture_of_abstract_type))
12160         return false;
12161     }
12162   }
12163 
12164   // Capture this variable in the lambda.
12165   Expr *CopyExpr = nullptr;
12166   if (BuildAndDiagnose) {
12167     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12168                                         CaptureType, DeclRefType, Loc,
12169                                         RefersToEnclosingLocal);
12170     if (!Result.isInvalid())
12171       CopyExpr = Result.get();
12172   }
12173 
12174   // Compute the type of a reference to this captured variable.
12175   if (ByRef)
12176     DeclRefType = CaptureType.getNonReferenceType();
12177   else {
12178     // C++ [expr.prim.lambda]p5:
12179     //   The closure type for a lambda-expression has a public inline
12180     //   function call operator [...]. This function call operator is
12181     //   declared const (9.3.1) if and only if the lambda-expression’s
12182     //   parameter-declaration-clause is not followed by mutable.
12183     DeclRefType = CaptureType.getNonReferenceType();
12184     if (!LSI->Mutable && !CaptureType->isReferenceType())
12185       DeclRefType.addConst();
12186   }
12187 
12188   // Add the capture.
12189   if (BuildAndDiagnose)
12190     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12191                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12192 
12193   return true;
12194 }
12195 
12196 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12197                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12198                               bool BuildAndDiagnose,
12199                               QualType &CaptureType,
12200                               QualType &DeclRefType,
12201 						                const unsigned *const FunctionScopeIndexToStopAt) {
12202   bool Nested = false;
12203 
12204   DeclContext *DC = CurContext;
12205   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12206       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12207   // We need to sync up the Declaration Context with the
12208   // FunctionScopeIndexToStopAt
12209   if (FunctionScopeIndexToStopAt) {
12210     unsigned FSIndex = FunctionScopes.size() - 1;
12211     while (FSIndex != MaxFunctionScopesIndex) {
12212       DC = getLambdaAwareParentOfDeclContext(DC);
12213       --FSIndex;
12214     }
12215   }
12216 
12217 
12218   // If the variable is declared in the current context (and is not an
12219   // init-capture), there is no need to capture it.
12220   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12221   if (!Var->hasLocalStorage()) return true;
12222 
12223   // Walk up the stack to determine whether we can capture the variable,
12224   // performing the "simple" checks that don't depend on type. We stop when
12225   // we've either hit the declared scope of the variable or find an existing
12226   // capture of that variable.  We start from the innermost capturing-entity
12227   // (the DC) and ensure that all intervening capturing-entities
12228   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12229   // declcontext can either capture the variable or have already captured
12230   // the variable.
12231   CaptureType = Var->getType();
12232   DeclRefType = CaptureType.getNonReferenceType();
12233   bool Explicit = (Kind != TryCapture_Implicit);
12234   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12235   do {
12236     // Only block literals, captured statements, and lambda expressions can
12237     // capture; other scopes don't work.
12238     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12239                                                               ExprLoc,
12240                                                               BuildAndDiagnose,
12241                                                               *this);
12242     if (!ParentDC) return true;
12243 
12244     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12245     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12246 
12247 
12248     // Check whether we've already captured it.
12249     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12250                                              DeclRefType))
12251       break;
12252     // If we are instantiating a generic lambda call operator body,
12253     // we do not want to capture new variables.  What was captured
12254     // during either a lambdas transformation or initial parsing
12255     // should be used.
12256     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12257       if (BuildAndDiagnose) {
12258         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12259         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12260           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12261           Diag(Var->getLocation(), diag::note_previous_decl)
12262              << Var->getDeclName();
12263           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12264         } else
12265           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12266       }
12267       return true;
12268     }
12269     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12270     // certain types of variables (unnamed, variably modified types etc.)
12271     // so check for eligibility.
12272     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12273        return true;
12274 
12275     // Try to capture variable-length arrays types.
12276     if (Var->getType()->isVariablyModifiedType()) {
12277       // We're going to walk down into the type and look for VLA
12278       // expressions.
12279       QualType QTy = Var->getType();
12280       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12281         QTy = PVD->getOriginalType();
12282       do {
12283         const Type *Ty = QTy.getTypePtr();
12284         switch (Ty->getTypeClass()) {
12285 #define TYPE(Class, Base)
12286 #define ABSTRACT_TYPE(Class, Base)
12287 #define NON_CANONICAL_TYPE(Class, Base)
12288 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12289 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12290 #include "clang/AST/TypeNodes.def"
12291           QTy = QualType();
12292           break;
12293         // These types are never variably-modified.
12294         case Type::Builtin:
12295         case Type::Complex:
12296         case Type::Vector:
12297         case Type::ExtVector:
12298         case Type::Record:
12299         case Type::Enum:
12300         case Type::Elaborated:
12301         case Type::TemplateSpecialization:
12302         case Type::ObjCObject:
12303         case Type::ObjCInterface:
12304         case Type::ObjCObjectPointer:
12305           llvm_unreachable("type class is never variably-modified!");
12306         case Type::Adjusted:
12307           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12308           break;
12309         case Type::Decayed:
12310           QTy = cast<DecayedType>(Ty)->getPointeeType();
12311           break;
12312         case Type::Pointer:
12313           QTy = cast<PointerType>(Ty)->getPointeeType();
12314           break;
12315         case Type::BlockPointer:
12316           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12317           break;
12318         case Type::LValueReference:
12319         case Type::RValueReference:
12320           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12321           break;
12322         case Type::MemberPointer:
12323           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12324           break;
12325         case Type::ConstantArray:
12326         case Type::IncompleteArray:
12327           // Losing element qualification here is fine.
12328           QTy = cast<ArrayType>(Ty)->getElementType();
12329           break;
12330         case Type::VariableArray: {
12331           // Losing element qualification here is fine.
12332           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
12333 
12334           // Unknown size indication requires no size computation.
12335           // Otherwise, evaluate and record it.
12336           if (auto Size = VAT->getSizeExpr()) {
12337             if (!CSI->isVLATypeCaptured(VAT)) {
12338               RecordDecl *CapRecord = nullptr;
12339               if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12340                 CapRecord = LSI->Lambda;
12341               } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12342                 CapRecord = CRSI->TheRecordDecl;
12343               }
12344               if (CapRecord) {
12345                 auto ExprLoc = Size->getExprLoc();
12346                 auto SizeType = Context.getSizeType();
12347                 // Build the non-static data member.
12348                 auto Field = FieldDecl::Create(
12349                     Context, CapRecord, ExprLoc, ExprLoc,
12350                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12351                     /*BW*/ nullptr, /*Mutable*/ false,
12352                     /*InitStyle*/ ICIS_NoInit);
12353                 Field->setImplicit(true);
12354                 Field->setAccess(AS_private);
12355                 Field->setCapturedVLAType(VAT);
12356                 CapRecord->addDecl(Field);
12357 
12358                 CSI->addVLATypeCapture(ExprLoc, SizeType);
12359               }
12360             }
12361           }
12362           QTy = VAT->getElementType();
12363           break;
12364         }
12365         case Type::FunctionProto:
12366         case Type::FunctionNoProto:
12367           QTy = cast<FunctionType>(Ty)->getReturnType();
12368           break;
12369         case Type::Paren:
12370         case Type::TypeOf:
12371         case Type::UnaryTransform:
12372         case Type::Attributed:
12373         case Type::SubstTemplateTypeParm:
12374         case Type::PackExpansion:
12375           // Keep walking after single level desugaring.
12376           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12377           break;
12378         case Type::Typedef:
12379           QTy = cast<TypedefType>(Ty)->desugar();
12380           break;
12381         case Type::Decltype:
12382           QTy = cast<DecltypeType>(Ty)->desugar();
12383           break;
12384         case Type::Auto:
12385           QTy = cast<AutoType>(Ty)->getDeducedType();
12386           break;
12387         case Type::TypeOfExpr:
12388           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12389           break;
12390         case Type::Atomic:
12391           QTy = cast<AtomicType>(Ty)->getValueType();
12392           break;
12393         }
12394       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12395     }
12396 
12397     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12398       // No capture-default, and this is not an explicit capture
12399       // so cannot capture this variable.
12400       if (BuildAndDiagnose) {
12401         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12402         Diag(Var->getLocation(), diag::note_previous_decl)
12403           << Var->getDeclName();
12404         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12405              diag::note_lambda_decl);
12406         // FIXME: If we error out because an outer lambda can not implicitly
12407         // capture a variable that an inner lambda explicitly captures, we
12408         // should have the inner lambda do the explicit capture - because
12409         // it makes for cleaner diagnostics later.  This would purely be done
12410         // so that the diagnostic does not misleadingly claim that a variable
12411         // can not be captured by a lambda implicitly even though it is captured
12412         // explicitly.  Suggestion:
12413         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12414         //    at the function head
12415         //  - cache the StartingDeclContext - this must be a lambda
12416         //  - captureInLambda in the innermost lambda the variable.
12417       }
12418       return true;
12419     }
12420 
12421     FunctionScopesIndex--;
12422     DC = ParentDC;
12423     Explicit = false;
12424   } while (!Var->getDeclContext()->Equals(DC));
12425 
12426   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12427   // computing the type of the capture at each step, checking type-specific
12428   // requirements, and adding captures if requested.
12429   // If the variable had already been captured previously, we start capturing
12430   // at the lambda nested within that one.
12431   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12432        ++I) {
12433     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12434 
12435     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12436       if (!captureInBlock(BSI, Var, ExprLoc,
12437                           BuildAndDiagnose, CaptureType,
12438                           DeclRefType, Nested, *this))
12439         return true;
12440       Nested = true;
12441     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12442       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12443                                    BuildAndDiagnose, CaptureType,
12444                                    DeclRefType, Nested, *this))
12445         return true;
12446       Nested = true;
12447     } else {
12448       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12449       if (!captureInLambda(LSI, Var, ExprLoc,
12450                            BuildAndDiagnose, CaptureType,
12451                            DeclRefType, Nested, Kind, EllipsisLoc,
12452                             /*IsTopScope*/I == N - 1, *this))
12453         return true;
12454       Nested = true;
12455     }
12456   }
12457   return false;
12458 }
12459 
12460 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12461                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12462   QualType CaptureType;
12463   QualType DeclRefType;
12464   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12465                             /*BuildAndDiagnose=*/true, CaptureType,
12466                             DeclRefType, nullptr);
12467 }
12468 
12469 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12470   QualType CaptureType;
12471   QualType DeclRefType;
12472 
12473   // Determine whether we can capture this variable.
12474   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12475                          /*BuildAndDiagnose=*/false, CaptureType,
12476                          DeclRefType, nullptr))
12477     return QualType();
12478 
12479   return DeclRefType;
12480 }
12481 
12482 
12483 
12484 // If either the type of the variable or the initializer is dependent,
12485 // return false. Otherwise, determine whether the variable is a constant
12486 // expression. Use this if you need to know if a variable that might or
12487 // might not be dependent is truly a constant expression.
12488 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12489     ASTContext &Context) {
12490 
12491   if (Var->getType()->isDependentType())
12492     return false;
12493   const VarDecl *DefVD = nullptr;
12494   Var->getAnyInitializer(DefVD);
12495   if (!DefVD)
12496     return false;
12497   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12498   Expr *Init = cast<Expr>(Eval->Value);
12499   if (Init->isValueDependent())
12500     return false;
12501   return IsVariableAConstantExpression(Var, Context);
12502 }
12503 
12504 
12505 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12506   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12507   // an object that satisfies the requirements for appearing in a
12508   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12509   // is immediately applied."  This function handles the lvalue-to-rvalue
12510   // conversion part.
12511   MaybeODRUseExprs.erase(E->IgnoreParens());
12512 
12513   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12514   // to a variable that is a constant expression, and if so, identify it as
12515   // a reference to a variable that does not involve an odr-use of that
12516   // variable.
12517   if (LambdaScopeInfo *LSI = getCurLambda()) {
12518     Expr *SansParensExpr = E->IgnoreParens();
12519     VarDecl *Var = nullptr;
12520     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12521       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12522     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12523       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12524 
12525     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12526       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12527   }
12528 }
12529 
12530 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12531   Res = CorrectDelayedTyposInExpr(Res);
12532 
12533   if (!Res.isUsable())
12534     return Res;
12535 
12536   // If a constant-expression is a reference to a variable where we delay
12537   // deciding whether it is an odr-use, just assume we will apply the
12538   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12539   // (a non-type template argument), we have special handling anyway.
12540   UpdateMarkingForLValueToRValue(Res.get());
12541   return Res;
12542 }
12543 
12544 void Sema::CleanupVarDeclMarking() {
12545   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12546                                         e = MaybeODRUseExprs.end();
12547        i != e; ++i) {
12548     VarDecl *Var;
12549     SourceLocation Loc;
12550     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12551       Var = cast<VarDecl>(DRE->getDecl());
12552       Loc = DRE->getLocation();
12553     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12554       Var = cast<VarDecl>(ME->getMemberDecl());
12555       Loc = ME->getMemberLoc();
12556     } else {
12557       llvm_unreachable("Unexpected expression");
12558     }
12559 
12560     MarkVarDeclODRUsed(Var, Loc, *this,
12561                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12562   }
12563 
12564   MaybeODRUseExprs.clear();
12565 }
12566 
12567 
12568 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12569                                     VarDecl *Var, Expr *E) {
12570   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12571          "Invalid Expr argument to DoMarkVarDeclReferenced");
12572   Var->setReferenced();
12573 
12574   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12575   bool MarkODRUsed = true;
12576 
12577   // If the context is not potentially evaluated, this is not an odr-use and
12578   // does not trigger instantiation.
12579   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12580     if (SemaRef.isUnevaluatedContext())
12581       return;
12582 
12583     // If we don't yet know whether this context is going to end up being an
12584     // evaluated context, and we're referencing a variable from an enclosing
12585     // scope, add a potential capture.
12586     //
12587     // FIXME: Is this necessary? These contexts are only used for default
12588     // arguments, where local variables can't be used.
12589     const bool RefersToEnclosingScope =
12590         (SemaRef.CurContext != Var->getDeclContext() &&
12591          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
12592     if (RefersToEnclosingScope) {
12593       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12594         // If a variable could potentially be odr-used, defer marking it so
12595         // until we finish analyzing the full expression for any
12596         // lvalue-to-rvalue
12597         // or discarded value conversions that would obviate odr-use.
12598         // Add it to the list of potential captures that will be analyzed
12599         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12600         // unless the variable is a reference that was initialized by a constant
12601         // expression (this will never need to be captured or odr-used).
12602         assert(E && "Capture variable should be used in an expression.");
12603         if (!Var->getType()->isReferenceType() ||
12604             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12605           LSI->addPotentialCapture(E->IgnoreParens());
12606       }
12607     }
12608 
12609     if (!isTemplateInstantiation(TSK))
12610     	return;
12611 
12612     // Instantiate, but do not mark as odr-used, variable templates.
12613     MarkODRUsed = false;
12614   }
12615 
12616   VarTemplateSpecializationDecl *VarSpec =
12617       dyn_cast<VarTemplateSpecializationDecl>(Var);
12618   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12619          "Can't instantiate a partial template specialization.");
12620 
12621   // Perform implicit instantiation of static data members, static data member
12622   // templates of class templates, and variable template specializations. Delay
12623   // instantiations of variable templates, except for those that could be used
12624   // in a constant expression.
12625   if (isTemplateInstantiation(TSK)) {
12626     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12627 
12628     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12629       if (Var->getPointOfInstantiation().isInvalid()) {
12630         // This is a modification of an existing AST node. Notify listeners.
12631         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12632           L->StaticDataMemberInstantiated(Var);
12633       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12634         // Don't bother trying to instantiate it again, unless we might need
12635         // its initializer before we get to the end of the TU.
12636         TryInstantiating = false;
12637     }
12638 
12639     if (Var->getPointOfInstantiation().isInvalid())
12640       Var->setTemplateSpecializationKind(TSK, Loc);
12641 
12642     if (TryInstantiating) {
12643       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12644       bool InstantiationDependent = false;
12645       bool IsNonDependent =
12646           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12647                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12648                   : true;
12649 
12650       // Do not instantiate specializations that are still type-dependent.
12651       if (IsNonDependent) {
12652         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12653           // Do not defer instantiations of variables which could be used in a
12654           // constant expression.
12655           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12656         } else {
12657           SemaRef.PendingInstantiations
12658               .push_back(std::make_pair(Var, PointOfInstantiation));
12659         }
12660       }
12661     }
12662   }
12663 
12664   if(!MarkODRUsed) return;
12665 
12666   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12667   // the requirements for appearing in a constant expression (5.19) and, if
12668   // it is an object, the lvalue-to-rvalue conversion (4.1)
12669   // is immediately applied."  We check the first part here, and
12670   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12671   // Note that we use the C++11 definition everywhere because nothing in
12672   // C++03 depends on whether we get the C++03 version correct. The second
12673   // part does not apply to references, since they are not objects.
12674   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12675     // A reference initialized by a constant expression can never be
12676     // odr-used, so simply ignore it.
12677     if (!Var->getType()->isReferenceType())
12678       SemaRef.MaybeODRUseExprs.insert(E);
12679   } else
12680     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12681                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12682 }
12683 
12684 /// \brief Mark a variable referenced, and check whether it is odr-used
12685 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12686 /// used directly for normal expressions referring to VarDecl.
12687 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12688   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12689 }
12690 
12691 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12692                                Decl *D, Expr *E, bool OdrUse) {
12693   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12694     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12695     return;
12696   }
12697 
12698   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12699 
12700   // If this is a call to a method via a cast, also mark the method in the
12701   // derived class used in case codegen can devirtualize the call.
12702   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12703   if (!ME)
12704     return;
12705   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12706   if (!MD)
12707     return;
12708   // Only attempt to devirtualize if this is truly a virtual call.
12709   bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
12710   if (!IsVirtualCall)
12711     return;
12712   const Expr *Base = ME->getBase();
12713   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12714   if (!MostDerivedClassDecl)
12715     return;
12716   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12717   if (!DM || DM->isPure())
12718     return;
12719   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12720 }
12721 
12722 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12723 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12724   // TODO: update this with DR# once a defect report is filed.
12725   // C++11 defect. The address of a pure member should not be an ODR use, even
12726   // if it's a qualified reference.
12727   bool OdrUse = true;
12728   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12729     if (Method->isVirtual())
12730       OdrUse = false;
12731   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12732 }
12733 
12734 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12735 void Sema::MarkMemberReferenced(MemberExpr *E) {
12736   // C++11 [basic.def.odr]p2:
12737   //   A non-overloaded function whose name appears as a potentially-evaluated
12738   //   expression or a member of a set of candidate functions, if selected by
12739   //   overload resolution when referred to from a potentially-evaluated
12740   //   expression, is odr-used, unless it is a pure virtual function and its
12741   //   name is not explicitly qualified.
12742   bool OdrUse = true;
12743   if (!E->hasQualifier()) {
12744     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12745       if (Method->isPure())
12746         OdrUse = false;
12747   }
12748   SourceLocation Loc = E->getMemberLoc().isValid() ?
12749                             E->getMemberLoc() : E->getLocStart();
12750   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12751 }
12752 
12753 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12754 /// marks the declaration referenced, and performs odr-use checking for
12755 /// functions and variables. This method should not be used when building a
12756 /// normal expression which refers to a variable.
12757 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12758   if (OdrUse) {
12759     if (auto *VD = dyn_cast<VarDecl>(D)) {
12760       MarkVariableReferenced(Loc, VD);
12761       return;
12762     }
12763   }
12764   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
12765     MarkFunctionReferenced(Loc, FD, OdrUse);
12766     return;
12767   }
12768   D->setReferenced();
12769 }
12770 
12771 namespace {
12772   // Mark all of the declarations referenced
12773   // FIXME: Not fully implemented yet! We need to have a better understanding
12774   // of when we're entering
12775   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12776     Sema &S;
12777     SourceLocation Loc;
12778 
12779   public:
12780     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12781 
12782     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12783 
12784     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12785     bool TraverseRecordType(RecordType *T);
12786   };
12787 }
12788 
12789 bool MarkReferencedDecls::TraverseTemplateArgument(
12790     const TemplateArgument &Arg) {
12791   if (Arg.getKind() == TemplateArgument::Declaration) {
12792     if (Decl *D = Arg.getAsDecl())
12793       S.MarkAnyDeclReferenced(Loc, D, true);
12794   }
12795 
12796   return Inherited::TraverseTemplateArgument(Arg);
12797 }
12798 
12799 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12800   if (ClassTemplateSpecializationDecl *Spec
12801                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12802     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12803     return TraverseTemplateArguments(Args.data(), Args.size());
12804   }
12805 
12806   return true;
12807 }
12808 
12809 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12810   MarkReferencedDecls Marker(*this, Loc);
12811   Marker.TraverseType(Context.getCanonicalType(T));
12812 }
12813 
12814 namespace {
12815   /// \brief Helper class that marks all of the declarations referenced by
12816   /// potentially-evaluated subexpressions as "referenced".
12817   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12818     Sema &S;
12819     bool SkipLocalVariables;
12820 
12821   public:
12822     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12823 
12824     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12825       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12826 
12827     void VisitDeclRefExpr(DeclRefExpr *E) {
12828       // If we were asked not to visit local variables, don't.
12829       if (SkipLocalVariables) {
12830         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12831           if (VD->hasLocalStorage())
12832             return;
12833       }
12834 
12835       S.MarkDeclRefReferenced(E);
12836     }
12837 
12838     void VisitMemberExpr(MemberExpr *E) {
12839       S.MarkMemberReferenced(E);
12840       Inherited::VisitMemberExpr(E);
12841     }
12842 
12843     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12844       S.MarkFunctionReferenced(E->getLocStart(),
12845             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12846       Visit(E->getSubExpr());
12847     }
12848 
12849     void VisitCXXNewExpr(CXXNewExpr *E) {
12850       if (E->getOperatorNew())
12851         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12852       if (E->getOperatorDelete())
12853         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12854       Inherited::VisitCXXNewExpr(E);
12855     }
12856 
12857     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12858       if (E->getOperatorDelete())
12859         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12860       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12861       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12862         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12863         S.MarkFunctionReferenced(E->getLocStart(),
12864                                     S.LookupDestructor(Record));
12865       }
12866 
12867       Inherited::VisitCXXDeleteExpr(E);
12868     }
12869 
12870     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12871       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12872       Inherited::VisitCXXConstructExpr(E);
12873     }
12874 
12875     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12876       Visit(E->getExpr());
12877     }
12878 
12879     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12880       Inherited::VisitImplicitCastExpr(E);
12881 
12882       if (E->getCastKind() == CK_LValueToRValue)
12883         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12884     }
12885   };
12886 }
12887 
12888 /// \brief Mark any declarations that appear within this expression or any
12889 /// potentially-evaluated subexpressions as "referenced".
12890 ///
12891 /// \param SkipLocalVariables If true, don't mark local variables as
12892 /// 'referenced'.
12893 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12894                                             bool SkipLocalVariables) {
12895   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12896 }
12897 
12898 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12899 /// of the program being compiled.
12900 ///
12901 /// This routine emits the given diagnostic when the code currently being
12902 /// type-checked is "potentially evaluated", meaning that there is a
12903 /// possibility that the code will actually be executable. Code in sizeof()
12904 /// expressions, code used only during overload resolution, etc., are not
12905 /// potentially evaluated. This routine will suppress such diagnostics or,
12906 /// in the absolutely nutty case of potentially potentially evaluated
12907 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12908 /// later.
12909 ///
12910 /// This routine should be used for all diagnostics that describe the run-time
12911 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12912 /// Failure to do so will likely result in spurious diagnostics or failures
12913 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12914 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12915                                const PartialDiagnostic &PD) {
12916   switch (ExprEvalContexts.back().Context) {
12917   case Unevaluated:
12918   case UnevaluatedAbstract:
12919     // The argument will never be evaluated, so don't complain.
12920     break;
12921 
12922   case ConstantEvaluated:
12923     // Relevant diagnostics should be produced by constant evaluation.
12924     break;
12925 
12926   case PotentiallyEvaluated:
12927   case PotentiallyEvaluatedIfUsed:
12928     if (Statement && getCurFunctionOrMethodDecl()) {
12929       FunctionScopes.back()->PossiblyUnreachableDiags.
12930         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12931     }
12932     else
12933       Diag(Loc, PD);
12934 
12935     return true;
12936   }
12937 
12938   return false;
12939 }
12940 
12941 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12942                                CallExpr *CE, FunctionDecl *FD) {
12943   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12944     return false;
12945 
12946   // If we're inside a decltype's expression, don't check for a valid return
12947   // type or construct temporaries until we know whether this is the last call.
12948   if (ExprEvalContexts.back().IsDecltype) {
12949     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12950     return false;
12951   }
12952 
12953   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12954     FunctionDecl *FD;
12955     CallExpr *CE;
12956 
12957   public:
12958     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12959       : FD(FD), CE(CE) { }
12960 
12961     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12962       if (!FD) {
12963         S.Diag(Loc, diag::err_call_incomplete_return)
12964           << T << CE->getSourceRange();
12965         return;
12966       }
12967 
12968       S.Diag(Loc, diag::err_call_function_incomplete_return)
12969         << CE->getSourceRange() << FD->getDeclName() << T;
12970       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12971           << FD->getDeclName();
12972     }
12973   } Diagnoser(FD, CE);
12974 
12975   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12976     return true;
12977 
12978   return false;
12979 }
12980 
12981 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12982 // will prevent this condition from triggering, which is what we want.
12983 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12984   SourceLocation Loc;
12985 
12986   unsigned diagnostic = diag::warn_condition_is_assignment;
12987   bool IsOrAssign = false;
12988 
12989   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12990     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12991       return;
12992 
12993     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12994 
12995     // Greylist some idioms by putting them into a warning subcategory.
12996     if (ObjCMessageExpr *ME
12997           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12998       Selector Sel = ME->getSelector();
12999 
13000       // self = [<foo> init...]
13001       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13002         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13003 
13004       // <foo> = [<bar> nextObject]
13005       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13006         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13007     }
13008 
13009     Loc = Op->getOperatorLoc();
13010   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13011     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13012       return;
13013 
13014     IsOrAssign = Op->getOperator() == OO_PipeEqual;
13015     Loc = Op->getOperatorLoc();
13016   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13017     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13018   else {
13019     // Not an assignment.
13020     return;
13021   }
13022 
13023   Diag(Loc, diagnostic) << E->getSourceRange();
13024 
13025   SourceLocation Open = E->getLocStart();
13026   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
13027   Diag(Loc, diag::note_condition_assign_silence)
13028         << FixItHint::CreateInsertion(Open, "(")
13029         << FixItHint::CreateInsertion(Close, ")");
13030 
13031   if (IsOrAssign)
13032     Diag(Loc, diag::note_condition_or_assign_to_comparison)
13033       << FixItHint::CreateReplacement(Loc, "!=");
13034   else
13035     Diag(Loc, diag::note_condition_assign_to_comparison)
13036       << FixItHint::CreateReplacement(Loc, "==");
13037 }
13038 
13039 /// \brief Redundant parentheses over an equality comparison can indicate
13040 /// that the user intended an assignment used as condition.
13041 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13042   // Don't warn if the parens came from a macro.
13043   SourceLocation parenLoc = ParenE->getLocStart();
13044   if (parenLoc.isInvalid() || parenLoc.isMacroID())
13045     return;
13046   // Don't warn for dependent expressions.
13047   if (ParenE->isTypeDependent())
13048     return;
13049 
13050   Expr *E = ParenE->IgnoreParens();
13051 
13052   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13053     if (opE->getOpcode() == BO_EQ &&
13054         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13055                                                            == Expr::MLV_Valid) {
13056       SourceLocation Loc = opE->getOperatorLoc();
13057 
13058       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13059       SourceRange ParenERange = ParenE->getSourceRange();
13060       Diag(Loc, diag::note_equality_comparison_silence)
13061         << FixItHint::CreateRemoval(ParenERange.getBegin())
13062         << FixItHint::CreateRemoval(ParenERange.getEnd());
13063       Diag(Loc, diag::note_equality_comparison_to_assign)
13064         << FixItHint::CreateReplacement(Loc, "=");
13065     }
13066 }
13067 
13068 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13069   DiagnoseAssignmentAsCondition(E);
13070   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13071     DiagnoseEqualityWithExtraParens(parenE);
13072 
13073   ExprResult result = CheckPlaceholderExpr(E);
13074   if (result.isInvalid()) return ExprError();
13075   E = result.get();
13076 
13077   if (!E->isTypeDependent()) {
13078     if (getLangOpts().CPlusPlus)
13079       return CheckCXXBooleanCondition(E); // C++ 6.4p4
13080 
13081     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13082     if (ERes.isInvalid())
13083       return ExprError();
13084     E = ERes.get();
13085 
13086     QualType T = E->getType();
13087     if (!T->isScalarType()) { // C99 6.8.4.1p1
13088       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13089         << T << E->getSourceRange();
13090       return ExprError();
13091     }
13092     CheckBoolLikeConversion(E, Loc);
13093   }
13094 
13095   return E;
13096 }
13097 
13098 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
13099                                        Expr *SubExpr) {
13100   if (!SubExpr)
13101     return ExprError();
13102 
13103   return CheckBooleanCondition(SubExpr, Loc);
13104 }
13105 
13106 namespace {
13107   /// A visitor for rebuilding a call to an __unknown_any expression
13108   /// to have an appropriate type.
13109   struct RebuildUnknownAnyFunction
13110     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13111 
13112     Sema &S;
13113 
13114     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13115 
13116     ExprResult VisitStmt(Stmt *S) {
13117       llvm_unreachable("unexpected statement!");
13118     }
13119 
13120     ExprResult VisitExpr(Expr *E) {
13121       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13122         << E->getSourceRange();
13123       return ExprError();
13124     }
13125 
13126     /// Rebuild an expression which simply semantically wraps another
13127     /// expression which it shares the type and value kind of.
13128     template <class T> ExprResult rebuildSugarExpr(T *E) {
13129       ExprResult SubResult = Visit(E->getSubExpr());
13130       if (SubResult.isInvalid()) return ExprError();
13131 
13132       Expr *SubExpr = SubResult.get();
13133       E->setSubExpr(SubExpr);
13134       E->setType(SubExpr->getType());
13135       E->setValueKind(SubExpr->getValueKind());
13136       assert(E->getObjectKind() == OK_Ordinary);
13137       return E;
13138     }
13139 
13140     ExprResult VisitParenExpr(ParenExpr *E) {
13141       return rebuildSugarExpr(E);
13142     }
13143 
13144     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13145       return rebuildSugarExpr(E);
13146     }
13147 
13148     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13149       ExprResult SubResult = Visit(E->getSubExpr());
13150       if (SubResult.isInvalid()) return ExprError();
13151 
13152       Expr *SubExpr = SubResult.get();
13153       E->setSubExpr(SubExpr);
13154       E->setType(S.Context.getPointerType(SubExpr->getType()));
13155       assert(E->getValueKind() == VK_RValue);
13156       assert(E->getObjectKind() == OK_Ordinary);
13157       return E;
13158     }
13159 
13160     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13161       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13162 
13163       E->setType(VD->getType());
13164 
13165       assert(E->getValueKind() == VK_RValue);
13166       if (S.getLangOpts().CPlusPlus &&
13167           !(isa<CXXMethodDecl>(VD) &&
13168             cast<CXXMethodDecl>(VD)->isInstance()))
13169         E->setValueKind(VK_LValue);
13170 
13171       return E;
13172     }
13173 
13174     ExprResult VisitMemberExpr(MemberExpr *E) {
13175       return resolveDecl(E, E->getMemberDecl());
13176     }
13177 
13178     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13179       return resolveDecl(E, E->getDecl());
13180     }
13181   };
13182 }
13183 
13184 /// Given a function expression of unknown-any type, try to rebuild it
13185 /// to have a function type.
13186 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13187   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13188   if (Result.isInvalid()) return ExprError();
13189   return S.DefaultFunctionArrayConversion(Result.get());
13190 }
13191 
13192 namespace {
13193   /// A visitor for rebuilding an expression of type __unknown_anytype
13194   /// into one which resolves the type directly on the referring
13195   /// expression.  Strict preservation of the original source
13196   /// structure is not a goal.
13197   struct RebuildUnknownAnyExpr
13198     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13199 
13200     Sema &S;
13201 
13202     /// The current destination type.
13203     QualType DestType;
13204 
13205     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13206       : S(S), DestType(CastType) {}
13207 
13208     ExprResult VisitStmt(Stmt *S) {
13209       llvm_unreachable("unexpected statement!");
13210     }
13211 
13212     ExprResult VisitExpr(Expr *E) {
13213       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13214         << E->getSourceRange();
13215       return ExprError();
13216     }
13217 
13218     ExprResult VisitCallExpr(CallExpr *E);
13219     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13220 
13221     /// Rebuild an expression which simply semantically wraps another
13222     /// expression which it shares the type and value kind of.
13223     template <class T> ExprResult rebuildSugarExpr(T *E) {
13224       ExprResult SubResult = Visit(E->getSubExpr());
13225       if (SubResult.isInvalid()) return ExprError();
13226       Expr *SubExpr = SubResult.get();
13227       E->setSubExpr(SubExpr);
13228       E->setType(SubExpr->getType());
13229       E->setValueKind(SubExpr->getValueKind());
13230       assert(E->getObjectKind() == OK_Ordinary);
13231       return E;
13232     }
13233 
13234     ExprResult VisitParenExpr(ParenExpr *E) {
13235       return rebuildSugarExpr(E);
13236     }
13237 
13238     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13239       return rebuildSugarExpr(E);
13240     }
13241 
13242     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13243       const PointerType *Ptr = DestType->getAs<PointerType>();
13244       if (!Ptr) {
13245         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13246           << E->getSourceRange();
13247         return ExprError();
13248       }
13249       assert(E->getValueKind() == VK_RValue);
13250       assert(E->getObjectKind() == OK_Ordinary);
13251       E->setType(DestType);
13252 
13253       // Build the sub-expression as if it were an object of the pointee type.
13254       DestType = Ptr->getPointeeType();
13255       ExprResult SubResult = Visit(E->getSubExpr());
13256       if (SubResult.isInvalid()) return ExprError();
13257       E->setSubExpr(SubResult.get());
13258       return E;
13259     }
13260 
13261     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13262 
13263     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13264 
13265     ExprResult VisitMemberExpr(MemberExpr *E) {
13266       return resolveDecl(E, E->getMemberDecl());
13267     }
13268 
13269     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13270       return resolveDecl(E, E->getDecl());
13271     }
13272   };
13273 }
13274 
13275 /// Rebuilds a call expression which yielded __unknown_anytype.
13276 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13277   Expr *CalleeExpr = E->getCallee();
13278 
13279   enum FnKind {
13280     FK_MemberFunction,
13281     FK_FunctionPointer,
13282     FK_BlockPointer
13283   };
13284 
13285   FnKind Kind;
13286   QualType CalleeType = CalleeExpr->getType();
13287   if (CalleeType == S.Context.BoundMemberTy) {
13288     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13289     Kind = FK_MemberFunction;
13290     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13291   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13292     CalleeType = Ptr->getPointeeType();
13293     Kind = FK_FunctionPointer;
13294   } else {
13295     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13296     Kind = FK_BlockPointer;
13297   }
13298   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13299 
13300   // Verify that this is a legal result type of a function.
13301   if (DestType->isArrayType() || DestType->isFunctionType()) {
13302     unsigned diagID = diag::err_func_returning_array_function;
13303     if (Kind == FK_BlockPointer)
13304       diagID = diag::err_block_returning_array_function;
13305 
13306     S.Diag(E->getExprLoc(), diagID)
13307       << DestType->isFunctionType() << DestType;
13308     return ExprError();
13309   }
13310 
13311   // Otherwise, go ahead and set DestType as the call's result.
13312   E->setType(DestType.getNonLValueExprType(S.Context));
13313   E->setValueKind(Expr::getValueKindForType(DestType));
13314   assert(E->getObjectKind() == OK_Ordinary);
13315 
13316   // Rebuild the function type, replacing the result type with DestType.
13317   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13318   if (Proto) {
13319     // __unknown_anytype(...) is a special case used by the debugger when
13320     // it has no idea what a function's signature is.
13321     //
13322     // We want to build this call essentially under the K&R
13323     // unprototyped rules, but making a FunctionNoProtoType in C++
13324     // would foul up all sorts of assumptions.  However, we cannot
13325     // simply pass all arguments as variadic arguments, nor can we
13326     // portably just call the function under a non-variadic type; see
13327     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13328     // However, it turns out that in practice it is generally safe to
13329     // call a function declared as "A foo(B,C,D);" under the prototype
13330     // "A foo(B,C,D,...);".  The only known exception is with the
13331     // Windows ABI, where any variadic function is implicitly cdecl
13332     // regardless of its normal CC.  Therefore we change the parameter
13333     // types to match the types of the arguments.
13334     //
13335     // This is a hack, but it is far superior to moving the
13336     // corresponding target-specific code from IR-gen to Sema/AST.
13337 
13338     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13339     SmallVector<QualType, 8> ArgTypes;
13340     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13341       ArgTypes.reserve(E->getNumArgs());
13342       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13343         Expr *Arg = E->getArg(i);
13344         QualType ArgType = Arg->getType();
13345         if (E->isLValue()) {
13346           ArgType = S.Context.getLValueReferenceType(ArgType);
13347         } else if (E->isXValue()) {
13348           ArgType = S.Context.getRValueReferenceType(ArgType);
13349         }
13350         ArgTypes.push_back(ArgType);
13351       }
13352       ParamTypes = ArgTypes;
13353     }
13354     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13355                                          Proto->getExtProtoInfo());
13356   } else {
13357     DestType = S.Context.getFunctionNoProtoType(DestType,
13358                                                 FnType->getExtInfo());
13359   }
13360 
13361   // Rebuild the appropriate pointer-to-function type.
13362   switch (Kind) {
13363   case FK_MemberFunction:
13364     // Nothing to do.
13365     break;
13366 
13367   case FK_FunctionPointer:
13368     DestType = S.Context.getPointerType(DestType);
13369     break;
13370 
13371   case FK_BlockPointer:
13372     DestType = S.Context.getBlockPointerType(DestType);
13373     break;
13374   }
13375 
13376   // Finally, we can recurse.
13377   ExprResult CalleeResult = Visit(CalleeExpr);
13378   if (!CalleeResult.isUsable()) return ExprError();
13379   E->setCallee(CalleeResult.get());
13380 
13381   // Bind a temporary if necessary.
13382   return S.MaybeBindToTemporary(E);
13383 }
13384 
13385 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13386   // Verify that this is a legal result type of a call.
13387   if (DestType->isArrayType() || DestType->isFunctionType()) {
13388     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13389       << DestType->isFunctionType() << DestType;
13390     return ExprError();
13391   }
13392 
13393   // Rewrite the method result type if available.
13394   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13395     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13396     Method->setReturnType(DestType);
13397   }
13398 
13399   // Change the type of the message.
13400   E->setType(DestType.getNonReferenceType());
13401   E->setValueKind(Expr::getValueKindForType(DestType));
13402 
13403   return S.MaybeBindToTemporary(E);
13404 }
13405 
13406 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13407   // The only case we should ever see here is a function-to-pointer decay.
13408   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13409     assert(E->getValueKind() == VK_RValue);
13410     assert(E->getObjectKind() == OK_Ordinary);
13411 
13412     E->setType(DestType);
13413 
13414     // Rebuild the sub-expression as the pointee (function) type.
13415     DestType = DestType->castAs<PointerType>()->getPointeeType();
13416 
13417     ExprResult Result = Visit(E->getSubExpr());
13418     if (!Result.isUsable()) return ExprError();
13419 
13420     E->setSubExpr(Result.get());
13421     return E;
13422   } else if (E->getCastKind() == CK_LValueToRValue) {
13423     assert(E->getValueKind() == VK_RValue);
13424     assert(E->getObjectKind() == OK_Ordinary);
13425 
13426     assert(isa<BlockPointerType>(E->getType()));
13427 
13428     E->setType(DestType);
13429 
13430     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13431     DestType = S.Context.getLValueReferenceType(DestType);
13432 
13433     ExprResult Result = Visit(E->getSubExpr());
13434     if (!Result.isUsable()) return ExprError();
13435 
13436     E->setSubExpr(Result.get());
13437     return E;
13438   } else {
13439     llvm_unreachable("Unhandled cast type!");
13440   }
13441 }
13442 
13443 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13444   ExprValueKind ValueKind = VK_LValue;
13445   QualType Type = DestType;
13446 
13447   // We know how to make this work for certain kinds of decls:
13448 
13449   //  - functions
13450   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13451     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13452       DestType = Ptr->getPointeeType();
13453       ExprResult Result = resolveDecl(E, VD);
13454       if (Result.isInvalid()) return ExprError();
13455       return S.ImpCastExprToType(Result.get(), Type,
13456                                  CK_FunctionToPointerDecay, VK_RValue);
13457     }
13458 
13459     if (!Type->isFunctionType()) {
13460       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13461         << VD << E->getSourceRange();
13462       return ExprError();
13463     }
13464     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
13465       // We must match the FunctionDecl's type to the hack introduced in
13466       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
13467       // type. See the lengthy commentary in that routine.
13468       QualType FDT = FD->getType();
13469       const FunctionType *FnType = FDT->castAs<FunctionType>();
13470       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
13471       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13472       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
13473         SourceLocation Loc = FD->getLocation();
13474         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
13475                                       FD->getDeclContext(),
13476                                       Loc, Loc, FD->getNameInfo().getName(),
13477                                       DestType, FD->getTypeSourceInfo(),
13478                                       SC_None, false/*isInlineSpecified*/,
13479                                       FD->hasPrototype(),
13480                                       false/*isConstexprSpecified*/);
13481 
13482         if (FD->getQualifier())
13483           NewFD->setQualifierInfo(FD->getQualifierLoc());
13484 
13485         SmallVector<ParmVarDecl*, 16> Params;
13486         for (const auto &AI : FT->param_types()) {
13487           ParmVarDecl *Param =
13488             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
13489           Param->setScopeInfo(0, Params.size());
13490           Params.push_back(Param);
13491         }
13492         NewFD->setParams(Params);
13493         DRE->setDecl(NewFD);
13494         VD = DRE->getDecl();
13495       }
13496     }
13497 
13498     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13499       if (MD->isInstance()) {
13500         ValueKind = VK_RValue;
13501         Type = S.Context.BoundMemberTy;
13502       }
13503 
13504     // Function references aren't l-values in C.
13505     if (!S.getLangOpts().CPlusPlus)
13506       ValueKind = VK_RValue;
13507 
13508   //  - variables
13509   } else if (isa<VarDecl>(VD)) {
13510     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13511       Type = RefTy->getPointeeType();
13512     } else if (Type->isFunctionType()) {
13513       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13514         << VD << E->getSourceRange();
13515       return ExprError();
13516     }
13517 
13518   //  - nothing else
13519   } else {
13520     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13521       << VD << E->getSourceRange();
13522     return ExprError();
13523   }
13524 
13525   // Modifying the declaration like this is friendly to IR-gen but
13526   // also really dangerous.
13527   VD->setType(DestType);
13528   E->setType(Type);
13529   E->setValueKind(ValueKind);
13530   return E;
13531 }
13532 
13533 /// Check a cast of an unknown-any type.  We intentionally only
13534 /// trigger this for C-style casts.
13535 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13536                                      Expr *CastExpr, CastKind &CastKind,
13537                                      ExprValueKind &VK, CXXCastPath &Path) {
13538   // Rewrite the casted expression from scratch.
13539   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13540   if (!result.isUsable()) return ExprError();
13541 
13542   CastExpr = result.get();
13543   VK = CastExpr->getValueKind();
13544   CastKind = CK_NoOp;
13545 
13546   return CastExpr;
13547 }
13548 
13549 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13550   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13551 }
13552 
13553 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13554                                     Expr *arg, QualType &paramType) {
13555   // If the syntactic form of the argument is not an explicit cast of
13556   // any sort, just do default argument promotion.
13557   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13558   if (!castArg) {
13559     ExprResult result = DefaultArgumentPromotion(arg);
13560     if (result.isInvalid()) return ExprError();
13561     paramType = result.get()->getType();
13562     return result;
13563   }
13564 
13565   // Otherwise, use the type that was written in the explicit cast.
13566   assert(!arg->hasPlaceholderType());
13567   paramType = castArg->getTypeAsWritten();
13568 
13569   // Copy-initialize a parameter of that type.
13570   InitializedEntity entity =
13571     InitializedEntity::InitializeParameter(Context, paramType,
13572                                            /*consumed*/ false);
13573   return PerformCopyInitialization(entity, callLoc, arg);
13574 }
13575 
13576 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13577   Expr *orig = E;
13578   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13579   while (true) {
13580     E = E->IgnoreParenImpCasts();
13581     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13582       E = call->getCallee();
13583       diagID = diag::err_uncasted_call_of_unknown_any;
13584     } else {
13585       break;
13586     }
13587   }
13588 
13589   SourceLocation loc;
13590   NamedDecl *d;
13591   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13592     loc = ref->getLocation();
13593     d = ref->getDecl();
13594   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13595     loc = mem->getMemberLoc();
13596     d = mem->getMemberDecl();
13597   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13598     diagID = diag::err_uncasted_call_of_unknown_any;
13599     loc = msg->getSelectorStartLoc();
13600     d = msg->getMethodDecl();
13601     if (!d) {
13602       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13603         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13604         << orig->getSourceRange();
13605       return ExprError();
13606     }
13607   } else {
13608     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13609       << E->getSourceRange();
13610     return ExprError();
13611   }
13612 
13613   S.Diag(loc, diagID) << d << orig->getSourceRange();
13614 
13615   // Never recoverable.
13616   return ExprError();
13617 }
13618 
13619 /// Check for operands with placeholder types and complain if found.
13620 /// Returns true if there was an error and no recovery was possible.
13621 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13622   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13623   if (!placeholderType) return E;
13624 
13625   switch (placeholderType->getKind()) {
13626 
13627   // Overloaded expressions.
13628   case BuiltinType::Overload: {
13629     // Try to resolve a single function template specialization.
13630     // This is obligatory.
13631     ExprResult result = E;
13632     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13633       return result;
13634 
13635     // If that failed, try to recover with a call.
13636     } else {
13637       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13638                            /*complain*/ true);
13639       return result;
13640     }
13641   }
13642 
13643   // Bound member functions.
13644   case BuiltinType::BoundMember: {
13645     ExprResult result = E;
13646     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13647                          /*complain*/ true);
13648     return result;
13649   }
13650 
13651   // ARC unbridged casts.
13652   case BuiltinType::ARCUnbridgedCast: {
13653     Expr *realCast = stripARCUnbridgedCast(E);
13654     diagnoseARCUnbridgedCast(realCast);
13655     return realCast;
13656   }
13657 
13658   // Expressions of unknown type.
13659   case BuiltinType::UnknownAny:
13660     return diagnoseUnknownAnyExpr(*this, E);
13661 
13662   // Pseudo-objects.
13663   case BuiltinType::PseudoObject:
13664     return checkPseudoObjectRValue(E);
13665 
13666   case BuiltinType::BuiltinFn: {
13667     // Accept __noop without parens by implicitly converting it to a call expr.
13668     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
13669     if (DRE) {
13670       auto *FD = cast<FunctionDecl>(DRE->getDecl());
13671       if (FD->getBuiltinID() == Builtin::BI__noop) {
13672         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
13673                               CK_BuiltinFnToFnPtr).get();
13674         return new (Context) CallExpr(Context, E, None, Context.IntTy,
13675                                       VK_RValue, SourceLocation());
13676       }
13677     }
13678 
13679     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13680     return ExprError();
13681   }
13682 
13683   // Everything else should be impossible.
13684 #define BUILTIN_TYPE(Id, SingletonId) \
13685   case BuiltinType::Id:
13686 #define PLACEHOLDER_TYPE(Id, SingletonId)
13687 #include "clang/AST/BuiltinTypes.def"
13688     break;
13689   }
13690 
13691   llvm_unreachable("invalid placeholder type!");
13692 }
13693 
13694 bool Sema::CheckCaseExpression(Expr *E) {
13695   if (E->isTypeDependent())
13696     return true;
13697   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13698     return E->getType()->isIntegralOrEnumerationType();
13699   return false;
13700 }
13701 
13702 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13703 ExprResult
13704 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13705   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13706          "Unknown Objective-C Boolean value!");
13707   QualType BoolT = Context.ObjCBuiltinBoolTy;
13708   if (!Context.getBOOLDecl()) {
13709     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13710                         Sema::LookupOrdinaryName);
13711     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13712       NamedDecl *ND = Result.getFoundDecl();
13713       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13714         Context.setBOOLDecl(TD);
13715     }
13716   }
13717   if (Context.getBOOLDecl())
13718     BoolT = Context.getBOOLType();
13719   return new (Context)
13720       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13721 }
13722