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 using namespace clang;
46 using namespace sema;
47 
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54 
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59 
60     // If the function has a deduced return type, and we can't deduce it,
61     // then we can't use it either.
62     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
63         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
64       return false;
65   }
66 
67   // See if this function is unavailable.
68   if (D->getAvailability() == AR_Unavailable &&
69       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
70     return false;
71 
72   return true;
73 }
74 
75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
76   // Warn if this is used but marked unused.
77   if (D->hasAttr<UnusedAttr>()) {
78     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
79     if (!DC->hasAttr<UnusedAttr>())
80       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
81   }
82 }
83 
84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
85                               NamedDecl *D, SourceLocation Loc,
86                               const ObjCInterfaceDecl *UnknownObjCClass,
87                               bool ObjCPropertyAccess) {
88   // See if this declaration is unavailable or deprecated.
89   std::string Message;
90 
91   // Forward class declarations get their attributes from their definition.
92   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
93     if (IDecl->getDefinition())
94       D = IDecl->getDefinition();
95   }
96   AvailabilityResult Result = D->getAvailability(&Message);
97   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
98     if (Result == AR_Available) {
99       const DeclContext *DC = ECD->getDeclContext();
100       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
101         Result = TheEnumDecl->getAvailability(&Message);
102     }
103 
104   const ObjCPropertyDecl *ObjCPDecl = nullptr;
105   if (Result == AR_Deprecated || Result == AR_Unavailable) {
106     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
107       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
108         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
109         if (PDeclResult == Result)
110           ObjCPDecl = PD;
111       }
112     }
113   }
114 
115   switch (Result) {
116     case AR_Available:
117     case AR_NotYetIntroduced:
118       break;
119 
120     case AR_Deprecated:
121       if (S.getCurContextAvailability() != AR_Deprecated)
122         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
123                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
124                                   ObjCPropertyAccess);
125       break;
126 
127     case AR_Unavailable:
128       if (S.getCurContextAvailability() != AR_Unavailable)
129         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
130                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
131                                   ObjCPropertyAccess);
132       break;
133 
134     }
135     return Result;
136 }
137 
138 /// \brief Emit a note explaining that this function is deleted.
139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140   assert(Decl->isDeleted());
141 
142   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
143 
144   if (Method && Method->isDeleted() && Method->isDefaulted()) {
145     // If the method was explicitly defaulted, point at that declaration.
146     if (!Method->isImplicit())
147       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
148 
149     // Try to diagnose why this special member function was implicitly
150     // deleted. This might fail, if that reason no longer applies.
151     CXXSpecialMember CSM = getSpecialMember(Method);
152     if (CSM != CXXInvalid)
153       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
154 
155     return;
156   }
157 
158   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
159     if (CXXConstructorDecl *BaseCD =
160             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
161       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
162       if (BaseCD->isDeleted()) {
163         NoteDeletedFunction(BaseCD);
164       } else {
165         // FIXME: An explanation of why exactly it can't be inherited
166         // would be nice.
167         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
168       }
169       return;
170     }
171   }
172 
173   Diag(Decl->getLocation(), diag::note_availability_specified_here)
174     << Decl << true;
175 }
176 
177 /// \brief Determine whether a FunctionDecl was ever declared with an
178 /// explicit storage class.
179 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
180   for (auto I : D->redecls()) {
181     if (I->getStorageClass() != SC_None)
182       return true;
183   }
184   return false;
185 }
186 
187 /// \brief Check whether we're in an extern inline function and referring to a
188 /// variable or function with internal linkage (C11 6.7.4p3).
189 ///
190 /// This is only a warning because we used to silently accept this code, but
191 /// in many cases it will not behave correctly. This is not enabled in C++ mode
192 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
193 /// and so while there may still be user mistakes, most of the time we can't
194 /// prove that there are errors.
195 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
196                                                       const NamedDecl *D,
197                                                       SourceLocation Loc) {
198   // This is disabled under C++; there are too many ways for this to fire in
199   // contexts where the warning is a false positive, or where it is technically
200   // correct but benign.
201   if (S.getLangOpts().CPlusPlus)
202     return;
203 
204   // Check if this is an inlined function or method.
205   FunctionDecl *Current = S.getCurFunctionDecl();
206   if (!Current)
207     return;
208   if (!Current->isInlined())
209     return;
210   if (!Current->isExternallyVisible())
211     return;
212 
213   // Check if the decl has internal linkage.
214   if (D->getFormalLinkage() != InternalLinkage)
215     return;
216 
217   // Downgrade from ExtWarn to Extension if
218   //  (1) the supposedly external inline function is in the main file,
219   //      and probably won't be included anywhere else.
220   //  (2) the thing we're referencing is a pure function.
221   //  (3) the thing we're referencing is another inline function.
222   // This last can give us false negatives, but it's better than warning on
223   // wrappers for simple C library functions.
224   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
225   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
226   if (!DowngradeWarning && UsedFn)
227     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
228 
229   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
230                                : diag::warn_internal_in_extern_inline)
231     << /*IsVar=*/!UsedFn << D;
232 
233   S.MaybeSuggestAddingStaticToDecl(Current);
234 
235   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
236       << D;
237 }
238 
239 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
240   const FunctionDecl *First = Cur->getFirstDecl();
241 
242   // Suggest "static" on the function, if possible.
243   if (!hasAnyExplicitStorageClass(First)) {
244     SourceLocation DeclBegin = First->getSourceRange().getBegin();
245     Diag(DeclBegin, diag::note_convert_inline_to_static)
246       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
247   }
248 }
249 
250 /// \brief Determine whether the use of this declaration is valid, and
251 /// emit any corresponding diagnostics.
252 ///
253 /// This routine diagnoses various problems with referencing
254 /// declarations that can occur when using a declaration. For example,
255 /// it might warn if a deprecated or unavailable declaration is being
256 /// used, or produce an error (and return true) if a C++0x deleted
257 /// function is being used.
258 ///
259 /// \returns true if there was an error (this declaration cannot be
260 /// referenced), false otherwise.
261 ///
262 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
263                              const ObjCInterfaceDecl *UnknownObjCClass,
264                              bool ObjCPropertyAccess) {
265   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
266     // If there were any diagnostics suppressed by template argument deduction,
267     // emit them now.
268     SuppressedDiagnosticsMap::iterator
269       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
270     if (Pos != SuppressedDiagnostics.end()) {
271       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
272       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
273         Diag(Suppressed[I].first, Suppressed[I].second);
274 
275       // Clear out the list of suppressed diagnostics, so that we don't emit
276       // them again for this specialization. However, we don't obsolete this
277       // entry from the table, because we want to avoid ever emitting these
278       // diagnostics again.
279       Suppressed.clear();
280     }
281 
282     // C++ [basic.start.main]p3:
283     //   The function 'main' shall not be used within a program.
284     if (cast<FunctionDecl>(D)->isMain())
285       Diag(Loc, diag::ext_main_used);
286   }
287 
288   // See if this is an auto-typed variable whose initializer we are parsing.
289   if (ParsingInitForAutoVars.count(D)) {
290     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
291       << D->getDeclName();
292     return true;
293   }
294 
295   // See if this is a deleted function.
296   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
297     if (FD->isDeleted()) {
298       Diag(Loc, diag::err_deleted_function_use);
299       NoteDeletedFunction(FD);
300       return true;
301     }
302 
303     // If the function has a deduced return type, and we can't deduce it,
304     // then we can't use it either.
305     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
306         DeduceReturnType(FD, Loc))
307       return true;
308   }
309   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
310 
311   DiagnoseUnusedOfDecl(*this, D, Loc);
312 
313   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
314 
315   return false;
316 }
317 
318 /// \brief Retrieve the message suffix that should be added to a
319 /// diagnostic complaining about the given function being deleted or
320 /// unavailable.
321 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
322   std::string Message;
323   if (FD->getAvailability(&Message))
324     return ": " + Message;
325 
326   return std::string();
327 }
328 
329 /// DiagnoseSentinelCalls - This routine checks whether a call or
330 /// message-send is to a declaration with the sentinel attribute, and
331 /// if so, it checks that the requirements of the sentinel are
332 /// satisfied.
333 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
334                                  ArrayRef<Expr *> Args) {
335   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
336   if (!attr)
337     return;
338 
339   // The number of formal parameters of the declaration.
340   unsigned numFormalParams;
341 
342   // The kind of declaration.  This is also an index into a %select in
343   // the diagnostic.
344   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
345 
346   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
347     numFormalParams = MD->param_size();
348     calleeType = CT_Method;
349   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
350     numFormalParams = FD->param_size();
351     calleeType = CT_Function;
352   } else if (isa<VarDecl>(D)) {
353     QualType type = cast<ValueDecl>(D)->getType();
354     const FunctionType *fn = nullptr;
355     if (const PointerType *ptr = type->getAs<PointerType>()) {
356       fn = ptr->getPointeeType()->getAs<FunctionType>();
357       if (!fn) return;
358       calleeType = CT_Function;
359     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
360       fn = ptr->getPointeeType()->castAs<FunctionType>();
361       calleeType = CT_Block;
362     } else {
363       return;
364     }
365 
366     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
367       numFormalParams = proto->getNumParams();
368     } else {
369       numFormalParams = 0;
370     }
371   } else {
372     return;
373   }
374 
375   // "nullPos" is the number of formal parameters at the end which
376   // effectively count as part of the variadic arguments.  This is
377   // useful if you would prefer to not have *any* formal parameters,
378   // but the language forces you to have at least one.
379   unsigned nullPos = attr->getNullPos();
380   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
381   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
382 
383   // The number of arguments which should follow the sentinel.
384   unsigned numArgsAfterSentinel = attr->getSentinel();
385 
386   // If there aren't enough arguments for all the formal parameters,
387   // the sentinel, and the args after the sentinel, complain.
388   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
389     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
390     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
391     return;
392   }
393 
394   // Otherwise, find the sentinel expression.
395   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
396   if (!sentinelExpr) return;
397   if (sentinelExpr->isValueDependent()) return;
398   if (Context.isSentinelNullExpr(sentinelExpr)) return;
399 
400   // Pick a reasonable string to insert.  Optimistically use 'nil' or
401   // 'NULL' if those are actually defined in the context.  Only use
402   // 'nil' for ObjC methods, where it's much more likely that the
403   // variadic arguments form a list of object pointers.
404   SourceLocation MissingNilLoc
405     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
406   std::string NullValue;
407   if (calleeType == CT_Method &&
408       PP.getIdentifierInfo("nil")->hasMacroDefinition())
409     NullValue = "nil";
410   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
411     NullValue = "NULL";
412   else
413     NullValue = "(void*) 0";
414 
415   if (MissingNilLoc.isInvalid())
416     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
417   else
418     Diag(MissingNilLoc, diag::warn_missing_sentinel)
419       << int(calleeType)
420       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
421   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
422 }
423 
424 SourceRange Sema::getExprRange(Expr *E) const {
425   return E ? E->getSourceRange() : SourceRange();
426 }
427 
428 //===----------------------------------------------------------------------===//
429 //  Standard Promotions and Conversions
430 //===----------------------------------------------------------------------===//
431 
432 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
433 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
434   // Handle any placeholder expressions which made it here.
435   if (E->getType()->isPlaceholderType()) {
436     ExprResult result = CheckPlaceholderExpr(E);
437     if (result.isInvalid()) return ExprError();
438     E = result.get();
439   }
440 
441   QualType Ty = E->getType();
442   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
443 
444   if (Ty->isFunctionType()) {
445     // If we are here, we are not calling a function but taking
446     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
447     if (getLangOpts().OpenCL) {
448       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
449       return ExprError();
450     }
451     E = ImpCastExprToType(E, Context.getPointerType(Ty),
452                           CK_FunctionToPointerDecay).get();
453   } else if (Ty->isArrayType()) {
454     // In C90 mode, arrays only promote to pointers if the array expression is
455     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
456     // type 'array of type' is converted to an expression that has type 'pointer
457     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
458     // that has type 'array of type' ...".  The relevant change is "an lvalue"
459     // (C90) to "an expression" (C99).
460     //
461     // C++ 4.2p1:
462     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
463     // T" can be converted to an rvalue of type "pointer to T".
464     //
465     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
466       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
467                             CK_ArrayToPointerDecay).get();
468   }
469   return E;
470 }
471 
472 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
473   // Check to see if we are dereferencing a null pointer.  If so,
474   // and if not volatile-qualified, this is undefined behavior that the
475   // optimizer will delete, so warn about it.  People sometimes try to use this
476   // to get a deterministic trap and are surprised by clang's behavior.  This
477   // only handles the pattern "*null", which is a very syntactic check.
478   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
479     if (UO->getOpcode() == UO_Deref &&
480         UO->getSubExpr()->IgnoreParenCasts()->
481           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
482         !UO->getType().isVolatileQualified()) {
483     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484                           S.PDiag(diag::warn_indirection_through_null)
485                             << UO->getSubExpr()->getSourceRange());
486     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
487                         S.PDiag(diag::note_indirection_through_null));
488   }
489 }
490 
491 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
492                                     SourceLocation AssignLoc,
493                                     const Expr* RHS) {
494   const ObjCIvarDecl *IV = OIRE->getDecl();
495   if (!IV)
496     return;
497 
498   DeclarationName MemberName = IV->getDeclName();
499   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
500   if (!Member || !Member->isStr("isa"))
501     return;
502 
503   const Expr *Base = OIRE->getBase();
504   QualType BaseType = Base->getType();
505   if (OIRE->isArrow())
506     BaseType = BaseType->getPointeeType();
507   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
508     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
509       ObjCInterfaceDecl *ClassDeclared = nullptr;
510       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
511       if (!ClassDeclared->getSuperClass()
512           && (*ClassDeclared->ivar_begin()) == IV) {
513         if (RHS) {
514           NamedDecl *ObjectSetClass =
515             S.LookupSingleName(S.TUScope,
516                                &S.Context.Idents.get("object_setClass"),
517                                SourceLocation(), S.LookupOrdinaryName);
518           if (ObjectSetClass) {
519             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
520             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
521             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
522             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
523                                                      AssignLoc), ",") <<
524             FixItHint::CreateInsertion(RHSLocEnd, ")");
525           }
526           else
527             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
528         } else {
529           NamedDecl *ObjectGetClass =
530             S.LookupSingleName(S.TUScope,
531                                &S.Context.Idents.get("object_getClass"),
532                                SourceLocation(), S.LookupOrdinaryName);
533           if (ObjectGetClass)
534             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
535             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
536             FixItHint::CreateReplacement(
537                                          SourceRange(OIRE->getOpLoc(),
538                                                      OIRE->getLocEnd()), ")");
539           else
540             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
541         }
542         S.Diag(IV->getLocation(), diag::note_ivar_decl);
543       }
544     }
545 }
546 
547 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
548   // Handle any placeholder expressions which made it here.
549   if (E->getType()->isPlaceholderType()) {
550     ExprResult result = CheckPlaceholderExpr(E);
551     if (result.isInvalid()) return ExprError();
552     E = result.get();
553   }
554 
555   // C++ [conv.lval]p1:
556   //   A glvalue of a non-function, non-array type T can be
557   //   converted to a prvalue.
558   if (!E->isGLValue()) return E;
559 
560   QualType T = E->getType();
561   assert(!T.isNull() && "r-value conversion on typeless expression?");
562 
563   // We don't want to throw lvalue-to-rvalue casts on top of
564   // expressions of certain types in C++.
565   if (getLangOpts().CPlusPlus &&
566       (E->getType() == Context.OverloadTy ||
567        T->isDependentType() ||
568        T->isRecordType()))
569     return E;
570 
571   // The C standard is actually really unclear on this point, and
572   // DR106 tells us what the result should be but not why.  It's
573   // generally best to say that void types just doesn't undergo
574   // lvalue-to-rvalue at all.  Note that expressions of unqualified
575   // 'void' type are never l-values, but qualified void can be.
576   if (T->isVoidType())
577     return E;
578 
579   // OpenCL usually rejects direct accesses to values of 'half' type.
580   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
581       T->isHalfType()) {
582     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
583       << 0 << T;
584     return ExprError();
585   }
586 
587   CheckForNullPointerDereference(*this, E);
588   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
589     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
590                                      &Context.Idents.get("object_getClass"),
591                                      SourceLocation(), LookupOrdinaryName);
592     if (ObjectGetClass)
593       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
594         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
595         FixItHint::CreateReplacement(
596                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
597     else
598       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
599   }
600   else if (const ObjCIvarRefExpr *OIRE =
601             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
602     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
603 
604   // C++ [conv.lval]p1:
605   //   [...] If T is a non-class type, the type of the prvalue is the
606   //   cv-unqualified version of T. Otherwise, the type of the
607   //   rvalue is T.
608   //
609   // C99 6.3.2.1p2:
610   //   If the lvalue has qualified type, the value has the unqualified
611   //   version of the type of the lvalue; otherwise, the value has the
612   //   type of the lvalue.
613   if (T.hasQualifiers())
614     T = T.getUnqualifiedType();
615 
616   UpdateMarkingForLValueToRValue(E);
617 
618   // Loading a __weak object implicitly retains the value, so we need a cleanup to
619   // balance that.
620   if (getLangOpts().ObjCAutoRefCount &&
621       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
622     ExprNeedsCleanups = true;
623 
624   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
625                                             nullptr, VK_RValue);
626 
627   // C11 6.3.2.1p2:
628   //   ... if the lvalue has atomic type, the value has the non-atomic version
629   //   of the type of the lvalue ...
630   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
631     T = Atomic->getValueType().getUnqualifiedType();
632     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
633                                    nullptr, VK_RValue);
634   }
635 
636   return Res;
637 }
638 
639 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
640   ExprResult Res = DefaultFunctionArrayConversion(E);
641   if (Res.isInvalid())
642     return ExprError();
643   Res = DefaultLvalueConversion(Res.get());
644   if (Res.isInvalid())
645     return ExprError();
646   return Res;
647 }
648 
649 /// CallExprUnaryConversions - a special case of an unary conversion
650 /// performed on a function designator of a call expression.
651 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
652   QualType Ty = E->getType();
653   ExprResult Res = E;
654   // Only do implicit cast for a function type, but not for a pointer
655   // to function type.
656   if (Ty->isFunctionType()) {
657     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
658                             CK_FunctionToPointerDecay).get();
659     if (Res.isInvalid())
660       return ExprError();
661   }
662   Res = DefaultLvalueConversion(Res.get());
663   if (Res.isInvalid())
664     return ExprError();
665   return Res.get();
666 }
667 
668 /// UsualUnaryConversions - Performs various conversions that are common to most
669 /// operators (C99 6.3). The conversions of array and function types are
670 /// sometimes suppressed. For example, the array->pointer conversion doesn't
671 /// apply if the array is an argument to the sizeof or address (&) operators.
672 /// In these instances, this routine should *not* be called.
673 ExprResult Sema::UsualUnaryConversions(Expr *E) {
674   // First, convert to an r-value.
675   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
676   if (Res.isInvalid())
677     return ExprError();
678   E = Res.get();
679 
680   QualType Ty = E->getType();
681   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
682 
683   // Half FP have to be promoted to float unless it is natively supported
684   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
685     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
686 
687   // Try to perform integral promotions if the object has a theoretically
688   // promotable type.
689   if (Ty->isIntegralOrUnscopedEnumerationType()) {
690     // C99 6.3.1.1p2:
691     //
692     //   The following may be used in an expression wherever an int or
693     //   unsigned int may be used:
694     //     - an object or expression with an integer type whose integer
695     //       conversion rank is less than or equal to the rank of int
696     //       and unsigned int.
697     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
698     //
699     //   If an int can represent all values of the original type, the
700     //   value is converted to an int; otherwise, it is converted to an
701     //   unsigned int. These are called the integer promotions. All
702     //   other types are unchanged by the integer promotions.
703 
704     QualType PTy = Context.isPromotableBitField(E);
705     if (!PTy.isNull()) {
706       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
707       return E;
708     }
709     if (Ty->isPromotableIntegerType()) {
710       QualType PT = Context.getPromotedIntegerType(Ty);
711       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
712       return E;
713     }
714   }
715   return E;
716 }
717 
718 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
719 /// do not have a prototype. Arguments that have type float or __fp16
720 /// are promoted to double. All other argument types are converted by
721 /// UsualUnaryConversions().
722 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
723   QualType Ty = E->getType();
724   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
725 
726   ExprResult Res = UsualUnaryConversions(E);
727   if (Res.isInvalid())
728     return ExprError();
729   E = Res.get();
730 
731   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
732   // double.
733   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
734   if (BTy && (BTy->getKind() == BuiltinType::Half ||
735               BTy->getKind() == BuiltinType::Float))
736     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
737 
738   // C++ performs lvalue-to-rvalue conversion as a default argument
739   // promotion, even on class types, but note:
740   //   C++11 [conv.lval]p2:
741   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
742   //     operand or a subexpression thereof the value contained in the
743   //     referenced object is not accessed. Otherwise, if the glvalue
744   //     has a class type, the conversion copy-initializes a temporary
745   //     of type T from the glvalue and the result of the conversion
746   //     is a prvalue for the temporary.
747   // FIXME: add some way to gate this entire thing for correctness in
748   // potentially potentially evaluated contexts.
749   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
750     ExprResult Temp = PerformCopyInitialization(
751                        InitializedEntity::InitializeTemporary(E->getType()),
752                                                 E->getExprLoc(), E);
753     if (Temp.isInvalid())
754       return ExprError();
755     E = Temp.get();
756   }
757 
758   return E;
759 }
760 
761 /// Determine the degree of POD-ness for an expression.
762 /// Incomplete types are considered POD, since this check can be performed
763 /// when we're in an unevaluated context.
764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
765   if (Ty->isIncompleteType()) {
766     // C++11 [expr.call]p7:
767     //   After these conversions, if the argument does not have arithmetic,
768     //   enumeration, pointer, pointer to member, or class type, the program
769     //   is ill-formed.
770     //
771     // Since we've already performed array-to-pointer and function-to-pointer
772     // decay, the only such type in C++ is cv void. This also handles
773     // initializer lists as variadic arguments.
774     if (Ty->isVoidType())
775       return VAK_Invalid;
776 
777     if (Ty->isObjCObjectType())
778       return VAK_Invalid;
779     return VAK_Valid;
780   }
781 
782   if (Ty.isCXX98PODType(Context))
783     return VAK_Valid;
784 
785   // C++11 [expr.call]p7:
786   //   Passing a potentially-evaluated argument of class type (Clause 9)
787   //   having a non-trivial copy constructor, a non-trivial move constructor,
788   //   or a non-trivial destructor, with no corresponding parameter,
789   //   is conditionally-supported with implementation-defined semantics.
790   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
791     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
792       if (!Record->hasNonTrivialCopyConstructor() &&
793           !Record->hasNonTrivialMoveConstructor() &&
794           !Record->hasNonTrivialDestructor())
795         return VAK_ValidInCXX11;
796 
797   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
798     return VAK_Valid;
799 
800   if (Ty->isObjCObjectType())
801     return VAK_Invalid;
802 
803   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
804   // permitted to reject them. We should consider doing so.
805   return VAK_Undefined;
806 }
807 
808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
809   // Don't allow one to pass an Objective-C interface to a vararg.
810   const QualType &Ty = E->getType();
811   VarArgKind VAK = isValidVarArgType(Ty);
812 
813   // Complain about passing non-POD types through varargs.
814   switch (VAK) {
815   case VAK_ValidInCXX11:
816     DiagRuntimeBehavior(
817         E->getLocStart(), nullptr,
818         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
819           << Ty << CT);
820     // Fall through.
821   case VAK_Valid:
822     if (Ty->isRecordType()) {
823       // This is unlikely to be what the user intended. If the class has a
824       // 'c_str' member function, the user probably meant to call that.
825       DiagRuntimeBehavior(E->getLocStart(), nullptr,
826                           PDiag(diag::warn_pass_class_arg_to_vararg)
827                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
828     }
829     break;
830 
831   case VAK_Undefined:
832     DiagRuntimeBehavior(
833         E->getLocStart(), nullptr,
834         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
835           << getLangOpts().CPlusPlus11 << Ty << CT);
836     break;
837 
838   case VAK_Invalid:
839     if (Ty->isObjCObjectType())
840       DiagRuntimeBehavior(
841           E->getLocStart(), nullptr,
842           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
843             << Ty << CT);
844     else
845       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
846         << isa<InitListExpr>(E) << Ty << CT;
847     break;
848   }
849 }
850 
851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
852 /// will create a trap if the resulting type is not a POD type.
853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
854                                                   FunctionDecl *FDecl) {
855   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
856     // Strip the unbridged-cast placeholder expression off, if applicable.
857     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
858         (CT == VariadicMethod ||
859          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
860       E = stripARCUnbridgedCast(E);
861 
862     // Otherwise, do normal placeholder checking.
863     } else {
864       ExprResult ExprRes = CheckPlaceholderExpr(E);
865       if (ExprRes.isInvalid())
866         return ExprError();
867       E = ExprRes.get();
868     }
869   }
870 
871   ExprResult ExprRes = DefaultArgumentPromotion(E);
872   if (ExprRes.isInvalid())
873     return ExprError();
874   E = ExprRes.get();
875 
876   // Diagnostics regarding non-POD argument types are
877   // emitted along with format string checking in Sema::CheckFunctionCall().
878   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
879     // Turn this into a trap.
880     CXXScopeSpec SS;
881     SourceLocation TemplateKWLoc;
882     UnqualifiedId Name;
883     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
884                        E->getLocStart());
885     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
886                                           Name, true, false);
887     if (TrapFn.isInvalid())
888       return ExprError();
889 
890     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
891                                     E->getLocStart(), None,
892                                     E->getLocEnd());
893     if (Call.isInvalid())
894       return ExprError();
895 
896     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
897                                   Call.get(), E);
898     if (Comma.isInvalid())
899       return ExprError();
900     return Comma.get();
901   }
902 
903   if (!getLangOpts().CPlusPlus &&
904       RequireCompleteType(E->getExprLoc(), E->getType(),
905                           diag::err_call_incomplete_argument))
906     return ExprError();
907 
908   return E;
909 }
910 
911 /// \brief Converts an integer to complex float type.  Helper function of
912 /// UsualArithmeticConversions()
913 ///
914 /// \return false if the integer expression is an integer type and is
915 /// successfully converted to the complex type.
916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
917                                                   ExprResult &ComplexExpr,
918                                                   QualType IntTy,
919                                                   QualType ComplexTy,
920                                                   bool SkipCast) {
921   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
922   if (SkipCast) return false;
923   if (IntTy->isIntegerType()) {
924     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
925     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
926     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
927                                   CK_FloatingRealToComplex);
928   } else {
929     assert(IntTy->isComplexIntegerType());
930     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
931                                   CK_IntegralComplexToFloatingComplex);
932   }
933   return false;
934 }
935 
936 /// \brief Takes two complex float types and converts them to the same type.
937 /// Helper function of UsualArithmeticConversions()
938 static QualType
939 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
940                                             ExprResult &RHS, QualType LHSType,
941                                             QualType RHSType,
942                                             bool IsCompAssign) {
943   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
944 
945   if (order < 0) {
946     // _Complex float -> _Complex double
947     if (!IsCompAssign)
948       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingComplexCast);
949     return RHSType;
950   }
951   if (order > 0)
952     // _Complex float -> _Complex double
953     RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingComplexCast);
954   return LHSType;
955 }
956 
957 /// \brief Converts otherExpr to complex float and promotes complexExpr if
958 /// necessary.  Helper function of UsualArithmeticConversions()
959 static QualType handleOtherComplexFloatConversion(Sema &S,
960                                                   ExprResult &ComplexExpr,
961                                                   ExprResult &OtherExpr,
962                                                   QualType ComplexTy,
963                                                   QualType OtherTy,
964                                                   bool ConvertComplexExpr,
965                                                   bool ConvertOtherExpr) {
966   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
967 
968   // If just the complexExpr is complex, the otherExpr needs to be converted,
969   // and the complexExpr might need to be promoted.
970   if (order > 0) { // complexExpr is wider
971     // float -> _Complex double
972     if (ConvertOtherExpr) {
973       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
974       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), fp, CK_FloatingCast);
975       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), ComplexTy,
976                                       CK_FloatingRealToComplex);
977     }
978     return ComplexTy;
979   }
980 
981   // otherTy is at least as wide.  Find its corresponding complex type.
982   QualType result = (order == 0 ? ComplexTy :
983                                   S.Context.getComplexType(OtherTy));
984 
985   // double -> _Complex double
986   if (ConvertOtherExpr)
987     OtherExpr = S.ImpCastExprToType(OtherExpr.get(), result,
988                                     CK_FloatingRealToComplex);
989 
990   // _Complex float -> _Complex double
991   if (ConvertComplexExpr && order < 0)
992     ComplexExpr = S.ImpCastExprToType(ComplexExpr.get(), result,
993                                       CK_FloatingComplexCast);
994 
995   return result;
996 }
997 
998 /// \brief Handle arithmetic conversion with complex types.  Helper function of
999 /// UsualArithmeticConversions()
1000 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1001                                              ExprResult &RHS, QualType LHSType,
1002                                              QualType RHSType,
1003                                              bool IsCompAssign) {
1004   // if we have an integer operand, the result is the complex type.
1005   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1006                                              /*skipCast*/false))
1007     return LHSType;
1008   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1009                                              /*skipCast*/IsCompAssign))
1010     return RHSType;
1011 
1012   // This handles complex/complex, complex/float, or float/complex.
1013   // When both operands are complex, the shorter operand is converted to the
1014   // type of the longer, and that is the type of the result. This corresponds
1015   // to what is done when combining two real floating-point operands.
1016   // The fun begins when size promotion occur across type domains.
1017   // From H&S 6.3.4: When one operand is complex and the other is a real
1018   // floating-point type, the less precise type is converted, within it's
1019   // real or complex domain, to the precision of the other type. For example,
1020   // when combining a "long double" with a "double _Complex", the
1021   // "double _Complex" is promoted to "long double _Complex".
1022 
1023   bool LHSComplexFloat = LHSType->isComplexType();
1024   bool RHSComplexFloat = RHSType->isComplexType();
1025 
1026   // If both are complex, just cast to the more precise type.
1027   if (LHSComplexFloat && RHSComplexFloat)
1028     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1029                                                        LHSType, RHSType,
1030                                                        IsCompAssign);
1031 
1032   // If only one operand is complex, promote it if necessary and convert the
1033   // other operand to complex.
1034   if (LHSComplexFloat)
1035     return handleOtherComplexFloatConversion(
1036         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1037         /*convertOtherExpr*/ true);
1038 
1039   assert(RHSComplexFloat);
1040   return handleOtherComplexFloatConversion(
1041       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1042       /*convertOtherExpr*/ !IsCompAssign);
1043 }
1044 
1045 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1046 /// of UsualArithmeticConversions()
1047 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1048                                            ExprResult &IntExpr,
1049                                            QualType FloatTy, QualType IntTy,
1050                                            bool ConvertFloat, bool ConvertInt) {
1051   if (IntTy->isIntegerType()) {
1052     if (ConvertInt)
1053       // Convert intExpr to the lhs floating point type.
1054       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1055                                     CK_IntegralToFloating);
1056     return FloatTy;
1057   }
1058 
1059   // Convert both sides to the appropriate complex float.
1060   assert(IntTy->isComplexIntegerType());
1061   QualType result = S.Context.getComplexType(FloatTy);
1062 
1063   // _Complex int -> _Complex float
1064   if (ConvertInt)
1065     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1066                                   CK_IntegralComplexToFloatingComplex);
1067 
1068   // float -> _Complex float
1069   if (ConvertFloat)
1070     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1071                                     CK_FloatingRealToComplex);
1072 
1073   return result;
1074 }
1075 
1076 /// \brief Handle arithmethic conversion with floating point types.  Helper
1077 /// function of UsualArithmeticConversions()
1078 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1079                                       ExprResult &RHS, QualType LHSType,
1080                                       QualType RHSType, bool IsCompAssign) {
1081   bool LHSFloat = LHSType->isRealFloatingType();
1082   bool RHSFloat = RHSType->isRealFloatingType();
1083 
1084   // If we have two real floating types, convert the smaller operand
1085   // to the bigger result.
1086   if (LHSFloat && RHSFloat) {
1087     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1088     if (order > 0) {
1089       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1090       return LHSType;
1091     }
1092 
1093     assert(order < 0 && "illegal float comparison");
1094     if (!IsCompAssign)
1095       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1096     return RHSType;
1097   }
1098 
1099   if (LHSFloat)
1100     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1101                                       /*convertFloat=*/!IsCompAssign,
1102                                       /*convertInt=*/ true);
1103   assert(RHSFloat);
1104   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1105                                     /*convertInt=*/ true,
1106                                     /*convertFloat=*/!IsCompAssign);
1107 }
1108 
1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1110 
1111 namespace {
1112 /// These helper callbacks are placed in an anonymous namespace to
1113 /// permit their use as function template parameters.
1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1115   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1116 }
1117 
1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1119   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1120                              CK_IntegralComplexCast);
1121 }
1122 }
1123 
1124 /// \brief Handle integer arithmetic conversions.  Helper function of
1125 /// UsualArithmeticConversions()
1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1128                                         ExprResult &RHS, QualType LHSType,
1129                                         QualType RHSType, bool IsCompAssign) {
1130   // The rules for this case are in C99 6.3.1.8
1131   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1132   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1133   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1134   if (LHSSigned == RHSSigned) {
1135     // Same signedness; use the higher-ranked type
1136     if (order >= 0) {
1137       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1138       return LHSType;
1139     } else if (!IsCompAssign)
1140       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1141     return RHSType;
1142   } else if (order != (LHSSigned ? 1 : -1)) {
1143     // The unsigned type has greater than or equal rank to the
1144     // signed type, so use the unsigned type
1145     if (RHSSigned) {
1146       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1147       return LHSType;
1148     } else if (!IsCompAssign)
1149       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1150     return RHSType;
1151   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1152     // The two types are different widths; if we are here, that
1153     // means the signed type is larger than the unsigned type, so
1154     // use the signed type.
1155     if (LHSSigned) {
1156       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1157       return LHSType;
1158     } else if (!IsCompAssign)
1159       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1160     return RHSType;
1161   } else {
1162     // The signed type is higher-ranked than the unsigned type,
1163     // but isn't actually any bigger (like unsigned int and long
1164     // on most 32-bit systems).  Use the unsigned type corresponding
1165     // to the signed type.
1166     QualType result =
1167       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1168     RHS = (*doRHSCast)(S, RHS.get(), result);
1169     if (!IsCompAssign)
1170       LHS = (*doLHSCast)(S, LHS.get(), result);
1171     return result;
1172   }
1173 }
1174 
1175 /// \brief Handle conversions with GCC complex int extension.  Helper function
1176 /// of UsualArithmeticConversions()
1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1178                                            ExprResult &RHS, QualType LHSType,
1179                                            QualType RHSType,
1180                                            bool IsCompAssign) {
1181   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1182   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1183 
1184   if (LHSComplexInt && RHSComplexInt) {
1185     QualType LHSEltType = LHSComplexInt->getElementType();
1186     QualType RHSEltType = RHSComplexInt->getElementType();
1187     QualType ScalarType =
1188       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1189         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1190 
1191     return S.Context.getComplexType(ScalarType);
1192   }
1193 
1194   if (LHSComplexInt) {
1195     QualType LHSEltType = LHSComplexInt->getElementType();
1196     QualType ScalarType =
1197       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1198         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1199     QualType ComplexType = S.Context.getComplexType(ScalarType);
1200     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1201                               CK_IntegralRealToComplex);
1202 
1203     return ComplexType;
1204   }
1205 
1206   assert(RHSComplexInt);
1207 
1208   QualType RHSEltType = RHSComplexInt->getElementType();
1209   QualType ScalarType =
1210     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1211       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1212   QualType ComplexType = S.Context.getComplexType(ScalarType);
1213 
1214   if (!IsCompAssign)
1215     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1216                               CK_IntegralRealToComplex);
1217   return ComplexType;
1218 }
1219 
1220 /// UsualArithmeticConversions - Performs various conversions that are common to
1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1222 /// routine returns the first non-arithmetic type found. The client is
1223 /// responsible for emitting appropriate error diagnostics.
1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1225                                           bool IsCompAssign) {
1226   if (!IsCompAssign) {
1227     LHS = UsualUnaryConversions(LHS.get());
1228     if (LHS.isInvalid())
1229       return QualType();
1230   }
1231 
1232   RHS = UsualUnaryConversions(RHS.get());
1233   if (RHS.isInvalid())
1234     return QualType();
1235 
1236   // For conversion purposes, we ignore any qualifiers.
1237   // For example, "const float" and "float" are equivalent.
1238   QualType LHSType =
1239     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1240   QualType RHSType =
1241     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1242 
1243   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1244   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1245     LHSType = AtomicLHS->getValueType();
1246 
1247   // If both types are identical, no conversion is needed.
1248   if (LHSType == RHSType)
1249     return LHSType;
1250 
1251   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1252   // The caller can deal with this (e.g. pointer + int).
1253   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1254     return QualType();
1255 
1256   // Apply unary and bitfield promotions to the LHS's type.
1257   QualType LHSUnpromotedType = LHSType;
1258   if (LHSType->isPromotableIntegerType())
1259     LHSType = Context.getPromotedIntegerType(LHSType);
1260   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1261   if (!LHSBitfieldPromoteTy.isNull())
1262     LHSType = LHSBitfieldPromoteTy;
1263   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1264     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1265 
1266   // If both types are identical, no conversion is needed.
1267   if (LHSType == RHSType)
1268     return LHSType;
1269 
1270   // At this point, we have two different arithmetic types.
1271 
1272   // Handle complex types first (C99 6.3.1.8p1).
1273   if (LHSType->isComplexType() || RHSType->isComplexType())
1274     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1275                                         IsCompAssign);
1276 
1277   // Now handle "real" floating types (i.e. float, double, long double).
1278   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1279     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1280                                  IsCompAssign);
1281 
1282   // Handle GCC complex int extension.
1283   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1284     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1285                                       IsCompAssign);
1286 
1287   // Finally, we have two differing integer types.
1288   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1289            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1290 }
1291 
1292 
1293 //===----------------------------------------------------------------------===//
1294 //  Semantic Analysis for various Expression Types
1295 //===----------------------------------------------------------------------===//
1296 
1297 
1298 ExprResult
1299 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1300                                 SourceLocation DefaultLoc,
1301                                 SourceLocation RParenLoc,
1302                                 Expr *ControllingExpr,
1303                                 ArrayRef<ParsedType> ArgTypes,
1304                                 ArrayRef<Expr *> ArgExprs) {
1305   unsigned NumAssocs = ArgTypes.size();
1306   assert(NumAssocs == ArgExprs.size());
1307 
1308   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1309   for (unsigned i = 0; i < NumAssocs; ++i) {
1310     if (ArgTypes[i])
1311       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1312     else
1313       Types[i] = nullptr;
1314   }
1315 
1316   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1317                                              ControllingExpr,
1318                                              llvm::makeArrayRef(Types, NumAssocs),
1319                                              ArgExprs);
1320   delete [] Types;
1321   return ER;
1322 }
1323 
1324 ExprResult
1325 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1326                                  SourceLocation DefaultLoc,
1327                                  SourceLocation RParenLoc,
1328                                  Expr *ControllingExpr,
1329                                  ArrayRef<TypeSourceInfo *> Types,
1330                                  ArrayRef<Expr *> Exprs) {
1331   unsigned NumAssocs = Types.size();
1332   assert(NumAssocs == Exprs.size());
1333   if (ControllingExpr->getType()->isPlaceholderType()) {
1334     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1335     if (result.isInvalid()) return ExprError();
1336     ControllingExpr = result.get();
1337   }
1338 
1339   bool TypeErrorFound = false,
1340        IsResultDependent = ControllingExpr->isTypeDependent(),
1341        ContainsUnexpandedParameterPack
1342          = ControllingExpr->containsUnexpandedParameterPack();
1343 
1344   for (unsigned i = 0; i < NumAssocs; ++i) {
1345     if (Exprs[i]->containsUnexpandedParameterPack())
1346       ContainsUnexpandedParameterPack = true;
1347 
1348     if (Types[i]) {
1349       if (Types[i]->getType()->containsUnexpandedParameterPack())
1350         ContainsUnexpandedParameterPack = true;
1351 
1352       if (Types[i]->getType()->isDependentType()) {
1353         IsResultDependent = true;
1354       } else {
1355         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1356         // complete object type other than a variably modified type."
1357         unsigned D = 0;
1358         if (Types[i]->getType()->isIncompleteType())
1359           D = diag::err_assoc_type_incomplete;
1360         else if (!Types[i]->getType()->isObjectType())
1361           D = diag::err_assoc_type_nonobject;
1362         else if (Types[i]->getType()->isVariablyModifiedType())
1363           D = diag::err_assoc_type_variably_modified;
1364 
1365         if (D != 0) {
1366           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1367             << Types[i]->getTypeLoc().getSourceRange()
1368             << Types[i]->getType();
1369           TypeErrorFound = true;
1370         }
1371 
1372         // C11 6.5.1.1p2 "No two generic associations in the same generic
1373         // selection shall specify compatible types."
1374         for (unsigned j = i+1; j < NumAssocs; ++j)
1375           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1376               Context.typesAreCompatible(Types[i]->getType(),
1377                                          Types[j]->getType())) {
1378             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1379                  diag::err_assoc_compatible_types)
1380               << Types[j]->getTypeLoc().getSourceRange()
1381               << Types[j]->getType()
1382               << Types[i]->getType();
1383             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1384                  diag::note_compat_assoc)
1385               << Types[i]->getTypeLoc().getSourceRange()
1386               << Types[i]->getType();
1387             TypeErrorFound = true;
1388           }
1389       }
1390     }
1391   }
1392   if (TypeErrorFound)
1393     return ExprError();
1394 
1395   // If we determined that the generic selection is result-dependent, don't
1396   // try to compute the result expression.
1397   if (IsResultDependent)
1398     return new (Context) GenericSelectionExpr(
1399         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1400         ContainsUnexpandedParameterPack);
1401 
1402   SmallVector<unsigned, 1> CompatIndices;
1403   unsigned DefaultIndex = -1U;
1404   for (unsigned i = 0; i < NumAssocs; ++i) {
1405     if (!Types[i])
1406       DefaultIndex = i;
1407     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1408                                         Types[i]->getType()))
1409       CompatIndices.push_back(i);
1410   }
1411 
1412   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1413   // type compatible with at most one of the types named in its generic
1414   // association list."
1415   if (CompatIndices.size() > 1) {
1416     // We strip parens here because the controlling expression is typically
1417     // parenthesized in macro definitions.
1418     ControllingExpr = ControllingExpr->IgnoreParens();
1419     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1420       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1421       << (unsigned) CompatIndices.size();
1422     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1423          E = CompatIndices.end(); I != E; ++I) {
1424       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1425            diag::note_compat_assoc)
1426         << Types[*I]->getTypeLoc().getSourceRange()
1427         << Types[*I]->getType();
1428     }
1429     return ExprError();
1430   }
1431 
1432   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1433   // its controlling expression shall have type compatible with exactly one of
1434   // the types named in its generic association list."
1435   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1436     // We strip parens here because the controlling expression is typically
1437     // parenthesized in macro definitions.
1438     ControllingExpr = ControllingExpr->IgnoreParens();
1439     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1440       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1441     return ExprError();
1442   }
1443 
1444   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1445   // type name that is compatible with the type of the controlling expression,
1446   // then the result expression of the generic selection is the expression
1447   // in that generic association. Otherwise, the result expression of the
1448   // generic selection is the expression in the default generic association."
1449   unsigned ResultIndex =
1450     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1451 
1452   return new (Context) GenericSelectionExpr(
1453       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1454       ContainsUnexpandedParameterPack, ResultIndex);
1455 }
1456 
1457 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1458 /// location of the token and the offset of the ud-suffix within it.
1459 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1460                                      unsigned Offset) {
1461   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1462                                         S.getLangOpts());
1463 }
1464 
1465 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1466 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1467 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1468                                                  IdentifierInfo *UDSuffix,
1469                                                  SourceLocation UDSuffixLoc,
1470                                                  ArrayRef<Expr*> Args,
1471                                                  SourceLocation LitEndLoc) {
1472   assert(Args.size() <= 2 && "too many arguments for literal operator");
1473 
1474   QualType ArgTy[2];
1475   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1476     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1477     if (ArgTy[ArgIdx]->isArrayType())
1478       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1479   }
1480 
1481   DeclarationName OpName =
1482     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1483   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1484   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1485 
1486   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1487   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1488                               /*AllowRaw*/false, /*AllowTemplate*/false,
1489                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1490     return ExprError();
1491 
1492   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1493 }
1494 
1495 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1496 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1497 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1498 /// multiple tokens.  However, the common case is that StringToks points to one
1499 /// string.
1500 ///
1501 ExprResult
1502 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1503                          Scope *UDLScope) {
1504   assert(NumStringToks && "Must have at least one string!");
1505 
1506   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1507   if (Literal.hadError)
1508     return ExprError();
1509 
1510   SmallVector<SourceLocation, 4> StringTokLocs;
1511   for (unsigned i = 0; i != NumStringToks; ++i)
1512     StringTokLocs.push_back(StringToks[i].getLocation());
1513 
1514   QualType CharTy = Context.CharTy;
1515   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1516   if (Literal.isWide()) {
1517     CharTy = Context.getWideCharType();
1518     Kind = StringLiteral::Wide;
1519   } else if (Literal.isUTF8()) {
1520     Kind = StringLiteral::UTF8;
1521   } else if (Literal.isUTF16()) {
1522     CharTy = Context.Char16Ty;
1523     Kind = StringLiteral::UTF16;
1524   } else if (Literal.isUTF32()) {
1525     CharTy = Context.Char32Ty;
1526     Kind = StringLiteral::UTF32;
1527   } else if (Literal.isPascal()) {
1528     CharTy = Context.UnsignedCharTy;
1529   }
1530 
1531   QualType CharTyConst = CharTy;
1532   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1533   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1534     CharTyConst.addConst();
1535 
1536   // Get an array type for the string, according to C99 6.4.5.  This includes
1537   // the nul terminator character as well as the string length for pascal
1538   // strings.
1539   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1540                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1541                                  ArrayType::Normal, 0);
1542 
1543   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1544   if (getLangOpts().OpenCL) {
1545     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1546   }
1547 
1548   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1549   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1550                                              Kind, Literal.Pascal, StrTy,
1551                                              &StringTokLocs[0],
1552                                              StringTokLocs.size());
1553   if (Literal.getUDSuffix().empty())
1554     return Lit;
1555 
1556   // We're building a user-defined literal.
1557   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1558   SourceLocation UDSuffixLoc =
1559     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1560                    Literal.getUDSuffixOffset());
1561 
1562   // Make sure we're allowed user-defined literals here.
1563   if (!UDLScope)
1564     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1565 
1566   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1567   //   operator "" X (str, len)
1568   QualType SizeType = Context.getSizeType();
1569 
1570   DeclarationName OpName =
1571     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1572   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1573   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1574 
1575   QualType ArgTy[] = {
1576     Context.getArrayDecayedType(StrTy), SizeType
1577   };
1578 
1579   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1580   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1581                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1582                                 /*AllowStringTemplate*/true)) {
1583 
1584   case LOLR_Cooked: {
1585     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1586     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1587                                                     StringTokLocs[0]);
1588     Expr *Args[] = { Lit, LenArg };
1589 
1590     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1591   }
1592 
1593   case LOLR_StringTemplate: {
1594     TemplateArgumentListInfo ExplicitArgs;
1595 
1596     unsigned CharBits = Context.getIntWidth(CharTy);
1597     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1598     llvm::APSInt Value(CharBits, CharIsUnsigned);
1599 
1600     TemplateArgument TypeArg(CharTy);
1601     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1602     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1603 
1604     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1605       Value = Lit->getCodeUnit(I);
1606       TemplateArgument Arg(Context, Value, CharTy);
1607       TemplateArgumentLocInfo ArgInfo;
1608       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1609     }
1610     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1611                                     &ExplicitArgs);
1612   }
1613   case LOLR_Raw:
1614   case LOLR_Template:
1615     llvm_unreachable("unexpected literal operator lookup result");
1616   case LOLR_Error:
1617     return ExprError();
1618   }
1619   llvm_unreachable("unexpected literal operator lookup result");
1620 }
1621 
1622 ExprResult
1623 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1624                        SourceLocation Loc,
1625                        const CXXScopeSpec *SS) {
1626   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1627   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1628 }
1629 
1630 /// BuildDeclRefExpr - Build an expression that references a
1631 /// declaration that does not require a closure capture.
1632 ExprResult
1633 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1634                        const DeclarationNameInfo &NameInfo,
1635                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1636                        const TemplateArgumentListInfo *TemplateArgs) {
1637   if (getLangOpts().CUDA)
1638     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1639       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1640         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1641                            CalleeTarget = IdentifyCUDATarget(Callee);
1642         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1643           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1644             << CalleeTarget << D->getIdentifier() << CallerTarget;
1645           Diag(D->getLocation(), diag::note_previous_decl)
1646             << D->getIdentifier();
1647           return ExprError();
1648         }
1649       }
1650 
1651   bool refersToEnclosingScope =
1652     (CurContext != D->getDeclContext() &&
1653      D->getDeclContext()->isFunctionOrMethod()) ||
1654     (isa<VarDecl>(D) &&
1655      cast<VarDecl>(D)->isInitCapture());
1656 
1657   DeclRefExpr *E;
1658   if (isa<VarTemplateSpecializationDecl>(D)) {
1659     VarTemplateSpecializationDecl *VarSpec =
1660         cast<VarTemplateSpecializationDecl>(D);
1661 
1662     E = DeclRefExpr::Create(
1663         Context,
1664         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1665         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1666         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1667   } else {
1668     assert(!TemplateArgs && "No template arguments for non-variable"
1669                             " template specialization references");
1670     E = DeclRefExpr::Create(
1671         Context,
1672         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1673         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1674   }
1675 
1676   MarkDeclRefReferenced(E);
1677 
1678   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1679       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1680       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1681       recordUseOfEvaluatedWeak(E);
1682 
1683   // Just in case we're building an illegal pointer-to-member.
1684   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1685   if (FD && FD->isBitField())
1686     E->setObjectKind(OK_BitField);
1687 
1688   return E;
1689 }
1690 
1691 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1692 /// possibly a list of template arguments.
1693 ///
1694 /// If this produces template arguments, it is permitted to call
1695 /// DecomposeTemplateName.
1696 ///
1697 /// This actually loses a lot of source location information for
1698 /// non-standard name kinds; we should consider preserving that in
1699 /// some way.
1700 void
1701 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1702                              TemplateArgumentListInfo &Buffer,
1703                              DeclarationNameInfo &NameInfo,
1704                              const TemplateArgumentListInfo *&TemplateArgs) {
1705   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1706     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1707     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1708 
1709     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1710                                        Id.TemplateId->NumArgs);
1711     translateTemplateArguments(TemplateArgsPtr, Buffer);
1712 
1713     TemplateName TName = Id.TemplateId->Template.get();
1714     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1715     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1716     TemplateArgs = &Buffer;
1717   } else {
1718     NameInfo = GetNameFromUnqualifiedId(Id);
1719     TemplateArgs = nullptr;
1720   }
1721 }
1722 
1723 /// Diagnose an empty lookup.
1724 ///
1725 /// \return false if new lookup candidates were found
1726 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1727                                CorrectionCandidateCallback &CCC,
1728                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1729                                ArrayRef<Expr *> Args) {
1730   DeclarationName Name = R.getLookupName();
1731 
1732   unsigned diagnostic = diag::err_undeclared_var_use;
1733   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1734   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1735       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1736       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1737     diagnostic = diag::err_undeclared_use;
1738     diagnostic_suggest = diag::err_undeclared_use_suggest;
1739   }
1740 
1741   // If the original lookup was an unqualified lookup, fake an
1742   // unqualified lookup.  This is useful when (for example) the
1743   // original lookup would not have found something because it was a
1744   // dependent name.
1745   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1746     ? CurContext : nullptr;
1747   while (DC) {
1748     if (isa<CXXRecordDecl>(DC)) {
1749       LookupQualifiedName(R, DC);
1750 
1751       if (!R.empty()) {
1752         // Don't give errors about ambiguities in this lookup.
1753         R.suppressDiagnostics();
1754 
1755         // During a default argument instantiation the CurContext points
1756         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1757         // function parameter list, hence add an explicit check.
1758         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1759                               ActiveTemplateInstantiations.back().Kind ==
1760             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1761         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1762         bool isInstance = CurMethod &&
1763                           CurMethod->isInstance() &&
1764                           DC == CurMethod->getParent() && !isDefaultArgument;
1765 
1766 
1767         // Give a code modification hint to insert 'this->'.
1768         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1769         // Actually quite difficult!
1770         if (getLangOpts().MSVCCompat)
1771           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1772         if (isInstance) {
1773           Diag(R.getNameLoc(), diagnostic) << Name
1774             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1775           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1776               CallsUndergoingInstantiation.back()->getCallee());
1777 
1778           CXXMethodDecl *DepMethod;
1779           if (CurMethod->isDependentContext())
1780             DepMethod = CurMethod;
1781           else if (CurMethod->getTemplatedKind() ==
1782               FunctionDecl::TK_FunctionTemplateSpecialization)
1783             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1784                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1785           else
1786             DepMethod = cast<CXXMethodDecl>(
1787                 CurMethod->getInstantiatedFromMemberFunction());
1788           assert(DepMethod && "No template pattern found");
1789 
1790           QualType DepThisType = DepMethod->getThisType(Context);
1791           CheckCXXThisCapture(R.getNameLoc());
1792           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1793                                      R.getNameLoc(), DepThisType, false);
1794           TemplateArgumentListInfo TList;
1795           if (ULE->hasExplicitTemplateArgs())
1796             ULE->copyTemplateArgumentsInto(TList);
1797 
1798           CXXScopeSpec SS;
1799           SS.Adopt(ULE->getQualifierLoc());
1800           CXXDependentScopeMemberExpr *DepExpr =
1801               CXXDependentScopeMemberExpr::Create(
1802                   Context, DepThis, DepThisType, true, SourceLocation(),
1803                   SS.getWithLocInContext(Context),
1804                   ULE->getTemplateKeywordLoc(), nullptr,
1805                   R.getLookupNameInfo(),
1806                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1807           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1808         } else {
1809           Diag(R.getNameLoc(), diagnostic) << Name;
1810         }
1811 
1812         // Do we really want to note all of these?
1813         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1814           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1815 
1816         // Return true if we are inside a default argument instantiation
1817         // and the found name refers to an instance member function, otherwise
1818         // the function calling DiagnoseEmptyLookup will try to create an
1819         // implicit member call and this is wrong for default argument.
1820         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1821           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1822           return true;
1823         }
1824 
1825         // Tell the callee to try to recover.
1826         return false;
1827       }
1828 
1829       R.clear();
1830     }
1831 
1832     // In Microsoft mode, if we are performing lookup from within a friend
1833     // function definition declared at class scope then we must set
1834     // DC to the lexical parent to be able to search into the parent
1835     // class.
1836     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1837         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1838         DC->getLexicalParent()->isRecord())
1839       DC = DC->getLexicalParent();
1840     else
1841       DC = DC->getParent();
1842   }
1843 
1844   // We didn't find anything, so try to correct for a typo.
1845   TypoCorrection Corrected;
1846   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1847                                     S, &SS, CCC, CTK_ErrorRecovery))) {
1848     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1849     bool DroppedSpecifier =
1850         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1851     R.setLookupName(Corrected.getCorrection());
1852 
1853     bool AcceptableWithRecovery = false;
1854     bool AcceptableWithoutRecovery = false;
1855     NamedDecl *ND = Corrected.getCorrectionDecl();
1856     if (ND) {
1857       if (Corrected.isOverloaded()) {
1858         OverloadCandidateSet OCS(R.getNameLoc(),
1859                                  OverloadCandidateSet::CSK_Normal);
1860         OverloadCandidateSet::iterator Best;
1861         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1862                                         CDEnd = Corrected.end();
1863              CD != CDEnd; ++CD) {
1864           if (FunctionTemplateDecl *FTD =
1865                    dyn_cast<FunctionTemplateDecl>(*CD))
1866             AddTemplateOverloadCandidate(
1867                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1868                 Args, OCS);
1869           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1870             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1871               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1872                                    Args, OCS);
1873         }
1874         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1875         case OR_Success:
1876           ND = Best->Function;
1877           Corrected.setCorrectionDecl(ND);
1878           break;
1879         default:
1880           // FIXME: Arbitrarily pick the first declaration for the note.
1881           Corrected.setCorrectionDecl(ND);
1882           break;
1883         }
1884       }
1885       R.addDecl(ND);
1886 
1887       AcceptableWithRecovery =
1888           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1889       // FIXME: If we ended up with a typo for a type name or
1890       // Objective-C class name, we're in trouble because the parser
1891       // is in the wrong place to recover. Suggest the typo
1892       // correction, but don't make it a fix-it since we're not going
1893       // to recover well anyway.
1894       AcceptableWithoutRecovery =
1895           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1896     } else {
1897       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1898       // because we aren't able to recover.
1899       AcceptableWithoutRecovery = true;
1900     }
1901 
1902     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1903       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1904                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1905                             ? diag::note_implicit_param_decl
1906                             : diag::note_previous_decl;
1907       if (SS.isEmpty())
1908         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1909                      PDiag(NoteID), AcceptableWithRecovery);
1910       else
1911         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1912                                   << Name << computeDeclContext(SS, false)
1913                                   << DroppedSpecifier << SS.getRange(),
1914                      PDiag(NoteID), AcceptableWithRecovery);
1915 
1916       // Tell the callee whether to try to recover.
1917       return !AcceptableWithRecovery;
1918     }
1919   }
1920   R.clear();
1921 
1922   // Emit a special diagnostic for failed member lookups.
1923   // FIXME: computing the declaration context might fail here (?)
1924   if (!SS.isEmpty()) {
1925     Diag(R.getNameLoc(), diag::err_no_member)
1926       << Name << computeDeclContext(SS, false)
1927       << SS.getRange();
1928     return true;
1929   }
1930 
1931   // Give up, we can't recover.
1932   Diag(R.getNameLoc(), diagnostic) << Name;
1933   return true;
1934 }
1935 
1936 /// In Microsoft mode, if we are inside a template class whose parent class has
1937 /// dependent base classes, and we can't resolve an unqualified identifier, then
1938 /// assume the identifier is a member of a dependent base class.  We can only
1939 /// recover successfully in static methods, instance methods, and other contexts
1940 /// where 'this' is available.  This doesn't precisely match MSVC's
1941 /// instantiation model, but it's close enough.
1942 static Expr *
1943 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1944                                DeclarationNameInfo &NameInfo,
1945                                SourceLocation TemplateKWLoc,
1946                                const TemplateArgumentListInfo *TemplateArgs) {
1947   // Only try to recover from lookup into dependent bases in static methods or
1948   // contexts where 'this' is available.
1949   QualType ThisType = S.getCurrentThisType();
1950   const CXXRecordDecl *RD = nullptr;
1951   if (!ThisType.isNull())
1952     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1953   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1954     RD = MD->getParent();
1955   if (!RD || !RD->hasAnyDependentBases())
1956     return nullptr;
1957 
1958   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1959   // is available, suggest inserting 'this->' as a fixit.
1960   SourceLocation Loc = NameInfo.getLoc();
1961   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1962   DB << NameInfo.getName() << RD;
1963 
1964   if (!ThisType.isNull()) {
1965     DB << FixItHint::CreateInsertion(Loc, "this->");
1966     return CXXDependentScopeMemberExpr::Create(
1967         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1968         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1969         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1970   }
1971 
1972   // Synthesize a fake NNS that points to the derived class.  This will
1973   // perform name lookup during template instantiation.
1974   CXXScopeSpec SS;
1975   auto *NNS =
1976       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1977   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1978   return DependentScopeDeclRefExpr::Create(
1979       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1980       TemplateArgs);
1981 }
1982 
1983 ExprResult Sema::ActOnIdExpression(Scope *S,
1984                                    CXXScopeSpec &SS,
1985                                    SourceLocation TemplateKWLoc,
1986                                    UnqualifiedId &Id,
1987                                    bool HasTrailingLParen,
1988                                    bool IsAddressOfOperand,
1989                                    CorrectionCandidateCallback *CCC,
1990                                    bool IsInlineAsmIdentifier) {
1991   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1992          "cannot be direct & operand and have a trailing lparen");
1993   if (SS.isInvalid())
1994     return ExprError();
1995 
1996   TemplateArgumentListInfo TemplateArgsBuffer;
1997 
1998   // Decompose the UnqualifiedId into the following data.
1999   DeclarationNameInfo NameInfo;
2000   const TemplateArgumentListInfo *TemplateArgs;
2001   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2002 
2003   DeclarationName Name = NameInfo.getName();
2004   IdentifierInfo *II = Name.getAsIdentifierInfo();
2005   SourceLocation NameLoc = NameInfo.getLoc();
2006 
2007   // C++ [temp.dep.expr]p3:
2008   //   An id-expression is type-dependent if it contains:
2009   //     -- an identifier that was declared with a dependent type,
2010   //        (note: handled after lookup)
2011   //     -- a template-id that is dependent,
2012   //        (note: handled in BuildTemplateIdExpr)
2013   //     -- a conversion-function-id that specifies a dependent type,
2014   //     -- a nested-name-specifier that contains a class-name that
2015   //        names a dependent type.
2016   // Determine whether this is a member of an unknown specialization;
2017   // we need to handle these differently.
2018   bool DependentID = false;
2019   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2020       Name.getCXXNameType()->isDependentType()) {
2021     DependentID = true;
2022   } else if (SS.isSet()) {
2023     if (DeclContext *DC = computeDeclContext(SS, false)) {
2024       if (RequireCompleteDeclContext(SS, DC))
2025         return ExprError();
2026     } else {
2027       DependentID = true;
2028     }
2029   }
2030 
2031   if (DependentID)
2032     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2033                                       IsAddressOfOperand, TemplateArgs);
2034 
2035   // Perform the required lookup.
2036   LookupResult R(*this, NameInfo,
2037                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2038                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2039   if (TemplateArgs) {
2040     // Lookup the template name again to correctly establish the context in
2041     // which it was found. This is really unfortunate as we already did the
2042     // lookup to determine that it was a template name in the first place. If
2043     // this becomes a performance hit, we can work harder to preserve those
2044     // results until we get here but it's likely not worth it.
2045     bool MemberOfUnknownSpecialization;
2046     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2047                        MemberOfUnknownSpecialization);
2048 
2049     if (MemberOfUnknownSpecialization ||
2050         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2051       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2052                                         IsAddressOfOperand, TemplateArgs);
2053   } else {
2054     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2055     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2056 
2057     // If the result might be in a dependent base class, this is a dependent
2058     // id-expression.
2059     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2060       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2061                                         IsAddressOfOperand, TemplateArgs);
2062 
2063     // If this reference is in an Objective-C method, then we need to do
2064     // some special Objective-C lookup, too.
2065     if (IvarLookupFollowUp) {
2066       ExprResult E(LookupInObjCMethod(R, S, II, true));
2067       if (E.isInvalid())
2068         return ExprError();
2069 
2070       if (Expr *Ex = E.getAs<Expr>())
2071         return Ex;
2072     }
2073   }
2074 
2075   if (R.isAmbiguous())
2076     return ExprError();
2077 
2078   // This could be an implicitly declared function reference (legal in C90,
2079   // extension in C99, forbidden in C++).
2080   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2081     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2082     if (D) R.addDecl(D);
2083   }
2084 
2085   // Determine whether this name might be a candidate for
2086   // argument-dependent lookup.
2087   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2088 
2089   if (R.empty() && !ADL) {
2090     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2091       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2092                                                    TemplateKWLoc, TemplateArgs))
2093         return E;
2094     }
2095 
2096     // Don't diagnose an empty lookup for inline assmebly.
2097     if (IsInlineAsmIdentifier)
2098       return ExprError();
2099 
2100     // If this name wasn't predeclared and if this is not a function
2101     // call, diagnose the problem.
2102     CorrectionCandidateCallback DefaultValidator;
2103     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2104       return ExprError();
2105 
2106     assert(!R.empty() &&
2107            "DiagnoseEmptyLookup returned false but added no results");
2108 
2109     // If we found an Objective-C instance variable, let
2110     // LookupInObjCMethod build the appropriate expression to
2111     // reference the ivar.
2112     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2113       R.clear();
2114       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2115       // In a hopelessly buggy code, Objective-C instance variable
2116       // lookup fails and no expression will be built to reference it.
2117       if (!E.isInvalid() && !E.get())
2118         return ExprError();
2119       return E;
2120     }
2121   }
2122 
2123   // This is guaranteed from this point on.
2124   assert(!R.empty() || ADL);
2125 
2126   // Check whether this might be a C++ implicit instance member access.
2127   // C++ [class.mfct.non-static]p3:
2128   //   When an id-expression that is not part of a class member access
2129   //   syntax and not used to form a pointer to member is used in the
2130   //   body of a non-static member function of class X, if name lookup
2131   //   resolves the name in the id-expression to a non-static non-type
2132   //   member of some class C, the id-expression is transformed into a
2133   //   class member access expression using (*this) as the
2134   //   postfix-expression to the left of the . operator.
2135   //
2136   // But we don't actually need to do this for '&' operands if R
2137   // resolved to a function or overloaded function set, because the
2138   // expression is ill-formed if it actually works out to be a
2139   // non-static member function:
2140   //
2141   // C++ [expr.ref]p4:
2142   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2143   //   [t]he expression can be used only as the left-hand operand of a
2144   //   member function call.
2145   //
2146   // There are other safeguards against such uses, but it's important
2147   // to get this right here so that we don't end up making a
2148   // spuriously dependent expression if we're inside a dependent
2149   // instance method.
2150   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2151     bool MightBeImplicitMember;
2152     if (!IsAddressOfOperand)
2153       MightBeImplicitMember = true;
2154     else if (!SS.isEmpty())
2155       MightBeImplicitMember = false;
2156     else if (R.isOverloadedResult())
2157       MightBeImplicitMember = false;
2158     else if (R.isUnresolvableResult())
2159       MightBeImplicitMember = true;
2160     else
2161       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2162                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2163                               isa<MSPropertyDecl>(R.getFoundDecl());
2164 
2165     if (MightBeImplicitMember)
2166       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2167                                              R, TemplateArgs);
2168   }
2169 
2170   if (TemplateArgs || TemplateKWLoc.isValid()) {
2171 
2172     // In C++1y, if this is a variable template id, then check it
2173     // in BuildTemplateIdExpr().
2174     // The single lookup result must be a variable template declaration.
2175     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2176         Id.TemplateId->Kind == TNK_Var_template) {
2177       assert(R.getAsSingle<VarTemplateDecl>() &&
2178              "There should only be one declaration found.");
2179     }
2180 
2181     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2182   }
2183 
2184   return BuildDeclarationNameExpr(SS, R, ADL);
2185 }
2186 
2187 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2188 /// declaration name, generally during template instantiation.
2189 /// There's a large number of things which don't need to be done along
2190 /// this path.
2191 ExprResult
2192 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2193                                         const DeclarationNameInfo &NameInfo,
2194                                         bool IsAddressOfOperand,
2195                                         TypeSourceInfo **RecoveryTSI) {
2196   DeclContext *DC = computeDeclContext(SS, false);
2197   if (!DC)
2198     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2199                                      NameInfo, /*TemplateArgs=*/nullptr);
2200 
2201   if (RequireCompleteDeclContext(SS, DC))
2202     return ExprError();
2203 
2204   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2205   LookupQualifiedName(R, DC);
2206 
2207   if (R.isAmbiguous())
2208     return ExprError();
2209 
2210   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2211     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2212                                      NameInfo, /*TemplateArgs=*/nullptr);
2213 
2214   if (R.empty()) {
2215     Diag(NameInfo.getLoc(), diag::err_no_member)
2216       << NameInfo.getName() << DC << SS.getRange();
2217     return ExprError();
2218   }
2219 
2220   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2221     // Diagnose a missing typename if this resolved unambiguously to a type in
2222     // a dependent context.  If we can recover with a type, downgrade this to
2223     // a warning in Microsoft compatibility mode.
2224     unsigned DiagID = diag::err_typename_missing;
2225     if (RecoveryTSI && getLangOpts().MSVCCompat)
2226       DiagID = diag::ext_typename_missing;
2227     SourceLocation Loc = SS.getBeginLoc();
2228     auto D = Diag(Loc, DiagID);
2229     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2230       << SourceRange(Loc, NameInfo.getEndLoc());
2231 
2232     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2233     // context.
2234     if (!RecoveryTSI)
2235       return ExprError();
2236 
2237     // Only issue the fixit if we're prepared to recover.
2238     D << FixItHint::CreateInsertion(Loc, "typename ");
2239 
2240     // Recover by pretending this was an elaborated type.
2241     QualType Ty = Context.getTypeDeclType(TD);
2242     TypeLocBuilder TLB;
2243     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2244 
2245     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2246     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2247     QTL.setElaboratedKeywordLoc(SourceLocation());
2248     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2249 
2250     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2251 
2252     return ExprEmpty();
2253   }
2254 
2255   // Defend against this resolving to an implicit member access. We usually
2256   // won't get here if this might be a legitimate a class member (we end up in
2257   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2258   // a pointer-to-member or in an unevaluated context in C++11.
2259   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2260     return BuildPossibleImplicitMemberExpr(SS,
2261                                            /*TemplateKWLoc=*/SourceLocation(),
2262                                            R, /*TemplateArgs=*/nullptr);
2263 
2264   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2265 }
2266 
2267 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2268 /// detected that we're currently inside an ObjC method.  Perform some
2269 /// additional lookup.
2270 ///
2271 /// Ideally, most of this would be done by lookup, but there's
2272 /// actually quite a lot of extra work involved.
2273 ///
2274 /// Returns a null sentinel to indicate trivial success.
2275 ExprResult
2276 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2277                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2278   SourceLocation Loc = Lookup.getNameLoc();
2279   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2280 
2281   // Check for error condition which is already reported.
2282   if (!CurMethod)
2283     return ExprError();
2284 
2285   // There are two cases to handle here.  1) scoped lookup could have failed,
2286   // in which case we should look for an ivar.  2) scoped lookup could have
2287   // found a decl, but that decl is outside the current instance method (i.e.
2288   // a global variable).  In these two cases, we do a lookup for an ivar with
2289   // this name, if the lookup sucedes, we replace it our current decl.
2290 
2291   // If we're in a class method, we don't normally want to look for
2292   // ivars.  But if we don't find anything else, and there's an
2293   // ivar, that's an error.
2294   bool IsClassMethod = CurMethod->isClassMethod();
2295 
2296   bool LookForIvars;
2297   if (Lookup.empty())
2298     LookForIvars = true;
2299   else if (IsClassMethod)
2300     LookForIvars = false;
2301   else
2302     LookForIvars = (Lookup.isSingleResult() &&
2303                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2304   ObjCInterfaceDecl *IFace = nullptr;
2305   if (LookForIvars) {
2306     IFace = CurMethod->getClassInterface();
2307     ObjCInterfaceDecl *ClassDeclared;
2308     ObjCIvarDecl *IV = nullptr;
2309     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2310       // Diagnose using an ivar in a class method.
2311       if (IsClassMethod)
2312         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2313                          << IV->getDeclName());
2314 
2315       // If we're referencing an invalid decl, just return this as a silent
2316       // error node.  The error diagnostic was already emitted on the decl.
2317       if (IV->isInvalidDecl())
2318         return ExprError();
2319 
2320       // Check if referencing a field with __attribute__((deprecated)).
2321       if (DiagnoseUseOfDecl(IV, Loc))
2322         return ExprError();
2323 
2324       // Diagnose the use of an ivar outside of the declaring class.
2325       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2326           !declaresSameEntity(ClassDeclared, IFace) &&
2327           !getLangOpts().DebuggerSupport)
2328         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2329 
2330       // FIXME: This should use a new expr for a direct reference, don't
2331       // turn this into Self->ivar, just return a BareIVarExpr or something.
2332       IdentifierInfo &II = Context.Idents.get("self");
2333       UnqualifiedId SelfName;
2334       SelfName.setIdentifier(&II, SourceLocation());
2335       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2336       CXXScopeSpec SelfScopeSpec;
2337       SourceLocation TemplateKWLoc;
2338       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2339                                               SelfName, false, false);
2340       if (SelfExpr.isInvalid())
2341         return ExprError();
2342 
2343       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2344       if (SelfExpr.isInvalid())
2345         return ExprError();
2346 
2347       MarkAnyDeclReferenced(Loc, IV, true);
2348 
2349       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2350       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2351           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2352         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2353 
2354       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2355                                                               Loc, IV->getLocation(),
2356                                                               SelfExpr.get(),
2357                                                               true, true);
2358 
2359       if (getLangOpts().ObjCAutoRefCount) {
2360         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2361           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2362             recordUseOfEvaluatedWeak(Result);
2363         }
2364         if (CurContext->isClosure())
2365           Diag(Loc, diag::warn_implicitly_retains_self)
2366             << FixItHint::CreateInsertion(Loc, "self->");
2367       }
2368 
2369       return Result;
2370     }
2371   } else if (CurMethod->isInstanceMethod()) {
2372     // We should warn if a local variable hides an ivar.
2373     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2374       ObjCInterfaceDecl *ClassDeclared;
2375       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2376         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2377             declaresSameEntity(IFace, ClassDeclared))
2378           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2379       }
2380     }
2381   } else if (Lookup.isSingleResult() &&
2382              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2383     // If accessing a stand-alone ivar in a class method, this is an error.
2384     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2385       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2386                        << IV->getDeclName());
2387   }
2388 
2389   if (Lookup.empty() && II && AllowBuiltinCreation) {
2390     // FIXME. Consolidate this with similar code in LookupName.
2391     if (unsigned BuiltinID = II->getBuiltinID()) {
2392       if (!(getLangOpts().CPlusPlus &&
2393             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2394         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2395                                            S, Lookup.isForRedeclaration(),
2396                                            Lookup.getNameLoc());
2397         if (D) Lookup.addDecl(D);
2398       }
2399     }
2400   }
2401   // Sentinel value saying that we didn't do anything special.
2402   return ExprResult((Expr *)nullptr);
2403 }
2404 
2405 /// \brief Cast a base object to a member's actual type.
2406 ///
2407 /// Logically this happens in three phases:
2408 ///
2409 /// * First we cast from the base type to the naming class.
2410 ///   The naming class is the class into which we were looking
2411 ///   when we found the member;  it's the qualifier type if a
2412 ///   qualifier was provided, and otherwise it's the base type.
2413 ///
2414 /// * Next we cast from the naming class to the declaring class.
2415 ///   If the member we found was brought into a class's scope by
2416 ///   a using declaration, this is that class;  otherwise it's
2417 ///   the class declaring the member.
2418 ///
2419 /// * Finally we cast from the declaring class to the "true"
2420 ///   declaring class of the member.  This conversion does not
2421 ///   obey access control.
2422 ExprResult
2423 Sema::PerformObjectMemberConversion(Expr *From,
2424                                     NestedNameSpecifier *Qualifier,
2425                                     NamedDecl *FoundDecl,
2426                                     NamedDecl *Member) {
2427   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2428   if (!RD)
2429     return From;
2430 
2431   QualType DestRecordType;
2432   QualType DestType;
2433   QualType FromRecordType;
2434   QualType FromType = From->getType();
2435   bool PointerConversions = false;
2436   if (isa<FieldDecl>(Member)) {
2437     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2438 
2439     if (FromType->getAs<PointerType>()) {
2440       DestType = Context.getPointerType(DestRecordType);
2441       FromRecordType = FromType->getPointeeType();
2442       PointerConversions = true;
2443     } else {
2444       DestType = DestRecordType;
2445       FromRecordType = FromType;
2446     }
2447   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2448     if (Method->isStatic())
2449       return From;
2450 
2451     DestType = Method->getThisType(Context);
2452     DestRecordType = DestType->getPointeeType();
2453 
2454     if (FromType->getAs<PointerType>()) {
2455       FromRecordType = FromType->getPointeeType();
2456       PointerConversions = true;
2457     } else {
2458       FromRecordType = FromType;
2459       DestType = DestRecordType;
2460     }
2461   } else {
2462     // No conversion necessary.
2463     return From;
2464   }
2465 
2466   if (DestType->isDependentType() || FromType->isDependentType())
2467     return From;
2468 
2469   // If the unqualified types are the same, no conversion is necessary.
2470   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2471     return From;
2472 
2473   SourceRange FromRange = From->getSourceRange();
2474   SourceLocation FromLoc = FromRange.getBegin();
2475 
2476   ExprValueKind VK = From->getValueKind();
2477 
2478   // C++ [class.member.lookup]p8:
2479   //   [...] Ambiguities can often be resolved by qualifying a name with its
2480   //   class name.
2481   //
2482   // If the member was a qualified name and the qualified referred to a
2483   // specific base subobject type, we'll cast to that intermediate type
2484   // first and then to the object in which the member is declared. That allows
2485   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2486   //
2487   //   class Base { public: int x; };
2488   //   class Derived1 : public Base { };
2489   //   class Derived2 : public Base { };
2490   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2491   //
2492   //   void VeryDerived::f() {
2493   //     x = 17; // error: ambiguous base subobjects
2494   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2495   //   }
2496   if (Qualifier && Qualifier->getAsType()) {
2497     QualType QType = QualType(Qualifier->getAsType(), 0);
2498     assert(QType->isRecordType() && "lookup done with non-record type");
2499 
2500     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2501 
2502     // In C++98, the qualifier type doesn't actually have to be a base
2503     // type of the object type, in which case we just ignore it.
2504     // Otherwise build the appropriate casts.
2505     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2506       CXXCastPath BasePath;
2507       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2508                                        FromLoc, FromRange, &BasePath))
2509         return ExprError();
2510 
2511       if (PointerConversions)
2512         QType = Context.getPointerType(QType);
2513       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2514                                VK, &BasePath).get();
2515 
2516       FromType = QType;
2517       FromRecordType = QRecordType;
2518 
2519       // If the qualifier type was the same as the destination type,
2520       // we're done.
2521       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2522         return From;
2523     }
2524   }
2525 
2526   bool IgnoreAccess = false;
2527 
2528   // If we actually found the member through a using declaration, cast
2529   // down to the using declaration's type.
2530   //
2531   // Pointer equality is fine here because only one declaration of a
2532   // class ever has member declarations.
2533   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2534     assert(isa<UsingShadowDecl>(FoundDecl));
2535     QualType URecordType = Context.getTypeDeclType(
2536                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2537 
2538     // We only need to do this if the naming-class to declaring-class
2539     // conversion is non-trivial.
2540     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2541       assert(IsDerivedFrom(FromRecordType, URecordType));
2542       CXXCastPath BasePath;
2543       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2544                                        FromLoc, FromRange, &BasePath))
2545         return ExprError();
2546 
2547       QualType UType = URecordType;
2548       if (PointerConversions)
2549         UType = Context.getPointerType(UType);
2550       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2551                                VK, &BasePath).get();
2552       FromType = UType;
2553       FromRecordType = URecordType;
2554     }
2555 
2556     // We don't do access control for the conversion from the
2557     // declaring class to the true declaring class.
2558     IgnoreAccess = true;
2559   }
2560 
2561   CXXCastPath BasePath;
2562   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2563                                    FromLoc, FromRange, &BasePath,
2564                                    IgnoreAccess))
2565     return ExprError();
2566 
2567   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2568                            VK, &BasePath);
2569 }
2570 
2571 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2572                                       const LookupResult &R,
2573                                       bool HasTrailingLParen) {
2574   // Only when used directly as the postfix-expression of a call.
2575   if (!HasTrailingLParen)
2576     return false;
2577 
2578   // Never if a scope specifier was provided.
2579   if (SS.isSet())
2580     return false;
2581 
2582   // Only in C++ or ObjC++.
2583   if (!getLangOpts().CPlusPlus)
2584     return false;
2585 
2586   // Turn off ADL when we find certain kinds of declarations during
2587   // normal lookup:
2588   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2589     NamedDecl *D = *I;
2590 
2591     // C++0x [basic.lookup.argdep]p3:
2592     //     -- a declaration of a class member
2593     // Since using decls preserve this property, we check this on the
2594     // original decl.
2595     if (D->isCXXClassMember())
2596       return false;
2597 
2598     // C++0x [basic.lookup.argdep]p3:
2599     //     -- a block-scope function declaration that is not a
2600     //        using-declaration
2601     // NOTE: we also trigger this for function templates (in fact, we
2602     // don't check the decl type at all, since all other decl types
2603     // turn off ADL anyway).
2604     if (isa<UsingShadowDecl>(D))
2605       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2606     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2607       return false;
2608 
2609     // C++0x [basic.lookup.argdep]p3:
2610     //     -- a declaration that is neither a function or a function
2611     //        template
2612     // And also for builtin functions.
2613     if (isa<FunctionDecl>(D)) {
2614       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2615 
2616       // But also builtin functions.
2617       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2618         return false;
2619     } else if (!isa<FunctionTemplateDecl>(D))
2620       return false;
2621   }
2622 
2623   return true;
2624 }
2625 
2626 
2627 /// Diagnoses obvious problems with the use of the given declaration
2628 /// as an expression.  This is only actually called for lookups that
2629 /// were not overloaded, and it doesn't promise that the declaration
2630 /// will in fact be used.
2631 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2632   if (isa<TypedefNameDecl>(D)) {
2633     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2634     return true;
2635   }
2636 
2637   if (isa<ObjCInterfaceDecl>(D)) {
2638     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2639     return true;
2640   }
2641 
2642   if (isa<NamespaceDecl>(D)) {
2643     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2644     return true;
2645   }
2646 
2647   return false;
2648 }
2649 
2650 ExprResult
2651 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2652                                LookupResult &R,
2653                                bool NeedsADL) {
2654   // If this is a single, fully-resolved result and we don't need ADL,
2655   // just build an ordinary singleton decl ref.
2656   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2657     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2658                                     R.getRepresentativeDecl());
2659 
2660   // We only need to check the declaration if there's exactly one
2661   // result, because in the overloaded case the results can only be
2662   // functions and function templates.
2663   if (R.isSingleResult() &&
2664       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2665     return ExprError();
2666 
2667   // Otherwise, just build an unresolved lookup expression.  Suppress
2668   // any lookup-related diagnostics; we'll hash these out later, when
2669   // we've picked a target.
2670   R.suppressDiagnostics();
2671 
2672   UnresolvedLookupExpr *ULE
2673     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2674                                    SS.getWithLocInContext(Context),
2675                                    R.getLookupNameInfo(),
2676                                    NeedsADL, R.isOverloadedResult(),
2677                                    R.begin(), R.end());
2678 
2679   return ULE;
2680 }
2681 
2682 /// \brief Complete semantic analysis for a reference to the given declaration.
2683 ExprResult Sema::BuildDeclarationNameExpr(
2684     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2685     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2686   assert(D && "Cannot refer to a NULL declaration");
2687   assert(!isa<FunctionTemplateDecl>(D) &&
2688          "Cannot refer unambiguously to a function template");
2689 
2690   SourceLocation Loc = NameInfo.getLoc();
2691   if (CheckDeclInExpr(*this, Loc, D))
2692     return ExprError();
2693 
2694   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2695     // Specifically diagnose references to class templates that are missing
2696     // a template argument list.
2697     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2698                                            << Template << SS.getRange();
2699     Diag(Template->getLocation(), diag::note_template_decl_here);
2700     return ExprError();
2701   }
2702 
2703   // Make sure that we're referring to a value.
2704   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2705   if (!VD) {
2706     Diag(Loc, diag::err_ref_non_value)
2707       << D << SS.getRange();
2708     Diag(D->getLocation(), diag::note_declared_at);
2709     return ExprError();
2710   }
2711 
2712   // Check whether this declaration can be used. Note that we suppress
2713   // this check when we're going to perform argument-dependent lookup
2714   // on this function name, because this might not be the function
2715   // that overload resolution actually selects.
2716   if (DiagnoseUseOfDecl(VD, Loc))
2717     return ExprError();
2718 
2719   // Only create DeclRefExpr's for valid Decl's.
2720   if (VD->isInvalidDecl())
2721     return ExprError();
2722 
2723   // Handle members of anonymous structs and unions.  If we got here,
2724   // and the reference is to a class member indirect field, then this
2725   // must be the subject of a pointer-to-member expression.
2726   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2727     if (!indirectField->isCXXClassMember())
2728       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2729                                                       indirectField);
2730 
2731   {
2732     QualType type = VD->getType();
2733     ExprValueKind valueKind = VK_RValue;
2734 
2735     switch (D->getKind()) {
2736     // Ignore all the non-ValueDecl kinds.
2737 #define ABSTRACT_DECL(kind)
2738 #define VALUE(type, base)
2739 #define DECL(type, base) \
2740     case Decl::type:
2741 #include "clang/AST/DeclNodes.inc"
2742       llvm_unreachable("invalid value decl kind");
2743 
2744     // These shouldn't make it here.
2745     case Decl::ObjCAtDefsField:
2746     case Decl::ObjCIvar:
2747       llvm_unreachable("forming non-member reference to ivar?");
2748 
2749     // Enum constants are always r-values and never references.
2750     // Unresolved using declarations are dependent.
2751     case Decl::EnumConstant:
2752     case Decl::UnresolvedUsingValue:
2753       valueKind = VK_RValue;
2754       break;
2755 
2756     // Fields and indirect fields that got here must be for
2757     // pointer-to-member expressions; we just call them l-values for
2758     // internal consistency, because this subexpression doesn't really
2759     // exist in the high-level semantics.
2760     case Decl::Field:
2761     case Decl::IndirectField:
2762       assert(getLangOpts().CPlusPlus &&
2763              "building reference to field in C?");
2764 
2765       // These can't have reference type in well-formed programs, but
2766       // for internal consistency we do this anyway.
2767       type = type.getNonReferenceType();
2768       valueKind = VK_LValue;
2769       break;
2770 
2771     // Non-type template parameters are either l-values or r-values
2772     // depending on the type.
2773     case Decl::NonTypeTemplateParm: {
2774       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2775         type = reftype->getPointeeType();
2776         valueKind = VK_LValue; // even if the parameter is an r-value reference
2777         break;
2778       }
2779 
2780       // For non-references, we need to strip qualifiers just in case
2781       // the template parameter was declared as 'const int' or whatever.
2782       valueKind = VK_RValue;
2783       type = type.getUnqualifiedType();
2784       break;
2785     }
2786 
2787     case Decl::Var:
2788     case Decl::VarTemplateSpecialization:
2789     case Decl::VarTemplatePartialSpecialization:
2790       // In C, "extern void blah;" is valid and is an r-value.
2791       if (!getLangOpts().CPlusPlus &&
2792           !type.hasQualifiers() &&
2793           type->isVoidType()) {
2794         valueKind = VK_RValue;
2795         break;
2796       }
2797       // fallthrough
2798 
2799     case Decl::ImplicitParam:
2800     case Decl::ParmVar: {
2801       // These are always l-values.
2802       valueKind = VK_LValue;
2803       type = type.getNonReferenceType();
2804 
2805       // FIXME: Does the addition of const really only apply in
2806       // potentially-evaluated contexts? Since the variable isn't actually
2807       // captured in an unevaluated context, it seems that the answer is no.
2808       if (!isUnevaluatedContext()) {
2809         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2810         if (!CapturedType.isNull())
2811           type = CapturedType;
2812       }
2813 
2814       break;
2815     }
2816 
2817     case Decl::Function: {
2818       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2819         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2820           type = Context.BuiltinFnTy;
2821           valueKind = VK_RValue;
2822           break;
2823         }
2824       }
2825 
2826       const FunctionType *fty = type->castAs<FunctionType>();
2827 
2828       // If we're referring to a function with an __unknown_anytype
2829       // result type, make the entire expression __unknown_anytype.
2830       if (fty->getReturnType() == Context.UnknownAnyTy) {
2831         type = Context.UnknownAnyTy;
2832         valueKind = VK_RValue;
2833         break;
2834       }
2835 
2836       // Functions are l-values in C++.
2837       if (getLangOpts().CPlusPlus) {
2838         valueKind = VK_LValue;
2839         break;
2840       }
2841 
2842       // C99 DR 316 says that, if a function type comes from a
2843       // function definition (without a prototype), that type is only
2844       // used for checking compatibility. Therefore, when referencing
2845       // the function, we pretend that we don't have the full function
2846       // type.
2847       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2848           isa<FunctionProtoType>(fty))
2849         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2850                                               fty->getExtInfo());
2851 
2852       // Functions are r-values in C.
2853       valueKind = VK_RValue;
2854       break;
2855     }
2856 
2857     case Decl::MSProperty:
2858       valueKind = VK_LValue;
2859       break;
2860 
2861     case Decl::CXXMethod:
2862       // If we're referring to a method with an __unknown_anytype
2863       // result type, make the entire expression __unknown_anytype.
2864       // This should only be possible with a type written directly.
2865       if (const FunctionProtoType *proto
2866             = dyn_cast<FunctionProtoType>(VD->getType()))
2867         if (proto->getReturnType() == Context.UnknownAnyTy) {
2868           type = Context.UnknownAnyTy;
2869           valueKind = VK_RValue;
2870           break;
2871         }
2872 
2873       // C++ methods are l-values if static, r-values if non-static.
2874       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2875         valueKind = VK_LValue;
2876         break;
2877       }
2878       // fallthrough
2879 
2880     case Decl::CXXConversion:
2881     case Decl::CXXDestructor:
2882     case Decl::CXXConstructor:
2883       valueKind = VK_RValue;
2884       break;
2885     }
2886 
2887     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2888                             TemplateArgs);
2889   }
2890 }
2891 
2892 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2893                                      PredefinedExpr::IdentType IT) {
2894   // Pick the current block, lambda, captured statement or function.
2895   Decl *currentDecl = nullptr;
2896   if (const BlockScopeInfo *BSI = getCurBlock())
2897     currentDecl = BSI->TheDecl;
2898   else if (const LambdaScopeInfo *LSI = getCurLambda())
2899     currentDecl = LSI->CallOperator;
2900   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2901     currentDecl = CSI->TheCapturedDecl;
2902   else
2903     currentDecl = getCurFunctionOrMethodDecl();
2904 
2905   if (!currentDecl) {
2906     Diag(Loc, diag::ext_predef_outside_function);
2907     currentDecl = Context.getTranslationUnitDecl();
2908   }
2909 
2910   QualType ResTy;
2911   if (cast<DeclContext>(currentDecl)->isDependentContext())
2912     ResTy = Context.DependentTy;
2913   else {
2914     // Pre-defined identifiers are of type char[x], where x is the length of
2915     // the string.
2916     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2917 
2918     llvm::APInt LengthI(32, Length + 1);
2919     if (IT == PredefinedExpr::LFunction)
2920       ResTy = Context.WideCharTy.withConst();
2921     else
2922       ResTy = Context.CharTy.withConst();
2923     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2924   }
2925 
2926   return new (Context) PredefinedExpr(Loc, ResTy, IT);
2927 }
2928 
2929 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2930   PredefinedExpr::IdentType IT;
2931 
2932   switch (Kind) {
2933   default: llvm_unreachable("Unknown simple primary expr!");
2934   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2935   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2936   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2937   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2938   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2939   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2940   }
2941 
2942   return BuildPredefinedExpr(Loc, IT);
2943 }
2944 
2945 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2946   SmallString<16> CharBuffer;
2947   bool Invalid = false;
2948   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2949   if (Invalid)
2950     return ExprError();
2951 
2952   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2953                             PP, Tok.getKind());
2954   if (Literal.hadError())
2955     return ExprError();
2956 
2957   QualType Ty;
2958   if (Literal.isWide())
2959     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2960   else if (Literal.isUTF16())
2961     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2962   else if (Literal.isUTF32())
2963     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2964   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2965     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2966   else
2967     Ty = Context.CharTy;  // 'x' -> char in C++
2968 
2969   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2970   if (Literal.isWide())
2971     Kind = CharacterLiteral::Wide;
2972   else if (Literal.isUTF16())
2973     Kind = CharacterLiteral::UTF16;
2974   else if (Literal.isUTF32())
2975     Kind = CharacterLiteral::UTF32;
2976 
2977   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2978                                              Tok.getLocation());
2979 
2980   if (Literal.getUDSuffix().empty())
2981     return Lit;
2982 
2983   // We're building a user-defined literal.
2984   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2985   SourceLocation UDSuffixLoc =
2986     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2987 
2988   // Make sure we're allowed user-defined literals here.
2989   if (!UDLScope)
2990     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2991 
2992   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2993   //   operator "" X (ch)
2994   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2995                                         Lit, Tok.getLocation());
2996 }
2997 
2998 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2999   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3000   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3001                                 Context.IntTy, Loc);
3002 }
3003 
3004 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3005                                   QualType Ty, SourceLocation Loc) {
3006   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3007 
3008   using llvm::APFloat;
3009   APFloat Val(Format);
3010 
3011   APFloat::opStatus result = Literal.GetFloatValue(Val);
3012 
3013   // Overflow is always an error, but underflow is only an error if
3014   // we underflowed to zero (APFloat reports denormals as underflow).
3015   if ((result & APFloat::opOverflow) ||
3016       ((result & APFloat::opUnderflow) && Val.isZero())) {
3017     unsigned diagnostic;
3018     SmallString<20> buffer;
3019     if (result & APFloat::opOverflow) {
3020       diagnostic = diag::warn_float_overflow;
3021       APFloat::getLargest(Format).toString(buffer);
3022     } else {
3023       diagnostic = diag::warn_float_underflow;
3024       APFloat::getSmallest(Format).toString(buffer);
3025     }
3026 
3027     S.Diag(Loc, diagnostic)
3028       << Ty
3029       << StringRef(buffer.data(), buffer.size());
3030   }
3031 
3032   bool isExact = (result == APFloat::opOK);
3033   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3034 }
3035 
3036 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3037   // Fast path for a single digit (which is quite common).  A single digit
3038   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3039   if (Tok.getLength() == 1) {
3040     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3041     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3042   }
3043 
3044   SmallString<128> SpellingBuffer;
3045   // NumericLiteralParser wants to overread by one character.  Add padding to
3046   // the buffer in case the token is copied to the buffer.  If getSpelling()
3047   // returns a StringRef to the memory buffer, it should have a null char at
3048   // the EOF, so it is also safe.
3049   SpellingBuffer.resize(Tok.getLength() + 1);
3050 
3051   // Get the spelling of the token, which eliminates trigraphs, etc.
3052   bool Invalid = false;
3053   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3054   if (Invalid)
3055     return ExprError();
3056 
3057   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3058   if (Literal.hadError)
3059     return ExprError();
3060 
3061   if (Literal.hasUDSuffix()) {
3062     // We're building a user-defined literal.
3063     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3064     SourceLocation UDSuffixLoc =
3065       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3066 
3067     // Make sure we're allowed user-defined literals here.
3068     if (!UDLScope)
3069       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3070 
3071     QualType CookedTy;
3072     if (Literal.isFloatingLiteral()) {
3073       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3074       // long double, the literal is treated as a call of the form
3075       //   operator "" X (f L)
3076       CookedTy = Context.LongDoubleTy;
3077     } else {
3078       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3079       // unsigned long long, the literal is treated as a call of the form
3080       //   operator "" X (n ULL)
3081       CookedTy = Context.UnsignedLongLongTy;
3082     }
3083 
3084     DeclarationName OpName =
3085       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3086     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3087     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3088 
3089     SourceLocation TokLoc = Tok.getLocation();
3090 
3091     // Perform literal operator lookup to determine if we're building a raw
3092     // literal or a cooked one.
3093     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3094     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3095                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3096                                   /*AllowStringTemplate*/false)) {
3097     case LOLR_Error:
3098       return ExprError();
3099 
3100     case LOLR_Cooked: {
3101       Expr *Lit;
3102       if (Literal.isFloatingLiteral()) {
3103         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3104       } else {
3105         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3106         if (Literal.GetIntegerValue(ResultVal))
3107           Diag(Tok.getLocation(), diag::err_integer_too_large);
3108         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3109                                      Tok.getLocation());
3110       }
3111       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3112     }
3113 
3114     case LOLR_Raw: {
3115       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3116       // literal is treated as a call of the form
3117       //   operator "" X ("n")
3118       unsigned Length = Literal.getUDSuffixOffset();
3119       QualType StrTy = Context.getConstantArrayType(
3120           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3121           ArrayType::Normal, 0);
3122       Expr *Lit = StringLiteral::Create(
3123           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3124           /*Pascal*/false, StrTy, &TokLoc, 1);
3125       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3126     }
3127 
3128     case LOLR_Template: {
3129       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3130       // template), L is treated as a call fo the form
3131       //   operator "" X <'c1', 'c2', ... 'ck'>()
3132       // where n is the source character sequence c1 c2 ... ck.
3133       TemplateArgumentListInfo ExplicitArgs;
3134       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3135       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3136       llvm::APSInt Value(CharBits, CharIsUnsigned);
3137       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3138         Value = TokSpelling[I];
3139         TemplateArgument Arg(Context, Value, Context.CharTy);
3140         TemplateArgumentLocInfo ArgInfo;
3141         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3142       }
3143       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3144                                       &ExplicitArgs);
3145     }
3146     case LOLR_StringTemplate:
3147       llvm_unreachable("unexpected literal operator lookup result");
3148     }
3149   }
3150 
3151   Expr *Res;
3152 
3153   if (Literal.isFloatingLiteral()) {
3154     QualType Ty;
3155     if (Literal.isFloat)
3156       Ty = Context.FloatTy;
3157     else if (!Literal.isLong)
3158       Ty = Context.DoubleTy;
3159     else
3160       Ty = Context.LongDoubleTy;
3161 
3162     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3163 
3164     if (Ty == Context.DoubleTy) {
3165       if (getLangOpts().SinglePrecisionConstants) {
3166         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3167       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3168         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3169         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3170       }
3171     }
3172   } else if (!Literal.isIntegerLiteral()) {
3173     return ExprError();
3174   } else {
3175     QualType Ty;
3176 
3177     // 'long long' is a C99 or C++11 feature.
3178     if (!getLangOpts().C99 && Literal.isLongLong) {
3179       if (getLangOpts().CPlusPlus)
3180         Diag(Tok.getLocation(),
3181              getLangOpts().CPlusPlus11 ?
3182              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3183       else
3184         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3185     }
3186 
3187     // Get the value in the widest-possible width.
3188     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3189     // The microsoft literal suffix extensions support 128-bit literals, which
3190     // may be wider than [u]intmax_t.
3191     // FIXME: Actually, they don't. We seem to have accidentally invented the
3192     //        i128 suffix.
3193     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3194         Context.getTargetInfo().hasInt128Type())
3195       MaxWidth = 128;
3196     llvm::APInt ResultVal(MaxWidth, 0);
3197 
3198     if (Literal.GetIntegerValue(ResultVal)) {
3199       // If this value didn't fit into uintmax_t, error and force to ull.
3200       Diag(Tok.getLocation(), diag::err_integer_too_large);
3201       Ty = Context.UnsignedLongLongTy;
3202       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3203              "long long is not intmax_t?");
3204     } else {
3205       // If this value fits into a ULL, try to figure out what else it fits into
3206       // according to the rules of C99 6.4.4.1p5.
3207 
3208       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3209       // be an unsigned int.
3210       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3211 
3212       // Check from smallest to largest, picking the smallest type we can.
3213       unsigned Width = 0;
3214       if (!Literal.isLong && !Literal.isLongLong) {
3215         // Are int/unsigned possibilities?
3216         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3217 
3218         // Does it fit in a unsigned int?
3219         if (ResultVal.isIntN(IntSize)) {
3220           // Does it fit in a signed int?
3221           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3222             Ty = Context.IntTy;
3223           else if (AllowUnsigned)
3224             Ty = Context.UnsignedIntTy;
3225           Width = IntSize;
3226         }
3227       }
3228 
3229       // Are long/unsigned long possibilities?
3230       if (Ty.isNull() && !Literal.isLongLong) {
3231         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3232 
3233         // Does it fit in a unsigned long?
3234         if (ResultVal.isIntN(LongSize)) {
3235           // Does it fit in a signed long?
3236           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3237             Ty = Context.LongTy;
3238           else if (AllowUnsigned)
3239             Ty = Context.UnsignedLongTy;
3240           Width = LongSize;
3241         }
3242       }
3243 
3244       // Check long long if needed.
3245       if (Ty.isNull()) {
3246         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3247 
3248         // Does it fit in a unsigned long long?
3249         if (ResultVal.isIntN(LongLongSize)) {
3250           // Does it fit in a signed long long?
3251           // To be compatible with MSVC, hex integer literals ending with the
3252           // LL or i64 suffix are always signed in Microsoft mode.
3253           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3254               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3255             Ty = Context.LongLongTy;
3256           else if (AllowUnsigned)
3257             Ty = Context.UnsignedLongLongTy;
3258           Width = LongLongSize;
3259         }
3260       }
3261 
3262       // If it doesn't fit in unsigned long long, and we're using Microsoft
3263       // extensions, then its a 128-bit integer literal.
3264       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3265           Context.getTargetInfo().hasInt128Type()) {
3266         if (Literal.isUnsigned)
3267           Ty = Context.UnsignedInt128Ty;
3268         else
3269           Ty = Context.Int128Ty;
3270         Width = 128;
3271       }
3272 
3273       // If we still couldn't decide a type, we probably have something that
3274       // does not fit in a signed long long, but has no U suffix.
3275       if (Ty.isNull()) {
3276         Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed);
3277         Ty = Context.UnsignedLongLongTy;
3278         Width = Context.getTargetInfo().getLongLongWidth();
3279       }
3280 
3281       if (ResultVal.getBitWidth() != Width)
3282         ResultVal = ResultVal.trunc(Width);
3283     }
3284     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3285   }
3286 
3287   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3288   if (Literal.isImaginary)
3289     Res = new (Context) ImaginaryLiteral(Res,
3290                                         Context.getComplexType(Res->getType()));
3291 
3292   return Res;
3293 }
3294 
3295 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3296   assert(E && "ActOnParenExpr() missing expr");
3297   return new (Context) ParenExpr(L, R, E);
3298 }
3299 
3300 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3301                                          SourceLocation Loc,
3302                                          SourceRange ArgRange) {
3303   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3304   // scalar or vector data type argument..."
3305   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3306   // type (C99 6.2.5p18) or void.
3307   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3308     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3309       << T << ArgRange;
3310     return true;
3311   }
3312 
3313   assert((T->isVoidType() || !T->isIncompleteType()) &&
3314          "Scalar types should always be complete");
3315   return false;
3316 }
3317 
3318 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3319                                            SourceLocation Loc,
3320                                            SourceRange ArgRange,
3321                                            UnaryExprOrTypeTrait TraitKind) {
3322   // Invalid types must be hard errors for SFINAE in C++.
3323   if (S.LangOpts.CPlusPlus)
3324     return true;
3325 
3326   // C99 6.5.3.4p1:
3327   if (T->isFunctionType() &&
3328       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3329     // sizeof(function)/alignof(function) is allowed as an extension.
3330     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3331       << TraitKind << ArgRange;
3332     return false;
3333   }
3334 
3335   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3336   // this is an error (OpenCL v1.1 s6.3.k)
3337   if (T->isVoidType()) {
3338     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3339                                         : diag::ext_sizeof_alignof_void_type;
3340     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3341     return false;
3342   }
3343 
3344   return true;
3345 }
3346 
3347 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3348                                              SourceLocation Loc,
3349                                              SourceRange ArgRange,
3350                                              UnaryExprOrTypeTrait TraitKind) {
3351   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3352   // runtime doesn't allow it.
3353   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3354     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3355       << T << (TraitKind == UETT_SizeOf)
3356       << ArgRange;
3357     return true;
3358   }
3359 
3360   return false;
3361 }
3362 
3363 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3364 /// pointer type is equal to T) and emit a warning if it is.
3365 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3366                                      Expr *E) {
3367   // Don't warn if the operation changed the type.
3368   if (T != E->getType())
3369     return;
3370 
3371   // Now look for array decays.
3372   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3373   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3374     return;
3375 
3376   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3377                                              << ICE->getType()
3378                                              << ICE->getSubExpr()->getType();
3379 }
3380 
3381 /// \brief Check the constraints on expression operands to unary type expression
3382 /// and type traits.
3383 ///
3384 /// Completes any types necessary and validates the constraints on the operand
3385 /// expression. The logic mostly mirrors the type-based overload, but may modify
3386 /// the expression as it completes the type for that expression through template
3387 /// instantiation, etc.
3388 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3389                                             UnaryExprOrTypeTrait ExprKind) {
3390   QualType ExprTy = E->getType();
3391   assert(!ExprTy->isReferenceType());
3392 
3393   if (ExprKind == UETT_VecStep)
3394     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3395                                         E->getSourceRange());
3396 
3397   // Whitelist some types as extensions
3398   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3399                                       E->getSourceRange(), ExprKind))
3400     return false;
3401 
3402   // 'alignof' applied to an expression only requires the base element type of
3403   // the expression to be complete. 'sizeof' requires the expression's type to
3404   // be complete (and will attempt to complete it if it's an array of unknown
3405   // bound).
3406   if (ExprKind == UETT_AlignOf) {
3407     if (RequireCompleteType(E->getExprLoc(),
3408                             Context.getBaseElementType(E->getType()),
3409                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3410                             E->getSourceRange()))
3411       return true;
3412   } else {
3413     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3414                                 ExprKind, E->getSourceRange()))
3415       return true;
3416   }
3417 
3418   // Completing the expression's type may have changed it.
3419   ExprTy = E->getType();
3420   assert(!ExprTy->isReferenceType());
3421 
3422   if (ExprTy->isFunctionType()) {
3423     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3424       << ExprKind << E->getSourceRange();
3425     return true;
3426   }
3427 
3428   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3429                                        E->getSourceRange(), ExprKind))
3430     return true;
3431 
3432   if (ExprKind == UETT_SizeOf) {
3433     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3434       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3435         QualType OType = PVD->getOriginalType();
3436         QualType Type = PVD->getType();
3437         if (Type->isPointerType() && OType->isArrayType()) {
3438           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3439             << Type << OType;
3440           Diag(PVD->getLocation(), diag::note_declared_at);
3441         }
3442       }
3443     }
3444 
3445     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3446     // decays into a pointer and returns an unintended result. This is most
3447     // likely a typo for "sizeof(array) op x".
3448     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3449       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3450                                BO->getLHS());
3451       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3452                                BO->getRHS());
3453     }
3454   }
3455 
3456   return false;
3457 }
3458 
3459 /// \brief Check the constraints on operands to unary expression and type
3460 /// traits.
3461 ///
3462 /// This will complete any types necessary, and validate the various constraints
3463 /// on those operands.
3464 ///
3465 /// The UsualUnaryConversions() function is *not* called by this routine.
3466 /// C99 6.3.2.1p[2-4] all state:
3467 ///   Except when it is the operand of the sizeof operator ...
3468 ///
3469 /// C++ [expr.sizeof]p4
3470 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3471 ///   standard conversions are not applied to the operand of sizeof.
3472 ///
3473 /// This policy is followed for all of the unary trait expressions.
3474 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3475                                             SourceLocation OpLoc,
3476                                             SourceRange ExprRange,
3477                                             UnaryExprOrTypeTrait ExprKind) {
3478   if (ExprType->isDependentType())
3479     return false;
3480 
3481   // C++ [expr.sizeof]p2:
3482   //     When applied to a reference or a reference type, the result
3483   //     is the size of the referenced type.
3484   // C++11 [expr.alignof]p3:
3485   //     When alignof is applied to a reference type, the result
3486   //     shall be the alignment of the referenced type.
3487   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3488     ExprType = Ref->getPointeeType();
3489 
3490   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3491   //   When alignof or _Alignof is applied to an array type, the result
3492   //   is the alignment of the element type.
3493   if (ExprKind == UETT_AlignOf)
3494     ExprType = Context.getBaseElementType(ExprType);
3495 
3496   if (ExprKind == UETT_VecStep)
3497     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3498 
3499   // Whitelist some types as extensions
3500   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3501                                       ExprKind))
3502     return false;
3503 
3504   if (RequireCompleteType(OpLoc, ExprType,
3505                           diag::err_sizeof_alignof_incomplete_type,
3506                           ExprKind, ExprRange))
3507     return true;
3508 
3509   if (ExprType->isFunctionType()) {
3510     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3511       << ExprKind << ExprRange;
3512     return true;
3513   }
3514 
3515   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3516                                        ExprKind))
3517     return true;
3518 
3519   return false;
3520 }
3521 
3522 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3523   E = E->IgnoreParens();
3524 
3525   // Cannot know anything else if the expression is dependent.
3526   if (E->isTypeDependent())
3527     return false;
3528 
3529   if (E->getObjectKind() == OK_BitField) {
3530     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3531        << 1 << E->getSourceRange();
3532     return true;
3533   }
3534 
3535   ValueDecl *D = nullptr;
3536   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3537     D = DRE->getDecl();
3538   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3539     D = ME->getMemberDecl();
3540   }
3541 
3542   // If it's a field, require the containing struct to have a
3543   // complete definition so that we can compute the layout.
3544   //
3545   // This can happen in C++11 onwards, either by naming the member
3546   // in a way that is not transformed into a member access expression
3547   // (in an unevaluated operand, for instance), or by naming the member
3548   // in a trailing-return-type.
3549   //
3550   // For the record, since __alignof__ on expressions is a GCC
3551   // extension, GCC seems to permit this but always gives the
3552   // nonsensical answer 0.
3553   //
3554   // We don't really need the layout here --- we could instead just
3555   // directly check for all the appropriate alignment-lowing
3556   // attributes --- but that would require duplicating a lot of
3557   // logic that just isn't worth duplicating for such a marginal
3558   // use-case.
3559   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3560     // Fast path this check, since we at least know the record has a
3561     // definition if we can find a member of it.
3562     if (!FD->getParent()->isCompleteDefinition()) {
3563       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3564         << E->getSourceRange();
3565       return true;
3566     }
3567 
3568     // Otherwise, if it's a field, and the field doesn't have
3569     // reference type, then it must have a complete type (or be a
3570     // flexible array member, which we explicitly want to
3571     // white-list anyway), which makes the following checks trivial.
3572     if (!FD->getType()->isReferenceType())
3573       return false;
3574   }
3575 
3576   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3577 }
3578 
3579 bool Sema::CheckVecStepExpr(Expr *E) {
3580   E = E->IgnoreParens();
3581 
3582   // Cannot know anything else if the expression is dependent.
3583   if (E->isTypeDependent())
3584     return false;
3585 
3586   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3587 }
3588 
3589 /// \brief Build a sizeof or alignof expression given a type operand.
3590 ExprResult
3591 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3592                                      SourceLocation OpLoc,
3593                                      UnaryExprOrTypeTrait ExprKind,
3594                                      SourceRange R) {
3595   if (!TInfo)
3596     return ExprError();
3597 
3598   QualType T = TInfo->getType();
3599 
3600   if (!T->isDependentType() &&
3601       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3602     return ExprError();
3603 
3604   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3605   return new (Context) UnaryExprOrTypeTraitExpr(
3606       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3607 }
3608 
3609 /// \brief Build a sizeof or alignof expression given an expression
3610 /// operand.
3611 ExprResult
3612 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3613                                      UnaryExprOrTypeTrait ExprKind) {
3614   ExprResult PE = CheckPlaceholderExpr(E);
3615   if (PE.isInvalid())
3616     return ExprError();
3617 
3618   E = PE.get();
3619 
3620   // Verify that the operand is valid.
3621   bool isInvalid = false;
3622   if (E->isTypeDependent()) {
3623     // Delay type-checking for type-dependent expressions.
3624   } else if (ExprKind == UETT_AlignOf) {
3625     isInvalid = CheckAlignOfExpr(*this, E);
3626   } else if (ExprKind == UETT_VecStep) {
3627     isInvalid = CheckVecStepExpr(E);
3628   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3629     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3630     isInvalid = true;
3631   } else {
3632     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3633   }
3634 
3635   if (isInvalid)
3636     return ExprError();
3637 
3638   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3639     PE = TransformToPotentiallyEvaluated(E);
3640     if (PE.isInvalid()) return ExprError();
3641     E = PE.get();
3642   }
3643 
3644   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3645   return new (Context) UnaryExprOrTypeTraitExpr(
3646       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3647 }
3648 
3649 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3650 /// expr and the same for @c alignof and @c __alignof
3651 /// Note that the ArgRange is invalid if isType is false.
3652 ExprResult
3653 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3654                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3655                                     void *TyOrEx, const SourceRange &ArgRange) {
3656   // If error parsing type, ignore.
3657   if (!TyOrEx) return ExprError();
3658 
3659   if (IsType) {
3660     TypeSourceInfo *TInfo;
3661     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3662     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3663   }
3664 
3665   Expr *ArgEx = (Expr *)TyOrEx;
3666   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3667   return Result;
3668 }
3669 
3670 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3671                                      bool IsReal) {
3672   if (V.get()->isTypeDependent())
3673     return S.Context.DependentTy;
3674 
3675   // _Real and _Imag are only l-values for normal l-values.
3676   if (V.get()->getObjectKind() != OK_Ordinary) {
3677     V = S.DefaultLvalueConversion(V.get());
3678     if (V.isInvalid())
3679       return QualType();
3680   }
3681 
3682   // These operators return the element type of a complex type.
3683   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3684     return CT->getElementType();
3685 
3686   // Otherwise they pass through real integer and floating point types here.
3687   if (V.get()->getType()->isArithmeticType())
3688     return V.get()->getType();
3689 
3690   // Test for placeholders.
3691   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3692   if (PR.isInvalid()) return QualType();
3693   if (PR.get() != V.get()) {
3694     V = PR;
3695     return CheckRealImagOperand(S, V, Loc, IsReal);
3696   }
3697 
3698   // Reject anything else.
3699   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3700     << (IsReal ? "__real" : "__imag");
3701   return QualType();
3702 }
3703 
3704 
3705 
3706 ExprResult
3707 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3708                           tok::TokenKind Kind, Expr *Input) {
3709   UnaryOperatorKind Opc;
3710   switch (Kind) {
3711   default: llvm_unreachable("Unknown unary op!");
3712   case tok::plusplus:   Opc = UO_PostInc; break;
3713   case tok::minusminus: Opc = UO_PostDec; break;
3714   }
3715 
3716   // Since this might is a postfix expression, get rid of ParenListExprs.
3717   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3718   if (Result.isInvalid()) return ExprError();
3719   Input = Result.get();
3720 
3721   return BuildUnaryOp(S, OpLoc, Opc, Input);
3722 }
3723 
3724 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3725 ///
3726 /// \return true on error
3727 static bool checkArithmeticOnObjCPointer(Sema &S,
3728                                          SourceLocation opLoc,
3729                                          Expr *op) {
3730   assert(op->getType()->isObjCObjectPointerType());
3731   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3732       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3733     return false;
3734 
3735   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3736     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3737     << op->getSourceRange();
3738   return true;
3739 }
3740 
3741 ExprResult
3742 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3743                               Expr *idx, SourceLocation rbLoc) {
3744   // Since this might be a postfix expression, get rid of ParenListExprs.
3745   if (isa<ParenListExpr>(base)) {
3746     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3747     if (result.isInvalid()) return ExprError();
3748     base = result.get();
3749   }
3750 
3751   // Handle any non-overload placeholder types in the base and index
3752   // expressions.  We can't handle overloads here because the other
3753   // operand might be an overloadable type, in which case the overload
3754   // resolution for the operator overload should get the first crack
3755   // at the overload.
3756   if (base->getType()->isNonOverloadPlaceholderType()) {
3757     ExprResult result = CheckPlaceholderExpr(base);
3758     if (result.isInvalid()) return ExprError();
3759     base = result.get();
3760   }
3761   if (idx->getType()->isNonOverloadPlaceholderType()) {
3762     ExprResult result = CheckPlaceholderExpr(idx);
3763     if (result.isInvalid()) return ExprError();
3764     idx = result.get();
3765   }
3766 
3767   // Build an unanalyzed expression if either operand is type-dependent.
3768   if (getLangOpts().CPlusPlus &&
3769       (base->isTypeDependent() || idx->isTypeDependent())) {
3770     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3771                                             VK_LValue, OK_Ordinary, rbLoc);
3772   }
3773 
3774   // Use C++ overloaded-operator rules if either operand has record
3775   // type.  The spec says to do this if either type is *overloadable*,
3776   // but enum types can't declare subscript operators or conversion
3777   // operators, so there's nothing interesting for overload resolution
3778   // to do if there aren't any record types involved.
3779   //
3780   // ObjC pointers have their own subscripting logic that is not tied
3781   // to overload resolution and so should not take this path.
3782   if (getLangOpts().CPlusPlus &&
3783       (base->getType()->isRecordType() ||
3784        (!base->getType()->isObjCObjectPointerType() &&
3785         idx->getType()->isRecordType()))) {
3786     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3787   }
3788 
3789   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3790 }
3791 
3792 ExprResult
3793 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3794                                       Expr *Idx, SourceLocation RLoc) {
3795   Expr *LHSExp = Base;
3796   Expr *RHSExp = Idx;
3797 
3798   // Perform default conversions.
3799   if (!LHSExp->getType()->getAs<VectorType>()) {
3800     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3801     if (Result.isInvalid())
3802       return ExprError();
3803     LHSExp = Result.get();
3804   }
3805   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3806   if (Result.isInvalid())
3807     return ExprError();
3808   RHSExp = Result.get();
3809 
3810   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3811   ExprValueKind VK = VK_LValue;
3812   ExprObjectKind OK = OK_Ordinary;
3813 
3814   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3815   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3816   // in the subscript position. As a result, we need to derive the array base
3817   // and index from the expression types.
3818   Expr *BaseExpr, *IndexExpr;
3819   QualType ResultType;
3820   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3821     BaseExpr = LHSExp;
3822     IndexExpr = RHSExp;
3823     ResultType = Context.DependentTy;
3824   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3825     BaseExpr = LHSExp;
3826     IndexExpr = RHSExp;
3827     ResultType = PTy->getPointeeType();
3828   } else if (const ObjCObjectPointerType *PTy =
3829                LHSTy->getAs<ObjCObjectPointerType>()) {
3830     BaseExpr = LHSExp;
3831     IndexExpr = RHSExp;
3832 
3833     // Use custom logic if this should be the pseudo-object subscript
3834     // expression.
3835     if (!LangOpts.isSubscriptPointerArithmetic())
3836       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3837                                           nullptr);
3838 
3839     ResultType = PTy->getPointeeType();
3840   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3841      // Handle the uncommon case of "123[Ptr]".
3842     BaseExpr = RHSExp;
3843     IndexExpr = LHSExp;
3844     ResultType = PTy->getPointeeType();
3845   } else if (const ObjCObjectPointerType *PTy =
3846                RHSTy->getAs<ObjCObjectPointerType>()) {
3847      // Handle the uncommon case of "123[Ptr]".
3848     BaseExpr = RHSExp;
3849     IndexExpr = LHSExp;
3850     ResultType = PTy->getPointeeType();
3851     if (!LangOpts.isSubscriptPointerArithmetic()) {
3852       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3853         << ResultType << BaseExpr->getSourceRange();
3854       return ExprError();
3855     }
3856   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3857     BaseExpr = LHSExp;    // vectors: V[123]
3858     IndexExpr = RHSExp;
3859     VK = LHSExp->getValueKind();
3860     if (VK != VK_RValue)
3861       OK = OK_VectorComponent;
3862 
3863     // FIXME: need to deal with const...
3864     ResultType = VTy->getElementType();
3865   } else if (LHSTy->isArrayType()) {
3866     // If we see an array that wasn't promoted by
3867     // DefaultFunctionArrayLvalueConversion, it must be an array that
3868     // wasn't promoted because of the C90 rule that doesn't
3869     // allow promoting non-lvalue arrays.  Warn, then
3870     // force the promotion here.
3871     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3872         LHSExp->getSourceRange();
3873     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3874                                CK_ArrayToPointerDecay).get();
3875     LHSTy = LHSExp->getType();
3876 
3877     BaseExpr = LHSExp;
3878     IndexExpr = RHSExp;
3879     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3880   } else if (RHSTy->isArrayType()) {
3881     // Same as previous, except for 123[f().a] case
3882     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3883         RHSExp->getSourceRange();
3884     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3885                                CK_ArrayToPointerDecay).get();
3886     RHSTy = RHSExp->getType();
3887 
3888     BaseExpr = RHSExp;
3889     IndexExpr = LHSExp;
3890     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3891   } else {
3892     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3893        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3894   }
3895   // C99 6.5.2.1p1
3896   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3897     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3898                      << IndexExpr->getSourceRange());
3899 
3900   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3901        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3902          && !IndexExpr->isTypeDependent())
3903     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3904 
3905   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3906   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3907   // type. Note that Functions are not objects, and that (in C99 parlance)
3908   // incomplete types are not object types.
3909   if (ResultType->isFunctionType()) {
3910     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3911       << ResultType << BaseExpr->getSourceRange();
3912     return ExprError();
3913   }
3914 
3915   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3916     // GNU extension: subscripting on pointer to void
3917     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3918       << BaseExpr->getSourceRange();
3919 
3920     // C forbids expressions of unqualified void type from being l-values.
3921     // See IsCForbiddenLValueType.
3922     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3923   } else if (!ResultType->isDependentType() &&
3924       RequireCompleteType(LLoc, ResultType,
3925                           diag::err_subscript_incomplete_type, BaseExpr))
3926     return ExprError();
3927 
3928   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3929          !ResultType.isCForbiddenLValueType());
3930 
3931   return new (Context)
3932       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
3933 }
3934 
3935 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3936                                         FunctionDecl *FD,
3937                                         ParmVarDecl *Param) {
3938   if (Param->hasUnparsedDefaultArg()) {
3939     Diag(CallLoc,
3940          diag::err_use_of_default_argument_to_function_declared_later) <<
3941       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3942     Diag(UnparsedDefaultArgLocs[Param],
3943          diag::note_default_argument_declared_here);
3944     return ExprError();
3945   }
3946 
3947   if (Param->hasUninstantiatedDefaultArg()) {
3948     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3949 
3950     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3951                                                  Param);
3952 
3953     // Instantiate the expression.
3954     MultiLevelTemplateArgumentList MutiLevelArgList
3955       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
3956 
3957     InstantiatingTemplate Inst(*this, CallLoc, Param,
3958                                MutiLevelArgList.getInnermost());
3959     if (Inst.isInvalid())
3960       return ExprError();
3961 
3962     ExprResult Result;
3963     {
3964       // C++ [dcl.fct.default]p5:
3965       //   The names in the [default argument] expression are bound, and
3966       //   the semantic constraints are checked, at the point where the
3967       //   default argument expression appears.
3968       ContextRAII SavedContext(*this, FD);
3969       LocalInstantiationScope Local(*this);
3970       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3971     }
3972     if (Result.isInvalid())
3973       return ExprError();
3974 
3975     // Check the expression as an initializer for the parameter.
3976     InitializedEntity Entity
3977       = InitializedEntity::InitializeParameter(Context, Param);
3978     InitializationKind Kind
3979       = InitializationKind::CreateCopy(Param->getLocation(),
3980              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3981     Expr *ResultE = Result.getAs<Expr>();
3982 
3983     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3984     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3985     if (Result.isInvalid())
3986       return ExprError();
3987 
3988     Expr *Arg = Result.getAs<Expr>();
3989     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3990     // Build the default argument expression.
3991     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
3992   }
3993 
3994   // If the default expression creates temporaries, we need to
3995   // push them to the current stack of expression temporaries so they'll
3996   // be properly destroyed.
3997   // FIXME: We should really be rebuilding the default argument with new
3998   // bound temporaries; see the comment in PR5810.
3999   // We don't need to do that with block decls, though, because
4000   // blocks in default argument expression can never capture anything.
4001   if (isa<ExprWithCleanups>(Param->getInit())) {
4002     // Set the "needs cleanups" bit regardless of whether there are
4003     // any explicit objects.
4004     ExprNeedsCleanups = true;
4005 
4006     // Append all the objects to the cleanup list.  Right now, this
4007     // should always be a no-op, because blocks in default argument
4008     // expressions should never be able to capture anything.
4009     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4010            "default argument expression has capturing blocks?");
4011   }
4012 
4013   // We already type-checked the argument, so we know it works.
4014   // Just mark all of the declarations in this potentially-evaluated expression
4015   // as being "referenced".
4016   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4017                                    /*SkipLocalVariables=*/true);
4018   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4019 }
4020 
4021 
4022 Sema::VariadicCallType
4023 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4024                           Expr *Fn) {
4025   if (Proto && Proto->isVariadic()) {
4026     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4027       return VariadicConstructor;
4028     else if (Fn && Fn->getType()->isBlockPointerType())
4029       return VariadicBlock;
4030     else if (FDecl) {
4031       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4032         if (Method->isInstance())
4033           return VariadicMethod;
4034     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4035       return VariadicMethod;
4036     return VariadicFunction;
4037   }
4038   return VariadicDoesNotApply;
4039 }
4040 
4041 namespace {
4042 class FunctionCallCCC : public FunctionCallFilterCCC {
4043 public:
4044   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4045                   unsigned NumArgs, MemberExpr *ME)
4046       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4047         FunctionName(FuncName) {}
4048 
4049   bool ValidateCandidate(const TypoCorrection &candidate) override {
4050     if (!candidate.getCorrectionSpecifier() ||
4051         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4052       return false;
4053     }
4054 
4055     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4056   }
4057 
4058 private:
4059   const IdentifierInfo *const FunctionName;
4060 };
4061 }
4062 
4063 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4064                                                FunctionDecl *FDecl,
4065                                                ArrayRef<Expr *> Args) {
4066   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4067   DeclarationName FuncName = FDecl->getDeclName();
4068   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4069   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4070 
4071   if (TypoCorrection Corrected = S.CorrectTypo(
4072           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4073           S.getScopeForContext(S.CurContext), nullptr, CCC,
4074           Sema::CTK_ErrorRecovery)) {
4075     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4076       if (Corrected.isOverloaded()) {
4077         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4078         OverloadCandidateSet::iterator Best;
4079         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4080                                            CDEnd = Corrected.end();
4081              CD != CDEnd; ++CD) {
4082           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4083             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4084                                    OCS);
4085         }
4086         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4087         case OR_Success:
4088           ND = Best->Function;
4089           Corrected.setCorrectionDecl(ND);
4090           break;
4091         default:
4092           break;
4093         }
4094       }
4095       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4096         return Corrected;
4097       }
4098     }
4099   }
4100   return TypoCorrection();
4101 }
4102 
4103 /// ConvertArgumentsForCall - Converts the arguments specified in
4104 /// Args/NumArgs to the parameter types of the function FDecl with
4105 /// function prototype Proto. Call is the call expression itself, and
4106 /// Fn is the function expression. For a C++ member function, this
4107 /// routine does not attempt to convert the object argument. Returns
4108 /// true if the call is ill-formed.
4109 bool
4110 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4111                               FunctionDecl *FDecl,
4112                               const FunctionProtoType *Proto,
4113                               ArrayRef<Expr *> Args,
4114                               SourceLocation RParenLoc,
4115                               bool IsExecConfig) {
4116   // Bail out early if calling a builtin with custom typechecking.
4117   // We don't need to do this in the
4118   if (FDecl)
4119     if (unsigned ID = FDecl->getBuiltinID())
4120       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4121         return false;
4122 
4123   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4124   // assignment, to the types of the corresponding parameter, ...
4125   unsigned NumParams = Proto->getNumParams();
4126   bool Invalid = false;
4127   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4128   unsigned FnKind = Fn->getType()->isBlockPointerType()
4129                        ? 1 /* block */
4130                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4131                                        : 0 /* function */);
4132 
4133   // If too few arguments are available (and we don't have default
4134   // arguments for the remaining parameters), don't make the call.
4135   if (Args.size() < NumParams) {
4136     if (Args.size() < MinArgs) {
4137       TypoCorrection TC;
4138       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4139         unsigned diag_id =
4140             MinArgs == NumParams && !Proto->isVariadic()
4141                 ? diag::err_typecheck_call_too_few_args_suggest
4142                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4143         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4144                                         << static_cast<unsigned>(Args.size())
4145                                         << TC.getCorrectionRange());
4146       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4147         Diag(RParenLoc,
4148              MinArgs == NumParams && !Proto->isVariadic()
4149                  ? diag::err_typecheck_call_too_few_args_one
4150                  : diag::err_typecheck_call_too_few_args_at_least_one)
4151             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4152       else
4153         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4154                             ? diag::err_typecheck_call_too_few_args
4155                             : diag::err_typecheck_call_too_few_args_at_least)
4156             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4157             << Fn->getSourceRange();
4158 
4159       // Emit the location of the prototype.
4160       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4161         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4162           << FDecl;
4163 
4164       return true;
4165     }
4166     Call->setNumArgs(Context, NumParams);
4167   }
4168 
4169   // If too many are passed and not variadic, error on the extras and drop
4170   // them.
4171   if (Args.size() > NumParams) {
4172     if (!Proto->isVariadic()) {
4173       TypoCorrection TC;
4174       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4175         unsigned diag_id =
4176             MinArgs == NumParams && !Proto->isVariadic()
4177                 ? diag::err_typecheck_call_too_many_args_suggest
4178                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4179         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4180                                         << static_cast<unsigned>(Args.size())
4181                                         << TC.getCorrectionRange());
4182       } else if (NumParams == 1 && FDecl &&
4183                  FDecl->getParamDecl(0)->getDeclName())
4184         Diag(Args[NumParams]->getLocStart(),
4185              MinArgs == NumParams
4186                  ? diag::err_typecheck_call_too_many_args_one
4187                  : diag::err_typecheck_call_too_many_args_at_most_one)
4188             << FnKind << FDecl->getParamDecl(0)
4189             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4190             << SourceRange(Args[NumParams]->getLocStart(),
4191                            Args.back()->getLocEnd());
4192       else
4193         Diag(Args[NumParams]->getLocStart(),
4194              MinArgs == NumParams
4195                  ? diag::err_typecheck_call_too_many_args
4196                  : diag::err_typecheck_call_too_many_args_at_most)
4197             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4198             << Fn->getSourceRange()
4199             << SourceRange(Args[NumParams]->getLocStart(),
4200                            Args.back()->getLocEnd());
4201 
4202       // Emit the location of the prototype.
4203       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4204         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4205           << FDecl;
4206 
4207       // This deletes the extra arguments.
4208       Call->setNumArgs(Context, NumParams);
4209       return true;
4210     }
4211   }
4212   SmallVector<Expr *, 8> AllArgs;
4213   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4214 
4215   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4216                                    Proto, 0, Args, AllArgs, CallType);
4217   if (Invalid)
4218     return true;
4219   unsigned TotalNumArgs = AllArgs.size();
4220   for (unsigned i = 0; i < TotalNumArgs; ++i)
4221     Call->setArg(i, AllArgs[i]);
4222 
4223   return false;
4224 }
4225 
4226 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4227                                   const FunctionProtoType *Proto,
4228                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4229                                   SmallVectorImpl<Expr *> &AllArgs,
4230                                   VariadicCallType CallType, bool AllowExplicit,
4231                                   bool IsListInitialization) {
4232   unsigned NumParams = Proto->getNumParams();
4233   bool Invalid = false;
4234   unsigned ArgIx = 0;
4235   // Continue to check argument types (even if we have too few/many args).
4236   for (unsigned i = FirstParam; i < NumParams; i++) {
4237     QualType ProtoArgType = Proto->getParamType(i);
4238 
4239     Expr *Arg;
4240     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4241     if (ArgIx < Args.size()) {
4242       Arg = Args[ArgIx++];
4243 
4244       if (RequireCompleteType(Arg->getLocStart(),
4245                               ProtoArgType,
4246                               diag::err_call_incomplete_argument, Arg))
4247         return true;
4248 
4249       // Strip the unbridged-cast placeholder expression off, if applicable.
4250       bool CFAudited = false;
4251       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4252           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4253           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4254         Arg = stripARCUnbridgedCast(Arg);
4255       else if (getLangOpts().ObjCAutoRefCount &&
4256                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4257                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4258         CFAudited = true;
4259 
4260       InitializedEntity Entity =
4261           Param ? InitializedEntity::InitializeParameter(Context, Param,
4262                                                          ProtoArgType)
4263                 : InitializedEntity::InitializeParameter(
4264                       Context, ProtoArgType, Proto->isParamConsumed(i));
4265 
4266       // Remember that parameter belongs to a CF audited API.
4267       if (CFAudited)
4268         Entity.setParameterCFAudited();
4269 
4270       ExprResult ArgE = PerformCopyInitialization(
4271           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4272       if (ArgE.isInvalid())
4273         return true;
4274 
4275       Arg = ArgE.getAs<Expr>();
4276     } else {
4277       assert(Param && "can't use default arguments without a known callee");
4278 
4279       ExprResult ArgExpr =
4280         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4281       if (ArgExpr.isInvalid())
4282         return true;
4283 
4284       Arg = ArgExpr.getAs<Expr>();
4285     }
4286 
4287     // Check for array bounds violations for each argument to the call. This
4288     // check only triggers warnings when the argument isn't a more complex Expr
4289     // with its own checking, such as a BinaryOperator.
4290     CheckArrayAccess(Arg);
4291 
4292     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4293     CheckStaticArrayArgument(CallLoc, Param, Arg);
4294 
4295     AllArgs.push_back(Arg);
4296   }
4297 
4298   // If this is a variadic call, handle args passed through "...".
4299   if (CallType != VariadicDoesNotApply) {
4300     // Assume that extern "C" functions with variadic arguments that
4301     // return __unknown_anytype aren't *really* variadic.
4302     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4303         FDecl->isExternC()) {
4304       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4305         QualType paramType; // ignored
4306         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4307         Invalid |= arg.isInvalid();
4308         AllArgs.push_back(arg.get());
4309       }
4310 
4311     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4312     } else {
4313       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4314         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4315                                                           FDecl);
4316         Invalid |= Arg.isInvalid();
4317         AllArgs.push_back(Arg.get());
4318       }
4319     }
4320 
4321     // Check for array bounds violations.
4322     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4323       CheckArrayAccess(Args[i]);
4324   }
4325   return Invalid;
4326 }
4327 
4328 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4329   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4330   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4331     TL = DTL.getOriginalLoc();
4332   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4333     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4334       << ATL.getLocalSourceRange();
4335 }
4336 
4337 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4338 /// array parameter, check that it is non-null, and that if it is formed by
4339 /// array-to-pointer decay, the underlying array is sufficiently large.
4340 ///
4341 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4342 /// array type derivation, then for each call to the function, the value of the
4343 /// corresponding actual argument shall provide access to the first element of
4344 /// an array with at least as many elements as specified by the size expression.
4345 void
4346 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4347                                ParmVarDecl *Param,
4348                                const Expr *ArgExpr) {
4349   // Static array parameters are not supported in C++.
4350   if (!Param || getLangOpts().CPlusPlus)
4351     return;
4352 
4353   QualType OrigTy = Param->getOriginalType();
4354 
4355   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4356   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4357     return;
4358 
4359   if (ArgExpr->isNullPointerConstant(Context,
4360                                      Expr::NPC_NeverValueDependent)) {
4361     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4362     DiagnoseCalleeStaticArrayParam(*this, Param);
4363     return;
4364   }
4365 
4366   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4367   if (!CAT)
4368     return;
4369 
4370   const ConstantArrayType *ArgCAT =
4371     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4372   if (!ArgCAT)
4373     return;
4374 
4375   if (ArgCAT->getSize().ult(CAT->getSize())) {
4376     Diag(CallLoc, diag::warn_static_array_too_small)
4377       << ArgExpr->getSourceRange()
4378       << (unsigned) ArgCAT->getSize().getZExtValue()
4379       << (unsigned) CAT->getSize().getZExtValue();
4380     DiagnoseCalleeStaticArrayParam(*this, Param);
4381   }
4382 }
4383 
4384 /// Given a function expression of unknown-any type, try to rebuild it
4385 /// to have a function type.
4386 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4387 
4388 /// Is the given type a placeholder that we need to lower out
4389 /// immediately during argument processing?
4390 static bool isPlaceholderToRemoveAsArg(QualType type) {
4391   // Placeholders are never sugared.
4392   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4393   if (!placeholder) return false;
4394 
4395   switch (placeholder->getKind()) {
4396   // Ignore all the non-placeholder types.
4397 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4398 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4399 #include "clang/AST/BuiltinTypes.def"
4400     return false;
4401 
4402   // We cannot lower out overload sets; they might validly be resolved
4403   // by the call machinery.
4404   case BuiltinType::Overload:
4405     return false;
4406 
4407   // Unbridged casts in ARC can be handled in some call positions and
4408   // should be left in place.
4409   case BuiltinType::ARCUnbridgedCast:
4410     return false;
4411 
4412   // Pseudo-objects should be converted as soon as possible.
4413   case BuiltinType::PseudoObject:
4414     return true;
4415 
4416   // The debugger mode could theoretically but currently does not try
4417   // to resolve unknown-typed arguments based on known parameter types.
4418   case BuiltinType::UnknownAny:
4419     return true;
4420 
4421   // These are always invalid as call arguments and should be reported.
4422   case BuiltinType::BoundMember:
4423   case BuiltinType::BuiltinFn:
4424     return true;
4425   }
4426   llvm_unreachable("bad builtin type kind");
4427 }
4428 
4429 /// Check an argument list for placeholders that we won't try to
4430 /// handle later.
4431 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4432   // Apply this processing to all the arguments at once instead of
4433   // dying at the first failure.
4434   bool hasInvalid = false;
4435   for (size_t i = 0, e = args.size(); i != e; i++) {
4436     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4437       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4438       if (result.isInvalid()) hasInvalid = true;
4439       else args[i] = result.get();
4440     }
4441   }
4442   return hasInvalid;
4443 }
4444 
4445 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4446 /// This provides the location of the left/right parens and a list of comma
4447 /// locations.
4448 ExprResult
4449 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4450                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4451                     Expr *ExecConfig, bool IsExecConfig) {
4452   // Since this might be a postfix expression, get rid of ParenListExprs.
4453   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4454   if (Result.isInvalid()) return ExprError();
4455   Fn = Result.get();
4456 
4457   if (checkArgsForPlaceholders(*this, ArgExprs))
4458     return ExprError();
4459 
4460   if (getLangOpts().CPlusPlus) {
4461     // If this is a pseudo-destructor expression, build the call immediately.
4462     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4463       if (!ArgExprs.empty()) {
4464         // Pseudo-destructor calls should not have any arguments.
4465         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4466           << FixItHint::CreateRemoval(
4467                                     SourceRange(ArgExprs[0]->getLocStart(),
4468                                                 ArgExprs.back()->getLocEnd()));
4469       }
4470 
4471       return new (Context)
4472           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4473     }
4474     if (Fn->getType() == Context.PseudoObjectTy) {
4475       ExprResult result = CheckPlaceholderExpr(Fn);
4476       if (result.isInvalid()) return ExprError();
4477       Fn = result.get();
4478     }
4479 
4480     // Determine whether this is a dependent call inside a C++ template,
4481     // in which case we won't do any semantic analysis now.
4482     // FIXME: Will need to cache the results of name lookup (including ADL) in
4483     // Fn.
4484     bool Dependent = false;
4485     if (Fn->isTypeDependent())
4486       Dependent = true;
4487     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4488       Dependent = true;
4489 
4490     if (Dependent) {
4491       if (ExecConfig) {
4492         return new (Context) CUDAKernelCallExpr(
4493             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4494             Context.DependentTy, VK_RValue, RParenLoc);
4495       } else {
4496         return new (Context) CallExpr(
4497             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4498       }
4499     }
4500 
4501     // Determine whether this is a call to an object (C++ [over.call.object]).
4502     if (Fn->getType()->isRecordType())
4503       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4504                                           RParenLoc);
4505 
4506     if (Fn->getType() == Context.UnknownAnyTy) {
4507       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4508       if (result.isInvalid()) return ExprError();
4509       Fn = result.get();
4510     }
4511 
4512     if (Fn->getType() == Context.BoundMemberTy) {
4513       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4514     }
4515   }
4516 
4517   // Check for overloaded calls.  This can happen even in C due to extensions.
4518   if (Fn->getType() == Context.OverloadTy) {
4519     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4520 
4521     // We aren't supposed to apply this logic for if there's an '&' involved.
4522     if (!find.HasFormOfMemberPointer) {
4523       OverloadExpr *ovl = find.Expression;
4524       if (isa<UnresolvedLookupExpr>(ovl)) {
4525         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4526         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4527                                        RParenLoc, ExecConfig);
4528       } else {
4529         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4530                                          RParenLoc);
4531       }
4532     }
4533   }
4534 
4535   // If we're directly calling a function, get the appropriate declaration.
4536   if (Fn->getType() == Context.UnknownAnyTy) {
4537     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4538     if (result.isInvalid()) return ExprError();
4539     Fn = result.get();
4540   }
4541 
4542   Expr *NakedFn = Fn->IgnoreParens();
4543 
4544   NamedDecl *NDecl = nullptr;
4545   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4546     if (UnOp->getOpcode() == UO_AddrOf)
4547       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4548 
4549   if (isa<DeclRefExpr>(NakedFn))
4550     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4551   else if (isa<MemberExpr>(NakedFn))
4552     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4553 
4554   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4555     if (FD->hasAttr<EnableIfAttr>()) {
4556       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4557         Diag(Fn->getLocStart(),
4558              isa<CXXMethodDecl>(FD) ?
4559                  diag::err_ovl_no_viable_member_function_in_call :
4560                  diag::err_ovl_no_viable_function_in_call)
4561           << FD << FD->getSourceRange();
4562         Diag(FD->getLocation(),
4563              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4564             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4565       }
4566     }
4567   }
4568 
4569   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4570                                ExecConfig, IsExecConfig);
4571 }
4572 
4573 ExprResult
4574 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4575                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4576   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4577   if (!ConfigDecl)
4578     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4579                           << "cudaConfigureCall");
4580   QualType ConfigQTy = ConfigDecl->getType();
4581 
4582   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4583       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4584   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4585 
4586   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
4587                        /*IsExecConfig=*/true);
4588 }
4589 
4590 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4591 ///
4592 /// __builtin_astype( value, dst type )
4593 ///
4594 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4595                                  SourceLocation BuiltinLoc,
4596                                  SourceLocation RParenLoc) {
4597   ExprValueKind VK = VK_RValue;
4598   ExprObjectKind OK = OK_Ordinary;
4599   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4600   QualType SrcTy = E->getType();
4601   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4602     return ExprError(Diag(BuiltinLoc,
4603                           diag::err_invalid_astype_of_different_size)
4604                      << DstTy
4605                      << SrcTy
4606                      << E->getSourceRange());
4607   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4608 }
4609 
4610 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4611 /// provided arguments.
4612 ///
4613 /// __builtin_convertvector( value, dst type )
4614 ///
4615 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4616                                         SourceLocation BuiltinLoc,
4617                                         SourceLocation RParenLoc) {
4618   TypeSourceInfo *TInfo;
4619   GetTypeFromParser(ParsedDestTy, &TInfo);
4620   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4621 }
4622 
4623 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4624 /// i.e. an expression not of \p OverloadTy.  The expression should
4625 /// unary-convert to an expression of function-pointer or
4626 /// block-pointer type.
4627 ///
4628 /// \param NDecl the declaration being called, if available
4629 ExprResult
4630 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4631                             SourceLocation LParenLoc,
4632                             ArrayRef<Expr *> Args,
4633                             SourceLocation RParenLoc,
4634                             Expr *Config, bool IsExecConfig) {
4635   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4636   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4637 
4638   // Promote the function operand.
4639   // We special-case function promotion here because we only allow promoting
4640   // builtin functions to function pointers in the callee of a call.
4641   ExprResult Result;
4642   if (BuiltinID &&
4643       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4644     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4645                                CK_BuiltinFnToFnPtr).get();
4646   } else {
4647     Result = CallExprUnaryConversions(Fn);
4648   }
4649   if (Result.isInvalid())
4650     return ExprError();
4651   Fn = Result.get();
4652 
4653   // Make the call expr early, before semantic checks.  This guarantees cleanup
4654   // of arguments and function on error.
4655   CallExpr *TheCall;
4656   if (Config)
4657     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4658                                                cast<CallExpr>(Config), Args,
4659                                                Context.BoolTy, VK_RValue,
4660                                                RParenLoc);
4661   else
4662     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4663                                      VK_RValue, RParenLoc);
4664 
4665   // Bail out early if calling a builtin with custom typechecking.
4666   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4667     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4668 
4669  retry:
4670   const FunctionType *FuncT;
4671   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4672     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4673     // have type pointer to function".
4674     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4675     if (!FuncT)
4676       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4677                          << Fn->getType() << Fn->getSourceRange());
4678   } else if (const BlockPointerType *BPT =
4679                Fn->getType()->getAs<BlockPointerType>()) {
4680     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4681   } else {
4682     // Handle calls to expressions of unknown-any type.
4683     if (Fn->getType() == Context.UnknownAnyTy) {
4684       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4685       if (rewrite.isInvalid()) return ExprError();
4686       Fn = rewrite.get();
4687       TheCall->setCallee(Fn);
4688       goto retry;
4689     }
4690 
4691     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4692       << Fn->getType() << Fn->getSourceRange());
4693   }
4694 
4695   if (getLangOpts().CUDA) {
4696     if (Config) {
4697       // CUDA: Kernel calls must be to global functions
4698       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4699         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4700             << FDecl->getName() << Fn->getSourceRange());
4701 
4702       // CUDA: Kernel function must have 'void' return type
4703       if (!FuncT->getReturnType()->isVoidType())
4704         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4705             << Fn->getType() << Fn->getSourceRange());
4706     } else {
4707       // CUDA: Calls to global functions must be configured
4708       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4709         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4710             << FDecl->getName() << Fn->getSourceRange());
4711     }
4712   }
4713 
4714   // Check for a valid return type
4715   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4716                           FDecl))
4717     return ExprError();
4718 
4719   // We know the result type of the call, set it.
4720   TheCall->setType(FuncT->getCallResultType(Context));
4721   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4722 
4723   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4724   if (Proto) {
4725     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4726                                 IsExecConfig))
4727       return ExprError();
4728   } else {
4729     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4730 
4731     if (FDecl) {
4732       // Check if we have too few/too many template arguments, based
4733       // on our knowledge of the function definition.
4734       const FunctionDecl *Def = nullptr;
4735       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4736         Proto = Def->getType()->getAs<FunctionProtoType>();
4737        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4738           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4739           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4740       }
4741 
4742       // If the function we're calling isn't a function prototype, but we have
4743       // a function prototype from a prior declaratiom, use that prototype.
4744       if (!FDecl->hasPrototype())
4745         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4746     }
4747 
4748     // Promote the arguments (C99 6.5.2.2p6).
4749     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4750       Expr *Arg = Args[i];
4751 
4752       if (Proto && i < Proto->getNumParams()) {
4753         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4754             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4755         ExprResult ArgE =
4756             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4757         if (ArgE.isInvalid())
4758           return true;
4759 
4760         Arg = ArgE.getAs<Expr>();
4761 
4762       } else {
4763         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4764 
4765         if (ArgE.isInvalid())
4766           return true;
4767 
4768         Arg = ArgE.getAs<Expr>();
4769       }
4770 
4771       if (RequireCompleteType(Arg->getLocStart(),
4772                               Arg->getType(),
4773                               diag::err_call_incomplete_argument, Arg))
4774         return ExprError();
4775 
4776       TheCall->setArg(i, Arg);
4777     }
4778   }
4779 
4780   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4781     if (!Method->isStatic())
4782       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4783         << Fn->getSourceRange());
4784 
4785   // Check for sentinels
4786   if (NDecl)
4787     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4788 
4789   // Do special checking on direct calls to functions.
4790   if (FDecl) {
4791     if (CheckFunctionCall(FDecl, TheCall, Proto))
4792       return ExprError();
4793 
4794     if (BuiltinID)
4795       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4796   } else if (NDecl) {
4797     if (CheckPointerCall(NDecl, TheCall, Proto))
4798       return ExprError();
4799   } else {
4800     if (CheckOtherCall(TheCall, Proto))
4801       return ExprError();
4802   }
4803 
4804   return MaybeBindToTemporary(TheCall);
4805 }
4806 
4807 ExprResult
4808 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4809                            SourceLocation RParenLoc, Expr *InitExpr) {
4810   assert(Ty && "ActOnCompoundLiteral(): missing type");
4811   // FIXME: put back this assert when initializers are worked out.
4812   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4813 
4814   TypeSourceInfo *TInfo;
4815   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4816   if (!TInfo)
4817     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4818 
4819   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4820 }
4821 
4822 ExprResult
4823 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4824                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4825   QualType literalType = TInfo->getType();
4826 
4827   if (literalType->isArrayType()) {
4828     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4829           diag::err_illegal_decl_array_incomplete_type,
4830           SourceRange(LParenLoc,
4831                       LiteralExpr->getSourceRange().getEnd())))
4832       return ExprError();
4833     if (literalType->isVariableArrayType())
4834       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4835         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4836   } else if (!literalType->isDependentType() &&
4837              RequireCompleteType(LParenLoc, literalType,
4838                diag::err_typecheck_decl_incomplete_type,
4839                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4840     return ExprError();
4841 
4842   InitializedEntity Entity
4843     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4844   InitializationKind Kind
4845     = InitializationKind::CreateCStyleCast(LParenLoc,
4846                                            SourceRange(LParenLoc, RParenLoc),
4847                                            /*InitList=*/true);
4848   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4849   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4850                                       &literalType);
4851   if (Result.isInvalid())
4852     return ExprError();
4853   LiteralExpr = Result.get();
4854 
4855   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4856   if (isFileScope &&
4857       !LiteralExpr->isTypeDependent() &&
4858       !LiteralExpr->isValueDependent() &&
4859       !literalType->isDependentType()) { // 6.5.2.5p3
4860     if (CheckForConstantInitializer(LiteralExpr, literalType))
4861       return ExprError();
4862   }
4863 
4864   // In C, compound literals are l-values for some reason.
4865   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4866 
4867   return MaybeBindToTemporary(
4868            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4869                                              VK, LiteralExpr, isFileScope));
4870 }
4871 
4872 ExprResult
4873 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4874                     SourceLocation RBraceLoc) {
4875   // Immediately handle non-overload placeholders.  Overloads can be
4876   // resolved contextually, but everything else here can't.
4877   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4878     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4879       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4880 
4881       // Ignore failures; dropping the entire initializer list because
4882       // of one failure would be terrible for indexing/etc.
4883       if (result.isInvalid()) continue;
4884 
4885       InitArgList[I] = result.get();
4886     }
4887   }
4888 
4889   // Semantic analysis for initializers is done by ActOnDeclarator() and
4890   // CheckInitializer() - it requires knowledge of the object being intialized.
4891 
4892   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4893                                                RBraceLoc);
4894   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4895   return E;
4896 }
4897 
4898 /// Do an explicit extend of the given block pointer if we're in ARC.
4899 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4900   assert(E.get()->getType()->isBlockPointerType());
4901   assert(E.get()->isRValue());
4902 
4903   // Only do this in an r-value context.
4904   if (!S.getLangOpts().ObjCAutoRefCount) return;
4905 
4906   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4907                                CK_ARCExtendBlockObject, E.get(),
4908                                /*base path*/ nullptr, VK_RValue);
4909   S.ExprNeedsCleanups = true;
4910 }
4911 
4912 /// Prepare a conversion of the given expression to an ObjC object
4913 /// pointer type.
4914 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4915   QualType type = E.get()->getType();
4916   if (type->isObjCObjectPointerType()) {
4917     return CK_BitCast;
4918   } else if (type->isBlockPointerType()) {
4919     maybeExtendBlockObject(*this, E);
4920     return CK_BlockPointerToObjCPointerCast;
4921   } else {
4922     assert(type->isPointerType());
4923     return CK_CPointerToObjCPointerCast;
4924   }
4925 }
4926 
4927 /// Prepares for a scalar cast, performing all the necessary stages
4928 /// except the final cast and returning the kind required.
4929 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4930   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4931   // Also, callers should have filtered out the invalid cases with
4932   // pointers.  Everything else should be possible.
4933 
4934   QualType SrcTy = Src.get()->getType();
4935   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4936     return CK_NoOp;
4937 
4938   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4939   case Type::STK_MemberPointer:
4940     llvm_unreachable("member pointer type in C");
4941 
4942   case Type::STK_CPointer:
4943   case Type::STK_BlockPointer:
4944   case Type::STK_ObjCObjectPointer:
4945     switch (DestTy->getScalarTypeKind()) {
4946     case Type::STK_CPointer: {
4947       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4948       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4949       if (SrcAS != DestAS)
4950         return CK_AddressSpaceConversion;
4951       return CK_BitCast;
4952     }
4953     case Type::STK_BlockPointer:
4954       return (SrcKind == Type::STK_BlockPointer
4955                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4956     case Type::STK_ObjCObjectPointer:
4957       if (SrcKind == Type::STK_ObjCObjectPointer)
4958         return CK_BitCast;
4959       if (SrcKind == Type::STK_CPointer)
4960         return CK_CPointerToObjCPointerCast;
4961       maybeExtendBlockObject(*this, Src);
4962       return CK_BlockPointerToObjCPointerCast;
4963     case Type::STK_Bool:
4964       return CK_PointerToBoolean;
4965     case Type::STK_Integral:
4966       return CK_PointerToIntegral;
4967     case Type::STK_Floating:
4968     case Type::STK_FloatingComplex:
4969     case Type::STK_IntegralComplex:
4970     case Type::STK_MemberPointer:
4971       llvm_unreachable("illegal cast from pointer");
4972     }
4973     llvm_unreachable("Should have returned before this");
4974 
4975   case Type::STK_Bool: // casting from bool is like casting from an integer
4976   case Type::STK_Integral:
4977     switch (DestTy->getScalarTypeKind()) {
4978     case Type::STK_CPointer:
4979     case Type::STK_ObjCObjectPointer:
4980     case Type::STK_BlockPointer:
4981       if (Src.get()->isNullPointerConstant(Context,
4982                                            Expr::NPC_ValueDependentIsNull))
4983         return CK_NullToPointer;
4984       return CK_IntegralToPointer;
4985     case Type::STK_Bool:
4986       return CK_IntegralToBoolean;
4987     case Type::STK_Integral:
4988       return CK_IntegralCast;
4989     case Type::STK_Floating:
4990       return CK_IntegralToFloating;
4991     case Type::STK_IntegralComplex:
4992       Src = ImpCastExprToType(Src.get(),
4993                               DestTy->castAs<ComplexType>()->getElementType(),
4994                               CK_IntegralCast);
4995       return CK_IntegralRealToComplex;
4996     case Type::STK_FloatingComplex:
4997       Src = ImpCastExprToType(Src.get(),
4998                               DestTy->castAs<ComplexType>()->getElementType(),
4999                               CK_IntegralToFloating);
5000       return CK_FloatingRealToComplex;
5001     case Type::STK_MemberPointer:
5002       llvm_unreachable("member pointer type in C");
5003     }
5004     llvm_unreachable("Should have returned before this");
5005 
5006   case Type::STK_Floating:
5007     switch (DestTy->getScalarTypeKind()) {
5008     case Type::STK_Floating:
5009       return CK_FloatingCast;
5010     case Type::STK_Bool:
5011       return CK_FloatingToBoolean;
5012     case Type::STK_Integral:
5013       return CK_FloatingToIntegral;
5014     case Type::STK_FloatingComplex:
5015       Src = ImpCastExprToType(Src.get(),
5016                               DestTy->castAs<ComplexType>()->getElementType(),
5017                               CK_FloatingCast);
5018       return CK_FloatingRealToComplex;
5019     case Type::STK_IntegralComplex:
5020       Src = ImpCastExprToType(Src.get(),
5021                               DestTy->castAs<ComplexType>()->getElementType(),
5022                               CK_FloatingToIntegral);
5023       return CK_IntegralRealToComplex;
5024     case Type::STK_CPointer:
5025     case Type::STK_ObjCObjectPointer:
5026     case Type::STK_BlockPointer:
5027       llvm_unreachable("valid float->pointer cast?");
5028     case Type::STK_MemberPointer:
5029       llvm_unreachable("member pointer type in C");
5030     }
5031     llvm_unreachable("Should have returned before this");
5032 
5033   case Type::STK_FloatingComplex:
5034     switch (DestTy->getScalarTypeKind()) {
5035     case Type::STK_FloatingComplex:
5036       return CK_FloatingComplexCast;
5037     case Type::STK_IntegralComplex:
5038       return CK_FloatingComplexToIntegralComplex;
5039     case Type::STK_Floating: {
5040       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5041       if (Context.hasSameType(ET, DestTy))
5042         return CK_FloatingComplexToReal;
5043       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5044       return CK_FloatingCast;
5045     }
5046     case Type::STK_Bool:
5047       return CK_FloatingComplexToBoolean;
5048     case Type::STK_Integral:
5049       Src = ImpCastExprToType(Src.get(),
5050                               SrcTy->castAs<ComplexType>()->getElementType(),
5051                               CK_FloatingComplexToReal);
5052       return CK_FloatingToIntegral;
5053     case Type::STK_CPointer:
5054     case Type::STK_ObjCObjectPointer:
5055     case Type::STK_BlockPointer:
5056       llvm_unreachable("valid complex float->pointer cast?");
5057     case Type::STK_MemberPointer:
5058       llvm_unreachable("member pointer type in C");
5059     }
5060     llvm_unreachable("Should have returned before this");
5061 
5062   case Type::STK_IntegralComplex:
5063     switch (DestTy->getScalarTypeKind()) {
5064     case Type::STK_FloatingComplex:
5065       return CK_IntegralComplexToFloatingComplex;
5066     case Type::STK_IntegralComplex:
5067       return CK_IntegralComplexCast;
5068     case Type::STK_Integral: {
5069       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5070       if (Context.hasSameType(ET, DestTy))
5071         return CK_IntegralComplexToReal;
5072       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5073       return CK_IntegralCast;
5074     }
5075     case Type::STK_Bool:
5076       return CK_IntegralComplexToBoolean;
5077     case Type::STK_Floating:
5078       Src = ImpCastExprToType(Src.get(),
5079                               SrcTy->castAs<ComplexType>()->getElementType(),
5080                               CK_IntegralComplexToReal);
5081       return CK_IntegralToFloating;
5082     case Type::STK_CPointer:
5083     case Type::STK_ObjCObjectPointer:
5084     case Type::STK_BlockPointer:
5085       llvm_unreachable("valid complex int->pointer cast?");
5086     case Type::STK_MemberPointer:
5087       llvm_unreachable("member pointer type in C");
5088     }
5089     llvm_unreachable("Should have returned before this");
5090   }
5091 
5092   llvm_unreachable("Unhandled scalar cast");
5093 }
5094 
5095 static bool breakDownVectorType(QualType type, uint64_t &len,
5096                                 QualType &eltType) {
5097   // Vectors are simple.
5098   if (const VectorType *vecType = type->getAs<VectorType>()) {
5099     len = vecType->getNumElements();
5100     eltType = vecType->getElementType();
5101     assert(eltType->isScalarType());
5102     return true;
5103   }
5104 
5105   // We allow lax conversion to and from non-vector types, but only if
5106   // they're real types (i.e. non-complex, non-pointer scalar types).
5107   if (!type->isRealType()) return false;
5108 
5109   len = 1;
5110   eltType = type;
5111   return true;
5112 }
5113 
5114 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5115   uint64_t srcLen, destLen;
5116   QualType srcElt, destElt;
5117   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5118   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5119 
5120   // ASTContext::getTypeSize will return the size rounded up to a
5121   // power of 2, so instead of using that, we need to use the raw
5122   // element size multiplied by the element count.
5123   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5124   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5125 
5126   return (srcLen * srcEltSize == destLen * destEltSize);
5127 }
5128 
5129 /// Is this a legal conversion between two known vector types?
5130 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5131   assert(destTy->isVectorType() || srcTy->isVectorType());
5132 
5133   if (!Context.getLangOpts().LaxVectorConversions)
5134     return false;
5135   return VectorTypesMatch(*this, srcTy, destTy);
5136 }
5137 
5138 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5139                            CastKind &Kind) {
5140   assert(VectorTy->isVectorType() && "Not a vector type!");
5141 
5142   if (Ty->isVectorType() || Ty->isIntegerType()) {
5143     if (!VectorTypesMatch(*this, Ty, VectorTy))
5144       return Diag(R.getBegin(),
5145                   Ty->isVectorType() ?
5146                   diag::err_invalid_conversion_between_vectors :
5147                   diag::err_invalid_conversion_between_vector_and_integer)
5148         << VectorTy << Ty << R;
5149   } else
5150     return Diag(R.getBegin(),
5151                 diag::err_invalid_conversion_between_vector_and_scalar)
5152       << VectorTy << Ty << R;
5153 
5154   Kind = CK_BitCast;
5155   return false;
5156 }
5157 
5158 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5159                                     Expr *CastExpr, CastKind &Kind) {
5160   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5161 
5162   QualType SrcTy = CastExpr->getType();
5163 
5164   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5165   // an ExtVectorType.
5166   // In OpenCL, casts between vectors of different types are not allowed.
5167   // (See OpenCL 6.2).
5168   if (SrcTy->isVectorType()) {
5169     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5170         || (getLangOpts().OpenCL &&
5171             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5172       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5173         << DestTy << SrcTy << R;
5174       return ExprError();
5175     }
5176     Kind = CK_BitCast;
5177     return CastExpr;
5178   }
5179 
5180   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5181   // conversion will take place first from scalar to elt type, and then
5182   // splat from elt type to vector.
5183   if (SrcTy->isPointerType())
5184     return Diag(R.getBegin(),
5185                 diag::err_invalid_conversion_between_vector_and_scalar)
5186       << DestTy << SrcTy << R;
5187 
5188   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5189   ExprResult CastExprRes = CastExpr;
5190   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5191   if (CastExprRes.isInvalid())
5192     return ExprError();
5193   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5194 
5195   Kind = CK_VectorSplat;
5196   return CastExpr;
5197 }
5198 
5199 ExprResult
5200 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5201                     Declarator &D, ParsedType &Ty,
5202                     SourceLocation RParenLoc, Expr *CastExpr) {
5203   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5204          "ActOnCastExpr(): missing type or expr");
5205 
5206   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5207   if (D.isInvalidType())
5208     return ExprError();
5209 
5210   if (getLangOpts().CPlusPlus) {
5211     // Check that there are no default arguments (C++ only).
5212     CheckExtraCXXDefaultArguments(D);
5213   }
5214 
5215   checkUnusedDeclAttributes(D);
5216 
5217   QualType castType = castTInfo->getType();
5218   Ty = CreateParsedType(castType, castTInfo);
5219 
5220   bool isVectorLiteral = false;
5221 
5222   // Check for an altivec or OpenCL literal,
5223   // i.e. all the elements are integer constants.
5224   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5225   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5226   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5227        && castType->isVectorType() && (PE || PLE)) {
5228     if (PLE && PLE->getNumExprs() == 0) {
5229       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5230       return ExprError();
5231     }
5232     if (PE || PLE->getNumExprs() == 1) {
5233       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5234       if (!E->getType()->isVectorType())
5235         isVectorLiteral = true;
5236     }
5237     else
5238       isVectorLiteral = true;
5239   }
5240 
5241   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5242   // then handle it as such.
5243   if (isVectorLiteral)
5244     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5245 
5246   // If the Expr being casted is a ParenListExpr, handle it specially.
5247   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5248   // sequence of BinOp comma operators.
5249   if (isa<ParenListExpr>(CastExpr)) {
5250     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5251     if (Result.isInvalid()) return ExprError();
5252     CastExpr = Result.get();
5253   }
5254 
5255   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5256       !getSourceManager().isInSystemMacro(LParenLoc))
5257     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5258 
5259   CheckTollFreeBridgeCast(castType, CastExpr);
5260 
5261   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5262 }
5263 
5264 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5265                                     SourceLocation RParenLoc, Expr *E,
5266                                     TypeSourceInfo *TInfo) {
5267   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5268          "Expected paren or paren list expression");
5269 
5270   Expr **exprs;
5271   unsigned numExprs;
5272   Expr *subExpr;
5273   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5274   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5275     LiteralLParenLoc = PE->getLParenLoc();
5276     LiteralRParenLoc = PE->getRParenLoc();
5277     exprs = PE->getExprs();
5278     numExprs = PE->getNumExprs();
5279   } else { // isa<ParenExpr> by assertion at function entrance
5280     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5281     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5282     subExpr = cast<ParenExpr>(E)->getSubExpr();
5283     exprs = &subExpr;
5284     numExprs = 1;
5285   }
5286 
5287   QualType Ty = TInfo->getType();
5288   assert(Ty->isVectorType() && "Expected vector type");
5289 
5290   SmallVector<Expr *, 8> initExprs;
5291   const VectorType *VTy = Ty->getAs<VectorType>();
5292   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5293 
5294   // '(...)' form of vector initialization in AltiVec: the number of
5295   // initializers must be one or must match the size of the vector.
5296   // If a single value is specified in the initializer then it will be
5297   // replicated to all the components of the vector
5298   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5299     // The number of initializers must be one or must match the size of the
5300     // vector. If a single value is specified in the initializer then it will
5301     // be replicated to all the components of the vector
5302     if (numExprs == 1) {
5303       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5304       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5305       if (Literal.isInvalid())
5306         return ExprError();
5307       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5308                                   PrepareScalarCast(Literal, ElemTy));
5309       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5310     }
5311     else if (numExprs < numElems) {
5312       Diag(E->getExprLoc(),
5313            diag::err_incorrect_number_of_vector_initializers);
5314       return ExprError();
5315     }
5316     else
5317       initExprs.append(exprs, exprs + numExprs);
5318   }
5319   else {
5320     // For OpenCL, when the number of initializers is a single value,
5321     // it will be replicated to all components of the vector.
5322     if (getLangOpts().OpenCL &&
5323         VTy->getVectorKind() == VectorType::GenericVector &&
5324         numExprs == 1) {
5325         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5326         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5327         if (Literal.isInvalid())
5328           return ExprError();
5329         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5330                                     PrepareScalarCast(Literal, ElemTy));
5331         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5332     }
5333 
5334     initExprs.append(exprs, exprs + numExprs);
5335   }
5336   // FIXME: This means that pretty-printing the final AST will produce curly
5337   // braces instead of the original commas.
5338   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5339                                                    initExprs, LiteralRParenLoc);
5340   initE->setType(Ty);
5341   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5342 }
5343 
5344 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5345 /// the ParenListExpr into a sequence of comma binary operators.
5346 ExprResult
5347 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5348   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5349   if (!E)
5350     return OrigExpr;
5351 
5352   ExprResult Result(E->getExpr(0));
5353 
5354   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5355     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5356                         E->getExpr(i));
5357 
5358   if (Result.isInvalid()) return ExprError();
5359 
5360   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5361 }
5362 
5363 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5364                                     SourceLocation R,
5365                                     MultiExprArg Val) {
5366   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5367   return expr;
5368 }
5369 
5370 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5371 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5372 /// emitted.
5373 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5374                                       SourceLocation QuestionLoc) {
5375   Expr *NullExpr = LHSExpr;
5376   Expr *NonPointerExpr = RHSExpr;
5377   Expr::NullPointerConstantKind NullKind =
5378       NullExpr->isNullPointerConstant(Context,
5379                                       Expr::NPC_ValueDependentIsNotNull);
5380 
5381   if (NullKind == Expr::NPCK_NotNull) {
5382     NullExpr = RHSExpr;
5383     NonPointerExpr = LHSExpr;
5384     NullKind =
5385         NullExpr->isNullPointerConstant(Context,
5386                                         Expr::NPC_ValueDependentIsNotNull);
5387   }
5388 
5389   if (NullKind == Expr::NPCK_NotNull)
5390     return false;
5391 
5392   if (NullKind == Expr::NPCK_ZeroExpression)
5393     return false;
5394 
5395   if (NullKind == Expr::NPCK_ZeroLiteral) {
5396     // In this case, check to make sure that we got here from a "NULL"
5397     // string in the source code.
5398     NullExpr = NullExpr->IgnoreParenImpCasts();
5399     SourceLocation loc = NullExpr->getExprLoc();
5400     if (!findMacroSpelling(loc, "NULL"))
5401       return false;
5402   }
5403 
5404   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5405   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5406       << NonPointerExpr->getType() << DiagType
5407       << NonPointerExpr->getSourceRange();
5408   return true;
5409 }
5410 
5411 /// \brief Return false if the condition expression is valid, true otherwise.
5412 static bool checkCondition(Sema &S, Expr *Cond) {
5413   QualType CondTy = Cond->getType();
5414 
5415   // C99 6.5.15p2
5416   if (CondTy->isScalarType()) return false;
5417 
5418   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5419   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5420     return false;
5421 
5422   // Emit the proper error message.
5423   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5424                               diag::err_typecheck_cond_expect_scalar :
5425                               diag::err_typecheck_cond_expect_scalar_or_vector)
5426     << CondTy;
5427   return true;
5428 }
5429 
5430 /// \brief Return false if the two expressions can be converted to a vector,
5431 /// true otherwise
5432 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5433                                                     ExprResult &RHS,
5434                                                     QualType CondTy) {
5435   // Both operands should be of scalar type.
5436   if (!LHS.get()->getType()->isScalarType()) {
5437     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5438       << CondTy;
5439     return true;
5440   }
5441   if (!RHS.get()->getType()->isScalarType()) {
5442     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5443       << CondTy;
5444     return true;
5445   }
5446 
5447   // Implicity convert these scalars to the type of the condition.
5448   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5449   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5450   return false;
5451 }
5452 
5453 /// \brief Handle when one or both operands are void type.
5454 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5455                                          ExprResult &RHS) {
5456     Expr *LHSExpr = LHS.get();
5457     Expr *RHSExpr = RHS.get();
5458 
5459     if (!LHSExpr->getType()->isVoidType())
5460       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5461         << RHSExpr->getSourceRange();
5462     if (!RHSExpr->getType()->isVoidType())
5463       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5464         << LHSExpr->getSourceRange();
5465     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5466     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5467     return S.Context.VoidTy;
5468 }
5469 
5470 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5471 /// true otherwise.
5472 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5473                                         QualType PointerTy) {
5474   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5475       !NullExpr.get()->isNullPointerConstant(S.Context,
5476                                             Expr::NPC_ValueDependentIsNull))
5477     return true;
5478 
5479   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5480   return false;
5481 }
5482 
5483 /// \brief Checks compatibility between two pointers and return the resulting
5484 /// type.
5485 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5486                                                      ExprResult &RHS,
5487                                                      SourceLocation Loc) {
5488   QualType LHSTy = LHS.get()->getType();
5489   QualType RHSTy = RHS.get()->getType();
5490 
5491   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5492     // Two identical pointers types are always compatible.
5493     return LHSTy;
5494   }
5495 
5496   QualType lhptee, rhptee;
5497 
5498   // Get the pointee types.
5499   bool IsBlockPointer = false;
5500   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5501     lhptee = LHSBTy->getPointeeType();
5502     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5503     IsBlockPointer = true;
5504   } else {
5505     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5506     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5507   }
5508 
5509   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5510   // differently qualified versions of compatible types, the result type is
5511   // a pointer to an appropriately qualified version of the composite
5512   // type.
5513 
5514   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5515   // clause doesn't make sense for our extensions. E.g. address space 2 should
5516   // be incompatible with address space 3: they may live on different devices or
5517   // anything.
5518   Qualifiers lhQual = lhptee.getQualifiers();
5519   Qualifiers rhQual = rhptee.getQualifiers();
5520 
5521   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5522   lhQual.removeCVRQualifiers();
5523   rhQual.removeCVRQualifiers();
5524 
5525   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5526   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5527 
5528   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5529 
5530   if (CompositeTy.isNull()) {
5531     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5532       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5533       << RHS.get()->getSourceRange();
5534     // In this situation, we assume void* type. No especially good
5535     // reason, but this is what gcc does, and we do have to pick
5536     // to get a consistent AST.
5537     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5538     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5539     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5540     return incompatTy;
5541   }
5542 
5543   // The pointer types are compatible.
5544   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5545   if (IsBlockPointer)
5546     ResultTy = S.Context.getBlockPointerType(ResultTy);
5547   else
5548     ResultTy = S.Context.getPointerType(ResultTy);
5549 
5550   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5551   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5552   return ResultTy;
5553 }
5554 
5555 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5556 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5557 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5558 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5559   if (QT->isObjCIdType())
5560     return true;
5561 
5562   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5563   if (!OPT)
5564     return false;
5565 
5566   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5567     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5568       return false;
5569 
5570   ObjCProtocolDecl* PNSCopying =
5571     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5572   ObjCProtocolDecl* PNSObject =
5573     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5574 
5575   for (auto *Proto : OPT->quals()) {
5576     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5577         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5578       ;
5579     else
5580       return false;
5581   }
5582   return true;
5583 }
5584 
5585 /// \brief Return the resulting type when the operands are both block pointers.
5586 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5587                                                           ExprResult &LHS,
5588                                                           ExprResult &RHS,
5589                                                           SourceLocation Loc) {
5590   QualType LHSTy = LHS.get()->getType();
5591   QualType RHSTy = RHS.get()->getType();
5592 
5593   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5594     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5595       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5596       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5597       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5598       return destType;
5599     }
5600     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5601       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5602       << RHS.get()->getSourceRange();
5603     return QualType();
5604   }
5605 
5606   // We have 2 block pointer types.
5607   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5608 }
5609 
5610 /// \brief Return the resulting type when the operands are both pointers.
5611 static QualType
5612 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5613                                             ExprResult &RHS,
5614                                             SourceLocation Loc) {
5615   // get the pointer types
5616   QualType LHSTy = LHS.get()->getType();
5617   QualType RHSTy = RHS.get()->getType();
5618 
5619   // get the "pointed to" types
5620   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5621   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5622 
5623   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5624   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5625     // Figure out necessary qualifiers (C99 6.5.15p6)
5626     QualType destPointee
5627       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5628     QualType destType = S.Context.getPointerType(destPointee);
5629     // Add qualifiers if necessary.
5630     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5631     // Promote to void*.
5632     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5633     return destType;
5634   }
5635   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5636     QualType destPointee
5637       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5638     QualType destType = S.Context.getPointerType(destPointee);
5639     // Add qualifiers if necessary.
5640     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5641     // Promote to void*.
5642     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5643     return destType;
5644   }
5645 
5646   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5647 }
5648 
5649 /// \brief Return false if the first expression is not an integer and the second
5650 /// expression is not a pointer, true otherwise.
5651 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5652                                         Expr* PointerExpr, SourceLocation Loc,
5653                                         bool IsIntFirstExpr) {
5654   if (!PointerExpr->getType()->isPointerType() ||
5655       !Int.get()->getType()->isIntegerType())
5656     return false;
5657 
5658   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5659   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5660 
5661   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5662     << Expr1->getType() << Expr2->getType()
5663     << Expr1->getSourceRange() << Expr2->getSourceRange();
5664   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5665                             CK_IntegralToPointer);
5666   return true;
5667 }
5668 
5669 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5670 /// In that case, LHS = cond.
5671 /// C99 6.5.15
5672 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5673                                         ExprResult &RHS, ExprValueKind &VK,
5674                                         ExprObjectKind &OK,
5675                                         SourceLocation QuestionLoc) {
5676 
5677   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5678   if (!LHSResult.isUsable()) return QualType();
5679   LHS = LHSResult;
5680 
5681   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5682   if (!RHSResult.isUsable()) return QualType();
5683   RHS = RHSResult;
5684 
5685   // C++ is sufficiently different to merit its own checker.
5686   if (getLangOpts().CPlusPlus)
5687     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5688 
5689   VK = VK_RValue;
5690   OK = OK_Ordinary;
5691 
5692   // First, check the condition.
5693   Cond = UsualUnaryConversions(Cond.get());
5694   if (Cond.isInvalid())
5695     return QualType();
5696   if (checkCondition(*this, Cond.get()))
5697     return QualType();
5698 
5699   // Now check the two expressions.
5700   if (LHS.get()->getType()->isVectorType() ||
5701       RHS.get()->getType()->isVectorType())
5702     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5703 
5704   UsualArithmeticConversions(LHS, RHS);
5705   if (LHS.isInvalid() || RHS.isInvalid())
5706     return QualType();
5707 
5708   QualType CondTy = Cond.get()->getType();
5709   QualType LHSTy = LHS.get()->getType();
5710   QualType RHSTy = RHS.get()->getType();
5711 
5712   // If the condition is a vector, and both operands are scalar,
5713   // attempt to implicity convert them to the vector type to act like the
5714   // built in select. (OpenCL v1.1 s6.3.i)
5715   if (getLangOpts().OpenCL && CondTy->isVectorType())
5716     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5717       return QualType();
5718 
5719   // If both operands have arithmetic type, do the usual arithmetic conversions
5720   // to find a common type: C99 6.5.15p3,5.
5721   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5722     return LHS.get()->getType();
5723 
5724   // If both operands are the same structure or union type, the result is that
5725   // type.
5726   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5727     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5728       if (LHSRT->getDecl() == RHSRT->getDecl())
5729         // "If both the operands have structure or union type, the result has
5730         // that type."  This implies that CV qualifiers are dropped.
5731         return LHSTy.getUnqualifiedType();
5732     // FIXME: Type of conditional expression must be complete in C mode.
5733   }
5734 
5735   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5736   // The following || allows only one side to be void (a GCC-ism).
5737   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5738     return checkConditionalVoidType(*this, LHS, RHS);
5739   }
5740 
5741   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5742   // the type of the other operand."
5743   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5744   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5745 
5746   // All objective-c pointer type analysis is done here.
5747   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5748                                                         QuestionLoc);
5749   if (LHS.isInvalid() || RHS.isInvalid())
5750     return QualType();
5751   if (!compositeType.isNull())
5752     return compositeType;
5753 
5754 
5755   // Handle block pointer types.
5756   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5757     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5758                                                      QuestionLoc);
5759 
5760   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5761   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5762     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5763                                                        QuestionLoc);
5764 
5765   // GCC compatibility: soften pointer/integer mismatch.  Note that
5766   // null pointers have been filtered out by this point.
5767   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5768       /*isIntFirstExpr=*/true))
5769     return RHSTy;
5770   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5771       /*isIntFirstExpr=*/false))
5772     return LHSTy;
5773 
5774   // Emit a better diagnostic if one of the expressions is a null pointer
5775   // constant and the other is not a pointer type. In this case, the user most
5776   // likely forgot to take the address of the other expression.
5777   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5778     return QualType();
5779 
5780   // Otherwise, the operands are not compatible.
5781   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5782     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5783     << RHS.get()->getSourceRange();
5784   return QualType();
5785 }
5786 
5787 /// FindCompositeObjCPointerType - Helper method to find composite type of
5788 /// two objective-c pointer types of the two input expressions.
5789 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5790                                             SourceLocation QuestionLoc) {
5791   QualType LHSTy = LHS.get()->getType();
5792   QualType RHSTy = RHS.get()->getType();
5793 
5794   // Handle things like Class and struct objc_class*.  Here we case the result
5795   // to the pseudo-builtin, because that will be implicitly cast back to the
5796   // redefinition type if an attempt is made to access its fields.
5797   if (LHSTy->isObjCClassType() &&
5798       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5799     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5800     return LHSTy;
5801   }
5802   if (RHSTy->isObjCClassType() &&
5803       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5804     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5805     return RHSTy;
5806   }
5807   // And the same for struct objc_object* / id
5808   if (LHSTy->isObjCIdType() &&
5809       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5810     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5811     return LHSTy;
5812   }
5813   if (RHSTy->isObjCIdType() &&
5814       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5815     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5816     return RHSTy;
5817   }
5818   // And the same for struct objc_selector* / SEL
5819   if (Context.isObjCSelType(LHSTy) &&
5820       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5821     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5822     return LHSTy;
5823   }
5824   if (Context.isObjCSelType(RHSTy) &&
5825       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5826     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5827     return RHSTy;
5828   }
5829   // Check constraints for Objective-C object pointers types.
5830   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5831 
5832     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5833       // Two identical object pointer types are always compatible.
5834       return LHSTy;
5835     }
5836     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5837     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5838     QualType compositeType = LHSTy;
5839 
5840     // If both operands are interfaces and either operand can be
5841     // assigned to the other, use that type as the composite
5842     // type. This allows
5843     //   xxx ? (A*) a : (B*) b
5844     // where B is a subclass of A.
5845     //
5846     // Additionally, as for assignment, if either type is 'id'
5847     // allow silent coercion. Finally, if the types are
5848     // incompatible then make sure to use 'id' as the composite
5849     // type so the result is acceptable for sending messages to.
5850 
5851     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5852     // It could return the composite type.
5853     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5854       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5855     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5856       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5857     } else if ((LHSTy->isObjCQualifiedIdType() ||
5858                 RHSTy->isObjCQualifiedIdType()) &&
5859                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5860       // Need to handle "id<xx>" explicitly.
5861       // GCC allows qualified id and any Objective-C type to devolve to
5862       // id. Currently localizing to here until clear this should be
5863       // part of ObjCQualifiedIdTypesAreCompatible.
5864       compositeType = Context.getObjCIdType();
5865     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5866       compositeType = Context.getObjCIdType();
5867     } else if (!(compositeType =
5868                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5869       ;
5870     else {
5871       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5872       << LHSTy << RHSTy
5873       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5874       QualType incompatTy = Context.getObjCIdType();
5875       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5876       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5877       return incompatTy;
5878     }
5879     // The object pointer types are compatible.
5880     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5881     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5882     return compositeType;
5883   }
5884   // Check Objective-C object pointer types and 'void *'
5885   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5886     if (getLangOpts().ObjCAutoRefCount) {
5887       // ARC forbids the implicit conversion of object pointers to 'void *',
5888       // so these types are not compatible.
5889       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5890           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5891       LHS = RHS = true;
5892       return QualType();
5893     }
5894     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5895     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5896     QualType destPointee
5897     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5898     QualType destType = Context.getPointerType(destPointee);
5899     // Add qualifiers if necessary.
5900     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5901     // Promote to void*.
5902     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5903     return destType;
5904   }
5905   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5906     if (getLangOpts().ObjCAutoRefCount) {
5907       // ARC forbids the implicit conversion of object pointers to 'void *',
5908       // so these types are not compatible.
5909       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5910           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5911       LHS = RHS = true;
5912       return QualType();
5913     }
5914     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5915     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5916     QualType destPointee
5917     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5918     QualType destType = Context.getPointerType(destPointee);
5919     // Add qualifiers if necessary.
5920     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5921     // Promote to void*.
5922     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5923     return destType;
5924   }
5925   return QualType();
5926 }
5927 
5928 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5929 /// ParenRange in parentheses.
5930 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5931                                const PartialDiagnostic &Note,
5932                                SourceRange ParenRange) {
5933   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5934   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5935       EndLoc.isValid()) {
5936     Self.Diag(Loc, Note)
5937       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5938       << FixItHint::CreateInsertion(EndLoc, ")");
5939   } else {
5940     // We can't display the parentheses, so just show the bare note.
5941     Self.Diag(Loc, Note) << ParenRange;
5942   }
5943 }
5944 
5945 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5946   return Opc >= BO_Mul && Opc <= BO_Shr;
5947 }
5948 
5949 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5950 /// expression, either using a built-in or overloaded operator,
5951 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5952 /// expression.
5953 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5954                                    Expr **RHSExprs) {
5955   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5956   E = E->IgnoreImpCasts();
5957   E = E->IgnoreConversionOperator();
5958   E = E->IgnoreImpCasts();
5959 
5960   // Built-in binary operator.
5961   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5962     if (IsArithmeticOp(OP->getOpcode())) {
5963       *Opcode = OP->getOpcode();
5964       *RHSExprs = OP->getRHS();
5965       return true;
5966     }
5967   }
5968 
5969   // Overloaded operator.
5970   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5971     if (Call->getNumArgs() != 2)
5972       return false;
5973 
5974     // Make sure this is really a binary operator that is safe to pass into
5975     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5976     OverloadedOperatorKind OO = Call->getOperator();
5977     if (OO < OO_Plus || OO > OO_Arrow ||
5978         OO == OO_PlusPlus || OO == OO_MinusMinus)
5979       return false;
5980 
5981     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5982     if (IsArithmeticOp(OpKind)) {
5983       *Opcode = OpKind;
5984       *RHSExprs = Call->getArg(1);
5985       return true;
5986     }
5987   }
5988 
5989   return false;
5990 }
5991 
5992 static bool IsLogicOp(BinaryOperatorKind Opc) {
5993   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5994 }
5995 
5996 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5997 /// or is a logical expression such as (x==y) which has int type, but is
5998 /// commonly interpreted as boolean.
5999 static bool ExprLooksBoolean(Expr *E) {
6000   E = E->IgnoreParenImpCasts();
6001 
6002   if (E->getType()->isBooleanType())
6003     return true;
6004   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6005     return IsLogicOp(OP->getOpcode());
6006   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6007     return OP->getOpcode() == UO_LNot;
6008 
6009   return false;
6010 }
6011 
6012 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6013 /// and binary operator are mixed in a way that suggests the programmer assumed
6014 /// the conditional operator has higher precedence, for example:
6015 /// "int x = a + someBinaryCondition ? 1 : 2".
6016 static void DiagnoseConditionalPrecedence(Sema &Self,
6017                                           SourceLocation OpLoc,
6018                                           Expr *Condition,
6019                                           Expr *LHSExpr,
6020                                           Expr *RHSExpr) {
6021   BinaryOperatorKind CondOpcode;
6022   Expr *CondRHS;
6023 
6024   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6025     return;
6026   if (!ExprLooksBoolean(CondRHS))
6027     return;
6028 
6029   // The condition is an arithmetic binary expression, with a right-
6030   // hand side that looks boolean, so warn.
6031 
6032   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6033       << Condition->getSourceRange()
6034       << BinaryOperator::getOpcodeStr(CondOpcode);
6035 
6036   SuggestParentheses(Self, OpLoc,
6037     Self.PDiag(diag::note_precedence_silence)
6038       << BinaryOperator::getOpcodeStr(CondOpcode),
6039     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6040 
6041   SuggestParentheses(Self, OpLoc,
6042     Self.PDiag(diag::note_precedence_conditional_first),
6043     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6044 }
6045 
6046 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6047 /// in the case of a the GNU conditional expr extension.
6048 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6049                                     SourceLocation ColonLoc,
6050                                     Expr *CondExpr, Expr *LHSExpr,
6051                                     Expr *RHSExpr) {
6052   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6053   // was the condition.
6054   OpaqueValueExpr *opaqueValue = nullptr;
6055   Expr *commonExpr = nullptr;
6056   if (!LHSExpr) {
6057     commonExpr = CondExpr;
6058     // Lower out placeholder types first.  This is important so that we don't
6059     // try to capture a placeholder. This happens in few cases in C++; such
6060     // as Objective-C++'s dictionary subscripting syntax.
6061     if (commonExpr->hasPlaceholderType()) {
6062       ExprResult result = CheckPlaceholderExpr(commonExpr);
6063       if (!result.isUsable()) return ExprError();
6064       commonExpr = result.get();
6065     }
6066     // We usually want to apply unary conversions *before* saving, except
6067     // in the special case of a C++ l-value conditional.
6068     if (!(getLangOpts().CPlusPlus
6069           && !commonExpr->isTypeDependent()
6070           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6071           && commonExpr->isGLValue()
6072           && commonExpr->isOrdinaryOrBitFieldObject()
6073           && RHSExpr->isOrdinaryOrBitFieldObject()
6074           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6075       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6076       if (commonRes.isInvalid())
6077         return ExprError();
6078       commonExpr = commonRes.get();
6079     }
6080 
6081     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6082                                                 commonExpr->getType(),
6083                                                 commonExpr->getValueKind(),
6084                                                 commonExpr->getObjectKind(),
6085                                                 commonExpr);
6086     LHSExpr = CondExpr = opaqueValue;
6087   }
6088 
6089   ExprValueKind VK = VK_RValue;
6090   ExprObjectKind OK = OK_Ordinary;
6091   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6092   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6093                                              VK, OK, QuestionLoc);
6094   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6095       RHS.isInvalid())
6096     return ExprError();
6097 
6098   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6099                                 RHS.get());
6100 
6101   if (!commonExpr)
6102     return new (Context)
6103         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6104                             RHS.get(), result, VK, OK);
6105 
6106   return new (Context) BinaryConditionalOperator(
6107       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6108       ColonLoc, result, VK, OK);
6109 }
6110 
6111 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6112 // being closely modeled after the C99 spec:-). The odd characteristic of this
6113 // routine is it effectively iqnores the qualifiers on the top level pointee.
6114 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6115 // FIXME: add a couple examples in this comment.
6116 static Sema::AssignConvertType
6117 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6118   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6119   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6120 
6121   // get the "pointed to" type (ignoring qualifiers at the top level)
6122   const Type *lhptee, *rhptee;
6123   Qualifiers lhq, rhq;
6124   std::tie(lhptee, lhq) =
6125       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6126   std::tie(rhptee, rhq) =
6127       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6128 
6129   Sema::AssignConvertType ConvTy = Sema::Compatible;
6130 
6131   // C99 6.5.16.1p1: This following citation is common to constraints
6132   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6133   // qualifiers of the type *pointed to* by the right;
6134 
6135   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6136   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6137       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6138     // Ignore lifetime for further calculation.
6139     lhq.removeObjCLifetime();
6140     rhq.removeObjCLifetime();
6141   }
6142 
6143   if (!lhq.compatiblyIncludes(rhq)) {
6144     // Treat address-space mismatches as fatal.  TODO: address subspaces
6145     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6146       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6147 
6148     // It's okay to add or remove GC or lifetime qualifiers when converting to
6149     // and from void*.
6150     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6151                         .compatiblyIncludes(
6152                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6153              && (lhptee->isVoidType() || rhptee->isVoidType()))
6154       ; // keep old
6155 
6156     // Treat lifetime mismatches as fatal.
6157     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6158       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6159 
6160     // For GCC compatibility, other qualifier mismatches are treated
6161     // as still compatible in C.
6162     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6163   }
6164 
6165   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6166   // incomplete type and the other is a pointer to a qualified or unqualified
6167   // version of void...
6168   if (lhptee->isVoidType()) {
6169     if (rhptee->isIncompleteOrObjectType())
6170       return ConvTy;
6171 
6172     // As an extension, we allow cast to/from void* to function pointer.
6173     assert(rhptee->isFunctionType());
6174     return Sema::FunctionVoidPointer;
6175   }
6176 
6177   if (rhptee->isVoidType()) {
6178     if (lhptee->isIncompleteOrObjectType())
6179       return ConvTy;
6180 
6181     // As an extension, we allow cast to/from void* to function pointer.
6182     assert(lhptee->isFunctionType());
6183     return Sema::FunctionVoidPointer;
6184   }
6185 
6186   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6187   // unqualified versions of compatible types, ...
6188   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6189   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6190     // Check if the pointee types are compatible ignoring the sign.
6191     // We explicitly check for char so that we catch "char" vs
6192     // "unsigned char" on systems where "char" is unsigned.
6193     if (lhptee->isCharType())
6194       ltrans = S.Context.UnsignedCharTy;
6195     else if (lhptee->hasSignedIntegerRepresentation())
6196       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6197 
6198     if (rhptee->isCharType())
6199       rtrans = S.Context.UnsignedCharTy;
6200     else if (rhptee->hasSignedIntegerRepresentation())
6201       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6202 
6203     if (ltrans == rtrans) {
6204       // Types are compatible ignoring the sign. Qualifier incompatibility
6205       // takes priority over sign incompatibility because the sign
6206       // warning can be disabled.
6207       if (ConvTy != Sema::Compatible)
6208         return ConvTy;
6209 
6210       return Sema::IncompatiblePointerSign;
6211     }
6212 
6213     // If we are a multi-level pointer, it's possible that our issue is simply
6214     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6215     // the eventual target type is the same and the pointers have the same
6216     // level of indirection, this must be the issue.
6217     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6218       do {
6219         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6220         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6221       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6222 
6223       if (lhptee == rhptee)
6224         return Sema::IncompatibleNestedPointerQualifiers;
6225     }
6226 
6227     // General pointer incompatibility takes priority over qualifiers.
6228     return Sema::IncompatiblePointer;
6229   }
6230   if (!S.getLangOpts().CPlusPlus &&
6231       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6232     return Sema::IncompatiblePointer;
6233   return ConvTy;
6234 }
6235 
6236 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6237 /// block pointer types are compatible or whether a block and normal pointer
6238 /// are compatible. It is more restrict than comparing two function pointer
6239 // types.
6240 static Sema::AssignConvertType
6241 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6242                                     QualType RHSType) {
6243   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6244   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6245 
6246   QualType lhptee, rhptee;
6247 
6248   // get the "pointed to" type (ignoring qualifiers at the top level)
6249   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6250   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6251 
6252   // In C++, the types have to match exactly.
6253   if (S.getLangOpts().CPlusPlus)
6254     return Sema::IncompatibleBlockPointer;
6255 
6256   Sema::AssignConvertType ConvTy = Sema::Compatible;
6257 
6258   // For blocks we enforce that qualifiers are identical.
6259   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6260     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6261 
6262   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6263     return Sema::IncompatibleBlockPointer;
6264 
6265   return ConvTy;
6266 }
6267 
6268 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6269 /// for assignment compatibility.
6270 static Sema::AssignConvertType
6271 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6272                                    QualType RHSType) {
6273   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6274   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6275 
6276   if (LHSType->isObjCBuiltinType()) {
6277     // Class is not compatible with ObjC object pointers.
6278     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6279         !RHSType->isObjCQualifiedClassType())
6280       return Sema::IncompatiblePointer;
6281     return Sema::Compatible;
6282   }
6283   if (RHSType->isObjCBuiltinType()) {
6284     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6285         !LHSType->isObjCQualifiedClassType())
6286       return Sema::IncompatiblePointer;
6287     return Sema::Compatible;
6288   }
6289   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6290   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6291 
6292   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6293       // make an exception for id<P>
6294       !LHSType->isObjCQualifiedIdType())
6295     return Sema::CompatiblePointerDiscardsQualifiers;
6296 
6297   if (S.Context.typesAreCompatible(LHSType, RHSType))
6298     return Sema::Compatible;
6299   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6300     return Sema::IncompatibleObjCQualifiedId;
6301   return Sema::IncompatiblePointer;
6302 }
6303 
6304 Sema::AssignConvertType
6305 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6306                                  QualType LHSType, QualType RHSType) {
6307   // Fake up an opaque expression.  We don't actually care about what
6308   // cast operations are required, so if CheckAssignmentConstraints
6309   // adds casts to this they'll be wasted, but fortunately that doesn't
6310   // usually happen on valid code.
6311   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6312   ExprResult RHSPtr = &RHSExpr;
6313   CastKind K = CK_Invalid;
6314 
6315   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6316 }
6317 
6318 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6319 /// has code to accommodate several GCC extensions when type checking
6320 /// pointers. Here are some objectionable examples that GCC considers warnings:
6321 ///
6322 ///  int a, *pint;
6323 ///  short *pshort;
6324 ///  struct foo *pfoo;
6325 ///
6326 ///  pint = pshort; // warning: assignment from incompatible pointer type
6327 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6328 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6329 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6330 ///
6331 /// As a result, the code for dealing with pointers is more complex than the
6332 /// C99 spec dictates.
6333 ///
6334 /// Sets 'Kind' for any result kind except Incompatible.
6335 Sema::AssignConvertType
6336 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6337                                  CastKind &Kind) {
6338   QualType RHSType = RHS.get()->getType();
6339   QualType OrigLHSType = LHSType;
6340 
6341   // Get canonical types.  We're not formatting these types, just comparing
6342   // them.
6343   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6344   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6345 
6346   // Common case: no conversion required.
6347   if (LHSType == RHSType) {
6348     Kind = CK_NoOp;
6349     return Compatible;
6350   }
6351 
6352   // If we have an atomic type, try a non-atomic assignment, then just add an
6353   // atomic qualification step.
6354   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6355     Sema::AssignConvertType result =
6356       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6357     if (result != Compatible)
6358       return result;
6359     if (Kind != CK_NoOp)
6360       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6361     Kind = CK_NonAtomicToAtomic;
6362     return Compatible;
6363   }
6364 
6365   // If the left-hand side is a reference type, then we are in a
6366   // (rare!) case where we've allowed the use of references in C,
6367   // e.g., as a parameter type in a built-in function. In this case,
6368   // just make sure that the type referenced is compatible with the
6369   // right-hand side type. The caller is responsible for adjusting
6370   // LHSType so that the resulting expression does not have reference
6371   // type.
6372   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6373     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6374       Kind = CK_LValueBitCast;
6375       return Compatible;
6376     }
6377     return Incompatible;
6378   }
6379 
6380   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6381   // to the same ExtVector type.
6382   if (LHSType->isExtVectorType()) {
6383     if (RHSType->isExtVectorType())
6384       return Incompatible;
6385     if (RHSType->isArithmeticType()) {
6386       // CK_VectorSplat does T -> vector T, so first cast to the
6387       // element type.
6388       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6389       if (elType != RHSType) {
6390         Kind = PrepareScalarCast(RHS, elType);
6391         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6392       }
6393       Kind = CK_VectorSplat;
6394       return Compatible;
6395     }
6396   }
6397 
6398   // Conversions to or from vector type.
6399   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6400     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6401       // Allow assignments of an AltiVec vector type to an equivalent GCC
6402       // vector type and vice versa
6403       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6404         Kind = CK_BitCast;
6405         return Compatible;
6406       }
6407 
6408       // If we are allowing lax vector conversions, and LHS and RHS are both
6409       // vectors, the total size only needs to be the same. This is a bitcast;
6410       // no bits are changed but the result type is different.
6411       if (isLaxVectorConversion(RHSType, LHSType)) {
6412         Kind = CK_BitCast;
6413         return IncompatibleVectors;
6414       }
6415     }
6416     return Incompatible;
6417   }
6418 
6419   // Arithmetic conversions.
6420   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6421       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6422     Kind = PrepareScalarCast(RHS, LHSType);
6423     return Compatible;
6424   }
6425 
6426   // Conversions to normal pointers.
6427   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6428     // U* -> T*
6429     if (isa<PointerType>(RHSType)) {
6430       Kind = CK_BitCast;
6431       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6432     }
6433 
6434     // int -> T*
6435     if (RHSType->isIntegerType()) {
6436       Kind = CK_IntegralToPointer; // FIXME: null?
6437       return IntToPointer;
6438     }
6439 
6440     // C pointers are not compatible with ObjC object pointers,
6441     // with two exceptions:
6442     if (isa<ObjCObjectPointerType>(RHSType)) {
6443       //  - conversions to void*
6444       if (LHSPointer->getPointeeType()->isVoidType()) {
6445         Kind = CK_BitCast;
6446         return Compatible;
6447       }
6448 
6449       //  - conversions from 'Class' to the redefinition type
6450       if (RHSType->isObjCClassType() &&
6451           Context.hasSameType(LHSType,
6452                               Context.getObjCClassRedefinitionType())) {
6453         Kind = CK_BitCast;
6454         return Compatible;
6455       }
6456 
6457       Kind = CK_BitCast;
6458       return IncompatiblePointer;
6459     }
6460 
6461     // U^ -> void*
6462     if (RHSType->getAs<BlockPointerType>()) {
6463       if (LHSPointer->getPointeeType()->isVoidType()) {
6464         Kind = CK_BitCast;
6465         return Compatible;
6466       }
6467     }
6468 
6469     return Incompatible;
6470   }
6471 
6472   // Conversions to block pointers.
6473   if (isa<BlockPointerType>(LHSType)) {
6474     // U^ -> T^
6475     if (RHSType->isBlockPointerType()) {
6476       Kind = CK_BitCast;
6477       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6478     }
6479 
6480     // int or null -> T^
6481     if (RHSType->isIntegerType()) {
6482       Kind = CK_IntegralToPointer; // FIXME: null
6483       return IntToBlockPointer;
6484     }
6485 
6486     // id -> T^
6487     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6488       Kind = CK_AnyPointerToBlockPointerCast;
6489       return Compatible;
6490     }
6491 
6492     // void* -> T^
6493     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6494       if (RHSPT->getPointeeType()->isVoidType()) {
6495         Kind = CK_AnyPointerToBlockPointerCast;
6496         return Compatible;
6497       }
6498 
6499     return Incompatible;
6500   }
6501 
6502   // Conversions to Objective-C pointers.
6503   if (isa<ObjCObjectPointerType>(LHSType)) {
6504     // A* -> B*
6505     if (RHSType->isObjCObjectPointerType()) {
6506       Kind = CK_BitCast;
6507       Sema::AssignConvertType result =
6508         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6509       if (getLangOpts().ObjCAutoRefCount &&
6510           result == Compatible &&
6511           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6512         result = IncompatibleObjCWeakRef;
6513       return result;
6514     }
6515 
6516     // int or null -> A*
6517     if (RHSType->isIntegerType()) {
6518       Kind = CK_IntegralToPointer; // FIXME: null
6519       return IntToPointer;
6520     }
6521 
6522     // In general, C pointers are not compatible with ObjC object pointers,
6523     // with two exceptions:
6524     if (isa<PointerType>(RHSType)) {
6525       Kind = CK_CPointerToObjCPointerCast;
6526 
6527       //  - conversions from 'void*'
6528       if (RHSType->isVoidPointerType()) {
6529         return Compatible;
6530       }
6531 
6532       //  - conversions to 'Class' from its redefinition type
6533       if (LHSType->isObjCClassType() &&
6534           Context.hasSameType(RHSType,
6535                               Context.getObjCClassRedefinitionType())) {
6536         return Compatible;
6537       }
6538 
6539       return IncompatiblePointer;
6540     }
6541 
6542     // Only under strict condition T^ is compatible with an Objective-C pointer.
6543     if (RHSType->isBlockPointerType() &&
6544         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6545       maybeExtendBlockObject(*this, RHS);
6546       Kind = CK_BlockPointerToObjCPointerCast;
6547       return Compatible;
6548     }
6549 
6550     return Incompatible;
6551   }
6552 
6553   // Conversions from pointers that are not covered by the above.
6554   if (isa<PointerType>(RHSType)) {
6555     // T* -> _Bool
6556     if (LHSType == Context.BoolTy) {
6557       Kind = CK_PointerToBoolean;
6558       return Compatible;
6559     }
6560 
6561     // T* -> int
6562     if (LHSType->isIntegerType()) {
6563       Kind = CK_PointerToIntegral;
6564       return PointerToInt;
6565     }
6566 
6567     return Incompatible;
6568   }
6569 
6570   // Conversions from Objective-C pointers that are not covered by the above.
6571   if (isa<ObjCObjectPointerType>(RHSType)) {
6572     // T* -> _Bool
6573     if (LHSType == Context.BoolTy) {
6574       Kind = CK_PointerToBoolean;
6575       return Compatible;
6576     }
6577 
6578     // T* -> int
6579     if (LHSType->isIntegerType()) {
6580       Kind = CK_PointerToIntegral;
6581       return PointerToInt;
6582     }
6583 
6584     return Incompatible;
6585   }
6586 
6587   // struct A -> struct B
6588   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6589     if (Context.typesAreCompatible(LHSType, RHSType)) {
6590       Kind = CK_NoOp;
6591       return Compatible;
6592     }
6593   }
6594 
6595   return Incompatible;
6596 }
6597 
6598 /// \brief Constructs a transparent union from an expression that is
6599 /// used to initialize the transparent union.
6600 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6601                                       ExprResult &EResult, QualType UnionType,
6602                                       FieldDecl *Field) {
6603   // Build an initializer list that designates the appropriate member
6604   // of the transparent union.
6605   Expr *E = EResult.get();
6606   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6607                                                    E, SourceLocation());
6608   Initializer->setType(UnionType);
6609   Initializer->setInitializedFieldInUnion(Field);
6610 
6611   // Build a compound literal constructing a value of the transparent
6612   // union type from this initializer list.
6613   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6614   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6615                                         VK_RValue, Initializer, false);
6616 }
6617 
6618 Sema::AssignConvertType
6619 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6620                                                ExprResult &RHS) {
6621   QualType RHSType = RHS.get()->getType();
6622 
6623   // If the ArgType is a Union type, we want to handle a potential
6624   // transparent_union GCC extension.
6625   const RecordType *UT = ArgType->getAsUnionType();
6626   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6627     return Incompatible;
6628 
6629   // The field to initialize within the transparent union.
6630   RecordDecl *UD = UT->getDecl();
6631   FieldDecl *InitField = nullptr;
6632   // It's compatible if the expression matches any of the fields.
6633   for (auto *it : UD->fields()) {
6634     if (it->getType()->isPointerType()) {
6635       // If the transparent union contains a pointer type, we allow:
6636       // 1) void pointer
6637       // 2) null pointer constant
6638       if (RHSType->isPointerType())
6639         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6640           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6641           InitField = it;
6642           break;
6643         }
6644 
6645       if (RHS.get()->isNullPointerConstant(Context,
6646                                            Expr::NPC_ValueDependentIsNull)) {
6647         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6648                                 CK_NullToPointer);
6649         InitField = it;
6650         break;
6651       }
6652     }
6653 
6654     CastKind Kind = CK_Invalid;
6655     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6656           == Compatible) {
6657       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6658       InitField = it;
6659       break;
6660     }
6661   }
6662 
6663   if (!InitField)
6664     return Incompatible;
6665 
6666   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6667   return Compatible;
6668 }
6669 
6670 Sema::AssignConvertType
6671 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6672                                        bool Diagnose,
6673                                        bool DiagnoseCFAudited) {
6674   if (getLangOpts().CPlusPlus) {
6675     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6676       // C++ 5.17p3: If the left operand is not of class type, the
6677       // expression is implicitly converted (C++ 4) to the
6678       // cv-unqualified type of the left operand.
6679       ExprResult Res;
6680       if (Diagnose) {
6681         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6682                                         AA_Assigning);
6683       } else {
6684         ImplicitConversionSequence ICS =
6685             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6686                                   /*SuppressUserConversions=*/false,
6687                                   /*AllowExplicit=*/false,
6688                                   /*InOverloadResolution=*/false,
6689                                   /*CStyle=*/false,
6690                                   /*AllowObjCWritebackConversion=*/false);
6691         if (ICS.isFailure())
6692           return Incompatible;
6693         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6694                                         ICS, AA_Assigning);
6695       }
6696       if (Res.isInvalid())
6697         return Incompatible;
6698       Sema::AssignConvertType result = Compatible;
6699       if (getLangOpts().ObjCAutoRefCount &&
6700           !CheckObjCARCUnavailableWeakConversion(LHSType,
6701                                                  RHS.get()->getType()))
6702         result = IncompatibleObjCWeakRef;
6703       RHS = Res;
6704       return result;
6705     }
6706 
6707     // FIXME: Currently, we fall through and treat C++ classes like C
6708     // structures.
6709     // FIXME: We also fall through for atomics; not sure what should
6710     // happen there, though.
6711   }
6712 
6713   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6714   // a null pointer constant.
6715   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6716        LHSType->isBlockPointerType()) &&
6717       RHS.get()->isNullPointerConstant(Context,
6718                                        Expr::NPC_ValueDependentIsNull)) {
6719     CastKind Kind;
6720     CXXCastPath Path;
6721     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6722     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6723     return Compatible;
6724   }
6725 
6726   // This check seems unnatural, however it is necessary to ensure the proper
6727   // conversion of functions/arrays. If the conversion were done for all
6728   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6729   // expressions that suppress this implicit conversion (&, sizeof).
6730   //
6731   // Suppress this for references: C++ 8.5.3p5.
6732   if (!LHSType->isReferenceType()) {
6733     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6734     if (RHS.isInvalid())
6735       return Incompatible;
6736   }
6737 
6738   CastKind Kind = CK_Invalid;
6739   Sema::AssignConvertType result =
6740     CheckAssignmentConstraints(LHSType, RHS, Kind);
6741 
6742   // C99 6.5.16.1p2: The value of the right operand is converted to the
6743   // type of the assignment expression.
6744   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6745   // so that we can use references in built-in functions even in C.
6746   // The getNonReferenceType() call makes sure that the resulting expression
6747   // does not have reference type.
6748   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6749     QualType Ty = LHSType.getNonLValueExprType(Context);
6750     Expr *E = RHS.get();
6751     if (getLangOpts().ObjCAutoRefCount)
6752       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6753                              DiagnoseCFAudited);
6754     if (getLangOpts().ObjC1 &&
6755         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6756                                           LHSType, E->getType(), E) ||
6757          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6758       RHS = E;
6759       return Compatible;
6760     }
6761 
6762     RHS = ImpCastExprToType(E, Ty, Kind);
6763   }
6764   return result;
6765 }
6766 
6767 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6768                                ExprResult &RHS) {
6769   Diag(Loc, diag::err_typecheck_invalid_operands)
6770     << LHS.get()->getType() << RHS.get()->getType()
6771     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6772   return QualType();
6773 }
6774 
6775 /// Try to convert a value of non-vector type to a vector type by converting
6776 /// the type to the element type of the vector and then performing a splat.
6777 /// If the language is OpenCL, we only use conversions that promote scalar
6778 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6779 /// for float->int.
6780 ///
6781 /// \param scalar - if non-null, actually perform the conversions
6782 /// \return true if the operation fails (but without diagnosing the failure)
6783 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6784                                      QualType scalarTy,
6785                                      QualType vectorEltTy,
6786                                      QualType vectorTy) {
6787   // The conversion to apply to the scalar before splatting it,
6788   // if necessary.
6789   CastKind scalarCast = CK_Invalid;
6790 
6791   if (vectorEltTy->isIntegralType(S.Context)) {
6792     if (!scalarTy->isIntegralType(S.Context))
6793       return true;
6794     if (S.getLangOpts().OpenCL &&
6795         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6796       return true;
6797     scalarCast = CK_IntegralCast;
6798   } else if (vectorEltTy->isRealFloatingType()) {
6799     if (scalarTy->isRealFloatingType()) {
6800       if (S.getLangOpts().OpenCL &&
6801           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6802         return true;
6803       scalarCast = CK_FloatingCast;
6804     }
6805     else if (scalarTy->isIntegralType(S.Context))
6806       scalarCast = CK_IntegralToFloating;
6807     else
6808       return true;
6809   } else {
6810     return true;
6811   }
6812 
6813   // Adjust scalar if desired.
6814   if (scalar) {
6815     if (scalarCast != CK_Invalid)
6816       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6817     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6818   }
6819   return false;
6820 }
6821 
6822 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6823                                    SourceLocation Loc, bool IsCompAssign) {
6824   if (!IsCompAssign) {
6825     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6826     if (LHS.isInvalid())
6827       return QualType();
6828   }
6829   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6830   if (RHS.isInvalid())
6831     return QualType();
6832 
6833   // For conversion purposes, we ignore any qualifiers.
6834   // For example, "const float" and "float" are equivalent.
6835   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6836   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6837 
6838   // If the vector types are identical, return.
6839   if (Context.hasSameType(LHSType, RHSType))
6840     return LHSType;
6841 
6842   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6843   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6844   assert(LHSVecType || RHSVecType);
6845 
6846   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6847   if (LHSVecType && RHSVecType &&
6848       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6849     if (isa<ExtVectorType>(LHSVecType)) {
6850       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6851       return LHSType;
6852     }
6853 
6854     if (!IsCompAssign)
6855       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6856     return RHSType;
6857   }
6858 
6859   // If there's an ext-vector type and a scalar, try to convert the scalar to
6860   // the vector element type and splat.
6861   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6862     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6863                                   LHSVecType->getElementType(), LHSType))
6864       return LHSType;
6865   }
6866   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6867     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6868                                   LHSType, RHSVecType->getElementType(),
6869                                   RHSType))
6870       return RHSType;
6871   }
6872 
6873   // If we're allowing lax vector conversions, only the total (data) size
6874   // needs to be the same.
6875   // FIXME: Should we really be allowing this?
6876   // FIXME: We really just pick the LHS type arbitrarily?
6877   if (isLaxVectorConversion(RHSType, LHSType)) {
6878     QualType resultType = LHSType;
6879     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
6880     return resultType;
6881   }
6882 
6883   // Okay, the expression is invalid.
6884 
6885   // If there's a non-vector, non-real operand, diagnose that.
6886   if ((!RHSVecType && !RHSType->isRealType()) ||
6887       (!LHSVecType && !LHSType->isRealType())) {
6888     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6889       << LHSType << RHSType
6890       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6891     return QualType();
6892   }
6893 
6894   // Otherwise, use the generic diagnostic.
6895   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6896     << LHSType << RHSType
6897     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6898   return QualType();
6899 }
6900 
6901 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6902 // expression.  These are mainly cases where the null pointer is used as an
6903 // integer instead of a pointer.
6904 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6905                                 SourceLocation Loc, bool IsCompare) {
6906   // The canonical way to check for a GNU null is with isNullPointerConstant,
6907   // but we use a bit of a hack here for speed; this is a relatively
6908   // hot path, and isNullPointerConstant is slow.
6909   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6910   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6911 
6912   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6913 
6914   // Avoid analyzing cases where the result will either be invalid (and
6915   // diagnosed as such) or entirely valid and not something to warn about.
6916   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6917       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6918     return;
6919 
6920   // Comparison operations would not make sense with a null pointer no matter
6921   // what the other expression is.
6922   if (!IsCompare) {
6923     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6924         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6925         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6926     return;
6927   }
6928 
6929   // The rest of the operations only make sense with a null pointer
6930   // if the other expression is a pointer.
6931   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6932       NonNullType->canDecayToPointerType())
6933     return;
6934 
6935   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6936       << LHSNull /* LHS is NULL */ << NonNullType
6937       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6938 }
6939 
6940 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6941                                            SourceLocation Loc,
6942                                            bool IsCompAssign, bool IsDiv) {
6943   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6944 
6945   if (LHS.get()->getType()->isVectorType() ||
6946       RHS.get()->getType()->isVectorType())
6947     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6948 
6949   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6950   if (LHS.isInvalid() || RHS.isInvalid())
6951     return QualType();
6952 
6953 
6954   if (compType.isNull() || !compType->isArithmeticType())
6955     return InvalidOperands(Loc, LHS, RHS);
6956 
6957   // Check for division by zero.
6958   llvm::APSInt RHSValue;
6959   if (IsDiv && !RHS.get()->isValueDependent() &&
6960       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6961     DiagRuntimeBehavior(Loc, RHS.get(),
6962                         PDiag(diag::warn_division_by_zero)
6963                           << RHS.get()->getSourceRange());
6964 
6965   return compType;
6966 }
6967 
6968 QualType Sema::CheckRemainderOperands(
6969   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6970   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6971 
6972   if (LHS.get()->getType()->isVectorType() ||
6973       RHS.get()->getType()->isVectorType()) {
6974     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6975         RHS.get()->getType()->hasIntegerRepresentation())
6976       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6977     return InvalidOperands(Loc, LHS, RHS);
6978   }
6979 
6980   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6981   if (LHS.isInvalid() || RHS.isInvalid())
6982     return QualType();
6983 
6984   if (compType.isNull() || !compType->isIntegerType())
6985     return InvalidOperands(Loc, LHS, RHS);
6986 
6987   // Check for remainder by zero.
6988   llvm::APSInt RHSValue;
6989   if (!RHS.get()->isValueDependent() &&
6990       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6991     DiagRuntimeBehavior(Loc, RHS.get(),
6992                         PDiag(diag::warn_remainder_by_zero)
6993                           << RHS.get()->getSourceRange());
6994 
6995   return compType;
6996 }
6997 
6998 /// \brief Diagnose invalid arithmetic on two void pointers.
6999 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7000                                                 Expr *LHSExpr, Expr *RHSExpr) {
7001   S.Diag(Loc, S.getLangOpts().CPlusPlus
7002                 ? diag::err_typecheck_pointer_arith_void_type
7003                 : diag::ext_gnu_void_ptr)
7004     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7005                             << RHSExpr->getSourceRange();
7006 }
7007 
7008 /// \brief Diagnose invalid arithmetic on a void pointer.
7009 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7010                                             Expr *Pointer) {
7011   S.Diag(Loc, S.getLangOpts().CPlusPlus
7012                 ? diag::err_typecheck_pointer_arith_void_type
7013                 : diag::ext_gnu_void_ptr)
7014     << 0 /* one pointer */ << Pointer->getSourceRange();
7015 }
7016 
7017 /// \brief Diagnose invalid arithmetic on two function pointers.
7018 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7019                                                     Expr *LHS, Expr *RHS) {
7020   assert(LHS->getType()->isAnyPointerType());
7021   assert(RHS->getType()->isAnyPointerType());
7022   S.Diag(Loc, S.getLangOpts().CPlusPlus
7023                 ? diag::err_typecheck_pointer_arith_function_type
7024                 : diag::ext_gnu_ptr_func_arith)
7025     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7026     // We only show the second type if it differs from the first.
7027     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7028                                                    RHS->getType())
7029     << RHS->getType()->getPointeeType()
7030     << LHS->getSourceRange() << RHS->getSourceRange();
7031 }
7032 
7033 /// \brief Diagnose invalid arithmetic on a function pointer.
7034 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7035                                                 Expr *Pointer) {
7036   assert(Pointer->getType()->isAnyPointerType());
7037   S.Diag(Loc, S.getLangOpts().CPlusPlus
7038                 ? diag::err_typecheck_pointer_arith_function_type
7039                 : diag::ext_gnu_ptr_func_arith)
7040     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7041     << 0 /* one pointer, so only one type */
7042     << Pointer->getSourceRange();
7043 }
7044 
7045 /// \brief Emit error if Operand is incomplete pointer type
7046 ///
7047 /// \returns True if pointer has incomplete type
7048 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7049                                                  Expr *Operand) {
7050   assert(Operand->getType()->isAnyPointerType() &&
7051          !Operand->getType()->isDependentType());
7052   QualType PointeeTy = Operand->getType()->getPointeeType();
7053   return S.RequireCompleteType(Loc, PointeeTy,
7054                                diag::err_typecheck_arithmetic_incomplete_type,
7055                                PointeeTy, Operand->getSourceRange());
7056 }
7057 
7058 /// \brief Check the validity of an arithmetic pointer operand.
7059 ///
7060 /// If the operand has pointer type, this code will check for pointer types
7061 /// which are invalid in arithmetic operations. These will be diagnosed
7062 /// appropriately, including whether or not the use is supported as an
7063 /// extension.
7064 ///
7065 /// \returns True when the operand is valid to use (even if as an extension).
7066 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7067                                             Expr *Operand) {
7068   if (!Operand->getType()->isAnyPointerType()) return true;
7069 
7070   QualType PointeeTy = Operand->getType()->getPointeeType();
7071   if (PointeeTy->isVoidType()) {
7072     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7073     return !S.getLangOpts().CPlusPlus;
7074   }
7075   if (PointeeTy->isFunctionType()) {
7076     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7077     return !S.getLangOpts().CPlusPlus;
7078   }
7079 
7080   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7081 
7082   return true;
7083 }
7084 
7085 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7086 /// operands.
7087 ///
7088 /// This routine will diagnose any invalid arithmetic on pointer operands much
7089 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7090 /// for emitting a single diagnostic even for operations where both LHS and RHS
7091 /// are (potentially problematic) pointers.
7092 ///
7093 /// \returns True when the operand is valid to use (even if as an extension).
7094 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7095                                                 Expr *LHSExpr, Expr *RHSExpr) {
7096   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7097   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7098   if (!isLHSPointer && !isRHSPointer) return true;
7099 
7100   QualType LHSPointeeTy, RHSPointeeTy;
7101   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7102   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7103 
7104   // Check for arithmetic on pointers to incomplete types.
7105   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7106   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7107   if (isLHSVoidPtr || isRHSVoidPtr) {
7108     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7109     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7110     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7111 
7112     return !S.getLangOpts().CPlusPlus;
7113   }
7114 
7115   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7116   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7117   if (isLHSFuncPtr || isRHSFuncPtr) {
7118     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7119     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7120                                                                 RHSExpr);
7121     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7122 
7123     return !S.getLangOpts().CPlusPlus;
7124   }
7125 
7126   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7127     return false;
7128   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7129     return false;
7130 
7131   return true;
7132 }
7133 
7134 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7135 /// literal.
7136 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7137                                   Expr *LHSExpr, Expr *RHSExpr) {
7138   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7139   Expr* IndexExpr = RHSExpr;
7140   if (!StrExpr) {
7141     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7142     IndexExpr = LHSExpr;
7143   }
7144 
7145   bool IsStringPlusInt = StrExpr &&
7146       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7147   if (!IsStringPlusInt)
7148     return;
7149 
7150   llvm::APSInt index;
7151   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7152     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7153     if (index.isNonNegative() &&
7154         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7155                               index.isUnsigned()))
7156       return;
7157   }
7158 
7159   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7160   Self.Diag(OpLoc, diag::warn_string_plus_int)
7161       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7162 
7163   // Only print a fixit for "str" + int, not for int + "str".
7164   if (IndexExpr == RHSExpr) {
7165     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7166     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7167         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7168         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7169         << FixItHint::CreateInsertion(EndLoc, "]");
7170   } else
7171     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7172 }
7173 
7174 /// \brief Emit a warning when adding a char literal to a string.
7175 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7176                                    Expr *LHSExpr, Expr *RHSExpr) {
7177   const DeclRefExpr *StringRefExpr =
7178       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7179   const CharacterLiteral *CharExpr =
7180       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7181   if (!StringRefExpr) {
7182     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7183     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7184   }
7185 
7186   if (!CharExpr || !StringRefExpr)
7187     return;
7188 
7189   const QualType StringType = StringRefExpr->getType();
7190 
7191   // Return if not a PointerType.
7192   if (!StringType->isAnyPointerType())
7193     return;
7194 
7195   // Return if not a CharacterType.
7196   if (!StringType->getPointeeType()->isAnyCharacterType())
7197     return;
7198 
7199   ASTContext &Ctx = Self.getASTContext();
7200   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7201 
7202   const QualType CharType = CharExpr->getType();
7203   if (!CharType->isAnyCharacterType() &&
7204       CharType->isIntegerType() &&
7205       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7206     Self.Diag(OpLoc, diag::warn_string_plus_char)
7207         << DiagRange << Ctx.CharTy;
7208   } else {
7209     Self.Diag(OpLoc, diag::warn_string_plus_char)
7210         << DiagRange << CharExpr->getType();
7211   }
7212 
7213   // Only print a fixit for str + char, not for char + str.
7214   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7215     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7216     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7217         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7218         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7219         << FixItHint::CreateInsertion(EndLoc, "]");
7220   } else {
7221     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7222   }
7223 }
7224 
7225 /// \brief Emit error when two pointers are incompatible.
7226 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7227                                            Expr *LHSExpr, Expr *RHSExpr) {
7228   assert(LHSExpr->getType()->isAnyPointerType());
7229   assert(RHSExpr->getType()->isAnyPointerType());
7230   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7231     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7232     << RHSExpr->getSourceRange();
7233 }
7234 
7235 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7236     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7237     QualType* CompLHSTy) {
7238   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7239 
7240   if (LHS.get()->getType()->isVectorType() ||
7241       RHS.get()->getType()->isVectorType()) {
7242     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7243     if (CompLHSTy) *CompLHSTy = compType;
7244     return compType;
7245   }
7246 
7247   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7248   if (LHS.isInvalid() || RHS.isInvalid())
7249     return QualType();
7250 
7251   // Diagnose "string literal" '+' int and string '+' "char literal".
7252   if (Opc == BO_Add) {
7253     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7254     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7255   }
7256 
7257   // handle the common case first (both operands are arithmetic).
7258   if (!compType.isNull() && compType->isArithmeticType()) {
7259     if (CompLHSTy) *CompLHSTy = compType;
7260     return compType;
7261   }
7262 
7263   // Type-checking.  Ultimately the pointer's going to be in PExp;
7264   // note that we bias towards the LHS being the pointer.
7265   Expr *PExp = LHS.get(), *IExp = RHS.get();
7266 
7267   bool isObjCPointer;
7268   if (PExp->getType()->isPointerType()) {
7269     isObjCPointer = false;
7270   } else if (PExp->getType()->isObjCObjectPointerType()) {
7271     isObjCPointer = true;
7272   } else {
7273     std::swap(PExp, IExp);
7274     if (PExp->getType()->isPointerType()) {
7275       isObjCPointer = false;
7276     } else if (PExp->getType()->isObjCObjectPointerType()) {
7277       isObjCPointer = true;
7278     } else {
7279       return InvalidOperands(Loc, LHS, RHS);
7280     }
7281   }
7282   assert(PExp->getType()->isAnyPointerType());
7283 
7284   if (!IExp->getType()->isIntegerType())
7285     return InvalidOperands(Loc, LHS, RHS);
7286 
7287   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7288     return QualType();
7289 
7290   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7291     return QualType();
7292 
7293   // Check array bounds for pointer arithemtic
7294   CheckArrayAccess(PExp, IExp);
7295 
7296   if (CompLHSTy) {
7297     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7298     if (LHSTy.isNull()) {
7299       LHSTy = LHS.get()->getType();
7300       if (LHSTy->isPromotableIntegerType())
7301         LHSTy = Context.getPromotedIntegerType(LHSTy);
7302     }
7303     *CompLHSTy = LHSTy;
7304   }
7305 
7306   return PExp->getType();
7307 }
7308 
7309 // C99 6.5.6
7310 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7311                                         SourceLocation Loc,
7312                                         QualType* CompLHSTy) {
7313   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7314 
7315   if (LHS.get()->getType()->isVectorType() ||
7316       RHS.get()->getType()->isVectorType()) {
7317     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7318     if (CompLHSTy) *CompLHSTy = compType;
7319     return compType;
7320   }
7321 
7322   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7323   if (LHS.isInvalid() || RHS.isInvalid())
7324     return QualType();
7325 
7326   // Enforce type constraints: C99 6.5.6p3.
7327 
7328   // Handle the common case first (both operands are arithmetic).
7329   if (!compType.isNull() && compType->isArithmeticType()) {
7330     if (CompLHSTy) *CompLHSTy = compType;
7331     return compType;
7332   }
7333 
7334   // Either ptr - int   or   ptr - ptr.
7335   if (LHS.get()->getType()->isAnyPointerType()) {
7336     QualType lpointee = LHS.get()->getType()->getPointeeType();
7337 
7338     // Diagnose bad cases where we step over interface counts.
7339     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7340         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7341       return QualType();
7342 
7343     // The result type of a pointer-int computation is the pointer type.
7344     if (RHS.get()->getType()->isIntegerType()) {
7345       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7346         return QualType();
7347 
7348       // Check array bounds for pointer arithemtic
7349       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7350                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7351 
7352       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7353       return LHS.get()->getType();
7354     }
7355 
7356     // Handle pointer-pointer subtractions.
7357     if (const PointerType *RHSPTy
7358           = RHS.get()->getType()->getAs<PointerType>()) {
7359       QualType rpointee = RHSPTy->getPointeeType();
7360 
7361       if (getLangOpts().CPlusPlus) {
7362         // Pointee types must be the same: C++ [expr.add]
7363         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7364           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7365         }
7366       } else {
7367         // Pointee types must be compatible C99 6.5.6p3
7368         if (!Context.typesAreCompatible(
7369                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7370                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7371           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7372           return QualType();
7373         }
7374       }
7375 
7376       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7377                                                LHS.get(), RHS.get()))
7378         return QualType();
7379 
7380       // The pointee type may have zero size.  As an extension, a structure or
7381       // union may have zero size or an array may have zero length.  In this
7382       // case subtraction does not make sense.
7383       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7384         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7385         if (ElementSize.isZero()) {
7386           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7387             << rpointee.getUnqualifiedType()
7388             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7389         }
7390       }
7391 
7392       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7393       return Context.getPointerDiffType();
7394     }
7395   }
7396 
7397   return InvalidOperands(Loc, LHS, RHS);
7398 }
7399 
7400 static bool isScopedEnumerationType(QualType T) {
7401   if (const EnumType *ET = dyn_cast<EnumType>(T))
7402     return ET->getDecl()->isScoped();
7403   return false;
7404 }
7405 
7406 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7407                                    SourceLocation Loc, unsigned Opc,
7408                                    QualType LHSType) {
7409   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7410   // so skip remaining warnings as we don't want to modify values within Sema.
7411   if (S.getLangOpts().OpenCL)
7412     return;
7413 
7414   llvm::APSInt Right;
7415   // Check right/shifter operand
7416   if (RHS.get()->isValueDependent() ||
7417       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7418     return;
7419 
7420   if (Right.isNegative()) {
7421     S.DiagRuntimeBehavior(Loc, RHS.get(),
7422                           S.PDiag(diag::warn_shift_negative)
7423                             << RHS.get()->getSourceRange());
7424     return;
7425   }
7426   llvm::APInt LeftBits(Right.getBitWidth(),
7427                        S.Context.getTypeSize(LHS.get()->getType()));
7428   if (Right.uge(LeftBits)) {
7429     S.DiagRuntimeBehavior(Loc, RHS.get(),
7430                           S.PDiag(diag::warn_shift_gt_typewidth)
7431                             << RHS.get()->getSourceRange());
7432     return;
7433   }
7434   if (Opc != BO_Shl)
7435     return;
7436 
7437   // When left shifting an ICE which is signed, we can check for overflow which
7438   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7439   // integers have defined behavior modulo one more than the maximum value
7440   // representable in the result type, so never warn for those.
7441   llvm::APSInt Left;
7442   if (LHS.get()->isValueDependent() ||
7443       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7444       LHSType->hasUnsignedIntegerRepresentation())
7445     return;
7446   llvm::APInt ResultBits =
7447       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7448   if (LeftBits.uge(ResultBits))
7449     return;
7450   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7451   Result = Result.shl(Right);
7452 
7453   // Print the bit representation of the signed integer as an unsigned
7454   // hexadecimal number.
7455   SmallString<40> HexResult;
7456   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7457 
7458   // If we are only missing a sign bit, this is less likely to result in actual
7459   // bugs -- if the result is cast back to an unsigned type, it will have the
7460   // expected value. Thus we place this behind a different warning that can be
7461   // turned off separately if needed.
7462   if (LeftBits == ResultBits - 1) {
7463     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7464         << HexResult.str() << LHSType
7465         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7466     return;
7467   }
7468 
7469   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7470     << HexResult.str() << Result.getMinSignedBits() << LHSType
7471     << Left.getBitWidth() << LHS.get()->getSourceRange()
7472     << RHS.get()->getSourceRange();
7473 }
7474 
7475 // C99 6.5.7
7476 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7477                                   SourceLocation Loc, unsigned Opc,
7478                                   bool IsCompAssign) {
7479   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7480 
7481   // Vector shifts promote their scalar inputs to vector type.
7482   if (LHS.get()->getType()->isVectorType() ||
7483       RHS.get()->getType()->isVectorType())
7484     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7485 
7486   // Shifts don't perform usual arithmetic conversions, they just do integer
7487   // promotions on each operand. C99 6.5.7p3
7488 
7489   // For the LHS, do usual unary conversions, but then reset them away
7490   // if this is a compound assignment.
7491   ExprResult OldLHS = LHS;
7492   LHS = UsualUnaryConversions(LHS.get());
7493   if (LHS.isInvalid())
7494     return QualType();
7495   QualType LHSType = LHS.get()->getType();
7496   if (IsCompAssign) LHS = OldLHS;
7497 
7498   // The RHS is simpler.
7499   RHS = UsualUnaryConversions(RHS.get());
7500   if (RHS.isInvalid())
7501     return QualType();
7502   QualType RHSType = RHS.get()->getType();
7503 
7504   // C99 6.5.7p2: Each of the operands shall have integer type.
7505   if (!LHSType->hasIntegerRepresentation() ||
7506       !RHSType->hasIntegerRepresentation())
7507     return InvalidOperands(Loc, LHS, RHS);
7508 
7509   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7510   // hasIntegerRepresentation() above instead of this.
7511   if (isScopedEnumerationType(LHSType) ||
7512       isScopedEnumerationType(RHSType)) {
7513     return InvalidOperands(Loc, LHS, RHS);
7514   }
7515   // Sanity-check shift operands
7516   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7517 
7518   // "The type of the result is that of the promoted left operand."
7519   return LHSType;
7520 }
7521 
7522 static bool IsWithinTemplateSpecialization(Decl *D) {
7523   if (DeclContext *DC = D->getDeclContext()) {
7524     if (isa<ClassTemplateSpecializationDecl>(DC))
7525       return true;
7526     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7527       return FD->isFunctionTemplateSpecialization();
7528   }
7529   return false;
7530 }
7531 
7532 /// If two different enums are compared, raise a warning.
7533 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7534                                 Expr *RHS) {
7535   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7536   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7537 
7538   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7539   if (!LHSEnumType)
7540     return;
7541   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7542   if (!RHSEnumType)
7543     return;
7544 
7545   // Ignore anonymous enums.
7546   if (!LHSEnumType->getDecl()->getIdentifier())
7547     return;
7548   if (!RHSEnumType->getDecl()->getIdentifier())
7549     return;
7550 
7551   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7552     return;
7553 
7554   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7555       << LHSStrippedType << RHSStrippedType
7556       << LHS->getSourceRange() << RHS->getSourceRange();
7557 }
7558 
7559 /// \brief Diagnose bad pointer comparisons.
7560 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7561                                               ExprResult &LHS, ExprResult &RHS,
7562                                               bool IsError) {
7563   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7564                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7565     << LHS.get()->getType() << RHS.get()->getType()
7566     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7567 }
7568 
7569 /// \brief Returns false if the pointers are converted to a composite type,
7570 /// true otherwise.
7571 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7572                                            ExprResult &LHS, ExprResult &RHS) {
7573   // C++ [expr.rel]p2:
7574   //   [...] Pointer conversions (4.10) and qualification
7575   //   conversions (4.4) are performed on pointer operands (or on
7576   //   a pointer operand and a null pointer constant) to bring
7577   //   them to their composite pointer type. [...]
7578   //
7579   // C++ [expr.eq]p1 uses the same notion for (in)equality
7580   // comparisons of pointers.
7581 
7582   // C++ [expr.eq]p2:
7583   //   In addition, pointers to members can be compared, or a pointer to
7584   //   member and a null pointer constant. Pointer to member conversions
7585   //   (4.11) and qualification conversions (4.4) are performed to bring
7586   //   them to a common type. If one operand is a null pointer constant,
7587   //   the common type is the type of the other operand. Otherwise, the
7588   //   common type is a pointer to member type similar (4.4) to the type
7589   //   of one of the operands, with a cv-qualification signature (4.4)
7590   //   that is the union of the cv-qualification signatures of the operand
7591   //   types.
7592 
7593   QualType LHSType = LHS.get()->getType();
7594   QualType RHSType = RHS.get()->getType();
7595   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7596          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7597 
7598   bool NonStandardCompositeType = false;
7599   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7600   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7601   if (T.isNull()) {
7602     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7603     return true;
7604   }
7605 
7606   if (NonStandardCompositeType)
7607     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7608       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7609       << RHS.get()->getSourceRange();
7610 
7611   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7612   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7613   return false;
7614 }
7615 
7616 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7617                                                     ExprResult &LHS,
7618                                                     ExprResult &RHS,
7619                                                     bool IsError) {
7620   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7621                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7622     << LHS.get()->getType() << RHS.get()->getType()
7623     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7624 }
7625 
7626 static bool isObjCObjectLiteral(ExprResult &E) {
7627   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7628   case Stmt::ObjCArrayLiteralClass:
7629   case Stmt::ObjCDictionaryLiteralClass:
7630   case Stmt::ObjCStringLiteralClass:
7631   case Stmt::ObjCBoxedExprClass:
7632     return true;
7633   default:
7634     // Note that ObjCBoolLiteral is NOT an object literal!
7635     return false;
7636   }
7637 }
7638 
7639 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7640   const ObjCObjectPointerType *Type =
7641     LHS->getType()->getAs<ObjCObjectPointerType>();
7642 
7643   // If this is not actually an Objective-C object, bail out.
7644   if (!Type)
7645     return false;
7646 
7647   // Get the LHS object's interface type.
7648   QualType InterfaceType = Type->getPointeeType();
7649   if (const ObjCObjectType *iQFaceTy =
7650       InterfaceType->getAsObjCQualifiedInterfaceType())
7651     InterfaceType = iQFaceTy->getBaseType();
7652 
7653   // If the RHS isn't an Objective-C object, bail out.
7654   if (!RHS->getType()->isObjCObjectPointerType())
7655     return false;
7656 
7657   // Try to find the -isEqual: method.
7658   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7659   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7660                                                       InterfaceType,
7661                                                       /*instance=*/true);
7662   if (!Method) {
7663     if (Type->isObjCIdType()) {
7664       // For 'id', just check the global pool.
7665       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7666                                                   /*receiverId=*/true,
7667                                                   /*warn=*/false);
7668     } else {
7669       // Check protocols.
7670       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7671                                              /*instance=*/true);
7672     }
7673   }
7674 
7675   if (!Method)
7676     return false;
7677 
7678   QualType T = Method->param_begin()[0]->getType();
7679   if (!T->isObjCObjectPointerType())
7680     return false;
7681 
7682   QualType R = Method->getReturnType();
7683   if (!R->isScalarType())
7684     return false;
7685 
7686   return true;
7687 }
7688 
7689 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7690   FromE = FromE->IgnoreParenImpCasts();
7691   switch (FromE->getStmtClass()) {
7692     default:
7693       break;
7694     case Stmt::ObjCStringLiteralClass:
7695       // "string literal"
7696       return LK_String;
7697     case Stmt::ObjCArrayLiteralClass:
7698       // "array literal"
7699       return LK_Array;
7700     case Stmt::ObjCDictionaryLiteralClass:
7701       // "dictionary literal"
7702       return LK_Dictionary;
7703     case Stmt::BlockExprClass:
7704       return LK_Block;
7705     case Stmt::ObjCBoxedExprClass: {
7706       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7707       switch (Inner->getStmtClass()) {
7708         case Stmt::IntegerLiteralClass:
7709         case Stmt::FloatingLiteralClass:
7710         case Stmt::CharacterLiteralClass:
7711         case Stmt::ObjCBoolLiteralExprClass:
7712         case Stmt::CXXBoolLiteralExprClass:
7713           // "numeric literal"
7714           return LK_Numeric;
7715         case Stmt::ImplicitCastExprClass: {
7716           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7717           // Boolean literals can be represented by implicit casts.
7718           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7719             return LK_Numeric;
7720           break;
7721         }
7722         default:
7723           break;
7724       }
7725       return LK_Boxed;
7726     }
7727   }
7728   return LK_None;
7729 }
7730 
7731 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7732                                           ExprResult &LHS, ExprResult &RHS,
7733                                           BinaryOperator::Opcode Opc){
7734   Expr *Literal;
7735   Expr *Other;
7736   if (isObjCObjectLiteral(LHS)) {
7737     Literal = LHS.get();
7738     Other = RHS.get();
7739   } else {
7740     Literal = RHS.get();
7741     Other = LHS.get();
7742   }
7743 
7744   // Don't warn on comparisons against nil.
7745   Other = Other->IgnoreParenCasts();
7746   if (Other->isNullPointerConstant(S.getASTContext(),
7747                                    Expr::NPC_ValueDependentIsNotNull))
7748     return;
7749 
7750   // This should be kept in sync with warn_objc_literal_comparison.
7751   // LK_String should always be after the other literals, since it has its own
7752   // warning flag.
7753   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7754   assert(LiteralKind != Sema::LK_Block);
7755   if (LiteralKind == Sema::LK_None) {
7756     llvm_unreachable("Unknown Objective-C object literal kind");
7757   }
7758 
7759   if (LiteralKind == Sema::LK_String)
7760     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7761       << Literal->getSourceRange();
7762   else
7763     S.Diag(Loc, diag::warn_objc_literal_comparison)
7764       << LiteralKind << Literal->getSourceRange();
7765 
7766   if (BinaryOperator::isEqualityOp(Opc) &&
7767       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7768     SourceLocation Start = LHS.get()->getLocStart();
7769     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7770     CharSourceRange OpRange =
7771       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7772 
7773     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7774       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7775       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7776       << FixItHint::CreateInsertion(End, "]");
7777   }
7778 }
7779 
7780 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7781                                                 ExprResult &RHS,
7782                                                 SourceLocation Loc,
7783                                                 unsigned OpaqueOpc) {
7784   // This checking requires bools.
7785   if (!S.getLangOpts().Bool) return;
7786 
7787   // Check that left hand side is !something.
7788   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7789   if (!UO || UO->getOpcode() != UO_LNot) return;
7790 
7791   // Only check if the right hand side is non-bool arithmetic type.
7792   if (RHS.get()->getType()->isBooleanType()) return;
7793 
7794   // Make sure that the something in !something is not bool.
7795   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7796   if (SubExpr->getType()->isBooleanType()) return;
7797 
7798   // Emit warning.
7799   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7800       << Loc;
7801 
7802   // First note suggest !(x < y)
7803   SourceLocation FirstOpen = SubExpr->getLocStart();
7804   SourceLocation FirstClose = RHS.get()->getLocEnd();
7805   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7806   if (FirstClose.isInvalid())
7807     FirstOpen = SourceLocation();
7808   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7809       << FixItHint::CreateInsertion(FirstOpen, "(")
7810       << FixItHint::CreateInsertion(FirstClose, ")");
7811 
7812   // Second note suggests (!x) < y
7813   SourceLocation SecondOpen = LHS.get()->getLocStart();
7814   SourceLocation SecondClose = LHS.get()->getLocEnd();
7815   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7816   if (SecondClose.isInvalid())
7817     SecondOpen = SourceLocation();
7818   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7819       << FixItHint::CreateInsertion(SecondOpen, "(")
7820       << FixItHint::CreateInsertion(SecondClose, ")");
7821 }
7822 
7823 // Get the decl for a simple expression: a reference to a variable,
7824 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7825 static ValueDecl *getCompareDecl(Expr *E) {
7826   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7827     return DR->getDecl();
7828   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7829     if (Ivar->isFreeIvar())
7830       return Ivar->getDecl();
7831   }
7832   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7833     if (Mem->isImplicitAccess())
7834       return Mem->getMemberDecl();
7835   }
7836   return nullptr;
7837 }
7838 
7839 // C99 6.5.8, C++ [expr.rel]
7840 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7841                                     SourceLocation Loc, unsigned OpaqueOpc,
7842                                     bool IsRelational) {
7843   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7844 
7845   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7846 
7847   // Handle vector comparisons separately.
7848   if (LHS.get()->getType()->isVectorType() ||
7849       RHS.get()->getType()->isVectorType())
7850     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7851 
7852   QualType LHSType = LHS.get()->getType();
7853   QualType RHSType = RHS.get()->getType();
7854 
7855   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7856   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7857 
7858   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7859   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7860 
7861   if (!LHSType->hasFloatingRepresentation() &&
7862       !(LHSType->isBlockPointerType() && IsRelational) &&
7863       !LHS.get()->getLocStart().isMacroID() &&
7864       !RHS.get()->getLocStart().isMacroID() &&
7865       ActiveTemplateInstantiations.empty()) {
7866     // For non-floating point types, check for self-comparisons of the form
7867     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7868     // often indicate logic errors in the program.
7869     //
7870     // NOTE: Don't warn about comparison expressions resulting from macro
7871     // expansion. Also don't warn about comparisons which are only self
7872     // comparisons within a template specialization. The warnings should catch
7873     // obvious cases in the definition of the template anyways. The idea is to
7874     // warn when the typed comparison operator will always evaluate to the same
7875     // result.
7876     ValueDecl *DL = getCompareDecl(LHSStripped);
7877     ValueDecl *DR = getCompareDecl(RHSStripped);
7878     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7879       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7880                           << 0 // self-
7881                           << (Opc == BO_EQ
7882                               || Opc == BO_LE
7883                               || Opc == BO_GE));
7884     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7885                !DL->getType()->isReferenceType() &&
7886                !DR->getType()->isReferenceType()) {
7887         // what is it always going to eval to?
7888         char always_evals_to;
7889         switch(Opc) {
7890         case BO_EQ: // e.g. array1 == array2
7891           always_evals_to = 0; // false
7892           break;
7893         case BO_NE: // e.g. array1 != array2
7894           always_evals_to = 1; // true
7895           break;
7896         default:
7897           // best we can say is 'a constant'
7898           always_evals_to = 2; // e.g. array1 <= array2
7899           break;
7900         }
7901         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7902                             << 1 // array
7903                             << always_evals_to);
7904     }
7905 
7906     if (isa<CastExpr>(LHSStripped))
7907       LHSStripped = LHSStripped->IgnoreParenCasts();
7908     if (isa<CastExpr>(RHSStripped))
7909       RHSStripped = RHSStripped->IgnoreParenCasts();
7910 
7911     // Warn about comparisons against a string constant (unless the other
7912     // operand is null), the user probably wants strcmp.
7913     Expr *literalString = nullptr;
7914     Expr *literalStringStripped = nullptr;
7915     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7916         !RHSStripped->isNullPointerConstant(Context,
7917                                             Expr::NPC_ValueDependentIsNull)) {
7918       literalString = LHS.get();
7919       literalStringStripped = LHSStripped;
7920     } else if ((isa<StringLiteral>(RHSStripped) ||
7921                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7922                !LHSStripped->isNullPointerConstant(Context,
7923                                             Expr::NPC_ValueDependentIsNull)) {
7924       literalString = RHS.get();
7925       literalStringStripped = RHSStripped;
7926     }
7927 
7928     if (literalString) {
7929       DiagRuntimeBehavior(Loc, nullptr,
7930         PDiag(diag::warn_stringcompare)
7931           << isa<ObjCEncodeExpr>(literalStringStripped)
7932           << literalString->getSourceRange());
7933     }
7934   }
7935 
7936   // C99 6.5.8p3 / C99 6.5.9p4
7937   UsualArithmeticConversions(LHS, RHS);
7938   if (LHS.isInvalid() || RHS.isInvalid())
7939     return QualType();
7940 
7941   LHSType = LHS.get()->getType();
7942   RHSType = RHS.get()->getType();
7943 
7944   // The result of comparisons is 'bool' in C++, 'int' in C.
7945   QualType ResultTy = Context.getLogicalOperationType();
7946 
7947   if (IsRelational) {
7948     if (LHSType->isRealType() && RHSType->isRealType())
7949       return ResultTy;
7950   } else {
7951     // Check for comparisons of floating point operands using != and ==.
7952     if (LHSType->hasFloatingRepresentation())
7953       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7954 
7955     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7956       return ResultTy;
7957   }
7958 
7959   const Expr::NullPointerConstantKind LHSNullKind =
7960       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7961   const Expr::NullPointerConstantKind RHSNullKind =
7962       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7963   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7964   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7965 
7966   if (!IsRelational && LHSIsNull != RHSIsNull) {
7967     bool IsEquality = Opc == BO_EQ;
7968     if (RHSIsNull)
7969       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7970                                    RHS.get()->getSourceRange());
7971     else
7972       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7973                                    LHS.get()->getSourceRange());
7974   }
7975 
7976   // All of the following pointer-related warnings are GCC extensions, except
7977   // when handling null pointer constants.
7978   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7979     QualType LCanPointeeTy =
7980       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7981     QualType RCanPointeeTy =
7982       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7983 
7984     if (getLangOpts().CPlusPlus) {
7985       if (LCanPointeeTy == RCanPointeeTy)
7986         return ResultTy;
7987       if (!IsRelational &&
7988           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7989         // Valid unless comparison between non-null pointer and function pointer
7990         // This is a gcc extension compatibility comparison.
7991         // In a SFINAE context, we treat this as a hard error to maintain
7992         // conformance with the C++ standard.
7993         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7994             && !LHSIsNull && !RHSIsNull) {
7995           diagnoseFunctionPointerToVoidComparison(
7996               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7997 
7998           if (isSFINAEContext())
7999             return QualType();
8000 
8001           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8002           return ResultTy;
8003         }
8004       }
8005 
8006       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8007         return QualType();
8008       else
8009         return ResultTy;
8010     }
8011     // C99 6.5.9p2 and C99 6.5.8p2
8012     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8013                                    RCanPointeeTy.getUnqualifiedType())) {
8014       // Valid unless a relational comparison of function pointers
8015       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8016         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8017           << LHSType << RHSType << LHS.get()->getSourceRange()
8018           << RHS.get()->getSourceRange();
8019       }
8020     } else if (!IsRelational &&
8021                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8022       // Valid unless comparison between non-null pointer and function pointer
8023       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8024           && !LHSIsNull && !RHSIsNull)
8025         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8026                                                 /*isError*/false);
8027     } else {
8028       // Invalid
8029       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8030     }
8031     if (LCanPointeeTy != RCanPointeeTy) {
8032       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8033       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8034       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8035                                                : CK_BitCast;
8036       if (LHSIsNull && !RHSIsNull)
8037         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8038       else
8039         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8040     }
8041     return ResultTy;
8042   }
8043 
8044   if (getLangOpts().CPlusPlus) {
8045     // Comparison of nullptr_t with itself.
8046     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8047       return ResultTy;
8048 
8049     // Comparison of pointers with null pointer constants and equality
8050     // comparisons of member pointers to null pointer constants.
8051     if (RHSIsNull &&
8052         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8053          (!IsRelational &&
8054           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8055       RHS = ImpCastExprToType(RHS.get(), LHSType,
8056                         LHSType->isMemberPointerType()
8057                           ? CK_NullToMemberPointer
8058                           : CK_NullToPointer);
8059       return ResultTy;
8060     }
8061     if (LHSIsNull &&
8062         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8063          (!IsRelational &&
8064           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8065       LHS = ImpCastExprToType(LHS.get(), RHSType,
8066                         RHSType->isMemberPointerType()
8067                           ? CK_NullToMemberPointer
8068                           : CK_NullToPointer);
8069       return ResultTy;
8070     }
8071 
8072     // Comparison of member pointers.
8073     if (!IsRelational &&
8074         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8075       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8076         return QualType();
8077       else
8078         return ResultTy;
8079     }
8080 
8081     // Handle scoped enumeration types specifically, since they don't promote
8082     // to integers.
8083     if (LHS.get()->getType()->isEnumeralType() &&
8084         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8085                                        RHS.get()->getType()))
8086       return ResultTy;
8087   }
8088 
8089   // Handle block pointer types.
8090   if (!IsRelational && LHSType->isBlockPointerType() &&
8091       RHSType->isBlockPointerType()) {
8092     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8093     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8094 
8095     if (!LHSIsNull && !RHSIsNull &&
8096         !Context.typesAreCompatible(lpointee, rpointee)) {
8097       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8098         << LHSType << RHSType << LHS.get()->getSourceRange()
8099         << RHS.get()->getSourceRange();
8100     }
8101     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8102     return ResultTy;
8103   }
8104 
8105   // Allow block pointers to be compared with null pointer constants.
8106   if (!IsRelational
8107       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8108           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8109     if (!LHSIsNull && !RHSIsNull) {
8110       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8111              ->getPointeeType()->isVoidType())
8112             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8113                 ->getPointeeType()->isVoidType())))
8114         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8115           << LHSType << RHSType << LHS.get()->getSourceRange()
8116           << RHS.get()->getSourceRange();
8117     }
8118     if (LHSIsNull && !RHSIsNull)
8119       LHS = ImpCastExprToType(LHS.get(), RHSType,
8120                               RHSType->isPointerType() ? CK_BitCast
8121                                 : CK_AnyPointerToBlockPointerCast);
8122     else
8123       RHS = ImpCastExprToType(RHS.get(), LHSType,
8124                               LHSType->isPointerType() ? CK_BitCast
8125                                 : CK_AnyPointerToBlockPointerCast);
8126     return ResultTy;
8127   }
8128 
8129   if (LHSType->isObjCObjectPointerType() ||
8130       RHSType->isObjCObjectPointerType()) {
8131     const PointerType *LPT = LHSType->getAs<PointerType>();
8132     const PointerType *RPT = RHSType->getAs<PointerType>();
8133     if (LPT || RPT) {
8134       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8135       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8136 
8137       if (!LPtrToVoid && !RPtrToVoid &&
8138           !Context.typesAreCompatible(LHSType, RHSType)) {
8139         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8140                                           /*isError*/false);
8141       }
8142       if (LHSIsNull && !RHSIsNull) {
8143         Expr *E = LHS.get();
8144         if (getLangOpts().ObjCAutoRefCount)
8145           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8146         LHS = ImpCastExprToType(E, RHSType,
8147                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8148       }
8149       else {
8150         Expr *E = RHS.get();
8151         if (getLangOpts().ObjCAutoRefCount)
8152           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8153                                  Opc);
8154         RHS = ImpCastExprToType(E, LHSType,
8155                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8156       }
8157       return ResultTy;
8158     }
8159     if (LHSType->isObjCObjectPointerType() &&
8160         RHSType->isObjCObjectPointerType()) {
8161       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8162         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8163                                           /*isError*/false);
8164       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8165         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8166 
8167       if (LHSIsNull && !RHSIsNull)
8168         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8169       else
8170         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8171       return ResultTy;
8172     }
8173   }
8174   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8175       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8176     unsigned DiagID = 0;
8177     bool isError = false;
8178     if (LangOpts.DebuggerSupport) {
8179       // Under a debugger, allow the comparison of pointers to integers,
8180       // since users tend to want to compare addresses.
8181     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8182         (RHSIsNull && RHSType->isIntegerType())) {
8183       if (IsRelational && !getLangOpts().CPlusPlus)
8184         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8185     } else if (IsRelational && !getLangOpts().CPlusPlus)
8186       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8187     else if (getLangOpts().CPlusPlus) {
8188       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8189       isError = true;
8190     } else
8191       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8192 
8193     if (DiagID) {
8194       Diag(Loc, DiagID)
8195         << LHSType << RHSType << LHS.get()->getSourceRange()
8196         << RHS.get()->getSourceRange();
8197       if (isError)
8198         return QualType();
8199     }
8200 
8201     if (LHSType->isIntegerType())
8202       LHS = ImpCastExprToType(LHS.get(), RHSType,
8203                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8204     else
8205       RHS = ImpCastExprToType(RHS.get(), LHSType,
8206                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8207     return ResultTy;
8208   }
8209 
8210   // Handle block pointers.
8211   if (!IsRelational && RHSIsNull
8212       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8213     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8214     return ResultTy;
8215   }
8216   if (!IsRelational && LHSIsNull
8217       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8218     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8219     return ResultTy;
8220   }
8221 
8222   return InvalidOperands(Loc, LHS, RHS);
8223 }
8224 
8225 
8226 // Return a signed type that is of identical size and number of elements.
8227 // For floating point vectors, return an integer type of identical size
8228 // and number of elements.
8229 QualType Sema::GetSignedVectorType(QualType V) {
8230   const VectorType *VTy = V->getAs<VectorType>();
8231   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8232   if (TypeSize == Context.getTypeSize(Context.CharTy))
8233     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8234   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8235     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8236   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8237     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8238   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8239     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8240   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8241          "Unhandled vector element size in vector compare");
8242   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8243 }
8244 
8245 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8246 /// operates on extended vector types.  Instead of producing an IntTy result,
8247 /// like a scalar comparison, a vector comparison produces a vector of integer
8248 /// types.
8249 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8250                                           SourceLocation Loc,
8251                                           bool IsRelational) {
8252   // Check to make sure we're operating on vectors of the same type and width,
8253   // Allowing one side to be a scalar of element type.
8254   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8255   if (vType.isNull())
8256     return vType;
8257 
8258   QualType LHSType = LHS.get()->getType();
8259 
8260   // If AltiVec, the comparison results in a numeric type, i.e.
8261   // bool for C++, int for C
8262   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8263     return Context.getLogicalOperationType();
8264 
8265   // For non-floating point types, check for self-comparisons of the form
8266   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8267   // often indicate logic errors in the program.
8268   if (!LHSType->hasFloatingRepresentation() &&
8269       ActiveTemplateInstantiations.empty()) {
8270     if (DeclRefExpr* DRL
8271           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8272       if (DeclRefExpr* DRR
8273             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8274         if (DRL->getDecl() == DRR->getDecl())
8275           DiagRuntimeBehavior(Loc, nullptr,
8276                               PDiag(diag::warn_comparison_always)
8277                                 << 0 // self-
8278                                 << 2 // "a constant"
8279                               );
8280   }
8281 
8282   // Check for comparisons of floating point operands using != and ==.
8283   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8284     assert (RHS.get()->getType()->hasFloatingRepresentation());
8285     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8286   }
8287 
8288   // Return a signed type for the vector.
8289   return GetSignedVectorType(LHSType);
8290 }
8291 
8292 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8293                                           SourceLocation Loc) {
8294   // Ensure that either both operands are of the same vector type, or
8295   // one operand is of a vector type and the other is of its element type.
8296   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8297   if (vType.isNull())
8298     return InvalidOperands(Loc, LHS, RHS);
8299   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8300       vType->hasFloatingRepresentation())
8301     return InvalidOperands(Loc, LHS, RHS);
8302 
8303   return GetSignedVectorType(LHS.get()->getType());
8304 }
8305 
8306 inline QualType Sema::CheckBitwiseOperands(
8307   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8308   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8309 
8310   if (LHS.get()->getType()->isVectorType() ||
8311       RHS.get()->getType()->isVectorType()) {
8312     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8313         RHS.get()->getType()->hasIntegerRepresentation())
8314       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8315 
8316     return InvalidOperands(Loc, LHS, RHS);
8317   }
8318 
8319   ExprResult LHSResult = LHS, RHSResult = RHS;
8320   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8321                                                  IsCompAssign);
8322   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8323     return QualType();
8324   LHS = LHSResult.get();
8325   RHS = RHSResult.get();
8326 
8327   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8328     return compType;
8329   return InvalidOperands(Loc, LHS, RHS);
8330 }
8331 
8332 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8333   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8334 
8335   // Check vector operands differently.
8336   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8337     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8338 
8339   // Diagnose cases where the user write a logical and/or but probably meant a
8340   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8341   // is a constant.
8342   if (LHS.get()->getType()->isIntegerType() &&
8343       !LHS.get()->getType()->isBooleanType() &&
8344       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8345       // Don't warn in macros or template instantiations.
8346       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8347     // If the RHS can be constant folded, and if it constant folds to something
8348     // that isn't 0 or 1 (which indicate a potential logical operation that
8349     // happened to fold to true/false) then warn.
8350     // Parens on the RHS are ignored.
8351     llvm::APSInt Result;
8352     if (RHS.get()->EvaluateAsInt(Result, Context))
8353       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8354            !RHS.get()->getExprLoc().isMacroID()) ||
8355           (Result != 0 && Result != 1)) {
8356         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8357           << RHS.get()->getSourceRange()
8358           << (Opc == BO_LAnd ? "&&" : "||");
8359         // Suggest replacing the logical operator with the bitwise version
8360         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8361             << (Opc == BO_LAnd ? "&" : "|")
8362             << FixItHint::CreateReplacement(SourceRange(
8363                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8364                                                 getLangOpts())),
8365                                             Opc == BO_LAnd ? "&" : "|");
8366         if (Opc == BO_LAnd)
8367           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8368           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8369               << FixItHint::CreateRemoval(
8370                   SourceRange(
8371                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8372                                                  0, getSourceManager(),
8373                                                  getLangOpts()),
8374                       RHS.get()->getLocEnd()));
8375       }
8376   }
8377 
8378   if (!Context.getLangOpts().CPlusPlus) {
8379     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8380     // not operate on the built-in scalar and vector float types.
8381     if (Context.getLangOpts().OpenCL &&
8382         Context.getLangOpts().OpenCLVersion < 120) {
8383       if (LHS.get()->getType()->isFloatingType() ||
8384           RHS.get()->getType()->isFloatingType())
8385         return InvalidOperands(Loc, LHS, RHS);
8386     }
8387 
8388     LHS = UsualUnaryConversions(LHS.get());
8389     if (LHS.isInvalid())
8390       return QualType();
8391 
8392     RHS = UsualUnaryConversions(RHS.get());
8393     if (RHS.isInvalid())
8394       return QualType();
8395 
8396     if (!LHS.get()->getType()->isScalarType() ||
8397         !RHS.get()->getType()->isScalarType())
8398       return InvalidOperands(Loc, LHS, RHS);
8399 
8400     return Context.IntTy;
8401   }
8402 
8403   // The following is safe because we only use this method for
8404   // non-overloadable operands.
8405 
8406   // C++ [expr.log.and]p1
8407   // C++ [expr.log.or]p1
8408   // The operands are both contextually converted to type bool.
8409   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8410   if (LHSRes.isInvalid())
8411     return InvalidOperands(Loc, LHS, RHS);
8412   LHS = LHSRes;
8413 
8414   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8415   if (RHSRes.isInvalid())
8416     return InvalidOperands(Loc, LHS, RHS);
8417   RHS = RHSRes;
8418 
8419   // C++ [expr.log.and]p2
8420   // C++ [expr.log.or]p2
8421   // The result is a bool.
8422   return Context.BoolTy;
8423 }
8424 
8425 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8426   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8427   if (!ME) return false;
8428   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8429   ObjCMessageExpr *Base =
8430     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8431   if (!Base) return false;
8432   return Base->getMethodDecl() != nullptr;
8433 }
8434 
8435 /// Is the given expression (which must be 'const') a reference to a
8436 /// variable which was originally non-const, but which has become
8437 /// 'const' due to being captured within a block?
8438 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8439 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8440   assert(E->isLValue() && E->getType().isConstQualified());
8441   E = E->IgnoreParens();
8442 
8443   // Must be a reference to a declaration from an enclosing scope.
8444   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8445   if (!DRE) return NCCK_None;
8446   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8447 
8448   // The declaration must be a variable which is not declared 'const'.
8449   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8450   if (!var) return NCCK_None;
8451   if (var->getType().isConstQualified()) return NCCK_None;
8452   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8453 
8454   // Decide whether the first capture was for a block or a lambda.
8455   DeclContext *DC = S.CurContext, *Prev = nullptr;
8456   while (DC != var->getDeclContext()) {
8457     Prev = DC;
8458     DC = DC->getParent();
8459   }
8460   // Unless we have an init-capture, we've gone one step too far.
8461   if (!var->isInitCapture())
8462     DC = Prev;
8463   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8464 }
8465 
8466 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8467 /// emit an error and return true.  If so, return false.
8468 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8469   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8470   SourceLocation OrigLoc = Loc;
8471   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8472                                                               &Loc);
8473   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8474     IsLV = Expr::MLV_InvalidMessageExpression;
8475   if (IsLV == Expr::MLV_Valid)
8476     return false;
8477 
8478   unsigned Diag = 0;
8479   bool NeedType = false;
8480   switch (IsLV) { // C99 6.5.16p2
8481   case Expr::MLV_ConstQualified:
8482     Diag = diag::err_typecheck_assign_const;
8483 
8484     // Use a specialized diagnostic when we're assigning to an object
8485     // from an enclosing function or block.
8486     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8487       if (NCCK == NCCK_Block)
8488         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8489       else
8490         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8491       break;
8492     }
8493 
8494     // In ARC, use some specialized diagnostics for occasions where we
8495     // infer 'const'.  These are always pseudo-strong variables.
8496     if (S.getLangOpts().ObjCAutoRefCount) {
8497       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8498       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8499         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8500 
8501         // Use the normal diagnostic if it's pseudo-__strong but the
8502         // user actually wrote 'const'.
8503         if (var->isARCPseudoStrong() &&
8504             (!var->getTypeSourceInfo() ||
8505              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8506           // There are two pseudo-strong cases:
8507           //  - self
8508           ObjCMethodDecl *method = S.getCurMethodDecl();
8509           if (method && var == method->getSelfDecl())
8510             Diag = method->isClassMethod()
8511               ? diag::err_typecheck_arc_assign_self_class_method
8512               : diag::err_typecheck_arc_assign_self;
8513 
8514           //  - fast enumeration variables
8515           else
8516             Diag = diag::err_typecheck_arr_assign_enumeration;
8517 
8518           SourceRange Assign;
8519           if (Loc != OrigLoc)
8520             Assign = SourceRange(OrigLoc, OrigLoc);
8521           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8522           // We need to preserve the AST regardless, so migration tool
8523           // can do its job.
8524           return false;
8525         }
8526       }
8527     }
8528 
8529     break;
8530   case Expr::MLV_ArrayType:
8531   case Expr::MLV_ArrayTemporary:
8532     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8533     NeedType = true;
8534     break;
8535   case Expr::MLV_NotObjectType:
8536     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8537     NeedType = true;
8538     break;
8539   case Expr::MLV_LValueCast:
8540     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8541     break;
8542   case Expr::MLV_Valid:
8543     llvm_unreachable("did not take early return for MLV_Valid");
8544   case Expr::MLV_InvalidExpression:
8545   case Expr::MLV_MemberFunction:
8546   case Expr::MLV_ClassTemporary:
8547     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8548     break;
8549   case Expr::MLV_IncompleteType:
8550   case Expr::MLV_IncompleteVoidType:
8551     return S.RequireCompleteType(Loc, E->getType(),
8552              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8553   case Expr::MLV_DuplicateVectorComponents:
8554     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8555     break;
8556   case Expr::MLV_NoSetterProperty:
8557     llvm_unreachable("readonly properties should be processed differently");
8558   case Expr::MLV_InvalidMessageExpression:
8559     Diag = diag::error_readonly_message_assignment;
8560     break;
8561   case Expr::MLV_SubObjCPropertySetting:
8562     Diag = diag::error_no_subobject_property_setting;
8563     break;
8564   }
8565 
8566   SourceRange Assign;
8567   if (Loc != OrigLoc)
8568     Assign = SourceRange(OrigLoc, OrigLoc);
8569   if (NeedType)
8570     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8571   else
8572     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8573   return true;
8574 }
8575 
8576 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8577                                          SourceLocation Loc,
8578                                          Sema &Sema) {
8579   // C / C++ fields
8580   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8581   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8582   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8583     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8584       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8585   }
8586 
8587   // Objective-C instance variables
8588   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8589   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8590   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8591     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8592     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8593     if (RL && RR && RL->getDecl() == RR->getDecl())
8594       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8595   }
8596 }
8597 
8598 // C99 6.5.16.1
8599 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8600                                        SourceLocation Loc,
8601                                        QualType CompoundType) {
8602   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8603 
8604   // Verify that LHS is a modifiable lvalue, and emit error if not.
8605   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8606     return QualType();
8607 
8608   QualType LHSType = LHSExpr->getType();
8609   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8610                                              CompoundType;
8611   AssignConvertType ConvTy;
8612   if (CompoundType.isNull()) {
8613     Expr *RHSCheck = RHS.get();
8614 
8615     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8616 
8617     QualType LHSTy(LHSType);
8618     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8619     if (RHS.isInvalid())
8620       return QualType();
8621     // Special case of NSObject attributes on c-style pointer types.
8622     if (ConvTy == IncompatiblePointer &&
8623         ((Context.isObjCNSObjectType(LHSType) &&
8624           RHSType->isObjCObjectPointerType()) ||
8625          (Context.isObjCNSObjectType(RHSType) &&
8626           LHSType->isObjCObjectPointerType())))
8627       ConvTy = Compatible;
8628 
8629     if (ConvTy == Compatible &&
8630         LHSType->isObjCObjectType())
8631         Diag(Loc, diag::err_objc_object_assignment)
8632           << LHSType;
8633 
8634     // If the RHS is a unary plus or minus, check to see if they = and + are
8635     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8636     // instead of "x += 4".
8637     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8638       RHSCheck = ICE->getSubExpr();
8639     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8640       if ((UO->getOpcode() == UO_Plus ||
8641            UO->getOpcode() == UO_Minus) &&
8642           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8643           // Only if the two operators are exactly adjacent.
8644           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8645           // And there is a space or other character before the subexpr of the
8646           // unary +/-.  We don't want to warn on "x=-1".
8647           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8648           UO->getSubExpr()->getLocStart().isFileID()) {
8649         Diag(Loc, diag::warn_not_compound_assign)
8650           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8651           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8652       }
8653     }
8654 
8655     if (ConvTy == Compatible) {
8656       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8657         // Warn about retain cycles where a block captures the LHS, but
8658         // not if the LHS is a simple variable into which the block is
8659         // being stored...unless that variable can be captured by reference!
8660         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8661         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8662         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8663           checkRetainCycles(LHSExpr, RHS.get());
8664 
8665         // It is safe to assign a weak reference into a strong variable.
8666         // Although this code can still have problems:
8667         //   id x = self.weakProp;
8668         //   id y = self.weakProp;
8669         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8670         // paths through the function. This should be revisited if
8671         // -Wrepeated-use-of-weak is made flow-sensitive.
8672         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8673                              RHS.get()->getLocStart()))
8674           getCurFunction()->markSafeWeakUse(RHS.get());
8675 
8676       } else if (getLangOpts().ObjCAutoRefCount) {
8677         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8678       }
8679     }
8680   } else {
8681     // Compound assignment "x += y"
8682     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8683   }
8684 
8685   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8686                                RHS.get(), AA_Assigning))
8687     return QualType();
8688 
8689   CheckForNullPointerDereference(*this, LHSExpr);
8690 
8691   // C99 6.5.16p3: The type of an assignment expression is the type of the
8692   // left operand unless the left operand has qualified type, in which case
8693   // it is the unqualified version of the type of the left operand.
8694   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8695   // is converted to the type of the assignment expression (above).
8696   // C++ 5.17p1: the type of the assignment expression is that of its left
8697   // operand.
8698   return (getLangOpts().CPlusPlus
8699           ? LHSType : LHSType.getUnqualifiedType());
8700 }
8701 
8702 // C99 6.5.17
8703 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8704                                    SourceLocation Loc) {
8705   LHS = S.CheckPlaceholderExpr(LHS.get());
8706   RHS = S.CheckPlaceholderExpr(RHS.get());
8707   if (LHS.isInvalid() || RHS.isInvalid())
8708     return QualType();
8709 
8710   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8711   // operands, but not unary promotions.
8712   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8713 
8714   // So we treat the LHS as a ignored value, and in C++ we allow the
8715   // containing site to determine what should be done with the RHS.
8716   LHS = S.IgnoredValueConversions(LHS.get());
8717   if (LHS.isInvalid())
8718     return QualType();
8719 
8720   S.DiagnoseUnusedExprResult(LHS.get());
8721 
8722   if (!S.getLangOpts().CPlusPlus) {
8723     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8724     if (RHS.isInvalid())
8725       return QualType();
8726     if (!RHS.get()->getType()->isVoidType())
8727       S.RequireCompleteType(Loc, RHS.get()->getType(),
8728                             diag::err_incomplete_type);
8729   }
8730 
8731   return RHS.get()->getType();
8732 }
8733 
8734 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8735 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8736 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8737                                                ExprValueKind &VK,
8738                                                SourceLocation OpLoc,
8739                                                bool IsInc, bool IsPrefix) {
8740   if (Op->isTypeDependent())
8741     return S.Context.DependentTy;
8742 
8743   QualType ResType = Op->getType();
8744   // Atomic types can be used for increment / decrement where the non-atomic
8745   // versions can, so ignore the _Atomic() specifier for the purpose of
8746   // checking.
8747   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8748     ResType = ResAtomicType->getValueType();
8749 
8750   assert(!ResType.isNull() && "no type for increment/decrement expression");
8751 
8752   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8753     // Decrement of bool is not allowed.
8754     if (!IsInc) {
8755       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8756       return QualType();
8757     }
8758     // Increment of bool sets it to true, but is deprecated.
8759     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8760   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8761     // Error on enum increments and decrements in C++ mode
8762     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8763     return QualType();
8764   } else if (ResType->isRealType()) {
8765     // OK!
8766   } else if (ResType->isPointerType()) {
8767     // C99 6.5.2.4p2, 6.5.6p2
8768     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8769       return QualType();
8770   } else if (ResType->isObjCObjectPointerType()) {
8771     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8772     // Otherwise, we just need a complete type.
8773     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8774         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8775       return QualType();
8776   } else if (ResType->isAnyComplexType()) {
8777     // C99 does not support ++/-- on complex types, we allow as an extension.
8778     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8779       << ResType << Op->getSourceRange();
8780   } else if (ResType->isPlaceholderType()) {
8781     ExprResult PR = S.CheckPlaceholderExpr(Op);
8782     if (PR.isInvalid()) return QualType();
8783     return CheckIncrementDecrementOperand(S, PR.get(), VK, OpLoc,
8784                                           IsInc, IsPrefix);
8785   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8786     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8787   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8788             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8789     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8790   } else {
8791     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8792       << ResType << int(IsInc) << Op->getSourceRange();
8793     return QualType();
8794   }
8795   // At this point, we know we have a real, complex or pointer type.
8796   // Now make sure the operand is a modifiable lvalue.
8797   if (CheckForModifiableLvalue(Op, OpLoc, S))
8798     return QualType();
8799   // In C++, a prefix increment is the same type as the operand. Otherwise
8800   // (in C or with postfix), the increment is the unqualified type of the
8801   // operand.
8802   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8803     VK = VK_LValue;
8804     return ResType;
8805   } else {
8806     VK = VK_RValue;
8807     return ResType.getUnqualifiedType();
8808   }
8809 }
8810 
8811 
8812 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8813 /// This routine allows us to typecheck complex/recursive expressions
8814 /// where the declaration is needed for type checking. We only need to
8815 /// handle cases when the expression references a function designator
8816 /// or is an lvalue. Here are some examples:
8817 ///  - &(x) => x
8818 ///  - &*****f => f for f a function designator.
8819 ///  - &s.xx => s
8820 ///  - &s.zz[1].yy -> s, if zz is an array
8821 ///  - *(x + 1) -> x, if x is an array
8822 ///  - &"123"[2] -> 0
8823 ///  - & __real__ x -> x
8824 static ValueDecl *getPrimaryDecl(Expr *E) {
8825   switch (E->getStmtClass()) {
8826   case Stmt::DeclRefExprClass:
8827     return cast<DeclRefExpr>(E)->getDecl();
8828   case Stmt::MemberExprClass:
8829     // If this is an arrow operator, the address is an offset from
8830     // the base's value, so the object the base refers to is
8831     // irrelevant.
8832     if (cast<MemberExpr>(E)->isArrow())
8833       return nullptr;
8834     // Otherwise, the expression refers to a part of the base
8835     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8836   case Stmt::ArraySubscriptExprClass: {
8837     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8838     // promotion of register arrays earlier.
8839     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8840     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8841       if (ICE->getSubExpr()->getType()->isArrayType())
8842         return getPrimaryDecl(ICE->getSubExpr());
8843     }
8844     return nullptr;
8845   }
8846   case Stmt::UnaryOperatorClass: {
8847     UnaryOperator *UO = cast<UnaryOperator>(E);
8848 
8849     switch(UO->getOpcode()) {
8850     case UO_Real:
8851     case UO_Imag:
8852     case UO_Extension:
8853       return getPrimaryDecl(UO->getSubExpr());
8854     default:
8855       return nullptr;
8856     }
8857   }
8858   case Stmt::ParenExprClass:
8859     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8860   case Stmt::ImplicitCastExprClass:
8861     // If the result of an implicit cast is an l-value, we care about
8862     // the sub-expression; otherwise, the result here doesn't matter.
8863     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8864   default:
8865     return nullptr;
8866   }
8867 }
8868 
8869 namespace {
8870   enum {
8871     AO_Bit_Field = 0,
8872     AO_Vector_Element = 1,
8873     AO_Property_Expansion = 2,
8874     AO_Register_Variable = 3,
8875     AO_No_Error = 4
8876   };
8877 }
8878 /// \brief Diagnose invalid operand for address of operations.
8879 ///
8880 /// \param Type The type of operand which cannot have its address taken.
8881 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8882                                          Expr *E, unsigned Type) {
8883   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8884 }
8885 
8886 /// CheckAddressOfOperand - The operand of & must be either a function
8887 /// designator or an lvalue designating an object. If it is an lvalue, the
8888 /// object cannot be declared with storage class register or be a bit field.
8889 /// Note: The usual conversions are *not* applied to the operand of the &
8890 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8891 /// In C++, the operand might be an overloaded function name, in which case
8892 /// we allow the '&' but retain the overloaded-function type.
8893 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8894   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8895     if (PTy->getKind() == BuiltinType::Overload) {
8896       Expr *E = OrigOp.get()->IgnoreParens();
8897       if (!isa<OverloadExpr>(E)) {
8898         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8899         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8900           << OrigOp.get()->getSourceRange();
8901         return QualType();
8902       }
8903 
8904       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8905       if (isa<UnresolvedMemberExpr>(Ovl))
8906         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8907           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8908             << OrigOp.get()->getSourceRange();
8909           return QualType();
8910         }
8911 
8912       return Context.OverloadTy;
8913     }
8914 
8915     if (PTy->getKind() == BuiltinType::UnknownAny)
8916       return Context.UnknownAnyTy;
8917 
8918     if (PTy->getKind() == BuiltinType::BoundMember) {
8919       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8920         << OrigOp.get()->getSourceRange();
8921       return QualType();
8922     }
8923 
8924     OrigOp = CheckPlaceholderExpr(OrigOp.get());
8925     if (OrigOp.isInvalid()) return QualType();
8926   }
8927 
8928   if (OrigOp.get()->isTypeDependent())
8929     return Context.DependentTy;
8930 
8931   assert(!OrigOp.get()->getType()->isPlaceholderType());
8932 
8933   // Make sure to ignore parentheses in subsequent checks
8934   Expr *op = OrigOp.get()->IgnoreParens();
8935 
8936   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8937   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8938     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8939     return QualType();
8940   }
8941 
8942   if (getLangOpts().C99) {
8943     // Implement C99-only parts of addressof rules.
8944     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8945       if (uOp->getOpcode() == UO_Deref)
8946         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8947         // (assuming the deref expression is valid).
8948         return uOp->getSubExpr()->getType();
8949     }
8950     // Technically, there should be a check for array subscript
8951     // expressions here, but the result of one is always an lvalue anyway.
8952   }
8953   ValueDecl *dcl = getPrimaryDecl(op);
8954   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8955   unsigned AddressOfError = AO_No_Error;
8956 
8957   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8958     bool sfinae = (bool)isSFINAEContext();
8959     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8960                                   : diag::ext_typecheck_addrof_temporary)
8961       << op->getType() << op->getSourceRange();
8962     if (sfinae)
8963       return QualType();
8964     // Materialize the temporary as an lvalue so that we can take its address.
8965     OrigOp = op = new (Context)
8966         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
8967   } else if (isa<ObjCSelectorExpr>(op)) {
8968     return Context.getPointerType(op->getType());
8969   } else if (lval == Expr::LV_MemberFunction) {
8970     // If it's an instance method, make a member pointer.
8971     // The expression must have exactly the form &A::foo.
8972 
8973     // If the underlying expression isn't a decl ref, give up.
8974     if (!isa<DeclRefExpr>(op)) {
8975       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8976         << OrigOp.get()->getSourceRange();
8977       return QualType();
8978     }
8979     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8980     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8981 
8982     // The id-expression was parenthesized.
8983     if (OrigOp.get() != DRE) {
8984       Diag(OpLoc, diag::err_parens_pointer_member_function)
8985         << OrigOp.get()->getSourceRange();
8986 
8987     // The method was named without a qualifier.
8988     } else if (!DRE->getQualifier()) {
8989       if (MD->getParent()->getName().empty())
8990         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8991           << op->getSourceRange();
8992       else {
8993         SmallString<32> Str;
8994         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8995         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8996           << op->getSourceRange()
8997           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8998       }
8999     }
9000 
9001     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9002     if (isa<CXXDestructorDecl>(MD))
9003       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9004 
9005     QualType MPTy = Context.getMemberPointerType(
9006         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9007     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9008       RequireCompleteType(OpLoc, MPTy, 0);
9009     return MPTy;
9010   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9011     // C99 6.5.3.2p1
9012     // The operand must be either an l-value or a function designator
9013     if (!op->getType()->isFunctionType()) {
9014       // Use a special diagnostic for loads from property references.
9015       if (isa<PseudoObjectExpr>(op)) {
9016         AddressOfError = AO_Property_Expansion;
9017       } else {
9018         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9019           << op->getType() << op->getSourceRange();
9020         return QualType();
9021       }
9022     }
9023   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9024     // The operand cannot be a bit-field
9025     AddressOfError = AO_Bit_Field;
9026   } else if (op->getObjectKind() == OK_VectorComponent) {
9027     // The operand cannot be an element of a vector
9028     AddressOfError = AO_Vector_Element;
9029   } else if (dcl) { // C99 6.5.3.2p1
9030     // We have an lvalue with a decl. Make sure the decl is not declared
9031     // with the register storage-class specifier.
9032     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9033       // in C++ it is not error to take address of a register
9034       // variable (c++03 7.1.1P3)
9035       if (vd->getStorageClass() == SC_Register &&
9036           !getLangOpts().CPlusPlus) {
9037         AddressOfError = AO_Register_Variable;
9038       }
9039     } else if (isa<FunctionTemplateDecl>(dcl)) {
9040       return Context.OverloadTy;
9041     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9042       // Okay: we can take the address of a field.
9043       // Could be a pointer to member, though, if there is an explicit
9044       // scope qualifier for the class.
9045       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9046         DeclContext *Ctx = dcl->getDeclContext();
9047         if (Ctx && Ctx->isRecord()) {
9048           if (dcl->getType()->isReferenceType()) {
9049             Diag(OpLoc,
9050                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9051               << dcl->getDeclName() << dcl->getType();
9052             return QualType();
9053           }
9054 
9055           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9056             Ctx = Ctx->getParent();
9057 
9058           QualType MPTy = Context.getMemberPointerType(
9059               op->getType(),
9060               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9061           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9062             RequireCompleteType(OpLoc, MPTy, 0);
9063           return MPTy;
9064         }
9065       }
9066     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9067       llvm_unreachable("Unknown/unexpected decl type");
9068   }
9069 
9070   if (AddressOfError != AO_No_Error) {
9071     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9072     return QualType();
9073   }
9074 
9075   if (lval == Expr::LV_IncompleteVoidType) {
9076     // Taking the address of a void variable is technically illegal, but we
9077     // allow it in cases which are otherwise valid.
9078     // Example: "extern void x; void* y = &x;".
9079     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9080   }
9081 
9082   // If the operand has type "type", the result has type "pointer to type".
9083   if (op->getType()->isObjCObjectType())
9084     return Context.getObjCObjectPointerType(op->getType());
9085   return Context.getPointerType(op->getType());
9086 }
9087 
9088 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9089 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9090                                         SourceLocation OpLoc) {
9091   if (Op->isTypeDependent())
9092     return S.Context.DependentTy;
9093 
9094   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9095   if (ConvResult.isInvalid())
9096     return QualType();
9097   Op = ConvResult.get();
9098   QualType OpTy = Op->getType();
9099   QualType Result;
9100 
9101   if (isa<CXXReinterpretCastExpr>(Op)) {
9102     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9103     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9104                                      Op->getSourceRange());
9105   }
9106 
9107   if (const PointerType *PT = OpTy->getAs<PointerType>())
9108     Result = PT->getPointeeType();
9109   else if (const ObjCObjectPointerType *OPT =
9110              OpTy->getAs<ObjCObjectPointerType>())
9111     Result = OPT->getPointeeType();
9112   else {
9113     ExprResult PR = S.CheckPlaceholderExpr(Op);
9114     if (PR.isInvalid()) return QualType();
9115     if (PR.get() != Op)
9116       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9117   }
9118 
9119   if (Result.isNull()) {
9120     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9121       << OpTy << Op->getSourceRange();
9122     return QualType();
9123   }
9124 
9125   // Note that per both C89 and C99, indirection is always legal, even if Result
9126   // is an incomplete type or void.  It would be possible to warn about
9127   // dereferencing a void pointer, but it's completely well-defined, and such a
9128   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9129   // for pointers to 'void' but is fine for any other pointer type:
9130   //
9131   // C++ [expr.unary.op]p1:
9132   //   [...] the expression to which [the unary * operator] is applied shall
9133   //   be a pointer to an object type, or a pointer to a function type
9134   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9135     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9136       << OpTy << Op->getSourceRange();
9137 
9138   // Dereferences are usually l-values...
9139   VK = VK_LValue;
9140 
9141   // ...except that certain expressions are never l-values in C.
9142   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9143     VK = VK_RValue;
9144 
9145   return Result;
9146 }
9147 
9148 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9149   tok::TokenKind Kind) {
9150   BinaryOperatorKind Opc;
9151   switch (Kind) {
9152   default: llvm_unreachable("Unknown binop!");
9153   case tok::periodstar:           Opc = BO_PtrMemD; break;
9154   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9155   case tok::star:                 Opc = BO_Mul; break;
9156   case tok::slash:                Opc = BO_Div; break;
9157   case tok::percent:              Opc = BO_Rem; break;
9158   case tok::plus:                 Opc = BO_Add; break;
9159   case tok::minus:                Opc = BO_Sub; break;
9160   case tok::lessless:             Opc = BO_Shl; break;
9161   case tok::greatergreater:       Opc = BO_Shr; break;
9162   case tok::lessequal:            Opc = BO_LE; break;
9163   case tok::less:                 Opc = BO_LT; break;
9164   case tok::greaterequal:         Opc = BO_GE; break;
9165   case tok::greater:              Opc = BO_GT; break;
9166   case tok::exclaimequal:         Opc = BO_NE; break;
9167   case tok::equalequal:           Opc = BO_EQ; break;
9168   case tok::amp:                  Opc = BO_And; break;
9169   case tok::caret:                Opc = BO_Xor; break;
9170   case tok::pipe:                 Opc = BO_Or; break;
9171   case tok::ampamp:               Opc = BO_LAnd; break;
9172   case tok::pipepipe:             Opc = BO_LOr; break;
9173   case tok::equal:                Opc = BO_Assign; break;
9174   case tok::starequal:            Opc = BO_MulAssign; break;
9175   case tok::slashequal:           Opc = BO_DivAssign; break;
9176   case tok::percentequal:         Opc = BO_RemAssign; break;
9177   case tok::plusequal:            Opc = BO_AddAssign; break;
9178   case tok::minusequal:           Opc = BO_SubAssign; break;
9179   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9180   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9181   case tok::ampequal:             Opc = BO_AndAssign; break;
9182   case tok::caretequal:           Opc = BO_XorAssign; break;
9183   case tok::pipeequal:            Opc = BO_OrAssign; break;
9184   case tok::comma:                Opc = BO_Comma; break;
9185   }
9186   return Opc;
9187 }
9188 
9189 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9190   tok::TokenKind Kind) {
9191   UnaryOperatorKind Opc;
9192   switch (Kind) {
9193   default: llvm_unreachable("Unknown unary op!");
9194   case tok::plusplus:     Opc = UO_PreInc; break;
9195   case tok::minusminus:   Opc = UO_PreDec; break;
9196   case tok::amp:          Opc = UO_AddrOf; break;
9197   case tok::star:         Opc = UO_Deref; break;
9198   case tok::plus:         Opc = UO_Plus; break;
9199   case tok::minus:        Opc = UO_Minus; break;
9200   case tok::tilde:        Opc = UO_Not; break;
9201   case tok::exclaim:      Opc = UO_LNot; break;
9202   case tok::kw___real:    Opc = UO_Real; break;
9203   case tok::kw___imag:    Opc = UO_Imag; break;
9204   case tok::kw___extension__: Opc = UO_Extension; break;
9205   }
9206   return Opc;
9207 }
9208 
9209 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9210 /// This warning is only emitted for builtin assignment operations. It is also
9211 /// suppressed in the event of macro expansions.
9212 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9213                                    SourceLocation OpLoc) {
9214   if (!S.ActiveTemplateInstantiations.empty())
9215     return;
9216   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9217     return;
9218   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9219   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9220   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9221   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9222   if (!LHSDeclRef || !RHSDeclRef ||
9223       LHSDeclRef->getLocation().isMacroID() ||
9224       RHSDeclRef->getLocation().isMacroID())
9225     return;
9226   const ValueDecl *LHSDecl =
9227     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9228   const ValueDecl *RHSDecl =
9229     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9230   if (LHSDecl != RHSDecl)
9231     return;
9232   if (LHSDecl->getType().isVolatileQualified())
9233     return;
9234   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9235     if (RefTy->getPointeeType().isVolatileQualified())
9236       return;
9237 
9238   S.Diag(OpLoc, diag::warn_self_assignment)
9239       << LHSDeclRef->getType()
9240       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9241 }
9242 
9243 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9244 /// is usually indicative of introspection within the Objective-C pointer.
9245 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9246                                           SourceLocation OpLoc) {
9247   if (!S.getLangOpts().ObjC1)
9248     return;
9249 
9250   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9251   const Expr *LHS = L.get();
9252   const Expr *RHS = R.get();
9253 
9254   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9255     ObjCPointerExpr = LHS;
9256     OtherExpr = RHS;
9257   }
9258   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9259     ObjCPointerExpr = RHS;
9260     OtherExpr = LHS;
9261   }
9262 
9263   // This warning is deliberately made very specific to reduce false
9264   // positives with logic that uses '&' for hashing.  This logic mainly
9265   // looks for code trying to introspect into tagged pointers, which
9266   // code should generally never do.
9267   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9268     unsigned Diag = diag::warn_objc_pointer_masking;
9269     // Determine if we are introspecting the result of performSelectorXXX.
9270     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9271     // Special case messages to -performSelector and friends, which
9272     // can return non-pointer values boxed in a pointer value.
9273     // Some clients may wish to silence warnings in this subcase.
9274     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9275       Selector S = ME->getSelector();
9276       StringRef SelArg0 = S.getNameForSlot(0);
9277       if (SelArg0.startswith("performSelector"))
9278         Diag = diag::warn_objc_pointer_masking_performSelector;
9279     }
9280 
9281     S.Diag(OpLoc, Diag)
9282       << ObjCPointerExpr->getSourceRange();
9283   }
9284 }
9285 
9286 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9287 /// operator @p Opc at location @c TokLoc. This routine only supports
9288 /// built-in operations; ActOnBinOp handles overloaded operators.
9289 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9290                                     BinaryOperatorKind Opc,
9291                                     Expr *LHSExpr, Expr *RHSExpr) {
9292   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9293     // The syntax only allows initializer lists on the RHS of assignment,
9294     // so we don't need to worry about accepting invalid code for
9295     // non-assignment operators.
9296     // C++11 5.17p9:
9297     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9298     //   of x = {} is x = T().
9299     InitializationKind Kind =
9300         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9301     InitializedEntity Entity =
9302         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9303     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9304     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9305     if (Init.isInvalid())
9306       return Init;
9307     RHSExpr = Init.get();
9308   }
9309 
9310   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9311   QualType ResultTy;     // Result type of the binary operator.
9312   // The following two variables are used for compound assignment operators
9313   QualType CompLHSTy;    // Type of LHS after promotions for computation
9314   QualType CompResultTy; // Type of computation result
9315   ExprValueKind VK = VK_RValue;
9316   ExprObjectKind OK = OK_Ordinary;
9317 
9318   switch (Opc) {
9319   case BO_Assign:
9320     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9321     if (getLangOpts().CPlusPlus &&
9322         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9323       VK = LHS.get()->getValueKind();
9324       OK = LHS.get()->getObjectKind();
9325     }
9326     if (!ResultTy.isNull())
9327       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9328     break;
9329   case BO_PtrMemD:
9330   case BO_PtrMemI:
9331     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9332                                             Opc == BO_PtrMemI);
9333     break;
9334   case BO_Mul:
9335   case BO_Div:
9336     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9337                                            Opc == BO_Div);
9338     break;
9339   case BO_Rem:
9340     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9341     break;
9342   case BO_Add:
9343     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9344     break;
9345   case BO_Sub:
9346     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9347     break;
9348   case BO_Shl:
9349   case BO_Shr:
9350     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9351     break;
9352   case BO_LE:
9353   case BO_LT:
9354   case BO_GE:
9355   case BO_GT:
9356     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9357     break;
9358   case BO_EQ:
9359   case BO_NE:
9360     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9361     break;
9362   case BO_And:
9363     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9364   case BO_Xor:
9365   case BO_Or:
9366     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9367     break;
9368   case BO_LAnd:
9369   case BO_LOr:
9370     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9371     break;
9372   case BO_MulAssign:
9373   case BO_DivAssign:
9374     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9375                                                Opc == BO_DivAssign);
9376     CompLHSTy = CompResultTy;
9377     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9378       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9379     break;
9380   case BO_RemAssign:
9381     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9382     CompLHSTy = CompResultTy;
9383     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9384       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9385     break;
9386   case BO_AddAssign:
9387     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9388     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9389       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9390     break;
9391   case BO_SubAssign:
9392     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9393     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9394       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9395     break;
9396   case BO_ShlAssign:
9397   case BO_ShrAssign:
9398     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9399     CompLHSTy = CompResultTy;
9400     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9401       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9402     break;
9403   case BO_AndAssign:
9404   case BO_OrAssign: // fallthrough
9405 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9406   case BO_XorAssign:
9407     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9408     CompLHSTy = CompResultTy;
9409     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9410       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9411     break;
9412   case BO_Comma:
9413     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9414     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9415       VK = RHS.get()->getValueKind();
9416       OK = RHS.get()->getObjectKind();
9417     }
9418     break;
9419   }
9420   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9421     return ExprError();
9422 
9423   // Check for array bounds violations for both sides of the BinaryOperator
9424   CheckArrayAccess(LHS.get());
9425   CheckArrayAccess(RHS.get());
9426 
9427   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9428     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9429                                                  &Context.Idents.get("object_setClass"),
9430                                                  SourceLocation(), LookupOrdinaryName);
9431     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9432       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9433       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9434       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9435       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9436       FixItHint::CreateInsertion(RHSLocEnd, ")");
9437     }
9438     else
9439       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9440   }
9441   else if (const ObjCIvarRefExpr *OIRE =
9442            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9443     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9444 
9445   if (CompResultTy.isNull())
9446     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9447                                         OK, OpLoc, FPFeatures.fp_contract);
9448   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9449       OK_ObjCProperty) {
9450     VK = VK_LValue;
9451     OK = LHS.get()->getObjectKind();
9452   }
9453   return new (Context) CompoundAssignOperator(
9454       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9455       OpLoc, FPFeatures.fp_contract);
9456 }
9457 
9458 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9459 /// operators are mixed in a way that suggests that the programmer forgot that
9460 /// comparison operators have higher precedence. The most typical example of
9461 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9462 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9463                                       SourceLocation OpLoc, Expr *LHSExpr,
9464                                       Expr *RHSExpr) {
9465   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9466   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9467 
9468   // Check that one of the sides is a comparison operator.
9469   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9470   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9471   if (!isLeftComp && !isRightComp)
9472     return;
9473 
9474   // Bitwise operations are sometimes used as eager logical ops.
9475   // Don't diagnose this.
9476   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9477   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9478   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9479     return;
9480 
9481   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9482                                                    OpLoc)
9483                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9484   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9485   SourceRange ParensRange = isLeftComp ?
9486       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9487     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9488 
9489   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9490     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9491   SuggestParentheses(Self, OpLoc,
9492     Self.PDiag(diag::note_precedence_silence) << OpStr,
9493     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9494   SuggestParentheses(Self, OpLoc,
9495     Self.PDiag(diag::note_precedence_bitwise_first)
9496       << BinaryOperator::getOpcodeStr(Opc),
9497     ParensRange);
9498 }
9499 
9500 /// \brief It accepts a '&' expr that is inside a '|' one.
9501 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9502 /// in parentheses.
9503 static void
9504 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9505                                        BinaryOperator *Bop) {
9506   assert(Bop->getOpcode() == BO_And);
9507   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9508       << Bop->getSourceRange() << OpLoc;
9509   SuggestParentheses(Self, Bop->getOperatorLoc(),
9510     Self.PDiag(diag::note_precedence_silence)
9511       << Bop->getOpcodeStr(),
9512     Bop->getSourceRange());
9513 }
9514 
9515 /// \brief It accepts a '&&' expr that is inside a '||' one.
9516 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9517 /// in parentheses.
9518 static void
9519 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9520                                        BinaryOperator *Bop) {
9521   assert(Bop->getOpcode() == BO_LAnd);
9522   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9523       << Bop->getSourceRange() << OpLoc;
9524   SuggestParentheses(Self, Bop->getOperatorLoc(),
9525     Self.PDiag(diag::note_precedence_silence)
9526       << Bop->getOpcodeStr(),
9527     Bop->getSourceRange());
9528 }
9529 
9530 /// \brief Returns true if the given expression can be evaluated as a constant
9531 /// 'true'.
9532 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9533   bool Res;
9534   return !E->isValueDependent() &&
9535          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9536 }
9537 
9538 /// \brief Returns true if the given expression can be evaluated as a constant
9539 /// 'false'.
9540 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9541   bool Res;
9542   return !E->isValueDependent() &&
9543          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9544 }
9545 
9546 /// \brief Look for '&&' in the left hand of a '||' expr.
9547 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9548                                              Expr *LHSExpr, Expr *RHSExpr) {
9549   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9550     if (Bop->getOpcode() == BO_LAnd) {
9551       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9552       if (EvaluatesAsFalse(S, RHSExpr))
9553         return;
9554       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9555       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9556         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9557     } else if (Bop->getOpcode() == BO_LOr) {
9558       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9559         // If it's "a || b && 1 || c" we didn't warn earlier for
9560         // "a || b && 1", but warn now.
9561         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9562           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9563       }
9564     }
9565   }
9566 }
9567 
9568 /// \brief Look for '&&' in the right hand of a '||' expr.
9569 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9570                                              Expr *LHSExpr, Expr *RHSExpr) {
9571   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9572     if (Bop->getOpcode() == BO_LAnd) {
9573       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9574       if (EvaluatesAsFalse(S, LHSExpr))
9575         return;
9576       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9577       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9578         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9579     }
9580   }
9581 }
9582 
9583 /// \brief Look for '&' in the left or right hand of a '|' expr.
9584 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9585                                              Expr *OrArg) {
9586   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9587     if (Bop->getOpcode() == BO_And)
9588       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9589   }
9590 }
9591 
9592 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9593                                     Expr *SubExpr, StringRef Shift) {
9594   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9595     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9596       StringRef Op = Bop->getOpcodeStr();
9597       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9598           << Bop->getSourceRange() << OpLoc << Shift << Op;
9599       SuggestParentheses(S, Bop->getOperatorLoc(),
9600           S.PDiag(diag::note_precedence_silence) << Op,
9601           Bop->getSourceRange());
9602     }
9603   }
9604 }
9605 
9606 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9607                                  Expr *LHSExpr, Expr *RHSExpr) {
9608   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9609   if (!OCE)
9610     return;
9611 
9612   FunctionDecl *FD = OCE->getDirectCallee();
9613   if (!FD || !FD->isOverloadedOperator())
9614     return;
9615 
9616   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9617   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9618     return;
9619 
9620   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9621       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9622       << (Kind == OO_LessLess);
9623   SuggestParentheses(S, OCE->getOperatorLoc(),
9624                      S.PDiag(diag::note_precedence_silence)
9625                          << (Kind == OO_LessLess ? "<<" : ">>"),
9626                      OCE->getSourceRange());
9627   SuggestParentheses(S, OpLoc,
9628                      S.PDiag(diag::note_evaluate_comparison_first),
9629                      SourceRange(OCE->getArg(1)->getLocStart(),
9630                                  RHSExpr->getLocEnd()));
9631 }
9632 
9633 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9634 /// precedence.
9635 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9636                                     SourceLocation OpLoc, Expr *LHSExpr,
9637                                     Expr *RHSExpr){
9638   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9639   if (BinaryOperator::isBitwiseOp(Opc))
9640     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9641 
9642   // Diagnose "arg1 & arg2 | arg3"
9643   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9644     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9645     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9646   }
9647 
9648   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9649   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9650   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9651     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9652     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9653   }
9654 
9655   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9656       || Opc == BO_Shr) {
9657     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9658     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9659     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9660   }
9661 
9662   // Warn on overloaded shift operators and comparisons, such as:
9663   // cout << 5 == 4;
9664   if (BinaryOperator::isComparisonOp(Opc))
9665     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9666 }
9667 
9668 // Binary Operators.  'Tok' is the token for the operator.
9669 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9670                             tok::TokenKind Kind,
9671                             Expr *LHSExpr, Expr *RHSExpr) {
9672   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9673   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9674   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9675 
9676   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9677   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9678 
9679   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9680 }
9681 
9682 /// Build an overloaded binary operator expression in the given scope.
9683 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9684                                        BinaryOperatorKind Opc,
9685                                        Expr *LHS, Expr *RHS) {
9686   // Find all of the overloaded operators visible from this
9687   // point. We perform both an operator-name lookup from the local
9688   // scope and an argument-dependent lookup based on the types of
9689   // the arguments.
9690   UnresolvedSet<16> Functions;
9691   OverloadedOperatorKind OverOp
9692     = BinaryOperator::getOverloadedOperator(Opc);
9693   if (Sc && OverOp != OO_None)
9694     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9695                                    RHS->getType(), Functions);
9696 
9697   // Build the (potentially-overloaded, potentially-dependent)
9698   // binary operation.
9699   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9700 }
9701 
9702 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9703                             BinaryOperatorKind Opc,
9704                             Expr *LHSExpr, Expr *RHSExpr) {
9705   // We want to end up calling one of checkPseudoObjectAssignment
9706   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9707   // both expressions are overloadable or either is type-dependent),
9708   // or CreateBuiltinBinOp (in any other case).  We also want to get
9709   // any placeholder types out of the way.
9710 
9711   // Handle pseudo-objects in the LHS.
9712   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9713     // Assignments with a pseudo-object l-value need special analysis.
9714     if (pty->getKind() == BuiltinType::PseudoObject &&
9715         BinaryOperator::isAssignmentOp(Opc))
9716       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9717 
9718     // Don't resolve overloads if the other type is overloadable.
9719     if (pty->getKind() == BuiltinType::Overload) {
9720       // We can't actually test that if we still have a placeholder,
9721       // though.  Fortunately, none of the exceptions we see in that
9722       // code below are valid when the LHS is an overload set.  Note
9723       // that an overload set can be dependently-typed, but it never
9724       // instantiates to having an overloadable type.
9725       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9726       if (resolvedRHS.isInvalid()) return ExprError();
9727       RHSExpr = resolvedRHS.get();
9728 
9729       if (RHSExpr->isTypeDependent() ||
9730           RHSExpr->getType()->isOverloadableType())
9731         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9732     }
9733 
9734     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9735     if (LHS.isInvalid()) return ExprError();
9736     LHSExpr = LHS.get();
9737   }
9738 
9739   // Handle pseudo-objects in the RHS.
9740   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9741     // An overload in the RHS can potentially be resolved by the type
9742     // being assigned to.
9743     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9744       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9745         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9746 
9747       if (LHSExpr->getType()->isOverloadableType())
9748         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9749 
9750       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9751     }
9752 
9753     // Don't resolve overloads if the other type is overloadable.
9754     if (pty->getKind() == BuiltinType::Overload &&
9755         LHSExpr->getType()->isOverloadableType())
9756       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9757 
9758     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9759     if (!resolvedRHS.isUsable()) return ExprError();
9760     RHSExpr = resolvedRHS.get();
9761   }
9762 
9763   if (getLangOpts().CPlusPlus) {
9764     // If either expression is type-dependent, always build an
9765     // overloaded op.
9766     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9767       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9768 
9769     // Otherwise, build an overloaded op if either expression has an
9770     // overloadable type.
9771     if (LHSExpr->getType()->isOverloadableType() ||
9772         RHSExpr->getType()->isOverloadableType())
9773       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9774   }
9775 
9776   // Build a built-in binary operation.
9777   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9778 }
9779 
9780 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9781                                       UnaryOperatorKind Opc,
9782                                       Expr *InputExpr) {
9783   ExprResult Input = InputExpr;
9784   ExprValueKind VK = VK_RValue;
9785   ExprObjectKind OK = OK_Ordinary;
9786   QualType resultType;
9787   switch (Opc) {
9788   case UO_PreInc:
9789   case UO_PreDec:
9790   case UO_PostInc:
9791   case UO_PostDec:
9792     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9793                                                 Opc == UO_PreInc ||
9794                                                 Opc == UO_PostInc,
9795                                                 Opc == UO_PreInc ||
9796                                                 Opc == UO_PreDec);
9797     break;
9798   case UO_AddrOf:
9799     resultType = CheckAddressOfOperand(Input, OpLoc);
9800     break;
9801   case UO_Deref: {
9802     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9803     if (Input.isInvalid()) return ExprError();
9804     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9805     break;
9806   }
9807   case UO_Plus:
9808   case UO_Minus:
9809     Input = UsualUnaryConversions(Input.get());
9810     if (Input.isInvalid()) return ExprError();
9811     resultType = Input.get()->getType();
9812     if (resultType->isDependentType())
9813       break;
9814     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9815         resultType->isVectorType())
9816       break;
9817     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9818              Opc == UO_Plus &&
9819              resultType->isPointerType())
9820       break;
9821 
9822     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9823       << resultType << Input.get()->getSourceRange());
9824 
9825   case UO_Not: // bitwise complement
9826     Input = UsualUnaryConversions(Input.get());
9827     if (Input.isInvalid())
9828       return ExprError();
9829     resultType = Input.get()->getType();
9830     if (resultType->isDependentType())
9831       break;
9832     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9833     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9834       // C99 does not support '~' for complex conjugation.
9835       Diag(OpLoc, diag::ext_integer_complement_complex)
9836           << resultType << Input.get()->getSourceRange();
9837     else if (resultType->hasIntegerRepresentation())
9838       break;
9839     else if (resultType->isExtVectorType()) {
9840       if (Context.getLangOpts().OpenCL) {
9841         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9842         // on vector float types.
9843         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9844         if (!T->isIntegerType())
9845           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9846                            << resultType << Input.get()->getSourceRange());
9847       }
9848       break;
9849     } else {
9850       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9851                        << resultType << Input.get()->getSourceRange());
9852     }
9853     break;
9854 
9855   case UO_LNot: // logical negation
9856     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9857     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9858     if (Input.isInvalid()) return ExprError();
9859     resultType = Input.get()->getType();
9860 
9861     // Though we still have to promote half FP to float...
9862     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9863       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9864       resultType = Context.FloatTy;
9865     }
9866 
9867     if (resultType->isDependentType())
9868       break;
9869     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9870       // C99 6.5.3.3p1: ok, fallthrough;
9871       if (Context.getLangOpts().CPlusPlus) {
9872         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9873         // operand contextually converted to bool.
9874         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
9875                                   ScalarTypeToBooleanCastKind(resultType));
9876       } else if (Context.getLangOpts().OpenCL &&
9877                  Context.getLangOpts().OpenCLVersion < 120) {
9878         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9879         // operate on scalar float types.
9880         if (!resultType->isIntegerType())
9881           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9882                            << resultType << Input.get()->getSourceRange());
9883       }
9884     } else if (resultType->isExtVectorType()) {
9885       if (Context.getLangOpts().OpenCL &&
9886           Context.getLangOpts().OpenCLVersion < 120) {
9887         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9888         // operate on vector float types.
9889         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9890         if (!T->isIntegerType())
9891           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9892                            << resultType << Input.get()->getSourceRange());
9893       }
9894       // Vector logical not returns the signed variant of the operand type.
9895       resultType = GetSignedVectorType(resultType);
9896       break;
9897     } else {
9898       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9899         << resultType << Input.get()->getSourceRange());
9900     }
9901 
9902     // LNot always has type int. C99 6.5.3.3p5.
9903     // In C++, it's bool. C++ 5.3.1p8
9904     resultType = Context.getLogicalOperationType();
9905     break;
9906   case UO_Real:
9907   case UO_Imag:
9908     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9909     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9910     // complex l-values to ordinary l-values and all other values to r-values.
9911     if (Input.isInvalid()) return ExprError();
9912     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9913       if (Input.get()->getValueKind() != VK_RValue &&
9914           Input.get()->getObjectKind() == OK_Ordinary)
9915         VK = Input.get()->getValueKind();
9916     } else if (!getLangOpts().CPlusPlus) {
9917       // In C, a volatile scalar is read by __imag. In C++, it is not.
9918       Input = DefaultLvalueConversion(Input.get());
9919     }
9920     break;
9921   case UO_Extension:
9922     resultType = Input.get()->getType();
9923     VK = Input.get()->getValueKind();
9924     OK = Input.get()->getObjectKind();
9925     break;
9926   }
9927   if (resultType.isNull() || Input.isInvalid())
9928     return ExprError();
9929 
9930   // Check for array bounds violations in the operand of the UnaryOperator,
9931   // except for the '*' and '&' operators that have to be handled specially
9932   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9933   // that are explicitly defined as valid by the standard).
9934   if (Opc != UO_AddrOf && Opc != UO_Deref)
9935     CheckArrayAccess(Input.get());
9936 
9937   return new (Context)
9938       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
9939 }
9940 
9941 /// \brief Determine whether the given expression is a qualified member
9942 /// access expression, of a form that could be turned into a pointer to member
9943 /// with the address-of operator.
9944 static bool isQualifiedMemberAccess(Expr *E) {
9945   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9946     if (!DRE->getQualifier())
9947       return false;
9948 
9949     ValueDecl *VD = DRE->getDecl();
9950     if (!VD->isCXXClassMember())
9951       return false;
9952 
9953     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9954       return true;
9955     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9956       return Method->isInstance();
9957 
9958     return false;
9959   }
9960 
9961   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9962     if (!ULE->getQualifier())
9963       return false;
9964 
9965     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9966                                            DEnd = ULE->decls_end();
9967          D != DEnd; ++D) {
9968       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9969         if (Method->isInstance())
9970           return true;
9971       } else {
9972         // Overload set does not contain methods.
9973         break;
9974       }
9975     }
9976 
9977     return false;
9978   }
9979 
9980   return false;
9981 }
9982 
9983 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9984                               UnaryOperatorKind Opc, Expr *Input) {
9985   // First things first: handle placeholders so that the
9986   // overloaded-operator check considers the right type.
9987   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9988     // Increment and decrement of pseudo-object references.
9989     if (pty->getKind() == BuiltinType::PseudoObject &&
9990         UnaryOperator::isIncrementDecrementOp(Opc))
9991       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9992 
9993     // extension is always a builtin operator.
9994     if (Opc == UO_Extension)
9995       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9996 
9997     // & gets special logic for several kinds of placeholder.
9998     // The builtin code knows what to do.
9999     if (Opc == UO_AddrOf &&
10000         (pty->getKind() == BuiltinType::Overload ||
10001          pty->getKind() == BuiltinType::UnknownAny ||
10002          pty->getKind() == BuiltinType::BoundMember))
10003       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10004 
10005     // Anything else needs to be handled now.
10006     ExprResult Result = CheckPlaceholderExpr(Input);
10007     if (Result.isInvalid()) return ExprError();
10008     Input = Result.get();
10009   }
10010 
10011   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10012       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10013       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10014     // Find all of the overloaded operators visible from this
10015     // point. We perform both an operator-name lookup from the local
10016     // scope and an argument-dependent lookup based on the types of
10017     // the arguments.
10018     UnresolvedSet<16> Functions;
10019     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10020     if (S && OverOp != OO_None)
10021       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10022                                    Functions);
10023 
10024     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10025   }
10026 
10027   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10028 }
10029 
10030 // Unary Operators.  'Tok' is the token for the operator.
10031 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10032                               tok::TokenKind Op, Expr *Input) {
10033   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10034 }
10035 
10036 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10037 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10038                                 LabelDecl *TheDecl) {
10039   TheDecl->markUsed(Context);
10040   // Create the AST node.  The address of a label always has type 'void*'.
10041   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10042                                      Context.getPointerType(Context.VoidTy));
10043 }
10044 
10045 /// Given the last statement in a statement-expression, check whether
10046 /// the result is a producing expression (like a call to an
10047 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10048 /// release out of the full-expression.  Otherwise, return null.
10049 /// Cannot fail.
10050 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10051   // Should always be wrapped with one of these.
10052   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10053   if (!cleanups) return nullptr;
10054 
10055   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10056   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10057     return nullptr;
10058 
10059   // Splice out the cast.  This shouldn't modify any interesting
10060   // features of the statement.
10061   Expr *producer = cast->getSubExpr();
10062   assert(producer->getType() == cast->getType());
10063   assert(producer->getValueKind() == cast->getValueKind());
10064   cleanups->setSubExpr(producer);
10065   return cleanups;
10066 }
10067 
10068 void Sema::ActOnStartStmtExpr() {
10069   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10070 }
10071 
10072 void Sema::ActOnStmtExprError() {
10073   // Note that function is also called by TreeTransform when leaving a
10074   // StmtExpr scope without rebuilding anything.
10075 
10076   DiscardCleanupsInEvaluationContext();
10077   PopExpressionEvaluationContext();
10078 }
10079 
10080 ExprResult
10081 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10082                     SourceLocation RPLoc) { // "({..})"
10083   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10084   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10085 
10086   if (hasAnyUnrecoverableErrorsInThisFunction())
10087     DiscardCleanupsInEvaluationContext();
10088   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10089   PopExpressionEvaluationContext();
10090 
10091   bool isFileScope
10092     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10093   if (isFileScope)
10094     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10095 
10096   // FIXME: there are a variety of strange constraints to enforce here, for
10097   // example, it is not possible to goto into a stmt expression apparently.
10098   // More semantic analysis is needed.
10099 
10100   // If there are sub-stmts in the compound stmt, take the type of the last one
10101   // as the type of the stmtexpr.
10102   QualType Ty = Context.VoidTy;
10103   bool StmtExprMayBindToTemp = false;
10104   if (!Compound->body_empty()) {
10105     Stmt *LastStmt = Compound->body_back();
10106     LabelStmt *LastLabelStmt = nullptr;
10107     // If LastStmt is a label, skip down through into the body.
10108     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10109       LastLabelStmt = Label;
10110       LastStmt = Label->getSubStmt();
10111     }
10112 
10113     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10114       // Do function/array conversion on the last expression, but not
10115       // lvalue-to-rvalue.  However, initialize an unqualified type.
10116       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10117       if (LastExpr.isInvalid())
10118         return ExprError();
10119       Ty = LastExpr.get()->getType().getUnqualifiedType();
10120 
10121       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10122         // In ARC, if the final expression ends in a consume, splice
10123         // the consume out and bind it later.  In the alternate case
10124         // (when dealing with a retainable type), the result
10125         // initialization will create a produce.  In both cases the
10126         // result will be +1, and we'll need to balance that out with
10127         // a bind.
10128         if (Expr *rebuiltLastStmt
10129               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10130           LastExpr = rebuiltLastStmt;
10131         } else {
10132           LastExpr = PerformCopyInitialization(
10133                             InitializedEntity::InitializeResult(LPLoc,
10134                                                                 Ty,
10135                                                                 false),
10136                                                    SourceLocation(),
10137                                                LastExpr);
10138         }
10139 
10140         if (LastExpr.isInvalid())
10141           return ExprError();
10142         if (LastExpr.get() != nullptr) {
10143           if (!LastLabelStmt)
10144             Compound->setLastStmt(LastExpr.get());
10145           else
10146             LastLabelStmt->setSubStmt(LastExpr.get());
10147           StmtExprMayBindToTemp = true;
10148         }
10149       }
10150     }
10151   }
10152 
10153   // FIXME: Check that expression type is complete/non-abstract; statement
10154   // expressions are not lvalues.
10155   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10156   if (StmtExprMayBindToTemp)
10157     return MaybeBindToTemporary(ResStmtExpr);
10158   return ResStmtExpr;
10159 }
10160 
10161 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10162                                       TypeSourceInfo *TInfo,
10163                                       OffsetOfComponent *CompPtr,
10164                                       unsigned NumComponents,
10165                                       SourceLocation RParenLoc) {
10166   QualType ArgTy = TInfo->getType();
10167   bool Dependent = ArgTy->isDependentType();
10168   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10169 
10170   // We must have at least one component that refers to the type, and the first
10171   // one is known to be a field designator.  Verify that the ArgTy represents
10172   // a struct/union/class.
10173   if (!Dependent && !ArgTy->isRecordType())
10174     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10175                        << ArgTy << TypeRange);
10176 
10177   // Type must be complete per C99 7.17p3 because a declaring a variable
10178   // with an incomplete type would be ill-formed.
10179   if (!Dependent
10180       && RequireCompleteType(BuiltinLoc, ArgTy,
10181                              diag::err_offsetof_incomplete_type, TypeRange))
10182     return ExprError();
10183 
10184   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10185   // GCC extension, diagnose them.
10186   // FIXME: This diagnostic isn't actually visible because the location is in
10187   // a system header!
10188   if (NumComponents != 1)
10189     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10190       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10191 
10192   bool DidWarnAboutNonPOD = false;
10193   QualType CurrentType = ArgTy;
10194   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10195   SmallVector<OffsetOfNode, 4> Comps;
10196   SmallVector<Expr*, 4> Exprs;
10197   for (unsigned i = 0; i != NumComponents; ++i) {
10198     const OffsetOfComponent &OC = CompPtr[i];
10199     if (OC.isBrackets) {
10200       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10201       if (!CurrentType->isDependentType()) {
10202         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10203         if(!AT)
10204           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10205                            << CurrentType);
10206         CurrentType = AT->getElementType();
10207       } else
10208         CurrentType = Context.DependentTy;
10209 
10210       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10211       if (IdxRval.isInvalid())
10212         return ExprError();
10213       Expr *Idx = IdxRval.get();
10214 
10215       // The expression must be an integral expression.
10216       // FIXME: An integral constant expression?
10217       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10218           !Idx->getType()->isIntegerType())
10219         return ExprError(Diag(Idx->getLocStart(),
10220                               diag::err_typecheck_subscript_not_integer)
10221                          << Idx->getSourceRange());
10222 
10223       // Record this array index.
10224       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10225       Exprs.push_back(Idx);
10226       continue;
10227     }
10228 
10229     // Offset of a field.
10230     if (CurrentType->isDependentType()) {
10231       // We have the offset of a field, but we can't look into the dependent
10232       // type. Just record the identifier of the field.
10233       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10234       CurrentType = Context.DependentTy;
10235       continue;
10236     }
10237 
10238     // We need to have a complete type to look into.
10239     if (RequireCompleteType(OC.LocStart, CurrentType,
10240                             diag::err_offsetof_incomplete_type))
10241       return ExprError();
10242 
10243     // Look for the designated field.
10244     const RecordType *RC = CurrentType->getAs<RecordType>();
10245     if (!RC)
10246       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10247                        << CurrentType);
10248     RecordDecl *RD = RC->getDecl();
10249 
10250     // C++ [lib.support.types]p5:
10251     //   The macro offsetof accepts a restricted set of type arguments in this
10252     //   International Standard. type shall be a POD structure or a POD union
10253     //   (clause 9).
10254     // C++11 [support.types]p4:
10255     //   If type is not a standard-layout class (Clause 9), the results are
10256     //   undefined.
10257     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10258       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10259       unsigned DiagID =
10260         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10261                             : diag::warn_offsetof_non_pod_type;
10262 
10263       if (!IsSafe && !DidWarnAboutNonPOD &&
10264           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10265                               PDiag(DiagID)
10266                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10267                               << CurrentType))
10268         DidWarnAboutNonPOD = true;
10269     }
10270 
10271     // Look for the field.
10272     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10273     LookupQualifiedName(R, RD);
10274     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10275     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10276     if (!MemberDecl) {
10277       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10278         MemberDecl = IndirectMemberDecl->getAnonField();
10279     }
10280 
10281     if (!MemberDecl)
10282       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10283                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10284                                                               OC.LocEnd));
10285 
10286     // C99 7.17p3:
10287     //   (If the specified member is a bit-field, the behavior is undefined.)
10288     //
10289     // We diagnose this as an error.
10290     if (MemberDecl->isBitField()) {
10291       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10292         << MemberDecl->getDeclName()
10293         << SourceRange(BuiltinLoc, RParenLoc);
10294       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10295       return ExprError();
10296     }
10297 
10298     RecordDecl *Parent = MemberDecl->getParent();
10299     if (IndirectMemberDecl)
10300       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10301 
10302     // If the member was found in a base class, introduce OffsetOfNodes for
10303     // the base class indirections.
10304     CXXBasePaths Paths;
10305     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10306       if (Paths.getDetectedVirtual()) {
10307         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10308           << MemberDecl->getDeclName()
10309           << SourceRange(BuiltinLoc, RParenLoc);
10310         return ExprError();
10311       }
10312 
10313       CXXBasePath &Path = Paths.front();
10314       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10315            B != BEnd; ++B)
10316         Comps.push_back(OffsetOfNode(B->Base));
10317     }
10318 
10319     if (IndirectMemberDecl) {
10320       for (auto *FI : IndirectMemberDecl->chain()) {
10321         assert(isa<FieldDecl>(FI));
10322         Comps.push_back(OffsetOfNode(OC.LocStart,
10323                                      cast<FieldDecl>(FI), OC.LocEnd));
10324       }
10325     } else
10326       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10327 
10328     CurrentType = MemberDecl->getType().getNonReferenceType();
10329   }
10330 
10331   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10332                               Comps, Exprs, RParenLoc);
10333 }
10334 
10335 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10336                                       SourceLocation BuiltinLoc,
10337                                       SourceLocation TypeLoc,
10338                                       ParsedType ParsedArgTy,
10339                                       OffsetOfComponent *CompPtr,
10340                                       unsigned NumComponents,
10341                                       SourceLocation RParenLoc) {
10342 
10343   TypeSourceInfo *ArgTInfo;
10344   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10345   if (ArgTy.isNull())
10346     return ExprError();
10347 
10348   if (!ArgTInfo)
10349     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10350 
10351   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10352                               RParenLoc);
10353 }
10354 
10355 
10356 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10357                                  Expr *CondExpr,
10358                                  Expr *LHSExpr, Expr *RHSExpr,
10359                                  SourceLocation RPLoc) {
10360   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10361 
10362   ExprValueKind VK = VK_RValue;
10363   ExprObjectKind OK = OK_Ordinary;
10364   QualType resType;
10365   bool ValueDependent = false;
10366   bool CondIsTrue = false;
10367   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10368     resType = Context.DependentTy;
10369     ValueDependent = true;
10370   } else {
10371     // The conditional expression is required to be a constant expression.
10372     llvm::APSInt condEval(32);
10373     ExprResult CondICE
10374       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10375           diag::err_typecheck_choose_expr_requires_constant, false);
10376     if (CondICE.isInvalid())
10377       return ExprError();
10378     CondExpr = CondICE.get();
10379     CondIsTrue = condEval.getZExtValue();
10380 
10381     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10382     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10383 
10384     resType = ActiveExpr->getType();
10385     ValueDependent = ActiveExpr->isValueDependent();
10386     VK = ActiveExpr->getValueKind();
10387     OK = ActiveExpr->getObjectKind();
10388   }
10389 
10390   return new (Context)
10391       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10392                  CondIsTrue, resType->isDependentType(), ValueDependent);
10393 }
10394 
10395 //===----------------------------------------------------------------------===//
10396 // Clang Extensions.
10397 //===----------------------------------------------------------------------===//
10398 
10399 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10400 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10401   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10402 
10403   if (LangOpts.CPlusPlus) {
10404     Decl *ManglingContextDecl;
10405     if (MangleNumberingContext *MCtx =
10406             getCurrentMangleNumberContext(Block->getDeclContext(),
10407                                           ManglingContextDecl)) {
10408       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10409       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10410     }
10411   }
10412 
10413   PushBlockScope(CurScope, Block);
10414   CurContext->addDecl(Block);
10415   if (CurScope)
10416     PushDeclContext(CurScope, Block);
10417   else
10418     CurContext = Block;
10419 
10420   getCurBlock()->HasImplicitReturnType = true;
10421 
10422   // Enter a new evaluation context to insulate the block from any
10423   // cleanups from the enclosing full-expression.
10424   PushExpressionEvaluationContext(PotentiallyEvaluated);
10425 }
10426 
10427 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10428                                Scope *CurScope) {
10429   assert(ParamInfo.getIdentifier() == nullptr &&
10430          "block-id should have no identifier!");
10431   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10432   BlockScopeInfo *CurBlock = getCurBlock();
10433 
10434   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10435   QualType T = Sig->getType();
10436 
10437   // FIXME: We should allow unexpanded parameter packs here, but that would,
10438   // in turn, make the block expression contain unexpanded parameter packs.
10439   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10440     // Drop the parameters.
10441     FunctionProtoType::ExtProtoInfo EPI;
10442     EPI.HasTrailingReturn = false;
10443     EPI.TypeQuals |= DeclSpec::TQ_const;
10444     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10445     Sig = Context.getTrivialTypeSourceInfo(T);
10446   }
10447 
10448   // GetTypeForDeclarator always produces a function type for a block
10449   // literal signature.  Furthermore, it is always a FunctionProtoType
10450   // unless the function was written with a typedef.
10451   assert(T->isFunctionType() &&
10452          "GetTypeForDeclarator made a non-function block signature");
10453 
10454   // Look for an explicit signature in that function type.
10455   FunctionProtoTypeLoc ExplicitSignature;
10456 
10457   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10458   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10459 
10460     // Check whether that explicit signature was synthesized by
10461     // GetTypeForDeclarator.  If so, don't save that as part of the
10462     // written signature.
10463     if (ExplicitSignature.getLocalRangeBegin() ==
10464         ExplicitSignature.getLocalRangeEnd()) {
10465       // This would be much cheaper if we stored TypeLocs instead of
10466       // TypeSourceInfos.
10467       TypeLoc Result = ExplicitSignature.getReturnLoc();
10468       unsigned Size = Result.getFullDataSize();
10469       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10470       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10471 
10472       ExplicitSignature = FunctionProtoTypeLoc();
10473     }
10474   }
10475 
10476   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10477   CurBlock->FunctionType = T;
10478 
10479   const FunctionType *Fn = T->getAs<FunctionType>();
10480   QualType RetTy = Fn->getReturnType();
10481   bool isVariadic =
10482     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10483 
10484   CurBlock->TheDecl->setIsVariadic(isVariadic);
10485 
10486   // Context.DependentTy is used as a placeholder for a missing block
10487   // return type.  TODO:  what should we do with declarators like:
10488   //   ^ * { ... }
10489   // If the answer is "apply template argument deduction"....
10490   if (RetTy != Context.DependentTy) {
10491     CurBlock->ReturnType = RetTy;
10492     CurBlock->TheDecl->setBlockMissingReturnType(false);
10493     CurBlock->HasImplicitReturnType = false;
10494   }
10495 
10496   // Push block parameters from the declarator if we had them.
10497   SmallVector<ParmVarDecl*, 8> Params;
10498   if (ExplicitSignature) {
10499     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10500       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10501       if (Param->getIdentifier() == nullptr &&
10502           !Param->isImplicit() &&
10503           !Param->isInvalidDecl() &&
10504           !getLangOpts().CPlusPlus)
10505         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10506       Params.push_back(Param);
10507     }
10508 
10509   // Fake up parameter variables if we have a typedef, like
10510   //   ^ fntype { ... }
10511   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10512     for (const auto &I : Fn->param_types()) {
10513       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10514           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10515       Params.push_back(Param);
10516     }
10517   }
10518 
10519   // Set the parameters on the block decl.
10520   if (!Params.empty()) {
10521     CurBlock->TheDecl->setParams(Params);
10522     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10523                              CurBlock->TheDecl->param_end(),
10524                              /*CheckParameterNames=*/false);
10525   }
10526 
10527   // Finally we can process decl attributes.
10528   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10529 
10530   // Put the parameter variables in scope.
10531   for (auto AI : CurBlock->TheDecl->params()) {
10532     AI->setOwningFunction(CurBlock->TheDecl);
10533 
10534     // If this has an identifier, add it to the scope stack.
10535     if (AI->getIdentifier()) {
10536       CheckShadow(CurBlock->TheScope, AI);
10537 
10538       PushOnScopeChains(AI, CurBlock->TheScope);
10539     }
10540   }
10541 }
10542 
10543 /// ActOnBlockError - If there is an error parsing a block, this callback
10544 /// is invoked to pop the information about the block from the action impl.
10545 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10546   // Leave the expression-evaluation context.
10547   DiscardCleanupsInEvaluationContext();
10548   PopExpressionEvaluationContext();
10549 
10550   // Pop off CurBlock, handle nested blocks.
10551   PopDeclContext();
10552   PopFunctionScopeInfo();
10553 }
10554 
10555 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10556 /// literal was successfully completed.  ^(int x){...}
10557 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10558                                     Stmt *Body, Scope *CurScope) {
10559   // If blocks are disabled, emit an error.
10560   if (!LangOpts.Blocks)
10561     Diag(CaretLoc, diag::err_blocks_disable);
10562 
10563   // Leave the expression-evaluation context.
10564   if (hasAnyUnrecoverableErrorsInThisFunction())
10565     DiscardCleanupsInEvaluationContext();
10566   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10567   PopExpressionEvaluationContext();
10568 
10569   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10570 
10571   if (BSI->HasImplicitReturnType)
10572     deduceClosureReturnType(*BSI);
10573 
10574   PopDeclContext();
10575 
10576   QualType RetTy = Context.VoidTy;
10577   if (!BSI->ReturnType.isNull())
10578     RetTy = BSI->ReturnType;
10579 
10580   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10581   QualType BlockTy;
10582 
10583   // Set the captured variables on the block.
10584   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10585   SmallVector<BlockDecl::Capture, 4> Captures;
10586   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10587     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10588     if (Cap.isThisCapture())
10589       continue;
10590     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10591                               Cap.isNested(), Cap.getInitExpr());
10592     Captures.push_back(NewCap);
10593   }
10594   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10595                             BSI->CXXThisCaptureIndex != 0);
10596 
10597   // If the user wrote a function type in some form, try to use that.
10598   if (!BSI->FunctionType.isNull()) {
10599     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10600 
10601     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10602     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10603 
10604     // Turn protoless block types into nullary block types.
10605     if (isa<FunctionNoProtoType>(FTy)) {
10606       FunctionProtoType::ExtProtoInfo EPI;
10607       EPI.ExtInfo = Ext;
10608       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10609 
10610     // Otherwise, if we don't need to change anything about the function type,
10611     // preserve its sugar structure.
10612     } else if (FTy->getReturnType() == RetTy &&
10613                (!NoReturn || FTy->getNoReturnAttr())) {
10614       BlockTy = BSI->FunctionType;
10615 
10616     // Otherwise, make the minimal modifications to the function type.
10617     } else {
10618       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10619       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10620       EPI.TypeQuals = 0; // FIXME: silently?
10621       EPI.ExtInfo = Ext;
10622       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10623     }
10624 
10625   // If we don't have a function type, just build one from nothing.
10626   } else {
10627     FunctionProtoType::ExtProtoInfo EPI;
10628     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10629     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10630   }
10631 
10632   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10633                            BSI->TheDecl->param_end());
10634   BlockTy = Context.getBlockPointerType(BlockTy);
10635 
10636   // If needed, diagnose invalid gotos and switches in the block.
10637   if (getCurFunction()->NeedsScopeChecking() &&
10638       !PP.isCodeCompletionEnabled())
10639     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10640 
10641   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10642 
10643   // Try to apply the named return value optimization. We have to check again
10644   // if we can do this, though, because blocks keep return statements around
10645   // to deduce an implicit return type.
10646   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10647       !BSI->TheDecl->isDependentContext())
10648     computeNRVO(Body, BSI);
10649 
10650   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10651   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10652   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10653 
10654   // If the block isn't obviously global, i.e. it captures anything at
10655   // all, then we need to do a few things in the surrounding context:
10656   if (Result->getBlockDecl()->hasCaptures()) {
10657     // First, this expression has a new cleanup object.
10658     ExprCleanupObjects.push_back(Result->getBlockDecl());
10659     ExprNeedsCleanups = true;
10660 
10661     // It also gets a branch-protected scope if any of the captured
10662     // variables needs destruction.
10663     for (const auto &CI : Result->getBlockDecl()->captures()) {
10664       const VarDecl *var = CI.getVariable();
10665       if (var->getType().isDestructedType() != QualType::DK_none) {
10666         getCurFunction()->setHasBranchProtectedScope();
10667         break;
10668       }
10669     }
10670   }
10671 
10672   return Result;
10673 }
10674 
10675 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10676                                         Expr *E, ParsedType Ty,
10677                                         SourceLocation RPLoc) {
10678   TypeSourceInfo *TInfo;
10679   GetTypeFromParser(Ty, &TInfo);
10680   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10681 }
10682 
10683 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10684                                 Expr *E, TypeSourceInfo *TInfo,
10685                                 SourceLocation RPLoc) {
10686   Expr *OrigExpr = E;
10687 
10688   // Get the va_list type
10689   QualType VaListType = Context.getBuiltinVaListType();
10690   if (VaListType->isArrayType()) {
10691     // Deal with implicit array decay; for example, on x86-64,
10692     // va_list is an array, but it's supposed to decay to
10693     // a pointer for va_arg.
10694     VaListType = Context.getArrayDecayedType(VaListType);
10695     // Make sure the input expression also decays appropriately.
10696     ExprResult Result = UsualUnaryConversions(E);
10697     if (Result.isInvalid())
10698       return ExprError();
10699     E = Result.get();
10700   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10701     // If va_list is a record type and we are compiling in C++ mode,
10702     // check the argument using reference binding.
10703     InitializedEntity Entity
10704       = InitializedEntity::InitializeParameter(Context,
10705           Context.getLValueReferenceType(VaListType), false);
10706     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10707     if (Init.isInvalid())
10708       return ExprError();
10709     E = Init.getAs<Expr>();
10710   } else {
10711     // Otherwise, the va_list argument must be an l-value because
10712     // it is modified by va_arg.
10713     if (!E->isTypeDependent() &&
10714         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10715       return ExprError();
10716   }
10717 
10718   if (!E->isTypeDependent() &&
10719       !Context.hasSameType(VaListType, E->getType())) {
10720     return ExprError(Diag(E->getLocStart(),
10721                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10722       << OrigExpr->getType() << E->getSourceRange());
10723   }
10724 
10725   if (!TInfo->getType()->isDependentType()) {
10726     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10727                             diag::err_second_parameter_to_va_arg_incomplete,
10728                             TInfo->getTypeLoc()))
10729       return ExprError();
10730 
10731     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10732                                TInfo->getType(),
10733                                diag::err_second_parameter_to_va_arg_abstract,
10734                                TInfo->getTypeLoc()))
10735       return ExprError();
10736 
10737     if (!TInfo->getType().isPODType(Context)) {
10738       Diag(TInfo->getTypeLoc().getBeginLoc(),
10739            TInfo->getType()->isObjCLifetimeType()
10740              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10741              : diag::warn_second_parameter_to_va_arg_not_pod)
10742         << TInfo->getType()
10743         << TInfo->getTypeLoc().getSourceRange();
10744     }
10745 
10746     // Check for va_arg where arguments of the given type will be promoted
10747     // (i.e. this va_arg is guaranteed to have undefined behavior).
10748     QualType PromoteType;
10749     if (TInfo->getType()->isPromotableIntegerType()) {
10750       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10751       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10752         PromoteType = QualType();
10753     }
10754     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10755       PromoteType = Context.DoubleTy;
10756     if (!PromoteType.isNull())
10757       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10758                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10759                           << TInfo->getType()
10760                           << PromoteType
10761                           << TInfo->getTypeLoc().getSourceRange());
10762   }
10763 
10764   QualType T = TInfo->getType().getNonLValueExprType(Context);
10765   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10766 }
10767 
10768 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10769   // The type of __null will be int or long, depending on the size of
10770   // pointers on the target.
10771   QualType Ty;
10772   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10773   if (pw == Context.getTargetInfo().getIntWidth())
10774     Ty = Context.IntTy;
10775   else if (pw == Context.getTargetInfo().getLongWidth())
10776     Ty = Context.LongTy;
10777   else if (pw == Context.getTargetInfo().getLongLongWidth())
10778     Ty = Context.LongLongTy;
10779   else {
10780     llvm_unreachable("I don't know size of pointer!");
10781   }
10782 
10783   return new (Context) GNUNullExpr(Ty, TokenLoc);
10784 }
10785 
10786 bool
10787 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10788   if (!getLangOpts().ObjC1)
10789     return false;
10790 
10791   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10792   if (!PT)
10793     return false;
10794 
10795   if (!PT->isObjCIdType()) {
10796     // Check if the destination is the 'NSString' interface.
10797     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10798     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10799       return false;
10800   }
10801 
10802   // Ignore any parens, implicit casts (should only be
10803   // array-to-pointer decays), and not-so-opaque values.  The last is
10804   // important for making this trigger for property assignments.
10805   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10806   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10807     if (OV->getSourceExpr())
10808       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10809 
10810   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10811   if (!SL || !SL->isAscii())
10812     return false;
10813   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10814     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10815   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10816   return true;
10817 }
10818 
10819 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10820                                     SourceLocation Loc,
10821                                     QualType DstType, QualType SrcType,
10822                                     Expr *SrcExpr, AssignmentAction Action,
10823                                     bool *Complained) {
10824   if (Complained)
10825     *Complained = false;
10826 
10827   // Decode the result (notice that AST's are still created for extensions).
10828   bool CheckInferredResultType = false;
10829   bool isInvalid = false;
10830   unsigned DiagKind = 0;
10831   FixItHint Hint;
10832   ConversionFixItGenerator ConvHints;
10833   bool MayHaveConvFixit = false;
10834   bool MayHaveFunctionDiff = false;
10835   const ObjCInterfaceDecl *IFace = nullptr;
10836   const ObjCProtocolDecl *PDecl = nullptr;
10837 
10838   switch (ConvTy) {
10839   case Compatible:
10840       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10841       return false;
10842 
10843   case PointerToInt:
10844     DiagKind = diag::ext_typecheck_convert_pointer_int;
10845     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10846     MayHaveConvFixit = true;
10847     break;
10848   case IntToPointer:
10849     DiagKind = diag::ext_typecheck_convert_int_pointer;
10850     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10851     MayHaveConvFixit = true;
10852     break;
10853   case IncompatiblePointer:
10854       DiagKind =
10855         (Action == AA_Passing_CFAudited ?
10856           diag::err_arc_typecheck_convert_incompatible_pointer :
10857           diag::ext_typecheck_convert_incompatible_pointer);
10858     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10859       SrcType->isObjCObjectPointerType();
10860     if (Hint.isNull() && !CheckInferredResultType) {
10861       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10862     }
10863     else if (CheckInferredResultType) {
10864       SrcType = SrcType.getUnqualifiedType();
10865       DstType = DstType.getUnqualifiedType();
10866     }
10867     MayHaveConvFixit = true;
10868     break;
10869   case IncompatiblePointerSign:
10870     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10871     break;
10872   case FunctionVoidPointer:
10873     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10874     break;
10875   case IncompatiblePointerDiscardsQualifiers: {
10876     // Perform array-to-pointer decay if necessary.
10877     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10878 
10879     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10880     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10881     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10882       DiagKind = diag::err_typecheck_incompatible_address_space;
10883       break;
10884 
10885 
10886     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10887       DiagKind = diag::err_typecheck_incompatible_ownership;
10888       break;
10889     }
10890 
10891     llvm_unreachable("unknown error case for discarding qualifiers!");
10892     // fallthrough
10893   }
10894   case CompatiblePointerDiscardsQualifiers:
10895     // If the qualifiers lost were because we were applying the
10896     // (deprecated) C++ conversion from a string literal to a char*
10897     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10898     // Ideally, this check would be performed in
10899     // checkPointerTypesForAssignment. However, that would require a
10900     // bit of refactoring (so that the second argument is an
10901     // expression, rather than a type), which should be done as part
10902     // of a larger effort to fix checkPointerTypesForAssignment for
10903     // C++ semantics.
10904     if (getLangOpts().CPlusPlus &&
10905         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10906       return false;
10907     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10908     break;
10909   case IncompatibleNestedPointerQualifiers:
10910     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10911     break;
10912   case IntToBlockPointer:
10913     DiagKind = diag::err_int_to_block_pointer;
10914     break;
10915   case IncompatibleBlockPointer:
10916     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10917     break;
10918   case IncompatibleObjCQualifiedId: {
10919     if (SrcType->isObjCQualifiedIdType()) {
10920       const ObjCObjectPointerType *srcOPT =
10921                 SrcType->getAs<ObjCObjectPointerType>();
10922       for (auto *srcProto : srcOPT->quals()) {
10923         PDecl = srcProto;
10924         break;
10925       }
10926       if (const ObjCInterfaceType *IFaceT =
10927             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10928         IFace = IFaceT->getDecl();
10929     }
10930     else if (DstType->isObjCQualifiedIdType()) {
10931       const ObjCObjectPointerType *dstOPT =
10932         DstType->getAs<ObjCObjectPointerType>();
10933       for (auto *dstProto : dstOPT->quals()) {
10934         PDecl = dstProto;
10935         break;
10936       }
10937       if (const ObjCInterfaceType *IFaceT =
10938             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10939         IFace = IFaceT->getDecl();
10940     }
10941     DiagKind = diag::warn_incompatible_qualified_id;
10942     break;
10943   }
10944   case IncompatibleVectors:
10945     DiagKind = diag::warn_incompatible_vectors;
10946     break;
10947   case IncompatibleObjCWeakRef:
10948     DiagKind = diag::err_arc_weak_unavailable_assign;
10949     break;
10950   case Incompatible:
10951     DiagKind = diag::err_typecheck_convert_incompatible;
10952     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10953     MayHaveConvFixit = true;
10954     isInvalid = true;
10955     MayHaveFunctionDiff = true;
10956     break;
10957   }
10958 
10959   QualType FirstType, SecondType;
10960   switch (Action) {
10961   case AA_Assigning:
10962   case AA_Initializing:
10963     // The destination type comes first.
10964     FirstType = DstType;
10965     SecondType = SrcType;
10966     break;
10967 
10968   case AA_Returning:
10969   case AA_Passing:
10970   case AA_Passing_CFAudited:
10971   case AA_Converting:
10972   case AA_Sending:
10973   case AA_Casting:
10974     // The source type comes first.
10975     FirstType = SrcType;
10976     SecondType = DstType;
10977     break;
10978   }
10979 
10980   PartialDiagnostic FDiag = PDiag(DiagKind);
10981   if (Action == AA_Passing_CFAudited)
10982     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10983   else
10984     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10985 
10986   // If we can fix the conversion, suggest the FixIts.
10987   assert(ConvHints.isNull() || Hint.isNull());
10988   if (!ConvHints.isNull()) {
10989     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10990          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10991       FDiag << *HI;
10992   } else {
10993     FDiag << Hint;
10994   }
10995   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10996 
10997   if (MayHaveFunctionDiff)
10998     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10999 
11000   Diag(Loc, FDiag);
11001   if (DiagKind == diag::warn_incompatible_qualified_id &&
11002       PDecl && IFace && !IFace->hasDefinition())
11003       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11004         << IFace->getName() << PDecl->getName();
11005 
11006   if (SecondType == Context.OverloadTy)
11007     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11008                               FirstType);
11009 
11010   if (CheckInferredResultType)
11011     EmitRelatedResultTypeNote(SrcExpr);
11012 
11013   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11014     EmitRelatedResultTypeNoteForReturn(DstType);
11015 
11016   if (Complained)
11017     *Complained = true;
11018   return isInvalid;
11019 }
11020 
11021 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11022                                                  llvm::APSInt *Result) {
11023   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11024   public:
11025     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11026       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11027     }
11028   } Diagnoser;
11029 
11030   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11031 }
11032 
11033 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11034                                                  llvm::APSInt *Result,
11035                                                  unsigned DiagID,
11036                                                  bool AllowFold) {
11037   class IDDiagnoser : public VerifyICEDiagnoser {
11038     unsigned DiagID;
11039 
11040   public:
11041     IDDiagnoser(unsigned DiagID)
11042       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11043 
11044     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11045       S.Diag(Loc, DiagID) << SR;
11046     }
11047   } Diagnoser(DiagID);
11048 
11049   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11050 }
11051 
11052 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11053                                             SourceRange SR) {
11054   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11055 }
11056 
11057 ExprResult
11058 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11059                                       VerifyICEDiagnoser &Diagnoser,
11060                                       bool AllowFold) {
11061   SourceLocation DiagLoc = E->getLocStart();
11062 
11063   if (getLangOpts().CPlusPlus11) {
11064     // C++11 [expr.const]p5:
11065     //   If an expression of literal class type is used in a context where an
11066     //   integral constant expression is required, then that class type shall
11067     //   have a single non-explicit conversion function to an integral or
11068     //   unscoped enumeration type
11069     ExprResult Converted;
11070     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11071     public:
11072       CXX11ConvertDiagnoser(bool Silent)
11073           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11074                                 Silent, true) {}
11075 
11076       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11077                                            QualType T) override {
11078         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11079       }
11080 
11081       SemaDiagnosticBuilder diagnoseIncomplete(
11082           Sema &S, SourceLocation Loc, QualType T) override {
11083         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11084       }
11085 
11086       SemaDiagnosticBuilder diagnoseExplicitConv(
11087           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11088         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11089       }
11090 
11091       SemaDiagnosticBuilder noteExplicitConv(
11092           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11093         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11094                  << ConvTy->isEnumeralType() << ConvTy;
11095       }
11096 
11097       SemaDiagnosticBuilder diagnoseAmbiguous(
11098           Sema &S, SourceLocation Loc, QualType T) override {
11099         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11100       }
11101 
11102       SemaDiagnosticBuilder noteAmbiguous(
11103           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11104         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11105                  << ConvTy->isEnumeralType() << ConvTy;
11106       }
11107 
11108       SemaDiagnosticBuilder diagnoseConversion(
11109           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11110         llvm_unreachable("conversion functions are permitted");
11111       }
11112     } ConvertDiagnoser(Diagnoser.Suppress);
11113 
11114     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11115                                                     ConvertDiagnoser);
11116     if (Converted.isInvalid())
11117       return Converted;
11118     E = Converted.get();
11119     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11120       return ExprError();
11121   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11122     // An ICE must be of integral or unscoped enumeration type.
11123     if (!Diagnoser.Suppress)
11124       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11125     return ExprError();
11126   }
11127 
11128   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11129   // in the non-ICE case.
11130   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11131     if (Result)
11132       *Result = E->EvaluateKnownConstInt(Context);
11133     return E;
11134   }
11135 
11136   Expr::EvalResult EvalResult;
11137   SmallVector<PartialDiagnosticAt, 8> Notes;
11138   EvalResult.Diag = &Notes;
11139 
11140   // Try to evaluate the expression, and produce diagnostics explaining why it's
11141   // not a constant expression as a side-effect.
11142   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11143                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11144 
11145   // In C++11, we can rely on diagnostics being produced for any expression
11146   // which is not a constant expression. If no diagnostics were produced, then
11147   // this is a constant expression.
11148   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11149     if (Result)
11150       *Result = EvalResult.Val.getInt();
11151     return E;
11152   }
11153 
11154   // If our only note is the usual "invalid subexpression" note, just point
11155   // the caret at its location rather than producing an essentially
11156   // redundant note.
11157   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11158         diag::note_invalid_subexpr_in_const_expr) {
11159     DiagLoc = Notes[0].first;
11160     Notes.clear();
11161   }
11162 
11163   if (!Folded || !AllowFold) {
11164     if (!Diagnoser.Suppress) {
11165       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11166       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11167         Diag(Notes[I].first, Notes[I].second);
11168     }
11169 
11170     return ExprError();
11171   }
11172 
11173   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11174   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11175     Diag(Notes[I].first, Notes[I].second);
11176 
11177   if (Result)
11178     *Result = EvalResult.Val.getInt();
11179   return E;
11180 }
11181 
11182 namespace {
11183   // Handle the case where we conclude a expression which we speculatively
11184   // considered to be unevaluated is actually evaluated.
11185   class TransformToPE : public TreeTransform<TransformToPE> {
11186     typedef TreeTransform<TransformToPE> BaseTransform;
11187 
11188   public:
11189     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11190 
11191     // Make sure we redo semantic analysis
11192     bool AlwaysRebuild() { return true; }
11193 
11194     // Make sure we handle LabelStmts correctly.
11195     // FIXME: This does the right thing, but maybe we need a more general
11196     // fix to TreeTransform?
11197     StmtResult TransformLabelStmt(LabelStmt *S) {
11198       S->getDecl()->setStmt(nullptr);
11199       return BaseTransform::TransformLabelStmt(S);
11200     }
11201 
11202     // We need to special-case DeclRefExprs referring to FieldDecls which
11203     // are not part of a member pointer formation; normal TreeTransforming
11204     // doesn't catch this case because of the way we represent them in the AST.
11205     // FIXME: This is a bit ugly; is it really the best way to handle this
11206     // case?
11207     //
11208     // Error on DeclRefExprs referring to FieldDecls.
11209     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11210       if (isa<FieldDecl>(E->getDecl()) &&
11211           !SemaRef.isUnevaluatedContext())
11212         return SemaRef.Diag(E->getLocation(),
11213                             diag::err_invalid_non_static_member_use)
11214             << E->getDecl() << E->getSourceRange();
11215 
11216       return BaseTransform::TransformDeclRefExpr(E);
11217     }
11218 
11219     // Exception: filter out member pointer formation
11220     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11221       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11222         return E;
11223 
11224       return BaseTransform::TransformUnaryOperator(E);
11225     }
11226 
11227     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11228       // Lambdas never need to be transformed.
11229       return E;
11230     }
11231   };
11232 }
11233 
11234 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11235   assert(isUnevaluatedContext() &&
11236          "Should only transform unevaluated expressions");
11237   ExprEvalContexts.back().Context =
11238       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11239   if (isUnevaluatedContext())
11240     return E;
11241   return TransformToPE(*this).TransformExpr(E);
11242 }
11243 
11244 void
11245 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11246                                       Decl *LambdaContextDecl,
11247                                       bool IsDecltype) {
11248   ExprEvalContexts.push_back(
11249              ExpressionEvaluationContextRecord(NewContext,
11250                                                ExprCleanupObjects.size(),
11251                                                ExprNeedsCleanups,
11252                                                LambdaContextDecl,
11253                                                IsDecltype));
11254   ExprNeedsCleanups = false;
11255   if (!MaybeODRUseExprs.empty())
11256     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11257 }
11258 
11259 void
11260 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11261                                       ReuseLambdaContextDecl_t,
11262                                       bool IsDecltype) {
11263   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11264   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11265 }
11266 
11267 void Sema::PopExpressionEvaluationContext() {
11268   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11269 
11270   if (!Rec.Lambdas.empty()) {
11271     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11272       unsigned D;
11273       if (Rec.isUnevaluated()) {
11274         // C++11 [expr.prim.lambda]p2:
11275         //   A lambda-expression shall not appear in an unevaluated operand
11276         //   (Clause 5).
11277         D = diag::err_lambda_unevaluated_operand;
11278       } else {
11279         // C++1y [expr.const]p2:
11280         //   A conditional-expression e is a core constant expression unless the
11281         //   evaluation of e, following the rules of the abstract machine, would
11282         //   evaluate [...] a lambda-expression.
11283         D = diag::err_lambda_in_constant_expression;
11284       }
11285       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11286         Diag(Rec.Lambdas[I]->getLocStart(), D);
11287     } else {
11288       // Mark the capture expressions odr-used. This was deferred
11289       // during lambda expression creation.
11290       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11291         LambdaExpr *Lambda = Rec.Lambdas[I];
11292         for (LambdaExpr::capture_init_iterator
11293                   C = Lambda->capture_init_begin(),
11294                CEnd = Lambda->capture_init_end();
11295              C != CEnd; ++C) {
11296           MarkDeclarationsReferencedInExpr(*C);
11297         }
11298       }
11299     }
11300   }
11301 
11302   // When are coming out of an unevaluated context, clear out any
11303   // temporaries that we may have created as part of the evaluation of
11304   // the expression in that context: they aren't relevant because they
11305   // will never be constructed.
11306   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11307     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11308                              ExprCleanupObjects.end());
11309     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11310     CleanupVarDeclMarking();
11311     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11312   // Otherwise, merge the contexts together.
11313   } else {
11314     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11315     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11316                             Rec.SavedMaybeODRUseExprs.end());
11317   }
11318 
11319   // Pop the current expression evaluation context off the stack.
11320   ExprEvalContexts.pop_back();
11321 }
11322 
11323 void Sema::DiscardCleanupsInEvaluationContext() {
11324   ExprCleanupObjects.erase(
11325          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11326          ExprCleanupObjects.end());
11327   ExprNeedsCleanups = false;
11328   MaybeODRUseExprs.clear();
11329 }
11330 
11331 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11332   if (!E->getType()->isVariablyModifiedType())
11333     return E;
11334   return TransformToPotentiallyEvaluated(E);
11335 }
11336 
11337 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11338   // Do not mark anything as "used" within a dependent context; wait for
11339   // an instantiation.
11340   if (SemaRef.CurContext->isDependentContext())
11341     return false;
11342 
11343   switch (SemaRef.ExprEvalContexts.back().Context) {
11344     case Sema::Unevaluated:
11345     case Sema::UnevaluatedAbstract:
11346       // We are in an expression that is not potentially evaluated; do nothing.
11347       // (Depending on how you read the standard, we actually do need to do
11348       // something here for null pointer constants, but the standard's
11349       // definition of a null pointer constant is completely crazy.)
11350       return false;
11351 
11352     case Sema::ConstantEvaluated:
11353     case Sema::PotentiallyEvaluated:
11354       // We are in a potentially evaluated expression (or a constant-expression
11355       // in C++03); we need to do implicit template instantiation, implicitly
11356       // define class members, and mark most declarations as used.
11357       return true;
11358 
11359     case Sema::PotentiallyEvaluatedIfUsed:
11360       // Referenced declarations will only be used if the construct in the
11361       // containing expression is used.
11362       return false;
11363   }
11364   llvm_unreachable("Invalid context");
11365 }
11366 
11367 /// \brief Mark a function referenced, and check whether it is odr-used
11368 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11369 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11370   assert(Func && "No function?");
11371 
11372   Func->setReferenced();
11373 
11374   // C++11 [basic.def.odr]p3:
11375   //   A function whose name appears as a potentially-evaluated expression is
11376   //   odr-used if it is the unique lookup result or the selected member of a
11377   //   set of overloaded functions [...].
11378   //
11379   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11380   // can just check that here. Skip the rest of this function if we've already
11381   // marked the function as used.
11382   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11383     // C++11 [temp.inst]p3:
11384     //   Unless a function template specialization has been explicitly
11385     //   instantiated or explicitly specialized, the function template
11386     //   specialization is implicitly instantiated when the specialization is
11387     //   referenced in a context that requires a function definition to exist.
11388     //
11389     // We consider constexpr function templates to be referenced in a context
11390     // that requires a definition to exist whenever they are referenced.
11391     //
11392     // FIXME: This instantiates constexpr functions too frequently. If this is
11393     // really an unevaluated context (and we're not just in the definition of a
11394     // function template or overload resolution or other cases which we
11395     // incorrectly consider to be unevaluated contexts), and we're not in a
11396     // subexpression which we actually need to evaluate (for instance, a
11397     // template argument, array bound or an expression in a braced-init-list),
11398     // we are not permitted to instantiate this constexpr function definition.
11399     //
11400     // FIXME: This also implicitly defines special members too frequently. They
11401     // are only supposed to be implicitly defined if they are odr-used, but they
11402     // are not odr-used from constant expressions in unevaluated contexts.
11403     // However, they cannot be referenced if they are deleted, and they are
11404     // deleted whenever the implicit definition of the special member would
11405     // fail.
11406     if (!Func->isConstexpr() || Func->getBody())
11407       return;
11408     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11409     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11410       return;
11411   }
11412 
11413   // Note that this declaration has been used.
11414   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11415     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11416     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11417       if (Constructor->isDefaultConstructor()) {
11418         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11419           return;
11420         DefineImplicitDefaultConstructor(Loc, Constructor);
11421       } else if (Constructor->isCopyConstructor()) {
11422         DefineImplicitCopyConstructor(Loc, Constructor);
11423       } else if (Constructor->isMoveConstructor()) {
11424         DefineImplicitMoveConstructor(Loc, Constructor);
11425       }
11426     } else if (Constructor->getInheritedConstructor()) {
11427       DefineInheritingConstructor(Loc, Constructor);
11428     }
11429 
11430     MarkVTableUsed(Loc, Constructor->getParent());
11431   } else if (CXXDestructorDecl *Destructor =
11432                  dyn_cast<CXXDestructorDecl>(Func)) {
11433     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11434     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11435       DefineImplicitDestructor(Loc, Destructor);
11436     if (Destructor->isVirtual())
11437       MarkVTableUsed(Loc, Destructor->getParent());
11438   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11439     if (MethodDecl->isOverloadedOperator() &&
11440         MethodDecl->getOverloadedOperator() == OO_Equal) {
11441       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11442       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11443         if (MethodDecl->isCopyAssignmentOperator())
11444           DefineImplicitCopyAssignment(Loc, MethodDecl);
11445         else
11446           DefineImplicitMoveAssignment(Loc, MethodDecl);
11447       }
11448     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11449                MethodDecl->getParent()->isLambda()) {
11450       CXXConversionDecl *Conversion =
11451           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11452       if (Conversion->isLambdaToBlockPointerConversion())
11453         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11454       else
11455         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11456     } else if (MethodDecl->isVirtual())
11457       MarkVTableUsed(Loc, MethodDecl->getParent());
11458   }
11459 
11460   // Recursive functions should be marked when used from another function.
11461   // FIXME: Is this really right?
11462   if (CurContext == Func) return;
11463 
11464   // Resolve the exception specification for any function which is
11465   // used: CodeGen will need it.
11466   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11467   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11468     ResolveExceptionSpec(Loc, FPT);
11469 
11470   // Implicit instantiation of function templates and member functions of
11471   // class templates.
11472   if (Func->isImplicitlyInstantiable()) {
11473     bool AlreadyInstantiated = false;
11474     SourceLocation PointOfInstantiation = Loc;
11475     if (FunctionTemplateSpecializationInfo *SpecInfo
11476                               = Func->getTemplateSpecializationInfo()) {
11477       if (SpecInfo->getPointOfInstantiation().isInvalid())
11478         SpecInfo->setPointOfInstantiation(Loc);
11479       else if (SpecInfo->getTemplateSpecializationKind()
11480                  == TSK_ImplicitInstantiation) {
11481         AlreadyInstantiated = true;
11482         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11483       }
11484     } else if (MemberSpecializationInfo *MSInfo
11485                                 = Func->getMemberSpecializationInfo()) {
11486       if (MSInfo->getPointOfInstantiation().isInvalid())
11487         MSInfo->setPointOfInstantiation(Loc);
11488       else if (MSInfo->getTemplateSpecializationKind()
11489                  == TSK_ImplicitInstantiation) {
11490         AlreadyInstantiated = true;
11491         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11492       }
11493     }
11494 
11495     if (!AlreadyInstantiated || Func->isConstexpr()) {
11496       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11497           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11498           ActiveTemplateInstantiations.size())
11499         PendingLocalImplicitInstantiations.push_back(
11500             std::make_pair(Func, PointOfInstantiation));
11501       else if (Func->isConstexpr())
11502         // Do not defer instantiations of constexpr functions, to avoid the
11503         // expression evaluator needing to call back into Sema if it sees a
11504         // call to such a function.
11505         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11506       else {
11507         PendingInstantiations.push_back(std::make_pair(Func,
11508                                                        PointOfInstantiation));
11509         // Notify the consumer that a function was implicitly instantiated.
11510         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11511       }
11512     }
11513   } else {
11514     // Walk redefinitions, as some of them may be instantiable.
11515     for (auto i : Func->redecls()) {
11516       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11517         MarkFunctionReferenced(Loc, i);
11518     }
11519   }
11520 
11521   // Keep track of used but undefined functions.
11522   if (!Func->isDefined()) {
11523     if (mightHaveNonExternalLinkage(Func))
11524       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11525     else if (Func->getMostRecentDecl()->isInlined() &&
11526              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11527              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11528       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11529   }
11530 
11531   // Normally the most current decl is marked used while processing the use and
11532   // any subsequent decls are marked used by decl merging. This fails with
11533   // template instantiation since marking can happen at the end of the file
11534   // and, because of the two phase lookup, this function is called with at
11535   // decl in the middle of a decl chain. We loop to maintain the invariant
11536   // that once a decl is used, all decls after it are also used.
11537   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11538     F->markUsed(Context);
11539     if (F == Func)
11540       break;
11541   }
11542 }
11543 
11544 static void
11545 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11546                                    VarDecl *var, DeclContext *DC) {
11547   DeclContext *VarDC = var->getDeclContext();
11548 
11549   //  If the parameter still belongs to the translation unit, then
11550   //  we're actually just using one parameter in the declaration of
11551   //  the next.
11552   if (isa<ParmVarDecl>(var) &&
11553       isa<TranslationUnitDecl>(VarDC))
11554     return;
11555 
11556   // For C code, don't diagnose about capture if we're not actually in code
11557   // right now; it's impossible to write a non-constant expression outside of
11558   // function context, so we'll get other (more useful) diagnostics later.
11559   //
11560   // For C++, things get a bit more nasty... it would be nice to suppress this
11561   // diagnostic for certain cases like using a local variable in an array bound
11562   // for a member of a local class, but the correct predicate is not obvious.
11563   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11564     return;
11565 
11566   if (isa<CXXMethodDecl>(VarDC) &&
11567       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11568     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11569       << var->getIdentifier();
11570   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11571     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11572       << var->getIdentifier() << fn->getDeclName();
11573   } else if (isa<BlockDecl>(VarDC)) {
11574     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11575       << var->getIdentifier();
11576   } else {
11577     // FIXME: Is there any other context where a local variable can be
11578     // declared?
11579     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11580       << var->getIdentifier();
11581   }
11582 
11583   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11584       << var->getIdentifier();
11585 
11586   // FIXME: Add additional diagnostic info about class etc. which prevents
11587   // capture.
11588 }
11589 
11590 
11591 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11592                                       bool &SubCapturesAreNested,
11593                                       QualType &CaptureType,
11594                                       QualType &DeclRefType) {
11595    // Check whether we've already captured it.
11596   if (CSI->CaptureMap.count(Var)) {
11597     // If we found a capture, any subcaptures are nested.
11598     SubCapturesAreNested = true;
11599 
11600     // Retrieve the capture type for this variable.
11601     CaptureType = CSI->getCapture(Var).getCaptureType();
11602 
11603     // Compute the type of an expression that refers to this variable.
11604     DeclRefType = CaptureType.getNonReferenceType();
11605 
11606     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11607     if (Cap.isCopyCapture() &&
11608         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11609       DeclRefType.addConst();
11610     return true;
11611   }
11612   return false;
11613 }
11614 
11615 // Only block literals, captured statements, and lambda expressions can
11616 // capture; other scopes don't work.
11617 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11618                                  SourceLocation Loc,
11619                                  const bool Diagnose, Sema &S) {
11620   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11621     return getLambdaAwareParentOfDeclContext(DC);
11622   else {
11623     if (Diagnose)
11624        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11625   }
11626   return nullptr;
11627 }
11628 
11629 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11630 // certain types of variables (unnamed, variably modified types etc.)
11631 // so check for eligibility.
11632 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11633                                  SourceLocation Loc,
11634                                  const bool Diagnose, Sema &S) {
11635 
11636   bool IsBlock = isa<BlockScopeInfo>(CSI);
11637   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11638 
11639   // Lambdas are not allowed to capture unnamed variables
11640   // (e.g. anonymous unions).
11641   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11642   // assuming that's the intent.
11643   if (IsLambda && !Var->getDeclName()) {
11644     if (Diagnose) {
11645       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11646       S.Diag(Var->getLocation(), diag::note_declared_at);
11647     }
11648     return false;
11649   }
11650 
11651   // Prohibit variably-modified types; they're difficult to deal with.
11652   if (Var->getType()->isVariablyModifiedType()) {
11653     if (Diagnose) {
11654       if (IsBlock)
11655         S.Diag(Loc, diag::err_ref_vm_type);
11656       else
11657         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11658       S.Diag(Var->getLocation(), diag::note_previous_decl)
11659         << Var->getDeclName();
11660     }
11661     return false;
11662   }
11663   // Prohibit structs with flexible array members too.
11664   // We cannot capture what is in the tail end of the struct.
11665   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11666     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11667       if (Diagnose) {
11668         if (IsBlock)
11669           S.Diag(Loc, diag::err_ref_flexarray_type);
11670         else
11671           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11672             << Var->getDeclName();
11673         S.Diag(Var->getLocation(), diag::note_previous_decl)
11674           << Var->getDeclName();
11675       }
11676       return false;
11677     }
11678   }
11679   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11680   // Lambdas and captured statements are not allowed to capture __block
11681   // variables; they don't support the expected semantics.
11682   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11683     if (Diagnose) {
11684       S.Diag(Loc, diag::err_capture_block_variable)
11685         << Var->getDeclName() << !IsLambda;
11686       S.Diag(Var->getLocation(), diag::note_previous_decl)
11687         << Var->getDeclName();
11688     }
11689     return false;
11690   }
11691 
11692   return true;
11693 }
11694 
11695 // Returns true if the capture by block was successful.
11696 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11697                                  SourceLocation Loc,
11698                                  const bool BuildAndDiagnose,
11699                                  QualType &CaptureType,
11700                                  QualType &DeclRefType,
11701                                  const bool Nested,
11702                                  Sema &S) {
11703   Expr *CopyExpr = nullptr;
11704   bool ByRef = false;
11705 
11706   // Blocks are not allowed to capture arrays.
11707   if (CaptureType->isArrayType()) {
11708     if (BuildAndDiagnose) {
11709       S.Diag(Loc, diag::err_ref_array_type);
11710       S.Diag(Var->getLocation(), diag::note_previous_decl)
11711       << Var->getDeclName();
11712     }
11713     return false;
11714   }
11715 
11716   // Forbid the block-capture of autoreleasing variables.
11717   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11718     if (BuildAndDiagnose) {
11719       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11720         << /*block*/ 0;
11721       S.Diag(Var->getLocation(), diag::note_previous_decl)
11722         << Var->getDeclName();
11723     }
11724     return false;
11725   }
11726   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11727   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11728     // Block capture by reference does not change the capture or
11729     // declaration reference types.
11730     ByRef = true;
11731   } else {
11732     // Block capture by copy introduces 'const'.
11733     CaptureType = CaptureType.getNonReferenceType().withConst();
11734     DeclRefType = CaptureType;
11735 
11736     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11737       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11738         // The capture logic needs the destructor, so make sure we mark it.
11739         // Usually this is unnecessary because most local variables have
11740         // their destructors marked at declaration time, but parameters are
11741         // an exception because it's technically only the call site that
11742         // actually requires the destructor.
11743         if (isa<ParmVarDecl>(Var))
11744           S.FinalizeVarWithDestructor(Var, Record);
11745 
11746         // Enter a new evaluation context to insulate the copy
11747         // full-expression.
11748         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11749 
11750         // According to the blocks spec, the capture of a variable from
11751         // the stack requires a const copy constructor.  This is not true
11752         // of the copy/move done to move a __block variable to the heap.
11753         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11754                                                   DeclRefType.withConst(),
11755                                                   VK_LValue, Loc);
11756 
11757         ExprResult Result
11758           = S.PerformCopyInitialization(
11759               InitializedEntity::InitializeBlock(Var->getLocation(),
11760                                                   CaptureType, false),
11761               Loc, DeclRef);
11762 
11763         // Build a full-expression copy expression if initialization
11764         // succeeded and used a non-trivial constructor.  Recover from
11765         // errors by pretending that the copy isn't necessary.
11766         if (!Result.isInvalid() &&
11767             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11768                 ->isTrivial()) {
11769           Result = S.MaybeCreateExprWithCleanups(Result);
11770           CopyExpr = Result.get();
11771         }
11772       }
11773     }
11774   }
11775 
11776   // Actually capture the variable.
11777   if (BuildAndDiagnose)
11778     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11779                     SourceLocation(), CaptureType, CopyExpr);
11780 
11781   return true;
11782 
11783 }
11784 
11785 
11786 /// \brief Capture the given variable in the captured region.
11787 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11788                                     VarDecl *Var,
11789                                     SourceLocation Loc,
11790                                     const bool BuildAndDiagnose,
11791                                     QualType &CaptureType,
11792                                     QualType &DeclRefType,
11793                                     const bool RefersToEnclosingLocal,
11794                                     Sema &S) {
11795 
11796   // By default, capture variables by reference.
11797   bool ByRef = true;
11798   // Using an LValue reference type is consistent with Lambdas (see below).
11799   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11800   Expr *CopyExpr = nullptr;
11801   if (BuildAndDiagnose) {
11802     // The current implementation assumes that all variables are captured
11803     // by references. Since there is no capture by copy, no expression
11804     // evaluation will be needed.
11805     RecordDecl *RD = RSI->TheRecordDecl;
11806 
11807     FieldDecl *Field
11808       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11809                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11810                           nullptr, false, ICIS_NoInit);
11811     Field->setImplicit(true);
11812     Field->setAccess(AS_private);
11813     RD->addDecl(Field);
11814 
11815     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11816                                             DeclRefType, VK_LValue, Loc);
11817     Var->setReferenced(true);
11818     Var->markUsed(S.Context);
11819   }
11820 
11821   // Actually capture the variable.
11822   if (BuildAndDiagnose)
11823     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11824                     SourceLocation(), CaptureType, CopyExpr);
11825 
11826 
11827   return true;
11828 }
11829 
11830 /// \brief Create a field within the lambda class for the variable
11831 ///  being captured.  Handle Array captures.
11832 static ExprResult addAsFieldToClosureType(Sema &S,
11833                                  LambdaScopeInfo *LSI,
11834                                   VarDecl *Var, QualType FieldType,
11835                                   QualType DeclRefType,
11836                                   SourceLocation Loc,
11837                                   bool RefersToEnclosingLocal) {
11838   CXXRecordDecl *Lambda = LSI->Lambda;
11839 
11840   // Build the non-static data member.
11841   FieldDecl *Field
11842     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11843                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11844                         nullptr, false, ICIS_NoInit);
11845   Field->setImplicit(true);
11846   Field->setAccess(AS_private);
11847   Lambda->addDecl(Field);
11848 
11849   // C++11 [expr.prim.lambda]p21:
11850   //   When the lambda-expression is evaluated, the entities that
11851   //   are captured by copy are used to direct-initialize each
11852   //   corresponding non-static data member of the resulting closure
11853   //   object. (For array members, the array elements are
11854   //   direct-initialized in increasing subscript order.) These
11855   //   initializations are performed in the (unspecified) order in
11856   //   which the non-static data members are declared.
11857 
11858   // Introduce a new evaluation context for the initialization, so
11859   // that temporaries introduced as part of the capture are retained
11860   // to be re-"exported" from the lambda expression itself.
11861   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11862 
11863   // C++ [expr.prim.labda]p12:
11864   //   An entity captured by a lambda-expression is odr-used (3.2) in
11865   //   the scope containing the lambda-expression.
11866   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11867                                           DeclRefType, VK_LValue, Loc);
11868   Var->setReferenced(true);
11869   Var->markUsed(S.Context);
11870 
11871   // When the field has array type, create index variables for each
11872   // dimension of the array. We use these index variables to subscript
11873   // the source array, and other clients (e.g., CodeGen) will perform
11874   // the necessary iteration with these index variables.
11875   SmallVector<VarDecl *, 4> IndexVariables;
11876   QualType BaseType = FieldType;
11877   QualType SizeType = S.Context.getSizeType();
11878   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11879   while (const ConstantArrayType *Array
11880                         = S.Context.getAsConstantArrayType(BaseType)) {
11881     // Create the iteration variable for this array index.
11882     IdentifierInfo *IterationVarName = nullptr;
11883     {
11884       SmallString<8> Str;
11885       llvm::raw_svector_ostream OS(Str);
11886       OS << "__i" << IndexVariables.size();
11887       IterationVarName = &S.Context.Idents.get(OS.str());
11888     }
11889     VarDecl *IterationVar
11890       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11891                         IterationVarName, SizeType,
11892                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11893                         SC_None);
11894     IndexVariables.push_back(IterationVar);
11895     LSI->ArrayIndexVars.push_back(IterationVar);
11896 
11897     // Create a reference to the iteration variable.
11898     ExprResult IterationVarRef
11899       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11900     assert(!IterationVarRef.isInvalid() &&
11901            "Reference to invented variable cannot fail!");
11902     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11903     assert(!IterationVarRef.isInvalid() &&
11904            "Conversion of invented variable cannot fail!");
11905 
11906     // Subscript the array with this iteration variable.
11907     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11908                              Ref, Loc, IterationVarRef.get(), Loc);
11909     if (Subscript.isInvalid()) {
11910       S.CleanupVarDeclMarking();
11911       S.DiscardCleanupsInEvaluationContext();
11912       return ExprError();
11913     }
11914 
11915     Ref = Subscript.get();
11916     BaseType = Array->getElementType();
11917   }
11918 
11919   // Construct the entity that we will be initializing. For an array, this
11920   // will be first element in the array, which may require several levels
11921   // of array-subscript entities.
11922   SmallVector<InitializedEntity, 4> Entities;
11923   Entities.reserve(1 + IndexVariables.size());
11924   Entities.push_back(
11925     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11926         Field->getType(), Loc));
11927   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11928     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11929                                                             0,
11930                                                             Entities.back()));
11931 
11932   InitializationKind InitKind
11933     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11934   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11935   ExprResult Result(true);
11936   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11937     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11938 
11939   // If this initialization requires any cleanups (e.g., due to a
11940   // default argument to a copy constructor), note that for the
11941   // lambda.
11942   if (S.ExprNeedsCleanups)
11943     LSI->ExprNeedsCleanups = true;
11944 
11945   // Exit the expression evaluation context used for the capture.
11946   S.CleanupVarDeclMarking();
11947   S.DiscardCleanupsInEvaluationContext();
11948   return Result;
11949 }
11950 
11951 
11952 
11953 /// \brief Capture the given variable in the lambda.
11954 static bool captureInLambda(LambdaScopeInfo *LSI,
11955                             VarDecl *Var,
11956                             SourceLocation Loc,
11957                             const bool BuildAndDiagnose,
11958                             QualType &CaptureType,
11959                             QualType &DeclRefType,
11960                             const bool RefersToEnclosingLocal,
11961                             const Sema::TryCaptureKind Kind,
11962                             SourceLocation EllipsisLoc,
11963                             const bool IsTopScope,
11964                             Sema &S) {
11965 
11966   // Determine whether we are capturing by reference or by value.
11967   bool ByRef = false;
11968   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11969     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11970   } else {
11971     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11972   }
11973 
11974   // Compute the type of the field that will capture this variable.
11975   if (ByRef) {
11976     // C++11 [expr.prim.lambda]p15:
11977     //   An entity is captured by reference if it is implicitly or
11978     //   explicitly captured but not captured by copy. It is
11979     //   unspecified whether additional unnamed non-static data
11980     //   members are declared in the closure type for entities
11981     //   captured by reference.
11982     //
11983     // FIXME: It is not clear whether we want to build an lvalue reference
11984     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11985     // to do the former, while EDG does the latter. Core issue 1249 will
11986     // clarify, but for now we follow GCC because it's a more permissive and
11987     // easily defensible position.
11988     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11989   } else {
11990     // C++11 [expr.prim.lambda]p14:
11991     //   For each entity captured by copy, an unnamed non-static
11992     //   data member is declared in the closure type. The
11993     //   declaration order of these members is unspecified. The type
11994     //   of such a data member is the type of the corresponding
11995     //   captured entity if the entity is not a reference to an
11996     //   object, or the referenced type otherwise. [Note: If the
11997     //   captured entity is a reference to a function, the
11998     //   corresponding data member is also a reference to a
11999     //   function. - end note ]
12000     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12001       if (!RefType->getPointeeType()->isFunctionType())
12002         CaptureType = RefType->getPointeeType();
12003     }
12004 
12005     // Forbid the lambda copy-capture of autoreleasing variables.
12006     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12007       if (BuildAndDiagnose) {
12008         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12009         S.Diag(Var->getLocation(), diag::note_previous_decl)
12010           << Var->getDeclName();
12011       }
12012       return false;
12013     }
12014 
12015     // Make sure that by-copy captures are of a complete and non-abstract type.
12016     if (BuildAndDiagnose) {
12017       if (!CaptureType->isDependentType() &&
12018           S.RequireCompleteType(Loc, CaptureType,
12019                                 diag::err_capture_of_incomplete_type,
12020                                 Var->getDeclName()))
12021         return false;
12022 
12023       if (S.RequireNonAbstractType(Loc, CaptureType,
12024                                    diag::err_capture_of_abstract_type))
12025         return false;
12026     }
12027   }
12028 
12029   // Capture this variable in the lambda.
12030   Expr *CopyExpr = nullptr;
12031   if (BuildAndDiagnose) {
12032     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12033                                         CaptureType, DeclRefType, Loc,
12034                                         RefersToEnclosingLocal);
12035     if (!Result.isInvalid())
12036       CopyExpr = Result.get();
12037   }
12038 
12039   // Compute the type of a reference to this captured variable.
12040   if (ByRef)
12041     DeclRefType = CaptureType.getNonReferenceType();
12042   else {
12043     // C++ [expr.prim.lambda]p5:
12044     //   The closure type for a lambda-expression has a public inline
12045     //   function call operator [...]. This function call operator is
12046     //   declared const (9.3.1) if and only if the lambda-expression’s
12047     //   parameter-declaration-clause is not followed by mutable.
12048     DeclRefType = CaptureType.getNonReferenceType();
12049     if (!LSI->Mutable && !CaptureType->isReferenceType())
12050       DeclRefType.addConst();
12051   }
12052 
12053   // Add the capture.
12054   if (BuildAndDiagnose)
12055     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12056                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12057 
12058   return true;
12059 }
12060 
12061 
12062 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12063                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12064                               bool BuildAndDiagnose,
12065                               QualType &CaptureType,
12066                               QualType &DeclRefType,
12067 						                const unsigned *const FunctionScopeIndexToStopAt) {
12068   bool Nested = false;
12069 
12070   DeclContext *DC = CurContext;
12071   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12072       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12073   // We need to sync up the Declaration Context with the
12074   // FunctionScopeIndexToStopAt
12075   if (FunctionScopeIndexToStopAt) {
12076     unsigned FSIndex = FunctionScopes.size() - 1;
12077     while (FSIndex != MaxFunctionScopesIndex) {
12078       DC = getLambdaAwareParentOfDeclContext(DC);
12079       --FSIndex;
12080     }
12081   }
12082 
12083 
12084   // If the variable is declared in the current context (and is not an
12085   // init-capture), there is no need to capture it.
12086   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12087   if (!Var->hasLocalStorage()) return true;
12088 
12089   // Walk up the stack to determine whether we can capture the variable,
12090   // performing the "simple" checks that don't depend on type. We stop when
12091   // we've either hit the declared scope of the variable or find an existing
12092   // capture of that variable.  We start from the innermost capturing-entity
12093   // (the DC) and ensure that all intervening capturing-entities
12094   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12095   // declcontext can either capture the variable or have already captured
12096   // the variable.
12097   CaptureType = Var->getType();
12098   DeclRefType = CaptureType.getNonReferenceType();
12099   bool Explicit = (Kind != TryCapture_Implicit);
12100   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12101   do {
12102     // Only block literals, captured statements, and lambda expressions can
12103     // capture; other scopes don't work.
12104     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12105                                                               ExprLoc,
12106                                                               BuildAndDiagnose,
12107                                                               *this);
12108     if (!ParentDC) return true;
12109 
12110     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12111     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12112 
12113 
12114     // Check whether we've already captured it.
12115     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12116                                              DeclRefType))
12117       break;
12118     // If we are instantiating a generic lambda call operator body,
12119     // we do not want to capture new variables.  What was captured
12120     // during either a lambdas transformation or initial parsing
12121     // should be used.
12122     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12123       if (BuildAndDiagnose) {
12124         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12125         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12126           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12127           Diag(Var->getLocation(), diag::note_previous_decl)
12128              << Var->getDeclName();
12129           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12130         } else
12131           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12132       }
12133       return true;
12134     }
12135     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12136     // certain types of variables (unnamed, variably modified types etc.)
12137     // so check for eligibility.
12138     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12139        return true;
12140 
12141     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12142       // No capture-default, and this is not an explicit capture
12143       // so cannot capture this variable.
12144       if (BuildAndDiagnose) {
12145         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12146         Diag(Var->getLocation(), diag::note_previous_decl)
12147           << Var->getDeclName();
12148         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12149              diag::note_lambda_decl);
12150         // FIXME: If we error out because an outer lambda can not implicitly
12151         // capture a variable that an inner lambda explicitly captures, we
12152         // should have the inner lambda do the explicit capture - because
12153         // it makes for cleaner diagnostics later.  This would purely be done
12154         // so that the diagnostic does not misleadingly claim that a variable
12155         // can not be captured by a lambda implicitly even though it is captured
12156         // explicitly.  Suggestion:
12157         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12158         //    at the function head
12159         //  - cache the StartingDeclContext - this must be a lambda
12160         //  - captureInLambda in the innermost lambda the variable.
12161       }
12162       return true;
12163     }
12164 
12165     FunctionScopesIndex--;
12166     DC = ParentDC;
12167     Explicit = false;
12168   } while (!Var->getDeclContext()->Equals(DC));
12169 
12170   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12171   // computing the type of the capture at each step, checking type-specific
12172   // requirements, and adding captures if requested.
12173   // If the variable had already been captured previously, we start capturing
12174   // at the lambda nested within that one.
12175   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12176        ++I) {
12177     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12178 
12179     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12180       if (!captureInBlock(BSI, Var, ExprLoc,
12181                           BuildAndDiagnose, CaptureType,
12182                           DeclRefType, Nested, *this))
12183         return true;
12184       Nested = true;
12185     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12186       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12187                                    BuildAndDiagnose, CaptureType,
12188                                    DeclRefType, Nested, *this))
12189         return true;
12190       Nested = true;
12191     } else {
12192       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12193       if (!captureInLambda(LSI, Var, ExprLoc,
12194                            BuildAndDiagnose, CaptureType,
12195                            DeclRefType, Nested, Kind, EllipsisLoc,
12196                             /*IsTopScope*/I == N - 1, *this))
12197         return true;
12198       Nested = true;
12199     }
12200   }
12201   return false;
12202 }
12203 
12204 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12205                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12206   QualType CaptureType;
12207   QualType DeclRefType;
12208   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12209                             /*BuildAndDiagnose=*/true, CaptureType,
12210                             DeclRefType, nullptr);
12211 }
12212 
12213 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12214   QualType CaptureType;
12215   QualType DeclRefType;
12216 
12217   // Determine whether we can capture this variable.
12218   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12219                          /*BuildAndDiagnose=*/false, CaptureType,
12220                          DeclRefType, nullptr))
12221     return QualType();
12222 
12223   return DeclRefType;
12224 }
12225 
12226 
12227 
12228 // If either the type of the variable or the initializer is dependent,
12229 // return false. Otherwise, determine whether the variable is a constant
12230 // expression. Use this if you need to know if a variable that might or
12231 // might not be dependent is truly a constant expression.
12232 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12233     ASTContext &Context) {
12234 
12235   if (Var->getType()->isDependentType())
12236     return false;
12237   const VarDecl *DefVD = nullptr;
12238   Var->getAnyInitializer(DefVD);
12239   if (!DefVD)
12240     return false;
12241   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12242   Expr *Init = cast<Expr>(Eval->Value);
12243   if (Init->isValueDependent())
12244     return false;
12245   return IsVariableAConstantExpression(Var, Context);
12246 }
12247 
12248 
12249 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12250   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12251   // an object that satisfies the requirements for appearing in a
12252   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12253   // is immediately applied."  This function handles the lvalue-to-rvalue
12254   // conversion part.
12255   MaybeODRUseExprs.erase(E->IgnoreParens());
12256 
12257   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12258   // to a variable that is a constant expression, and if so, identify it as
12259   // a reference to a variable that does not involve an odr-use of that
12260   // variable.
12261   if (LambdaScopeInfo *LSI = getCurLambda()) {
12262     Expr *SansParensExpr = E->IgnoreParens();
12263     VarDecl *Var = nullptr;
12264     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12265       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12266     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12267       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12268 
12269     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12270       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12271   }
12272 }
12273 
12274 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12275   if (!Res.isUsable())
12276     return Res;
12277 
12278   // If a constant-expression is a reference to a variable where we delay
12279   // deciding whether it is an odr-use, just assume we will apply the
12280   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12281   // (a non-type template argument), we have special handling anyway.
12282   UpdateMarkingForLValueToRValue(Res.get());
12283   return Res;
12284 }
12285 
12286 void Sema::CleanupVarDeclMarking() {
12287   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12288                                         e = MaybeODRUseExprs.end();
12289        i != e; ++i) {
12290     VarDecl *Var;
12291     SourceLocation Loc;
12292     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12293       Var = cast<VarDecl>(DRE->getDecl());
12294       Loc = DRE->getLocation();
12295     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12296       Var = cast<VarDecl>(ME->getMemberDecl());
12297       Loc = ME->getMemberLoc();
12298     } else {
12299       llvm_unreachable("Unexpcted expression");
12300     }
12301 
12302     MarkVarDeclODRUsed(Var, Loc, *this,
12303                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12304   }
12305 
12306   MaybeODRUseExprs.clear();
12307 }
12308 
12309 
12310 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12311                                     VarDecl *Var, Expr *E) {
12312   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12313          "Invalid Expr argument to DoMarkVarDeclReferenced");
12314   Var->setReferenced();
12315 
12316   // If the context is not potentially evaluated, this is not an odr-use and
12317   // does not trigger instantiation.
12318   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12319     if (SemaRef.isUnevaluatedContext())
12320       return;
12321 
12322     // If we don't yet know whether this context is going to end up being an
12323     // evaluated context, and we're referencing a variable from an enclosing
12324     // scope, add a potential capture.
12325     //
12326     // FIXME: Is this necessary? These contexts are only used for default
12327     // arguments, where local variables can't be used.
12328     const bool RefersToEnclosingScope =
12329         (SemaRef.CurContext != Var->getDeclContext() &&
12330          Var->getDeclContext()->isFunctionOrMethod() &&
12331          Var->hasLocalStorage());
12332     if (!RefersToEnclosingScope)
12333       return;
12334 
12335     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12336       // If a variable could potentially be odr-used, defer marking it so
12337       // until we finish analyzing the full expression for any lvalue-to-rvalue
12338       // or discarded value conversions that would obviate odr-use.
12339       // Add it to the list of potential captures that will be analyzed
12340       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12341       // unless the variable is a reference that was initialized by a constant
12342       // expression (this will never need to be captured or odr-used).
12343       assert(E && "Capture variable should be used in an expression.");
12344       if (!Var->getType()->isReferenceType() ||
12345           !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12346         LSI->addPotentialCapture(E->IgnoreParens());
12347     }
12348     return;
12349   }
12350 
12351   VarTemplateSpecializationDecl *VarSpec =
12352       dyn_cast<VarTemplateSpecializationDecl>(Var);
12353   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12354          "Can't instantiate a partial template specialization.");
12355 
12356   // Perform implicit instantiation of static data members, static data member
12357   // templates of class templates, and variable template specializations. Delay
12358   // instantiations of variable templates, except for those that could be used
12359   // in a constant expression.
12360   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12361   if (isTemplateInstantiation(TSK)) {
12362     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12363 
12364     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12365       if (Var->getPointOfInstantiation().isInvalid()) {
12366         // This is a modification of an existing AST node. Notify listeners.
12367         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12368           L->StaticDataMemberInstantiated(Var);
12369       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12370         // Don't bother trying to instantiate it again, unless we might need
12371         // its initializer before we get to the end of the TU.
12372         TryInstantiating = false;
12373     }
12374 
12375     if (Var->getPointOfInstantiation().isInvalid())
12376       Var->setTemplateSpecializationKind(TSK, Loc);
12377 
12378     if (TryInstantiating) {
12379       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12380       bool InstantiationDependent = false;
12381       bool IsNonDependent =
12382           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12383                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12384                   : true;
12385 
12386       // Do not instantiate specializations that are still type-dependent.
12387       if (IsNonDependent) {
12388         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12389           // Do not defer instantiations of variables which could be used in a
12390           // constant expression.
12391           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12392         } else {
12393           SemaRef.PendingInstantiations
12394               .push_back(std::make_pair(Var, PointOfInstantiation));
12395         }
12396       }
12397     }
12398   }
12399 
12400   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12401   // the requirements for appearing in a constant expression (5.19) and, if
12402   // it is an object, the lvalue-to-rvalue conversion (4.1)
12403   // is immediately applied."  We check the first part here, and
12404   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12405   // Note that we use the C++11 definition everywhere because nothing in
12406   // C++03 depends on whether we get the C++03 version correct. The second
12407   // part does not apply to references, since they are not objects.
12408   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12409     // A reference initialized by a constant expression can never be
12410     // odr-used, so simply ignore it.
12411     if (!Var->getType()->isReferenceType())
12412       SemaRef.MaybeODRUseExprs.insert(E);
12413   } else
12414     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12415                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12416 }
12417 
12418 /// \brief Mark a variable referenced, and check whether it is odr-used
12419 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12420 /// used directly for normal expressions referring to VarDecl.
12421 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12422   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12423 }
12424 
12425 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12426                                Decl *D, Expr *E, bool OdrUse) {
12427   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12428     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12429     return;
12430   }
12431 
12432   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12433 
12434   // If this is a call to a method via a cast, also mark the method in the
12435   // derived class used in case codegen can devirtualize the call.
12436   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12437   if (!ME)
12438     return;
12439   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12440   if (!MD)
12441     return;
12442   const Expr *Base = ME->getBase();
12443   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12444   if (!MostDerivedClassDecl)
12445     return;
12446   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12447   if (!DM || DM->isPure())
12448     return;
12449   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12450 }
12451 
12452 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12453 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12454   // TODO: update this with DR# once a defect report is filed.
12455   // C++11 defect. The address of a pure member should not be an ODR use, even
12456   // if it's a qualified reference.
12457   bool OdrUse = true;
12458   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12459     if (Method->isVirtual())
12460       OdrUse = false;
12461   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12462 }
12463 
12464 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12465 void Sema::MarkMemberReferenced(MemberExpr *E) {
12466   // C++11 [basic.def.odr]p2:
12467   //   A non-overloaded function whose name appears as a potentially-evaluated
12468   //   expression or a member of a set of candidate functions, if selected by
12469   //   overload resolution when referred to from a potentially-evaluated
12470   //   expression, is odr-used, unless it is a pure virtual function and its
12471   //   name is not explicitly qualified.
12472   bool OdrUse = true;
12473   if (!E->hasQualifier()) {
12474     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12475       if (Method->isPure())
12476         OdrUse = false;
12477   }
12478   SourceLocation Loc = E->getMemberLoc().isValid() ?
12479                             E->getMemberLoc() : E->getLocStart();
12480   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12481 }
12482 
12483 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12484 /// marks the declaration referenced, and performs odr-use checking for
12485 /// functions and variables. This method should not be used when building a
12486 /// normal expression which refers to a variable.
12487 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12488   if (OdrUse) {
12489     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12490       MarkVariableReferenced(Loc, VD);
12491       return;
12492     }
12493     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12494       MarkFunctionReferenced(Loc, FD);
12495       return;
12496     }
12497   }
12498   D->setReferenced();
12499 }
12500 
12501 namespace {
12502   // Mark all of the declarations referenced
12503   // FIXME: Not fully implemented yet! We need to have a better understanding
12504   // of when we're entering
12505   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12506     Sema &S;
12507     SourceLocation Loc;
12508 
12509   public:
12510     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12511 
12512     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12513 
12514     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12515     bool TraverseRecordType(RecordType *T);
12516   };
12517 }
12518 
12519 bool MarkReferencedDecls::TraverseTemplateArgument(
12520     const TemplateArgument &Arg) {
12521   if (Arg.getKind() == TemplateArgument::Declaration) {
12522     if (Decl *D = Arg.getAsDecl())
12523       S.MarkAnyDeclReferenced(Loc, D, true);
12524   }
12525 
12526   return Inherited::TraverseTemplateArgument(Arg);
12527 }
12528 
12529 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12530   if (ClassTemplateSpecializationDecl *Spec
12531                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12532     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12533     return TraverseTemplateArguments(Args.data(), Args.size());
12534   }
12535 
12536   return true;
12537 }
12538 
12539 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12540   MarkReferencedDecls Marker(*this, Loc);
12541   Marker.TraverseType(Context.getCanonicalType(T));
12542 }
12543 
12544 namespace {
12545   /// \brief Helper class that marks all of the declarations referenced by
12546   /// potentially-evaluated subexpressions as "referenced".
12547   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12548     Sema &S;
12549     bool SkipLocalVariables;
12550 
12551   public:
12552     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12553 
12554     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12555       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12556 
12557     void VisitDeclRefExpr(DeclRefExpr *E) {
12558       // If we were asked not to visit local variables, don't.
12559       if (SkipLocalVariables) {
12560         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12561           if (VD->hasLocalStorage())
12562             return;
12563       }
12564 
12565       S.MarkDeclRefReferenced(E);
12566     }
12567 
12568     void VisitMemberExpr(MemberExpr *E) {
12569       S.MarkMemberReferenced(E);
12570       Inherited::VisitMemberExpr(E);
12571     }
12572 
12573     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12574       S.MarkFunctionReferenced(E->getLocStart(),
12575             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12576       Visit(E->getSubExpr());
12577     }
12578 
12579     void VisitCXXNewExpr(CXXNewExpr *E) {
12580       if (E->getOperatorNew())
12581         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12582       if (E->getOperatorDelete())
12583         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12584       Inherited::VisitCXXNewExpr(E);
12585     }
12586 
12587     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12588       if (E->getOperatorDelete())
12589         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12590       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12591       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12592         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12593         S.MarkFunctionReferenced(E->getLocStart(),
12594                                     S.LookupDestructor(Record));
12595       }
12596 
12597       Inherited::VisitCXXDeleteExpr(E);
12598     }
12599 
12600     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12601       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12602       Inherited::VisitCXXConstructExpr(E);
12603     }
12604 
12605     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12606       Visit(E->getExpr());
12607     }
12608 
12609     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12610       Inherited::VisitImplicitCastExpr(E);
12611 
12612       if (E->getCastKind() == CK_LValueToRValue)
12613         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12614     }
12615   };
12616 }
12617 
12618 /// \brief Mark any declarations that appear within this expression or any
12619 /// potentially-evaluated subexpressions as "referenced".
12620 ///
12621 /// \param SkipLocalVariables If true, don't mark local variables as
12622 /// 'referenced'.
12623 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12624                                             bool SkipLocalVariables) {
12625   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12626 }
12627 
12628 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12629 /// of the program being compiled.
12630 ///
12631 /// This routine emits the given diagnostic when the code currently being
12632 /// type-checked is "potentially evaluated", meaning that there is a
12633 /// possibility that the code will actually be executable. Code in sizeof()
12634 /// expressions, code used only during overload resolution, etc., are not
12635 /// potentially evaluated. This routine will suppress such diagnostics or,
12636 /// in the absolutely nutty case of potentially potentially evaluated
12637 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12638 /// later.
12639 ///
12640 /// This routine should be used for all diagnostics that describe the run-time
12641 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12642 /// Failure to do so will likely result in spurious diagnostics or failures
12643 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12644 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12645                                const PartialDiagnostic &PD) {
12646   switch (ExprEvalContexts.back().Context) {
12647   case Unevaluated:
12648   case UnevaluatedAbstract:
12649     // The argument will never be evaluated, so don't complain.
12650     break;
12651 
12652   case ConstantEvaluated:
12653     // Relevant diagnostics should be produced by constant evaluation.
12654     break;
12655 
12656   case PotentiallyEvaluated:
12657   case PotentiallyEvaluatedIfUsed:
12658     if (Statement && getCurFunctionOrMethodDecl()) {
12659       FunctionScopes.back()->PossiblyUnreachableDiags.
12660         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12661     }
12662     else
12663       Diag(Loc, PD);
12664 
12665     return true;
12666   }
12667 
12668   return false;
12669 }
12670 
12671 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12672                                CallExpr *CE, FunctionDecl *FD) {
12673   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12674     return false;
12675 
12676   // If we're inside a decltype's expression, don't check for a valid return
12677   // type or construct temporaries until we know whether this is the last call.
12678   if (ExprEvalContexts.back().IsDecltype) {
12679     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12680     return false;
12681   }
12682 
12683   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12684     FunctionDecl *FD;
12685     CallExpr *CE;
12686 
12687   public:
12688     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12689       : FD(FD), CE(CE) { }
12690 
12691     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12692       if (!FD) {
12693         S.Diag(Loc, diag::err_call_incomplete_return)
12694           << T << CE->getSourceRange();
12695         return;
12696       }
12697 
12698       S.Diag(Loc, diag::err_call_function_incomplete_return)
12699         << CE->getSourceRange() << FD->getDeclName() << T;
12700       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12701           << FD->getDeclName();
12702     }
12703   } Diagnoser(FD, CE);
12704 
12705   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12706     return true;
12707 
12708   return false;
12709 }
12710 
12711 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12712 // will prevent this condition from triggering, which is what we want.
12713 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12714   SourceLocation Loc;
12715 
12716   unsigned diagnostic = diag::warn_condition_is_assignment;
12717   bool IsOrAssign = false;
12718 
12719   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12720     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12721       return;
12722 
12723     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12724 
12725     // Greylist some idioms by putting them into a warning subcategory.
12726     if (ObjCMessageExpr *ME
12727           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12728       Selector Sel = ME->getSelector();
12729 
12730       // self = [<foo> init...]
12731       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12732         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12733 
12734       // <foo> = [<bar> nextObject]
12735       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12736         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12737     }
12738 
12739     Loc = Op->getOperatorLoc();
12740   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12741     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12742       return;
12743 
12744     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12745     Loc = Op->getOperatorLoc();
12746   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12747     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12748   else {
12749     // Not an assignment.
12750     return;
12751   }
12752 
12753   Diag(Loc, diagnostic) << E->getSourceRange();
12754 
12755   SourceLocation Open = E->getLocStart();
12756   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12757   Diag(Loc, diag::note_condition_assign_silence)
12758         << FixItHint::CreateInsertion(Open, "(")
12759         << FixItHint::CreateInsertion(Close, ")");
12760 
12761   if (IsOrAssign)
12762     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12763       << FixItHint::CreateReplacement(Loc, "!=");
12764   else
12765     Diag(Loc, diag::note_condition_assign_to_comparison)
12766       << FixItHint::CreateReplacement(Loc, "==");
12767 }
12768 
12769 /// \brief Redundant parentheses over an equality comparison can indicate
12770 /// that the user intended an assignment used as condition.
12771 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12772   // Don't warn if the parens came from a macro.
12773   SourceLocation parenLoc = ParenE->getLocStart();
12774   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12775     return;
12776   // Don't warn for dependent expressions.
12777   if (ParenE->isTypeDependent())
12778     return;
12779 
12780   Expr *E = ParenE->IgnoreParens();
12781 
12782   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12783     if (opE->getOpcode() == BO_EQ &&
12784         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12785                                                            == Expr::MLV_Valid) {
12786       SourceLocation Loc = opE->getOperatorLoc();
12787 
12788       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12789       SourceRange ParenERange = ParenE->getSourceRange();
12790       Diag(Loc, diag::note_equality_comparison_silence)
12791         << FixItHint::CreateRemoval(ParenERange.getBegin())
12792         << FixItHint::CreateRemoval(ParenERange.getEnd());
12793       Diag(Loc, diag::note_equality_comparison_to_assign)
12794         << FixItHint::CreateReplacement(Loc, "=");
12795     }
12796 }
12797 
12798 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12799   DiagnoseAssignmentAsCondition(E);
12800   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12801     DiagnoseEqualityWithExtraParens(parenE);
12802 
12803   ExprResult result = CheckPlaceholderExpr(E);
12804   if (result.isInvalid()) return ExprError();
12805   E = result.get();
12806 
12807   if (!E->isTypeDependent()) {
12808     if (getLangOpts().CPlusPlus)
12809       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12810 
12811     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12812     if (ERes.isInvalid())
12813       return ExprError();
12814     E = ERes.get();
12815 
12816     QualType T = E->getType();
12817     if (!T->isScalarType()) { // C99 6.8.4.1p1
12818       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12819         << T << E->getSourceRange();
12820       return ExprError();
12821     }
12822   }
12823 
12824   return E;
12825 }
12826 
12827 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12828                                        Expr *SubExpr) {
12829   if (!SubExpr)
12830     return ExprError();
12831 
12832   return CheckBooleanCondition(SubExpr, Loc);
12833 }
12834 
12835 namespace {
12836   /// A visitor for rebuilding a call to an __unknown_any expression
12837   /// to have an appropriate type.
12838   struct RebuildUnknownAnyFunction
12839     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12840 
12841     Sema &S;
12842 
12843     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12844 
12845     ExprResult VisitStmt(Stmt *S) {
12846       llvm_unreachable("unexpected statement!");
12847     }
12848 
12849     ExprResult VisitExpr(Expr *E) {
12850       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12851         << E->getSourceRange();
12852       return ExprError();
12853     }
12854 
12855     /// Rebuild an expression which simply semantically wraps another
12856     /// expression which it shares the type and value kind of.
12857     template <class T> ExprResult rebuildSugarExpr(T *E) {
12858       ExprResult SubResult = Visit(E->getSubExpr());
12859       if (SubResult.isInvalid()) return ExprError();
12860 
12861       Expr *SubExpr = SubResult.get();
12862       E->setSubExpr(SubExpr);
12863       E->setType(SubExpr->getType());
12864       E->setValueKind(SubExpr->getValueKind());
12865       assert(E->getObjectKind() == OK_Ordinary);
12866       return E;
12867     }
12868 
12869     ExprResult VisitParenExpr(ParenExpr *E) {
12870       return rebuildSugarExpr(E);
12871     }
12872 
12873     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12874       return rebuildSugarExpr(E);
12875     }
12876 
12877     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12878       ExprResult SubResult = Visit(E->getSubExpr());
12879       if (SubResult.isInvalid()) return ExprError();
12880 
12881       Expr *SubExpr = SubResult.get();
12882       E->setSubExpr(SubExpr);
12883       E->setType(S.Context.getPointerType(SubExpr->getType()));
12884       assert(E->getValueKind() == VK_RValue);
12885       assert(E->getObjectKind() == OK_Ordinary);
12886       return E;
12887     }
12888 
12889     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12890       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12891 
12892       E->setType(VD->getType());
12893 
12894       assert(E->getValueKind() == VK_RValue);
12895       if (S.getLangOpts().CPlusPlus &&
12896           !(isa<CXXMethodDecl>(VD) &&
12897             cast<CXXMethodDecl>(VD)->isInstance()))
12898         E->setValueKind(VK_LValue);
12899 
12900       return E;
12901     }
12902 
12903     ExprResult VisitMemberExpr(MemberExpr *E) {
12904       return resolveDecl(E, E->getMemberDecl());
12905     }
12906 
12907     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12908       return resolveDecl(E, E->getDecl());
12909     }
12910   };
12911 }
12912 
12913 /// Given a function expression of unknown-any type, try to rebuild it
12914 /// to have a function type.
12915 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12916   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12917   if (Result.isInvalid()) return ExprError();
12918   return S.DefaultFunctionArrayConversion(Result.get());
12919 }
12920 
12921 namespace {
12922   /// A visitor for rebuilding an expression of type __unknown_anytype
12923   /// into one which resolves the type directly on the referring
12924   /// expression.  Strict preservation of the original source
12925   /// structure is not a goal.
12926   struct RebuildUnknownAnyExpr
12927     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12928 
12929     Sema &S;
12930 
12931     /// The current destination type.
12932     QualType DestType;
12933 
12934     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12935       : S(S), DestType(CastType) {}
12936 
12937     ExprResult VisitStmt(Stmt *S) {
12938       llvm_unreachable("unexpected statement!");
12939     }
12940 
12941     ExprResult VisitExpr(Expr *E) {
12942       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12943         << E->getSourceRange();
12944       return ExprError();
12945     }
12946 
12947     ExprResult VisitCallExpr(CallExpr *E);
12948     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12949 
12950     /// Rebuild an expression which simply semantically wraps another
12951     /// expression which it shares the type and value kind of.
12952     template <class T> ExprResult rebuildSugarExpr(T *E) {
12953       ExprResult SubResult = Visit(E->getSubExpr());
12954       if (SubResult.isInvalid()) return ExprError();
12955       Expr *SubExpr = SubResult.get();
12956       E->setSubExpr(SubExpr);
12957       E->setType(SubExpr->getType());
12958       E->setValueKind(SubExpr->getValueKind());
12959       assert(E->getObjectKind() == OK_Ordinary);
12960       return E;
12961     }
12962 
12963     ExprResult VisitParenExpr(ParenExpr *E) {
12964       return rebuildSugarExpr(E);
12965     }
12966 
12967     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12968       return rebuildSugarExpr(E);
12969     }
12970 
12971     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12972       const PointerType *Ptr = DestType->getAs<PointerType>();
12973       if (!Ptr) {
12974         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12975           << E->getSourceRange();
12976         return ExprError();
12977       }
12978       assert(E->getValueKind() == VK_RValue);
12979       assert(E->getObjectKind() == OK_Ordinary);
12980       E->setType(DestType);
12981 
12982       // Build the sub-expression as if it were an object of the pointee type.
12983       DestType = Ptr->getPointeeType();
12984       ExprResult SubResult = Visit(E->getSubExpr());
12985       if (SubResult.isInvalid()) return ExprError();
12986       E->setSubExpr(SubResult.get());
12987       return E;
12988     }
12989 
12990     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12991 
12992     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12993 
12994     ExprResult VisitMemberExpr(MemberExpr *E) {
12995       return resolveDecl(E, E->getMemberDecl());
12996     }
12997 
12998     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12999       return resolveDecl(E, E->getDecl());
13000     }
13001   };
13002 }
13003 
13004 /// Rebuilds a call expression which yielded __unknown_anytype.
13005 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13006   Expr *CalleeExpr = E->getCallee();
13007 
13008   enum FnKind {
13009     FK_MemberFunction,
13010     FK_FunctionPointer,
13011     FK_BlockPointer
13012   };
13013 
13014   FnKind Kind;
13015   QualType CalleeType = CalleeExpr->getType();
13016   if (CalleeType == S.Context.BoundMemberTy) {
13017     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13018     Kind = FK_MemberFunction;
13019     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13020   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13021     CalleeType = Ptr->getPointeeType();
13022     Kind = FK_FunctionPointer;
13023   } else {
13024     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13025     Kind = FK_BlockPointer;
13026   }
13027   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13028 
13029   // Verify that this is a legal result type of a function.
13030   if (DestType->isArrayType() || DestType->isFunctionType()) {
13031     unsigned diagID = diag::err_func_returning_array_function;
13032     if (Kind == FK_BlockPointer)
13033       diagID = diag::err_block_returning_array_function;
13034 
13035     S.Diag(E->getExprLoc(), diagID)
13036       << DestType->isFunctionType() << DestType;
13037     return ExprError();
13038   }
13039 
13040   // Otherwise, go ahead and set DestType as the call's result.
13041   E->setType(DestType.getNonLValueExprType(S.Context));
13042   E->setValueKind(Expr::getValueKindForType(DestType));
13043   assert(E->getObjectKind() == OK_Ordinary);
13044 
13045   // Rebuild the function type, replacing the result type with DestType.
13046   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13047   if (Proto) {
13048     // __unknown_anytype(...) is a special case used by the debugger when
13049     // it has no idea what a function's signature is.
13050     //
13051     // We want to build this call essentially under the K&R
13052     // unprototyped rules, but making a FunctionNoProtoType in C++
13053     // would foul up all sorts of assumptions.  However, we cannot
13054     // simply pass all arguments as variadic arguments, nor can we
13055     // portably just call the function under a non-variadic type; see
13056     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13057     // However, it turns out that in practice it is generally safe to
13058     // call a function declared as "A foo(B,C,D);" under the prototype
13059     // "A foo(B,C,D,...);".  The only known exception is with the
13060     // Windows ABI, where any variadic function is implicitly cdecl
13061     // regardless of its normal CC.  Therefore we change the parameter
13062     // types to match the types of the arguments.
13063     //
13064     // This is a hack, but it is far superior to moving the
13065     // corresponding target-specific code from IR-gen to Sema/AST.
13066 
13067     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13068     SmallVector<QualType, 8> ArgTypes;
13069     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13070       ArgTypes.reserve(E->getNumArgs());
13071       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13072         Expr *Arg = E->getArg(i);
13073         QualType ArgType = Arg->getType();
13074         if (E->isLValue()) {
13075           ArgType = S.Context.getLValueReferenceType(ArgType);
13076         } else if (E->isXValue()) {
13077           ArgType = S.Context.getRValueReferenceType(ArgType);
13078         }
13079         ArgTypes.push_back(ArgType);
13080       }
13081       ParamTypes = ArgTypes;
13082     }
13083     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13084                                          Proto->getExtProtoInfo());
13085   } else {
13086     DestType = S.Context.getFunctionNoProtoType(DestType,
13087                                                 FnType->getExtInfo());
13088   }
13089 
13090   // Rebuild the appropriate pointer-to-function type.
13091   switch (Kind) {
13092   case FK_MemberFunction:
13093     // Nothing to do.
13094     break;
13095 
13096   case FK_FunctionPointer:
13097     DestType = S.Context.getPointerType(DestType);
13098     break;
13099 
13100   case FK_BlockPointer:
13101     DestType = S.Context.getBlockPointerType(DestType);
13102     break;
13103   }
13104 
13105   // Finally, we can recurse.
13106   ExprResult CalleeResult = Visit(CalleeExpr);
13107   if (!CalleeResult.isUsable()) return ExprError();
13108   E->setCallee(CalleeResult.get());
13109 
13110   // Bind a temporary if necessary.
13111   return S.MaybeBindToTemporary(E);
13112 }
13113 
13114 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13115   // Verify that this is a legal result type of a call.
13116   if (DestType->isArrayType() || DestType->isFunctionType()) {
13117     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13118       << DestType->isFunctionType() << DestType;
13119     return ExprError();
13120   }
13121 
13122   // Rewrite the method result type if available.
13123   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13124     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13125     Method->setReturnType(DestType);
13126   }
13127 
13128   // Change the type of the message.
13129   E->setType(DestType.getNonReferenceType());
13130   E->setValueKind(Expr::getValueKindForType(DestType));
13131 
13132   return S.MaybeBindToTemporary(E);
13133 }
13134 
13135 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13136   // The only case we should ever see here is a function-to-pointer decay.
13137   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13138     assert(E->getValueKind() == VK_RValue);
13139     assert(E->getObjectKind() == OK_Ordinary);
13140 
13141     E->setType(DestType);
13142 
13143     // Rebuild the sub-expression as the pointee (function) type.
13144     DestType = DestType->castAs<PointerType>()->getPointeeType();
13145 
13146     ExprResult Result = Visit(E->getSubExpr());
13147     if (!Result.isUsable()) return ExprError();
13148 
13149     E->setSubExpr(Result.get());
13150     return E;
13151   } else if (E->getCastKind() == CK_LValueToRValue) {
13152     assert(E->getValueKind() == VK_RValue);
13153     assert(E->getObjectKind() == OK_Ordinary);
13154 
13155     assert(isa<BlockPointerType>(E->getType()));
13156 
13157     E->setType(DestType);
13158 
13159     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13160     DestType = S.Context.getLValueReferenceType(DestType);
13161 
13162     ExprResult Result = Visit(E->getSubExpr());
13163     if (!Result.isUsable()) return ExprError();
13164 
13165     E->setSubExpr(Result.get());
13166     return E;
13167   } else {
13168     llvm_unreachable("Unhandled cast type!");
13169   }
13170 }
13171 
13172 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13173   ExprValueKind ValueKind = VK_LValue;
13174   QualType Type = DestType;
13175 
13176   // We know how to make this work for certain kinds of decls:
13177 
13178   //  - functions
13179   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13180     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13181       DestType = Ptr->getPointeeType();
13182       ExprResult Result = resolveDecl(E, VD);
13183       if (Result.isInvalid()) return ExprError();
13184       return S.ImpCastExprToType(Result.get(), Type,
13185                                  CK_FunctionToPointerDecay, VK_RValue);
13186     }
13187 
13188     if (!Type->isFunctionType()) {
13189       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13190         << VD << E->getSourceRange();
13191       return ExprError();
13192     }
13193 
13194     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13195       if (MD->isInstance()) {
13196         ValueKind = VK_RValue;
13197         Type = S.Context.BoundMemberTy;
13198       }
13199 
13200     // Function references aren't l-values in C.
13201     if (!S.getLangOpts().CPlusPlus)
13202       ValueKind = VK_RValue;
13203 
13204   //  - variables
13205   } else if (isa<VarDecl>(VD)) {
13206     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13207       Type = RefTy->getPointeeType();
13208     } else if (Type->isFunctionType()) {
13209       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13210         << VD << E->getSourceRange();
13211       return ExprError();
13212     }
13213 
13214   //  - nothing else
13215   } else {
13216     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13217       << VD << E->getSourceRange();
13218     return ExprError();
13219   }
13220 
13221   // Modifying the declaration like this is friendly to IR-gen but
13222   // also really dangerous.
13223   VD->setType(DestType);
13224   E->setType(Type);
13225   E->setValueKind(ValueKind);
13226   return E;
13227 }
13228 
13229 /// Check a cast of an unknown-any type.  We intentionally only
13230 /// trigger this for C-style casts.
13231 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13232                                      Expr *CastExpr, CastKind &CastKind,
13233                                      ExprValueKind &VK, CXXCastPath &Path) {
13234   // Rewrite the casted expression from scratch.
13235   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13236   if (!result.isUsable()) return ExprError();
13237 
13238   CastExpr = result.get();
13239   VK = CastExpr->getValueKind();
13240   CastKind = CK_NoOp;
13241 
13242   return CastExpr;
13243 }
13244 
13245 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13246   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13247 }
13248 
13249 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13250                                     Expr *arg, QualType &paramType) {
13251   // If the syntactic form of the argument is not an explicit cast of
13252   // any sort, just do default argument promotion.
13253   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13254   if (!castArg) {
13255     ExprResult result = DefaultArgumentPromotion(arg);
13256     if (result.isInvalid()) return ExprError();
13257     paramType = result.get()->getType();
13258     return result;
13259   }
13260 
13261   // Otherwise, use the type that was written in the explicit cast.
13262   assert(!arg->hasPlaceholderType());
13263   paramType = castArg->getTypeAsWritten();
13264 
13265   // Copy-initialize a parameter of that type.
13266   InitializedEntity entity =
13267     InitializedEntity::InitializeParameter(Context, paramType,
13268                                            /*consumed*/ false);
13269   return PerformCopyInitialization(entity, callLoc, arg);
13270 }
13271 
13272 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13273   Expr *orig = E;
13274   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13275   while (true) {
13276     E = E->IgnoreParenImpCasts();
13277     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13278       E = call->getCallee();
13279       diagID = diag::err_uncasted_call_of_unknown_any;
13280     } else {
13281       break;
13282     }
13283   }
13284 
13285   SourceLocation loc;
13286   NamedDecl *d;
13287   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13288     loc = ref->getLocation();
13289     d = ref->getDecl();
13290   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13291     loc = mem->getMemberLoc();
13292     d = mem->getMemberDecl();
13293   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13294     diagID = diag::err_uncasted_call_of_unknown_any;
13295     loc = msg->getSelectorStartLoc();
13296     d = msg->getMethodDecl();
13297     if (!d) {
13298       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13299         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13300         << orig->getSourceRange();
13301       return ExprError();
13302     }
13303   } else {
13304     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13305       << E->getSourceRange();
13306     return ExprError();
13307   }
13308 
13309   S.Diag(loc, diagID) << d << orig->getSourceRange();
13310 
13311   // Never recoverable.
13312   return ExprError();
13313 }
13314 
13315 /// Check for operands with placeholder types and complain if found.
13316 /// Returns true if there was an error and no recovery was possible.
13317 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13318   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13319   if (!placeholderType) return E;
13320 
13321   switch (placeholderType->getKind()) {
13322 
13323   // Overloaded expressions.
13324   case BuiltinType::Overload: {
13325     // Try to resolve a single function template specialization.
13326     // This is obligatory.
13327     ExprResult result = E;
13328     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13329       return result;
13330 
13331     // If that failed, try to recover with a call.
13332     } else {
13333       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13334                            /*complain*/ true);
13335       return result;
13336     }
13337   }
13338 
13339   // Bound member functions.
13340   case BuiltinType::BoundMember: {
13341     ExprResult result = E;
13342     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13343                          /*complain*/ true);
13344     return result;
13345   }
13346 
13347   // ARC unbridged casts.
13348   case BuiltinType::ARCUnbridgedCast: {
13349     Expr *realCast = stripARCUnbridgedCast(E);
13350     diagnoseARCUnbridgedCast(realCast);
13351     return realCast;
13352   }
13353 
13354   // Expressions of unknown type.
13355   case BuiltinType::UnknownAny:
13356     return diagnoseUnknownAnyExpr(*this, E);
13357 
13358   // Pseudo-objects.
13359   case BuiltinType::PseudoObject:
13360     return checkPseudoObjectRValue(E);
13361 
13362   case BuiltinType::BuiltinFn:
13363     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13364     return ExprError();
13365 
13366   // Everything else should be impossible.
13367 #define BUILTIN_TYPE(Id, SingletonId) \
13368   case BuiltinType::Id:
13369 #define PLACEHOLDER_TYPE(Id, SingletonId)
13370 #include "clang/AST/BuiltinTypes.def"
13371     break;
13372   }
13373 
13374   llvm_unreachable("invalid placeholder type!");
13375 }
13376 
13377 bool Sema::CheckCaseExpression(Expr *E) {
13378   if (E->isTypeDependent())
13379     return true;
13380   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13381     return E->getType()->isIntegralOrEnumerationType();
13382   return false;
13383 }
13384 
13385 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13386 ExprResult
13387 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13388   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13389          "Unknown Objective-C Boolean value!");
13390   QualType BoolT = Context.ObjCBuiltinBoolTy;
13391   if (!Context.getBOOLDecl()) {
13392     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13393                         Sema::LookupOrdinaryName);
13394     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13395       NamedDecl *ND = Result.getFoundDecl();
13396       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13397         Context.setBOOLDecl(TD);
13398     }
13399   }
13400   if (Context.getBOOLDecl())
13401     BoolT = Context.getBOOLType();
13402   return new (Context)
13403       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13404 }
13405