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(ArrayRef<Token> StringToks, Scope *UDLScope) {
1503   assert(!StringToks.empty() && "Must have at least one string!");
1504 
1505   StringLiteralParser Literal(StringToks, PP);
1506   if (Literal.hadError)
1507     return ExprError();
1508 
1509   SmallVector<SourceLocation, 4> StringTokLocs;
1510   for (unsigned i = 0; i != StringToks.size(); ++i)
1511     StringTokLocs.push_back(StringToks[i].getLocation());
1512 
1513   QualType CharTy = Context.CharTy;
1514   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1515   if (Literal.isWide()) {
1516     CharTy = Context.getWideCharType();
1517     Kind = StringLiteral::Wide;
1518   } else if (Literal.isUTF8()) {
1519     Kind = StringLiteral::UTF8;
1520   } else if (Literal.isUTF16()) {
1521     CharTy = Context.Char16Ty;
1522     Kind = StringLiteral::UTF16;
1523   } else if (Literal.isUTF32()) {
1524     CharTy = Context.Char32Ty;
1525     Kind = StringLiteral::UTF32;
1526   } else if (Literal.isPascal()) {
1527     CharTy = Context.UnsignedCharTy;
1528   }
1529 
1530   QualType CharTyConst = CharTy;
1531   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1532   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1533     CharTyConst.addConst();
1534 
1535   // Get an array type for the string, according to C99 6.4.5.  This includes
1536   // the nul terminator character as well as the string length for pascal
1537   // strings.
1538   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1539                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1540                                  ArrayType::Normal, 0);
1541 
1542   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1543   if (getLangOpts().OpenCL) {
1544     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1545   }
1546 
1547   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1548   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1549                                              Kind, Literal.Pascal, StrTy,
1550                                              &StringTokLocs[0],
1551                                              StringTokLocs.size());
1552   if (Literal.getUDSuffix().empty())
1553     return Lit;
1554 
1555   // We're building a user-defined literal.
1556   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1557   SourceLocation UDSuffixLoc =
1558     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1559                    Literal.getUDSuffixOffset());
1560 
1561   // Make sure we're allowed user-defined literals here.
1562   if (!UDLScope)
1563     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1564 
1565   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1566   //   operator "" X (str, len)
1567   QualType SizeType = Context.getSizeType();
1568 
1569   DeclarationName OpName =
1570     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1571   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1572   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1573 
1574   QualType ArgTy[] = {
1575     Context.getArrayDecayedType(StrTy), SizeType
1576   };
1577 
1578   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1579   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1580                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1581                                 /*AllowStringTemplate*/true)) {
1582 
1583   case LOLR_Cooked: {
1584     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1585     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1586                                                     StringTokLocs[0]);
1587     Expr *Args[] = { Lit, LenArg };
1588 
1589     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1590   }
1591 
1592   case LOLR_StringTemplate: {
1593     TemplateArgumentListInfo ExplicitArgs;
1594 
1595     unsigned CharBits = Context.getIntWidth(CharTy);
1596     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1597     llvm::APSInt Value(CharBits, CharIsUnsigned);
1598 
1599     TemplateArgument TypeArg(CharTy);
1600     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1601     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1602 
1603     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1604       Value = Lit->getCodeUnit(I);
1605       TemplateArgument Arg(Context, Value, CharTy);
1606       TemplateArgumentLocInfo ArgInfo;
1607       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1608     }
1609     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1610                                     &ExplicitArgs);
1611   }
1612   case LOLR_Raw:
1613   case LOLR_Template:
1614     llvm_unreachable("unexpected literal operator lookup result");
1615   case LOLR_Error:
1616     return ExprError();
1617   }
1618   llvm_unreachable("unexpected literal operator lookup result");
1619 }
1620 
1621 ExprResult
1622 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1623                        SourceLocation Loc,
1624                        const CXXScopeSpec *SS) {
1625   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1626   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1627 }
1628 
1629 /// BuildDeclRefExpr - Build an expression that references a
1630 /// declaration that does not require a closure capture.
1631 ExprResult
1632 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1633                        const DeclarationNameInfo &NameInfo,
1634                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1635                        const TemplateArgumentListInfo *TemplateArgs) {
1636   if (getLangOpts().CUDA)
1637     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1638       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1639         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1640                            CalleeTarget = IdentifyCUDATarget(Callee);
1641         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1642           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1643             << CalleeTarget << D->getIdentifier() << CallerTarget;
1644           Diag(D->getLocation(), diag::note_previous_decl)
1645             << D->getIdentifier();
1646           return ExprError();
1647         }
1648       }
1649 
1650   bool refersToEnclosingScope =
1651     (CurContext != D->getDeclContext() &&
1652      D->getDeclContext()->isFunctionOrMethod()) ||
1653     (isa<VarDecl>(D) &&
1654      cast<VarDecl>(D)->isInitCapture());
1655 
1656   DeclRefExpr *E;
1657   if (isa<VarTemplateSpecializationDecl>(D)) {
1658     VarTemplateSpecializationDecl *VarSpec =
1659         cast<VarTemplateSpecializationDecl>(D);
1660 
1661     E = DeclRefExpr::Create(
1662         Context,
1663         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1664         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1665         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1666   } else {
1667     assert(!TemplateArgs && "No template arguments for non-variable"
1668                             " template specialization references");
1669     E = DeclRefExpr::Create(
1670         Context,
1671         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1672         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1673   }
1674 
1675   MarkDeclRefReferenced(E);
1676 
1677   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1678       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1679       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1680       recordUseOfEvaluatedWeak(E);
1681 
1682   // Just in case we're building an illegal pointer-to-member.
1683   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1684   if (FD && FD->isBitField())
1685     E->setObjectKind(OK_BitField);
1686 
1687   return E;
1688 }
1689 
1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1691 /// possibly a list of template arguments.
1692 ///
1693 /// If this produces template arguments, it is permitted to call
1694 /// DecomposeTemplateName.
1695 ///
1696 /// This actually loses a lot of source location information for
1697 /// non-standard name kinds; we should consider preserving that in
1698 /// some way.
1699 void
1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1701                              TemplateArgumentListInfo &Buffer,
1702                              DeclarationNameInfo &NameInfo,
1703                              const TemplateArgumentListInfo *&TemplateArgs) {
1704   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1705     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1706     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1707 
1708     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1709                                        Id.TemplateId->NumArgs);
1710     translateTemplateArguments(TemplateArgsPtr, Buffer);
1711 
1712     TemplateName TName = Id.TemplateId->Template.get();
1713     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1714     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1715     TemplateArgs = &Buffer;
1716   } else {
1717     NameInfo = GetNameFromUnqualifiedId(Id);
1718     TemplateArgs = nullptr;
1719   }
1720 }
1721 
1722 /// Diagnose an empty lookup.
1723 ///
1724 /// \return false if new lookup candidates were found
1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1726                                CorrectionCandidateCallback &CCC,
1727                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1728                                ArrayRef<Expr *> Args) {
1729   DeclarationName Name = R.getLookupName();
1730 
1731   unsigned diagnostic = diag::err_undeclared_var_use;
1732   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1733   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1734       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1735       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1736     diagnostic = diag::err_undeclared_use;
1737     diagnostic_suggest = diag::err_undeclared_use_suggest;
1738   }
1739 
1740   // If the original lookup was an unqualified lookup, fake an
1741   // unqualified lookup.  This is useful when (for example) the
1742   // original lookup would not have found something because it was a
1743   // dependent name.
1744   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1745     ? CurContext : nullptr;
1746   while (DC) {
1747     if (isa<CXXRecordDecl>(DC)) {
1748       LookupQualifiedName(R, DC);
1749 
1750       if (!R.empty()) {
1751         // Don't give errors about ambiguities in this lookup.
1752         R.suppressDiagnostics();
1753 
1754         // During a default argument instantiation the CurContext points
1755         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1756         // function parameter list, hence add an explicit check.
1757         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1758                               ActiveTemplateInstantiations.back().Kind ==
1759             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1760         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1761         bool isInstance = CurMethod &&
1762                           CurMethod->isInstance() &&
1763                           DC == CurMethod->getParent() && !isDefaultArgument;
1764 
1765 
1766         // Give a code modification hint to insert 'this->'.
1767         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1768         // Actually quite difficult!
1769         if (getLangOpts().MSVCCompat)
1770           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1771         if (isInstance) {
1772           Diag(R.getNameLoc(), diagnostic) << Name
1773             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1774           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1775               CallsUndergoingInstantiation.back()->getCallee());
1776 
1777           CXXMethodDecl *DepMethod;
1778           if (CurMethod->isDependentContext())
1779             DepMethod = CurMethod;
1780           else if (CurMethod->getTemplatedKind() ==
1781               FunctionDecl::TK_FunctionTemplateSpecialization)
1782             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1783                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1784           else
1785             DepMethod = cast<CXXMethodDecl>(
1786                 CurMethod->getInstantiatedFromMemberFunction());
1787           assert(DepMethod && "No template pattern found");
1788 
1789           QualType DepThisType = DepMethod->getThisType(Context);
1790           CheckCXXThisCapture(R.getNameLoc());
1791           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1792                                      R.getNameLoc(), DepThisType, false);
1793           TemplateArgumentListInfo TList;
1794           if (ULE->hasExplicitTemplateArgs())
1795             ULE->copyTemplateArgumentsInto(TList);
1796 
1797           CXXScopeSpec SS;
1798           SS.Adopt(ULE->getQualifierLoc());
1799           CXXDependentScopeMemberExpr *DepExpr =
1800               CXXDependentScopeMemberExpr::Create(
1801                   Context, DepThis, DepThisType, true, SourceLocation(),
1802                   SS.getWithLocInContext(Context),
1803                   ULE->getTemplateKeywordLoc(), nullptr,
1804                   R.getLookupNameInfo(),
1805                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1806           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1807         } else {
1808           Diag(R.getNameLoc(), diagnostic) << Name;
1809         }
1810 
1811         // Do we really want to note all of these?
1812         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1813           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1814 
1815         // Return true if we are inside a default argument instantiation
1816         // and the found name refers to an instance member function, otherwise
1817         // the function calling DiagnoseEmptyLookup will try to create an
1818         // implicit member call and this is wrong for default argument.
1819         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1820           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1821           return true;
1822         }
1823 
1824         // Tell the callee to try to recover.
1825         return false;
1826       }
1827 
1828       R.clear();
1829     }
1830 
1831     // In Microsoft mode, if we are performing lookup from within a friend
1832     // function definition declared at class scope then we must set
1833     // DC to the lexical parent to be able to search into the parent
1834     // class.
1835     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1836         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1837         DC->getLexicalParent()->isRecord())
1838       DC = DC->getLexicalParent();
1839     else
1840       DC = DC->getParent();
1841   }
1842 
1843   // We didn't find anything, so try to correct for a typo.
1844   TypoCorrection Corrected;
1845   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1846                                     S, &SS, CCC, CTK_ErrorRecovery))) {
1847     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1848     bool DroppedSpecifier =
1849         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1850     R.setLookupName(Corrected.getCorrection());
1851 
1852     bool AcceptableWithRecovery = false;
1853     bool AcceptableWithoutRecovery = false;
1854     NamedDecl *ND = Corrected.getCorrectionDecl();
1855     if (ND) {
1856       if (Corrected.isOverloaded()) {
1857         OverloadCandidateSet OCS(R.getNameLoc(),
1858                                  OverloadCandidateSet::CSK_Normal);
1859         OverloadCandidateSet::iterator Best;
1860         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1861                                         CDEnd = Corrected.end();
1862              CD != CDEnd; ++CD) {
1863           if (FunctionTemplateDecl *FTD =
1864                    dyn_cast<FunctionTemplateDecl>(*CD))
1865             AddTemplateOverloadCandidate(
1866                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1867                 Args, OCS);
1868           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1869             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1870               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1871                                    Args, OCS);
1872         }
1873         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1874         case OR_Success:
1875           ND = Best->Function;
1876           Corrected.setCorrectionDecl(ND);
1877           break;
1878         default:
1879           // FIXME: Arbitrarily pick the first declaration for the note.
1880           Corrected.setCorrectionDecl(ND);
1881           break;
1882         }
1883       }
1884       R.addDecl(ND);
1885       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1886         CXXRecordDecl *Record = nullptr;
1887         if (Corrected.getCorrectionSpecifier()) {
1888           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1889           Record = Ty->getAsCXXRecordDecl();
1890         }
1891         if (!Record)
1892           Record = cast<CXXRecordDecl>(
1893               ND->getDeclContext()->getRedeclContext());
1894         R.setNamingClass(Record);
1895       }
1896 
1897       AcceptableWithRecovery =
1898           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1899       // FIXME: If we ended up with a typo for a type name or
1900       // Objective-C class name, we're in trouble because the parser
1901       // is in the wrong place to recover. Suggest the typo
1902       // correction, but don't make it a fix-it since we're not going
1903       // to recover well anyway.
1904       AcceptableWithoutRecovery =
1905           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1906     } else {
1907       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1908       // because we aren't able to recover.
1909       AcceptableWithoutRecovery = true;
1910     }
1911 
1912     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1913       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1914                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1915                             ? diag::note_implicit_param_decl
1916                             : diag::note_previous_decl;
1917       if (SS.isEmpty())
1918         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1919                      PDiag(NoteID), AcceptableWithRecovery);
1920       else
1921         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1922                                   << Name << computeDeclContext(SS, false)
1923                                   << DroppedSpecifier << SS.getRange(),
1924                      PDiag(NoteID), AcceptableWithRecovery);
1925 
1926       // Tell the callee whether to try to recover.
1927       return !AcceptableWithRecovery;
1928     }
1929   }
1930   R.clear();
1931 
1932   // Emit a special diagnostic for failed member lookups.
1933   // FIXME: computing the declaration context might fail here (?)
1934   if (!SS.isEmpty()) {
1935     Diag(R.getNameLoc(), diag::err_no_member)
1936       << Name << computeDeclContext(SS, false)
1937       << SS.getRange();
1938     return true;
1939   }
1940 
1941   // Give up, we can't recover.
1942   Diag(R.getNameLoc(), diagnostic) << Name;
1943   return true;
1944 }
1945 
1946 /// In Microsoft mode, if we are inside a template class whose parent class has
1947 /// dependent base classes, and we can't resolve an unqualified identifier, then
1948 /// assume the identifier is a member of a dependent base class.  We can only
1949 /// recover successfully in static methods, instance methods, and other contexts
1950 /// where 'this' is available.  This doesn't precisely match MSVC's
1951 /// instantiation model, but it's close enough.
1952 static Expr *
1953 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1954                                DeclarationNameInfo &NameInfo,
1955                                SourceLocation TemplateKWLoc,
1956                                const TemplateArgumentListInfo *TemplateArgs) {
1957   // Only try to recover from lookup into dependent bases in static methods or
1958   // contexts where 'this' is available.
1959   QualType ThisType = S.getCurrentThisType();
1960   const CXXRecordDecl *RD = nullptr;
1961   if (!ThisType.isNull())
1962     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1963   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1964     RD = MD->getParent();
1965   if (!RD || !RD->hasAnyDependentBases())
1966     return nullptr;
1967 
1968   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1969   // is available, suggest inserting 'this->' as a fixit.
1970   SourceLocation Loc = NameInfo.getLoc();
1971   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1972   DB << NameInfo.getName() << RD;
1973 
1974   if (!ThisType.isNull()) {
1975     DB << FixItHint::CreateInsertion(Loc, "this->");
1976     return CXXDependentScopeMemberExpr::Create(
1977         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1978         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1979         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1980   }
1981 
1982   // Synthesize a fake NNS that points to the derived class.  This will
1983   // perform name lookup during template instantiation.
1984   CXXScopeSpec SS;
1985   auto *NNS =
1986       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1987   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1988   return DependentScopeDeclRefExpr::Create(
1989       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1990       TemplateArgs);
1991 }
1992 
1993 ExprResult Sema::ActOnIdExpression(Scope *S,
1994                                    CXXScopeSpec &SS,
1995                                    SourceLocation TemplateKWLoc,
1996                                    UnqualifiedId &Id,
1997                                    bool HasTrailingLParen,
1998                                    bool IsAddressOfOperand,
1999                                    CorrectionCandidateCallback *CCC,
2000                                    bool IsInlineAsmIdentifier) {
2001   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2002          "cannot be direct & operand and have a trailing lparen");
2003   if (SS.isInvalid())
2004     return ExprError();
2005 
2006   TemplateArgumentListInfo TemplateArgsBuffer;
2007 
2008   // Decompose the UnqualifiedId into the following data.
2009   DeclarationNameInfo NameInfo;
2010   const TemplateArgumentListInfo *TemplateArgs;
2011   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2012 
2013   DeclarationName Name = NameInfo.getName();
2014   IdentifierInfo *II = Name.getAsIdentifierInfo();
2015   SourceLocation NameLoc = NameInfo.getLoc();
2016 
2017   // C++ [temp.dep.expr]p3:
2018   //   An id-expression is type-dependent if it contains:
2019   //     -- an identifier that was declared with a dependent type,
2020   //        (note: handled after lookup)
2021   //     -- a template-id that is dependent,
2022   //        (note: handled in BuildTemplateIdExpr)
2023   //     -- a conversion-function-id that specifies a dependent type,
2024   //     -- a nested-name-specifier that contains a class-name that
2025   //        names a dependent type.
2026   // Determine whether this is a member of an unknown specialization;
2027   // we need to handle these differently.
2028   bool DependentID = false;
2029   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2030       Name.getCXXNameType()->isDependentType()) {
2031     DependentID = true;
2032   } else if (SS.isSet()) {
2033     if (DeclContext *DC = computeDeclContext(SS, false)) {
2034       if (RequireCompleteDeclContext(SS, DC))
2035         return ExprError();
2036     } else {
2037       DependentID = true;
2038     }
2039   }
2040 
2041   if (DependentID)
2042     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2043                                       IsAddressOfOperand, TemplateArgs);
2044 
2045   // Perform the required lookup.
2046   LookupResult R(*this, NameInfo,
2047                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2048                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2049   if (TemplateArgs) {
2050     // Lookup the template name again to correctly establish the context in
2051     // which it was found. This is really unfortunate as we already did the
2052     // lookup to determine that it was a template name in the first place. If
2053     // this becomes a performance hit, we can work harder to preserve those
2054     // results until we get here but it's likely not worth it.
2055     bool MemberOfUnknownSpecialization;
2056     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2057                        MemberOfUnknownSpecialization);
2058 
2059     if (MemberOfUnknownSpecialization ||
2060         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2061       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2062                                         IsAddressOfOperand, TemplateArgs);
2063   } else {
2064     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2065     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2066 
2067     // If the result might be in a dependent base class, this is a dependent
2068     // id-expression.
2069     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2070       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2071                                         IsAddressOfOperand, TemplateArgs);
2072 
2073     // If this reference is in an Objective-C method, then we need to do
2074     // some special Objective-C lookup, too.
2075     if (IvarLookupFollowUp) {
2076       ExprResult E(LookupInObjCMethod(R, S, II, true));
2077       if (E.isInvalid())
2078         return ExprError();
2079 
2080       if (Expr *Ex = E.getAs<Expr>())
2081         return Ex;
2082     }
2083   }
2084 
2085   if (R.isAmbiguous())
2086     return ExprError();
2087 
2088   // This could be an implicitly declared function reference (legal in C90,
2089   // extension in C99, forbidden in C++).
2090   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2091     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2092     if (D) R.addDecl(D);
2093   }
2094 
2095   // Determine whether this name might be a candidate for
2096   // argument-dependent lookup.
2097   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2098 
2099   if (R.empty() && !ADL) {
2100     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2101       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2102                                                    TemplateKWLoc, TemplateArgs))
2103         return E;
2104     }
2105 
2106     // Don't diagnose an empty lookup for inline assmebly.
2107     if (IsInlineAsmIdentifier)
2108       return ExprError();
2109 
2110     // If this name wasn't predeclared and if this is not a function
2111     // call, diagnose the problem.
2112     CorrectionCandidateCallback DefaultValidator;
2113     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2114     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2115            "Typo correction callback misconfigured");
2116     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2117       return ExprError();
2118 
2119     assert(!R.empty() &&
2120            "DiagnoseEmptyLookup returned false but added no results");
2121 
2122     // If we found an Objective-C instance variable, let
2123     // LookupInObjCMethod build the appropriate expression to
2124     // reference the ivar.
2125     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2126       R.clear();
2127       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2128       // In a hopelessly buggy code, Objective-C instance variable
2129       // lookup fails and no expression will be built to reference it.
2130       if (!E.isInvalid() && !E.get())
2131         return ExprError();
2132       return E;
2133     }
2134   }
2135 
2136   // This is guaranteed from this point on.
2137   assert(!R.empty() || ADL);
2138 
2139   // Check whether this might be a C++ implicit instance member access.
2140   // C++ [class.mfct.non-static]p3:
2141   //   When an id-expression that is not part of a class member access
2142   //   syntax and not used to form a pointer to member is used in the
2143   //   body of a non-static member function of class X, if name lookup
2144   //   resolves the name in the id-expression to a non-static non-type
2145   //   member of some class C, the id-expression is transformed into a
2146   //   class member access expression using (*this) as the
2147   //   postfix-expression to the left of the . operator.
2148   //
2149   // But we don't actually need to do this for '&' operands if R
2150   // resolved to a function or overloaded function set, because the
2151   // expression is ill-formed if it actually works out to be a
2152   // non-static member function:
2153   //
2154   // C++ [expr.ref]p4:
2155   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2156   //   [t]he expression can be used only as the left-hand operand of a
2157   //   member function call.
2158   //
2159   // There are other safeguards against such uses, but it's important
2160   // to get this right here so that we don't end up making a
2161   // spuriously dependent expression if we're inside a dependent
2162   // instance method.
2163   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2164     bool MightBeImplicitMember;
2165     if (!IsAddressOfOperand)
2166       MightBeImplicitMember = true;
2167     else if (!SS.isEmpty())
2168       MightBeImplicitMember = false;
2169     else if (R.isOverloadedResult())
2170       MightBeImplicitMember = false;
2171     else if (R.isUnresolvableResult())
2172       MightBeImplicitMember = true;
2173     else
2174       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2175                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2176                               isa<MSPropertyDecl>(R.getFoundDecl());
2177 
2178     if (MightBeImplicitMember)
2179       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2180                                              R, TemplateArgs);
2181   }
2182 
2183   if (TemplateArgs || TemplateKWLoc.isValid()) {
2184 
2185     // In C++1y, if this is a variable template id, then check it
2186     // in BuildTemplateIdExpr().
2187     // The single lookup result must be a variable template declaration.
2188     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2189         Id.TemplateId->Kind == TNK_Var_template) {
2190       assert(R.getAsSingle<VarTemplateDecl>() &&
2191              "There should only be one declaration found.");
2192     }
2193 
2194     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2195   }
2196 
2197   return BuildDeclarationNameExpr(SS, R, ADL);
2198 }
2199 
2200 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2201 /// declaration name, generally during template instantiation.
2202 /// There's a large number of things which don't need to be done along
2203 /// this path.
2204 ExprResult
2205 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2206                                         const DeclarationNameInfo &NameInfo,
2207                                         bool IsAddressOfOperand,
2208                                         TypeSourceInfo **RecoveryTSI) {
2209   DeclContext *DC = computeDeclContext(SS, false);
2210   if (!DC)
2211     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2212                                      NameInfo, /*TemplateArgs=*/nullptr);
2213 
2214   if (RequireCompleteDeclContext(SS, DC))
2215     return ExprError();
2216 
2217   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2218   LookupQualifiedName(R, DC);
2219 
2220   if (R.isAmbiguous())
2221     return ExprError();
2222 
2223   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2224     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2225                                      NameInfo, /*TemplateArgs=*/nullptr);
2226 
2227   if (R.empty()) {
2228     Diag(NameInfo.getLoc(), diag::err_no_member)
2229       << NameInfo.getName() << DC << SS.getRange();
2230     return ExprError();
2231   }
2232 
2233   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2234     // Diagnose a missing typename if this resolved unambiguously to a type in
2235     // a dependent context.  If we can recover with a type, downgrade this to
2236     // a warning in Microsoft compatibility mode.
2237     unsigned DiagID = diag::err_typename_missing;
2238     if (RecoveryTSI && getLangOpts().MSVCCompat)
2239       DiagID = diag::ext_typename_missing;
2240     SourceLocation Loc = SS.getBeginLoc();
2241     auto D = Diag(Loc, DiagID);
2242     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2243       << SourceRange(Loc, NameInfo.getEndLoc());
2244 
2245     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2246     // context.
2247     if (!RecoveryTSI)
2248       return ExprError();
2249 
2250     // Only issue the fixit if we're prepared to recover.
2251     D << FixItHint::CreateInsertion(Loc, "typename ");
2252 
2253     // Recover by pretending this was an elaborated type.
2254     QualType Ty = Context.getTypeDeclType(TD);
2255     TypeLocBuilder TLB;
2256     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2257 
2258     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2259     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2260     QTL.setElaboratedKeywordLoc(SourceLocation());
2261     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2262 
2263     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2264 
2265     return ExprEmpty();
2266   }
2267 
2268   // Defend against this resolving to an implicit member access. We usually
2269   // won't get here if this might be a legitimate a class member (we end up in
2270   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2271   // a pointer-to-member or in an unevaluated context in C++11.
2272   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2273     return BuildPossibleImplicitMemberExpr(SS,
2274                                            /*TemplateKWLoc=*/SourceLocation(),
2275                                            R, /*TemplateArgs=*/nullptr);
2276 
2277   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2278 }
2279 
2280 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2281 /// detected that we're currently inside an ObjC method.  Perform some
2282 /// additional lookup.
2283 ///
2284 /// Ideally, most of this would be done by lookup, but there's
2285 /// actually quite a lot of extra work involved.
2286 ///
2287 /// Returns a null sentinel to indicate trivial success.
2288 ExprResult
2289 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2290                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2291   SourceLocation Loc = Lookup.getNameLoc();
2292   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2293 
2294   // Check for error condition which is already reported.
2295   if (!CurMethod)
2296     return ExprError();
2297 
2298   // There are two cases to handle here.  1) scoped lookup could have failed,
2299   // in which case we should look for an ivar.  2) scoped lookup could have
2300   // found a decl, but that decl is outside the current instance method (i.e.
2301   // a global variable).  In these two cases, we do a lookup for an ivar with
2302   // this name, if the lookup sucedes, we replace it our current decl.
2303 
2304   // If we're in a class method, we don't normally want to look for
2305   // ivars.  But if we don't find anything else, and there's an
2306   // ivar, that's an error.
2307   bool IsClassMethod = CurMethod->isClassMethod();
2308 
2309   bool LookForIvars;
2310   if (Lookup.empty())
2311     LookForIvars = true;
2312   else if (IsClassMethod)
2313     LookForIvars = false;
2314   else
2315     LookForIvars = (Lookup.isSingleResult() &&
2316                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2317   ObjCInterfaceDecl *IFace = nullptr;
2318   if (LookForIvars) {
2319     IFace = CurMethod->getClassInterface();
2320     ObjCInterfaceDecl *ClassDeclared;
2321     ObjCIvarDecl *IV = nullptr;
2322     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2323       // Diagnose using an ivar in a class method.
2324       if (IsClassMethod)
2325         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2326                          << IV->getDeclName());
2327 
2328       // If we're referencing an invalid decl, just return this as a silent
2329       // error node.  The error diagnostic was already emitted on the decl.
2330       if (IV->isInvalidDecl())
2331         return ExprError();
2332 
2333       // Check if referencing a field with __attribute__((deprecated)).
2334       if (DiagnoseUseOfDecl(IV, Loc))
2335         return ExprError();
2336 
2337       // Diagnose the use of an ivar outside of the declaring class.
2338       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2339           !declaresSameEntity(ClassDeclared, IFace) &&
2340           !getLangOpts().DebuggerSupport)
2341         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2342 
2343       // FIXME: This should use a new expr for a direct reference, don't
2344       // turn this into Self->ivar, just return a BareIVarExpr or something.
2345       IdentifierInfo &II = Context.Idents.get("self");
2346       UnqualifiedId SelfName;
2347       SelfName.setIdentifier(&II, SourceLocation());
2348       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2349       CXXScopeSpec SelfScopeSpec;
2350       SourceLocation TemplateKWLoc;
2351       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2352                                               SelfName, false, false);
2353       if (SelfExpr.isInvalid())
2354         return ExprError();
2355 
2356       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2357       if (SelfExpr.isInvalid())
2358         return ExprError();
2359 
2360       MarkAnyDeclReferenced(Loc, IV, true);
2361 
2362       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2363       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2364           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2365         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2366 
2367       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2368                                                               Loc, IV->getLocation(),
2369                                                               SelfExpr.get(),
2370                                                               true, true);
2371 
2372       if (getLangOpts().ObjCAutoRefCount) {
2373         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2374           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2375             recordUseOfEvaluatedWeak(Result);
2376         }
2377         if (CurContext->isClosure())
2378           Diag(Loc, diag::warn_implicitly_retains_self)
2379             << FixItHint::CreateInsertion(Loc, "self->");
2380       }
2381 
2382       return Result;
2383     }
2384   } else if (CurMethod->isInstanceMethod()) {
2385     // We should warn if a local variable hides an ivar.
2386     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2387       ObjCInterfaceDecl *ClassDeclared;
2388       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2389         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2390             declaresSameEntity(IFace, ClassDeclared))
2391           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2392       }
2393     }
2394   } else if (Lookup.isSingleResult() &&
2395              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2396     // If accessing a stand-alone ivar in a class method, this is an error.
2397     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2398       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2399                        << IV->getDeclName());
2400   }
2401 
2402   if (Lookup.empty() && II && AllowBuiltinCreation) {
2403     // FIXME. Consolidate this with similar code in LookupName.
2404     if (unsigned BuiltinID = II->getBuiltinID()) {
2405       if (!(getLangOpts().CPlusPlus &&
2406             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2407         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2408                                            S, Lookup.isForRedeclaration(),
2409                                            Lookup.getNameLoc());
2410         if (D) Lookup.addDecl(D);
2411       }
2412     }
2413   }
2414   // Sentinel value saying that we didn't do anything special.
2415   return ExprResult((Expr *)nullptr);
2416 }
2417 
2418 /// \brief Cast a base object to a member's actual type.
2419 ///
2420 /// Logically this happens in three phases:
2421 ///
2422 /// * First we cast from the base type to the naming class.
2423 ///   The naming class is the class into which we were looking
2424 ///   when we found the member;  it's the qualifier type if a
2425 ///   qualifier was provided, and otherwise it's the base type.
2426 ///
2427 /// * Next we cast from the naming class to the declaring class.
2428 ///   If the member we found was brought into a class's scope by
2429 ///   a using declaration, this is that class;  otherwise it's
2430 ///   the class declaring the member.
2431 ///
2432 /// * Finally we cast from the declaring class to the "true"
2433 ///   declaring class of the member.  This conversion does not
2434 ///   obey access control.
2435 ExprResult
2436 Sema::PerformObjectMemberConversion(Expr *From,
2437                                     NestedNameSpecifier *Qualifier,
2438                                     NamedDecl *FoundDecl,
2439                                     NamedDecl *Member) {
2440   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2441   if (!RD)
2442     return From;
2443 
2444   QualType DestRecordType;
2445   QualType DestType;
2446   QualType FromRecordType;
2447   QualType FromType = From->getType();
2448   bool PointerConversions = false;
2449   if (isa<FieldDecl>(Member)) {
2450     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2451 
2452     if (FromType->getAs<PointerType>()) {
2453       DestType = Context.getPointerType(DestRecordType);
2454       FromRecordType = FromType->getPointeeType();
2455       PointerConversions = true;
2456     } else {
2457       DestType = DestRecordType;
2458       FromRecordType = FromType;
2459     }
2460   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2461     if (Method->isStatic())
2462       return From;
2463 
2464     DestType = Method->getThisType(Context);
2465     DestRecordType = DestType->getPointeeType();
2466 
2467     if (FromType->getAs<PointerType>()) {
2468       FromRecordType = FromType->getPointeeType();
2469       PointerConversions = true;
2470     } else {
2471       FromRecordType = FromType;
2472       DestType = DestRecordType;
2473     }
2474   } else {
2475     // No conversion necessary.
2476     return From;
2477   }
2478 
2479   if (DestType->isDependentType() || FromType->isDependentType())
2480     return From;
2481 
2482   // If the unqualified types are the same, no conversion is necessary.
2483   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2484     return From;
2485 
2486   SourceRange FromRange = From->getSourceRange();
2487   SourceLocation FromLoc = FromRange.getBegin();
2488 
2489   ExprValueKind VK = From->getValueKind();
2490 
2491   // C++ [class.member.lookup]p8:
2492   //   [...] Ambiguities can often be resolved by qualifying a name with its
2493   //   class name.
2494   //
2495   // If the member was a qualified name and the qualified referred to a
2496   // specific base subobject type, we'll cast to that intermediate type
2497   // first and then to the object in which the member is declared. That allows
2498   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2499   //
2500   //   class Base { public: int x; };
2501   //   class Derived1 : public Base { };
2502   //   class Derived2 : public Base { };
2503   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2504   //
2505   //   void VeryDerived::f() {
2506   //     x = 17; // error: ambiguous base subobjects
2507   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2508   //   }
2509   if (Qualifier && Qualifier->getAsType()) {
2510     QualType QType = QualType(Qualifier->getAsType(), 0);
2511     assert(QType->isRecordType() && "lookup done with non-record type");
2512 
2513     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2514 
2515     // In C++98, the qualifier type doesn't actually have to be a base
2516     // type of the object type, in which case we just ignore it.
2517     // Otherwise build the appropriate casts.
2518     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2519       CXXCastPath BasePath;
2520       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2521                                        FromLoc, FromRange, &BasePath))
2522         return ExprError();
2523 
2524       if (PointerConversions)
2525         QType = Context.getPointerType(QType);
2526       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2527                                VK, &BasePath).get();
2528 
2529       FromType = QType;
2530       FromRecordType = QRecordType;
2531 
2532       // If the qualifier type was the same as the destination type,
2533       // we're done.
2534       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2535         return From;
2536     }
2537   }
2538 
2539   bool IgnoreAccess = false;
2540 
2541   // If we actually found the member through a using declaration, cast
2542   // down to the using declaration's type.
2543   //
2544   // Pointer equality is fine here because only one declaration of a
2545   // class ever has member declarations.
2546   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2547     assert(isa<UsingShadowDecl>(FoundDecl));
2548     QualType URecordType = Context.getTypeDeclType(
2549                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2550 
2551     // We only need to do this if the naming-class to declaring-class
2552     // conversion is non-trivial.
2553     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2554       assert(IsDerivedFrom(FromRecordType, URecordType));
2555       CXXCastPath BasePath;
2556       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2557                                        FromLoc, FromRange, &BasePath))
2558         return ExprError();
2559 
2560       QualType UType = URecordType;
2561       if (PointerConversions)
2562         UType = Context.getPointerType(UType);
2563       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2564                                VK, &BasePath).get();
2565       FromType = UType;
2566       FromRecordType = URecordType;
2567     }
2568 
2569     // We don't do access control for the conversion from the
2570     // declaring class to the true declaring class.
2571     IgnoreAccess = true;
2572   }
2573 
2574   CXXCastPath BasePath;
2575   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2576                                    FromLoc, FromRange, &BasePath,
2577                                    IgnoreAccess))
2578     return ExprError();
2579 
2580   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2581                            VK, &BasePath);
2582 }
2583 
2584 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2585                                       const LookupResult &R,
2586                                       bool HasTrailingLParen) {
2587   // Only when used directly as the postfix-expression of a call.
2588   if (!HasTrailingLParen)
2589     return false;
2590 
2591   // Never if a scope specifier was provided.
2592   if (SS.isSet())
2593     return false;
2594 
2595   // Only in C++ or ObjC++.
2596   if (!getLangOpts().CPlusPlus)
2597     return false;
2598 
2599   // Turn off ADL when we find certain kinds of declarations during
2600   // normal lookup:
2601   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2602     NamedDecl *D = *I;
2603 
2604     // C++0x [basic.lookup.argdep]p3:
2605     //     -- a declaration of a class member
2606     // Since using decls preserve this property, we check this on the
2607     // original decl.
2608     if (D->isCXXClassMember())
2609       return false;
2610 
2611     // C++0x [basic.lookup.argdep]p3:
2612     //     -- a block-scope function declaration that is not a
2613     //        using-declaration
2614     // NOTE: we also trigger this for function templates (in fact, we
2615     // don't check the decl type at all, since all other decl types
2616     // turn off ADL anyway).
2617     if (isa<UsingShadowDecl>(D))
2618       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2619     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2620       return false;
2621 
2622     // C++0x [basic.lookup.argdep]p3:
2623     //     -- a declaration that is neither a function or a function
2624     //        template
2625     // And also for builtin functions.
2626     if (isa<FunctionDecl>(D)) {
2627       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2628 
2629       // But also builtin functions.
2630       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2631         return false;
2632     } else if (!isa<FunctionTemplateDecl>(D))
2633       return false;
2634   }
2635 
2636   return true;
2637 }
2638 
2639 
2640 /// Diagnoses obvious problems with the use of the given declaration
2641 /// as an expression.  This is only actually called for lookups that
2642 /// were not overloaded, and it doesn't promise that the declaration
2643 /// will in fact be used.
2644 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2645   if (isa<TypedefNameDecl>(D)) {
2646     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2647     return true;
2648   }
2649 
2650   if (isa<ObjCInterfaceDecl>(D)) {
2651     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2652     return true;
2653   }
2654 
2655   if (isa<NamespaceDecl>(D)) {
2656     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2657     return true;
2658   }
2659 
2660   return false;
2661 }
2662 
2663 ExprResult
2664 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2665                                LookupResult &R,
2666                                bool NeedsADL) {
2667   // If this is a single, fully-resolved result and we don't need ADL,
2668   // just build an ordinary singleton decl ref.
2669   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2670     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2671                                     R.getRepresentativeDecl());
2672 
2673   // We only need to check the declaration if there's exactly one
2674   // result, because in the overloaded case the results can only be
2675   // functions and function templates.
2676   if (R.isSingleResult() &&
2677       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2678     return ExprError();
2679 
2680   // Otherwise, just build an unresolved lookup expression.  Suppress
2681   // any lookup-related diagnostics; we'll hash these out later, when
2682   // we've picked a target.
2683   R.suppressDiagnostics();
2684 
2685   UnresolvedLookupExpr *ULE
2686     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2687                                    SS.getWithLocInContext(Context),
2688                                    R.getLookupNameInfo(),
2689                                    NeedsADL, R.isOverloadedResult(),
2690                                    R.begin(), R.end());
2691 
2692   return ULE;
2693 }
2694 
2695 /// \brief Complete semantic analysis for a reference to the given declaration.
2696 ExprResult Sema::BuildDeclarationNameExpr(
2697     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2698     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2699   assert(D && "Cannot refer to a NULL declaration");
2700   assert(!isa<FunctionTemplateDecl>(D) &&
2701          "Cannot refer unambiguously to a function template");
2702 
2703   SourceLocation Loc = NameInfo.getLoc();
2704   if (CheckDeclInExpr(*this, Loc, D))
2705     return ExprError();
2706 
2707   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2708     // Specifically diagnose references to class templates that are missing
2709     // a template argument list.
2710     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2711                                            << Template << SS.getRange();
2712     Diag(Template->getLocation(), diag::note_template_decl_here);
2713     return ExprError();
2714   }
2715 
2716   // Make sure that we're referring to a value.
2717   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2718   if (!VD) {
2719     Diag(Loc, diag::err_ref_non_value)
2720       << D << SS.getRange();
2721     Diag(D->getLocation(), diag::note_declared_at);
2722     return ExprError();
2723   }
2724 
2725   // Check whether this declaration can be used. Note that we suppress
2726   // this check when we're going to perform argument-dependent lookup
2727   // on this function name, because this might not be the function
2728   // that overload resolution actually selects.
2729   if (DiagnoseUseOfDecl(VD, Loc))
2730     return ExprError();
2731 
2732   // Only create DeclRefExpr's for valid Decl's.
2733   if (VD->isInvalidDecl())
2734     return ExprError();
2735 
2736   // Handle members of anonymous structs and unions.  If we got here,
2737   // and the reference is to a class member indirect field, then this
2738   // must be the subject of a pointer-to-member expression.
2739   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2740     if (!indirectField->isCXXClassMember())
2741       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2742                                                       indirectField);
2743 
2744   {
2745     QualType type = VD->getType();
2746     ExprValueKind valueKind = VK_RValue;
2747 
2748     switch (D->getKind()) {
2749     // Ignore all the non-ValueDecl kinds.
2750 #define ABSTRACT_DECL(kind)
2751 #define VALUE(type, base)
2752 #define DECL(type, base) \
2753     case Decl::type:
2754 #include "clang/AST/DeclNodes.inc"
2755       llvm_unreachable("invalid value decl kind");
2756 
2757     // These shouldn't make it here.
2758     case Decl::ObjCAtDefsField:
2759     case Decl::ObjCIvar:
2760       llvm_unreachable("forming non-member reference to ivar?");
2761 
2762     // Enum constants are always r-values and never references.
2763     // Unresolved using declarations are dependent.
2764     case Decl::EnumConstant:
2765     case Decl::UnresolvedUsingValue:
2766       valueKind = VK_RValue;
2767       break;
2768 
2769     // Fields and indirect fields that got here must be for
2770     // pointer-to-member expressions; we just call them l-values for
2771     // internal consistency, because this subexpression doesn't really
2772     // exist in the high-level semantics.
2773     case Decl::Field:
2774     case Decl::IndirectField:
2775       assert(getLangOpts().CPlusPlus &&
2776              "building reference to field in C?");
2777 
2778       // These can't have reference type in well-formed programs, but
2779       // for internal consistency we do this anyway.
2780       type = type.getNonReferenceType();
2781       valueKind = VK_LValue;
2782       break;
2783 
2784     // Non-type template parameters are either l-values or r-values
2785     // depending on the type.
2786     case Decl::NonTypeTemplateParm: {
2787       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2788         type = reftype->getPointeeType();
2789         valueKind = VK_LValue; // even if the parameter is an r-value reference
2790         break;
2791       }
2792 
2793       // For non-references, we need to strip qualifiers just in case
2794       // the template parameter was declared as 'const int' or whatever.
2795       valueKind = VK_RValue;
2796       type = type.getUnqualifiedType();
2797       break;
2798     }
2799 
2800     case Decl::Var:
2801     case Decl::VarTemplateSpecialization:
2802     case Decl::VarTemplatePartialSpecialization:
2803       // In C, "extern void blah;" is valid and is an r-value.
2804       if (!getLangOpts().CPlusPlus &&
2805           !type.hasQualifiers() &&
2806           type->isVoidType()) {
2807         valueKind = VK_RValue;
2808         break;
2809       }
2810       // fallthrough
2811 
2812     case Decl::ImplicitParam:
2813     case Decl::ParmVar: {
2814       // These are always l-values.
2815       valueKind = VK_LValue;
2816       type = type.getNonReferenceType();
2817 
2818       // FIXME: Does the addition of const really only apply in
2819       // potentially-evaluated contexts? Since the variable isn't actually
2820       // captured in an unevaluated context, it seems that the answer is no.
2821       if (!isUnevaluatedContext()) {
2822         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2823         if (!CapturedType.isNull())
2824           type = CapturedType;
2825       }
2826 
2827       break;
2828     }
2829 
2830     case Decl::Function: {
2831       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2832         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2833           type = Context.BuiltinFnTy;
2834           valueKind = VK_RValue;
2835           break;
2836         }
2837       }
2838 
2839       const FunctionType *fty = type->castAs<FunctionType>();
2840 
2841       // If we're referring to a function with an __unknown_anytype
2842       // result type, make the entire expression __unknown_anytype.
2843       if (fty->getReturnType() == Context.UnknownAnyTy) {
2844         type = Context.UnknownAnyTy;
2845         valueKind = VK_RValue;
2846         break;
2847       }
2848 
2849       // Functions are l-values in C++.
2850       if (getLangOpts().CPlusPlus) {
2851         valueKind = VK_LValue;
2852         break;
2853       }
2854 
2855       // C99 DR 316 says that, if a function type comes from a
2856       // function definition (without a prototype), that type is only
2857       // used for checking compatibility. Therefore, when referencing
2858       // the function, we pretend that we don't have the full function
2859       // type.
2860       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2861           isa<FunctionProtoType>(fty))
2862         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2863                                               fty->getExtInfo());
2864 
2865       // Functions are r-values in C.
2866       valueKind = VK_RValue;
2867       break;
2868     }
2869 
2870     case Decl::MSProperty:
2871       valueKind = VK_LValue;
2872       break;
2873 
2874     case Decl::CXXMethod:
2875       // If we're referring to a method with an __unknown_anytype
2876       // result type, make the entire expression __unknown_anytype.
2877       // This should only be possible with a type written directly.
2878       if (const FunctionProtoType *proto
2879             = dyn_cast<FunctionProtoType>(VD->getType()))
2880         if (proto->getReturnType() == Context.UnknownAnyTy) {
2881           type = Context.UnknownAnyTy;
2882           valueKind = VK_RValue;
2883           break;
2884         }
2885 
2886       // C++ methods are l-values if static, r-values if non-static.
2887       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2888         valueKind = VK_LValue;
2889         break;
2890       }
2891       // fallthrough
2892 
2893     case Decl::CXXConversion:
2894     case Decl::CXXDestructor:
2895     case Decl::CXXConstructor:
2896       valueKind = VK_RValue;
2897       break;
2898     }
2899 
2900     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2901                             TemplateArgs);
2902   }
2903 }
2904 
2905 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2906                                      PredefinedExpr::IdentType IT) {
2907   // Pick the current block, lambda, captured statement or function.
2908   Decl *currentDecl = nullptr;
2909   if (const BlockScopeInfo *BSI = getCurBlock())
2910     currentDecl = BSI->TheDecl;
2911   else if (const LambdaScopeInfo *LSI = getCurLambda())
2912     currentDecl = LSI->CallOperator;
2913   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2914     currentDecl = CSI->TheCapturedDecl;
2915   else
2916     currentDecl = getCurFunctionOrMethodDecl();
2917 
2918   if (!currentDecl) {
2919     Diag(Loc, diag::ext_predef_outside_function);
2920     currentDecl = Context.getTranslationUnitDecl();
2921   }
2922 
2923   QualType ResTy;
2924   if (cast<DeclContext>(currentDecl)->isDependentContext())
2925     ResTy = Context.DependentTy;
2926   else {
2927     // Pre-defined identifiers are of type char[x], where x is the length of
2928     // the string.
2929     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2930 
2931     llvm::APInt LengthI(32, Length + 1);
2932     if (IT == PredefinedExpr::LFunction)
2933       ResTy = Context.WideCharTy.withConst();
2934     else
2935       ResTy = Context.CharTy.withConst();
2936     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2937   }
2938 
2939   return new (Context) PredefinedExpr(Loc, ResTy, IT);
2940 }
2941 
2942 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2943   PredefinedExpr::IdentType IT;
2944 
2945   switch (Kind) {
2946   default: llvm_unreachable("Unknown simple primary expr!");
2947   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2948   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2949   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2950   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2951   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2952   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2953   }
2954 
2955   return BuildPredefinedExpr(Loc, IT);
2956 }
2957 
2958 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2959   SmallString<16> CharBuffer;
2960   bool Invalid = false;
2961   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2962   if (Invalid)
2963     return ExprError();
2964 
2965   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2966                             PP, Tok.getKind());
2967   if (Literal.hadError())
2968     return ExprError();
2969 
2970   QualType Ty;
2971   if (Literal.isWide())
2972     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2973   else if (Literal.isUTF16())
2974     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2975   else if (Literal.isUTF32())
2976     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2977   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2978     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2979   else
2980     Ty = Context.CharTy;  // 'x' -> char in C++
2981 
2982   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2983   if (Literal.isWide())
2984     Kind = CharacterLiteral::Wide;
2985   else if (Literal.isUTF16())
2986     Kind = CharacterLiteral::UTF16;
2987   else if (Literal.isUTF32())
2988     Kind = CharacterLiteral::UTF32;
2989 
2990   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2991                                              Tok.getLocation());
2992 
2993   if (Literal.getUDSuffix().empty())
2994     return Lit;
2995 
2996   // We're building a user-defined literal.
2997   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2998   SourceLocation UDSuffixLoc =
2999     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3000 
3001   // Make sure we're allowed user-defined literals here.
3002   if (!UDLScope)
3003     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3004 
3005   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3006   //   operator "" X (ch)
3007   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3008                                         Lit, Tok.getLocation());
3009 }
3010 
3011 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3012   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3013   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3014                                 Context.IntTy, Loc);
3015 }
3016 
3017 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3018                                   QualType Ty, SourceLocation Loc) {
3019   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3020 
3021   using llvm::APFloat;
3022   APFloat Val(Format);
3023 
3024   APFloat::opStatus result = Literal.GetFloatValue(Val);
3025 
3026   // Overflow is always an error, but underflow is only an error if
3027   // we underflowed to zero (APFloat reports denormals as underflow).
3028   if ((result & APFloat::opOverflow) ||
3029       ((result & APFloat::opUnderflow) && Val.isZero())) {
3030     unsigned diagnostic;
3031     SmallString<20> buffer;
3032     if (result & APFloat::opOverflow) {
3033       diagnostic = diag::warn_float_overflow;
3034       APFloat::getLargest(Format).toString(buffer);
3035     } else {
3036       diagnostic = diag::warn_float_underflow;
3037       APFloat::getSmallest(Format).toString(buffer);
3038     }
3039 
3040     S.Diag(Loc, diagnostic)
3041       << Ty
3042       << StringRef(buffer.data(), buffer.size());
3043   }
3044 
3045   bool isExact = (result == APFloat::opOK);
3046   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3047 }
3048 
3049 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3050   // Fast path for a single digit (which is quite common).  A single digit
3051   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3052   if (Tok.getLength() == 1) {
3053     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3054     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3055   }
3056 
3057   SmallString<128> SpellingBuffer;
3058   // NumericLiteralParser wants to overread by one character.  Add padding to
3059   // the buffer in case the token is copied to the buffer.  If getSpelling()
3060   // returns a StringRef to the memory buffer, it should have a null char at
3061   // the EOF, so it is also safe.
3062   SpellingBuffer.resize(Tok.getLength() + 1);
3063 
3064   // Get the spelling of the token, which eliminates trigraphs, etc.
3065   bool Invalid = false;
3066   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3067   if (Invalid)
3068     return ExprError();
3069 
3070   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3071   if (Literal.hadError)
3072     return ExprError();
3073 
3074   if (Literal.hasUDSuffix()) {
3075     // We're building a user-defined literal.
3076     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3077     SourceLocation UDSuffixLoc =
3078       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3079 
3080     // Make sure we're allowed user-defined literals here.
3081     if (!UDLScope)
3082       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3083 
3084     QualType CookedTy;
3085     if (Literal.isFloatingLiteral()) {
3086       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3087       // long double, the literal is treated as a call of the form
3088       //   operator "" X (f L)
3089       CookedTy = Context.LongDoubleTy;
3090     } else {
3091       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3092       // unsigned long long, the literal is treated as a call of the form
3093       //   operator "" X (n ULL)
3094       CookedTy = Context.UnsignedLongLongTy;
3095     }
3096 
3097     DeclarationName OpName =
3098       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3099     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3100     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3101 
3102     SourceLocation TokLoc = Tok.getLocation();
3103 
3104     // Perform literal operator lookup to determine if we're building a raw
3105     // literal or a cooked one.
3106     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3107     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3108                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3109                                   /*AllowStringTemplate*/false)) {
3110     case LOLR_Error:
3111       return ExprError();
3112 
3113     case LOLR_Cooked: {
3114       Expr *Lit;
3115       if (Literal.isFloatingLiteral()) {
3116         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3117       } else {
3118         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3119         if (Literal.GetIntegerValue(ResultVal))
3120           Diag(Tok.getLocation(), diag::err_integer_too_large);
3121         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3122                                      Tok.getLocation());
3123       }
3124       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3125     }
3126 
3127     case LOLR_Raw: {
3128       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3129       // literal is treated as a call of the form
3130       //   operator "" X ("n")
3131       unsigned Length = Literal.getUDSuffixOffset();
3132       QualType StrTy = Context.getConstantArrayType(
3133           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3134           ArrayType::Normal, 0);
3135       Expr *Lit = StringLiteral::Create(
3136           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3137           /*Pascal*/false, StrTy, &TokLoc, 1);
3138       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3139     }
3140 
3141     case LOLR_Template: {
3142       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3143       // template), L is treated as a call fo the form
3144       //   operator "" X <'c1', 'c2', ... 'ck'>()
3145       // where n is the source character sequence c1 c2 ... ck.
3146       TemplateArgumentListInfo ExplicitArgs;
3147       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3148       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3149       llvm::APSInt Value(CharBits, CharIsUnsigned);
3150       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3151         Value = TokSpelling[I];
3152         TemplateArgument Arg(Context, Value, Context.CharTy);
3153         TemplateArgumentLocInfo ArgInfo;
3154         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3155       }
3156       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3157                                       &ExplicitArgs);
3158     }
3159     case LOLR_StringTemplate:
3160       llvm_unreachable("unexpected literal operator lookup result");
3161     }
3162   }
3163 
3164   Expr *Res;
3165 
3166   if (Literal.isFloatingLiteral()) {
3167     QualType Ty;
3168     if (Literal.isFloat)
3169       Ty = Context.FloatTy;
3170     else if (!Literal.isLong)
3171       Ty = Context.DoubleTy;
3172     else
3173       Ty = Context.LongDoubleTy;
3174 
3175     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3176 
3177     if (Ty == Context.DoubleTy) {
3178       if (getLangOpts().SinglePrecisionConstants) {
3179         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3180       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3181         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3182         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3183       }
3184     }
3185   } else if (!Literal.isIntegerLiteral()) {
3186     return ExprError();
3187   } else {
3188     QualType Ty;
3189 
3190     // 'long long' is a C99 or C++11 feature.
3191     if (!getLangOpts().C99 && Literal.isLongLong) {
3192       if (getLangOpts().CPlusPlus)
3193         Diag(Tok.getLocation(),
3194              getLangOpts().CPlusPlus11 ?
3195              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3196       else
3197         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3198     }
3199 
3200     // Get the value in the widest-possible width.
3201     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3202     // The microsoft literal suffix extensions support 128-bit literals, which
3203     // may be wider than [u]intmax_t.
3204     // FIXME: Actually, they don't. We seem to have accidentally invented the
3205     //        i128 suffix.
3206     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3207         Context.getTargetInfo().hasInt128Type())
3208       MaxWidth = 128;
3209     llvm::APInt ResultVal(MaxWidth, 0);
3210 
3211     if (Literal.GetIntegerValue(ResultVal)) {
3212       // If this value didn't fit into uintmax_t, error and force to ull.
3213       Diag(Tok.getLocation(), diag::err_integer_too_large);
3214       Ty = Context.UnsignedLongLongTy;
3215       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3216              "long long is not intmax_t?");
3217     } else {
3218       // If this value fits into a ULL, try to figure out what else it fits into
3219       // according to the rules of C99 6.4.4.1p5.
3220 
3221       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3222       // be an unsigned int.
3223       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3224 
3225       // Check from smallest to largest, picking the smallest type we can.
3226       unsigned Width = 0;
3227 
3228       // Microsoft specific integer suffixes are explicitly sized.
3229       if (Literal.MicrosoftInteger) {
3230         if (Literal.MicrosoftInteger > MaxWidth) {
3231           // If this target doesn't support __int128, error and force to ull.
3232           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3233           Width = MaxWidth;
3234           Ty = Context.getIntMaxType();
3235         } else {
3236           Width = Literal.MicrosoftInteger;
3237           Ty = Context.getIntTypeForBitwidth(Width,
3238                                              /*Signed=*/!Literal.isUnsigned);
3239         }
3240       }
3241 
3242       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3243         // Are int/unsigned possibilities?
3244         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3245 
3246         // Does it fit in a unsigned int?
3247         if (ResultVal.isIntN(IntSize)) {
3248           // Does it fit in a signed int?
3249           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3250             Ty = Context.IntTy;
3251           else if (AllowUnsigned)
3252             Ty = Context.UnsignedIntTy;
3253           Width = IntSize;
3254         }
3255       }
3256 
3257       // Are long/unsigned long possibilities?
3258       if (Ty.isNull() && !Literal.isLongLong) {
3259         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3260 
3261         // Does it fit in a unsigned long?
3262         if (ResultVal.isIntN(LongSize)) {
3263           // Does it fit in a signed long?
3264           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3265             Ty = Context.LongTy;
3266           else if (AllowUnsigned)
3267             Ty = Context.UnsignedLongTy;
3268           Width = LongSize;
3269         }
3270       }
3271 
3272       // Check long long if needed.
3273       if (Ty.isNull()) {
3274         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3275 
3276         // Does it fit in a unsigned long long?
3277         if (ResultVal.isIntN(LongLongSize)) {
3278           // Does it fit in a signed long long?
3279           // To be compatible with MSVC, hex integer literals ending with the
3280           // LL or i64 suffix are always signed in Microsoft mode.
3281           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3282               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3283             Ty = Context.LongLongTy;
3284           else if (AllowUnsigned)
3285             Ty = Context.UnsignedLongLongTy;
3286           Width = LongLongSize;
3287         }
3288       }
3289 
3290       // If we still couldn't decide a type, we probably have something that
3291       // does not fit in a signed long long, but has no U suffix.
3292       if (Ty.isNull()) {
3293         Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed);
3294         Ty = Context.UnsignedLongLongTy;
3295         Width = Context.getTargetInfo().getLongLongWidth();
3296       }
3297 
3298       if (ResultVal.getBitWidth() != Width)
3299         ResultVal = ResultVal.trunc(Width);
3300     }
3301     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3302   }
3303 
3304   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3305   if (Literal.isImaginary)
3306     Res = new (Context) ImaginaryLiteral(Res,
3307                                         Context.getComplexType(Res->getType()));
3308 
3309   return Res;
3310 }
3311 
3312 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3313   assert(E && "ActOnParenExpr() missing expr");
3314   return new (Context) ParenExpr(L, R, E);
3315 }
3316 
3317 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3318                                          SourceLocation Loc,
3319                                          SourceRange ArgRange) {
3320   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3321   // scalar or vector data type argument..."
3322   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3323   // type (C99 6.2.5p18) or void.
3324   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3325     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3326       << T << ArgRange;
3327     return true;
3328   }
3329 
3330   assert((T->isVoidType() || !T->isIncompleteType()) &&
3331          "Scalar types should always be complete");
3332   return false;
3333 }
3334 
3335 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3336                                            SourceLocation Loc,
3337                                            SourceRange ArgRange,
3338                                            UnaryExprOrTypeTrait TraitKind) {
3339   // Invalid types must be hard errors for SFINAE in C++.
3340   if (S.LangOpts.CPlusPlus)
3341     return true;
3342 
3343   // C99 6.5.3.4p1:
3344   if (T->isFunctionType() &&
3345       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3346     // sizeof(function)/alignof(function) is allowed as an extension.
3347     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3348       << TraitKind << ArgRange;
3349     return false;
3350   }
3351 
3352   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3353   // this is an error (OpenCL v1.1 s6.3.k)
3354   if (T->isVoidType()) {
3355     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3356                                         : diag::ext_sizeof_alignof_void_type;
3357     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3358     return false;
3359   }
3360 
3361   return true;
3362 }
3363 
3364 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3365                                              SourceLocation Loc,
3366                                              SourceRange ArgRange,
3367                                              UnaryExprOrTypeTrait TraitKind) {
3368   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3369   // runtime doesn't allow it.
3370   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3371     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3372       << T << (TraitKind == UETT_SizeOf)
3373       << ArgRange;
3374     return true;
3375   }
3376 
3377   return false;
3378 }
3379 
3380 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3381 /// pointer type is equal to T) and emit a warning if it is.
3382 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3383                                      Expr *E) {
3384   // Don't warn if the operation changed the type.
3385   if (T != E->getType())
3386     return;
3387 
3388   // Now look for array decays.
3389   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3390   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3391     return;
3392 
3393   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3394                                              << ICE->getType()
3395                                              << ICE->getSubExpr()->getType();
3396 }
3397 
3398 /// \brief Check the constraints on expression operands to unary type expression
3399 /// and type traits.
3400 ///
3401 /// Completes any types necessary and validates the constraints on the operand
3402 /// expression. The logic mostly mirrors the type-based overload, but may modify
3403 /// the expression as it completes the type for that expression through template
3404 /// instantiation, etc.
3405 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3406                                             UnaryExprOrTypeTrait ExprKind) {
3407   QualType ExprTy = E->getType();
3408   assert(!ExprTy->isReferenceType());
3409 
3410   if (ExprKind == UETT_VecStep)
3411     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3412                                         E->getSourceRange());
3413 
3414   // Whitelist some types as extensions
3415   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3416                                       E->getSourceRange(), ExprKind))
3417     return false;
3418 
3419   // 'alignof' applied to an expression only requires the base element type of
3420   // the expression to be complete. 'sizeof' requires the expression's type to
3421   // be complete (and will attempt to complete it if it's an array of unknown
3422   // bound).
3423   if (ExprKind == UETT_AlignOf) {
3424     if (RequireCompleteType(E->getExprLoc(),
3425                             Context.getBaseElementType(E->getType()),
3426                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3427                             E->getSourceRange()))
3428       return true;
3429   } else {
3430     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3431                                 ExprKind, E->getSourceRange()))
3432       return true;
3433   }
3434 
3435   // Completing the expression's type may have changed it.
3436   ExprTy = E->getType();
3437   assert(!ExprTy->isReferenceType());
3438 
3439   if (ExprTy->isFunctionType()) {
3440     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3441       << ExprKind << E->getSourceRange();
3442     return true;
3443   }
3444 
3445   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3446                                        E->getSourceRange(), ExprKind))
3447     return true;
3448 
3449   if (ExprKind == UETT_SizeOf) {
3450     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3451       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3452         QualType OType = PVD->getOriginalType();
3453         QualType Type = PVD->getType();
3454         if (Type->isPointerType() && OType->isArrayType()) {
3455           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3456             << Type << OType;
3457           Diag(PVD->getLocation(), diag::note_declared_at);
3458         }
3459       }
3460     }
3461 
3462     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3463     // decays into a pointer and returns an unintended result. This is most
3464     // likely a typo for "sizeof(array) op x".
3465     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3466       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3467                                BO->getLHS());
3468       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3469                                BO->getRHS());
3470     }
3471   }
3472 
3473   return false;
3474 }
3475 
3476 /// \brief Check the constraints on operands to unary expression and type
3477 /// traits.
3478 ///
3479 /// This will complete any types necessary, and validate the various constraints
3480 /// on those operands.
3481 ///
3482 /// The UsualUnaryConversions() function is *not* called by this routine.
3483 /// C99 6.3.2.1p[2-4] all state:
3484 ///   Except when it is the operand of the sizeof operator ...
3485 ///
3486 /// C++ [expr.sizeof]p4
3487 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3488 ///   standard conversions are not applied to the operand of sizeof.
3489 ///
3490 /// This policy is followed for all of the unary trait expressions.
3491 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3492                                             SourceLocation OpLoc,
3493                                             SourceRange ExprRange,
3494                                             UnaryExprOrTypeTrait ExprKind) {
3495   if (ExprType->isDependentType())
3496     return false;
3497 
3498   // C++ [expr.sizeof]p2:
3499   //     When applied to a reference or a reference type, the result
3500   //     is the size of the referenced type.
3501   // C++11 [expr.alignof]p3:
3502   //     When alignof is applied to a reference type, the result
3503   //     shall be the alignment of the referenced type.
3504   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3505     ExprType = Ref->getPointeeType();
3506 
3507   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3508   //   When alignof or _Alignof is applied to an array type, the result
3509   //   is the alignment of the element type.
3510   if (ExprKind == UETT_AlignOf)
3511     ExprType = Context.getBaseElementType(ExprType);
3512 
3513   if (ExprKind == UETT_VecStep)
3514     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3515 
3516   // Whitelist some types as extensions
3517   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3518                                       ExprKind))
3519     return false;
3520 
3521   if (RequireCompleteType(OpLoc, ExprType,
3522                           diag::err_sizeof_alignof_incomplete_type,
3523                           ExprKind, ExprRange))
3524     return true;
3525 
3526   if (ExprType->isFunctionType()) {
3527     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3528       << ExprKind << ExprRange;
3529     return true;
3530   }
3531 
3532   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3533                                        ExprKind))
3534     return true;
3535 
3536   return false;
3537 }
3538 
3539 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3540   E = E->IgnoreParens();
3541 
3542   // Cannot know anything else if the expression is dependent.
3543   if (E->isTypeDependent())
3544     return false;
3545 
3546   if (E->getObjectKind() == OK_BitField) {
3547     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3548        << 1 << E->getSourceRange();
3549     return true;
3550   }
3551 
3552   ValueDecl *D = nullptr;
3553   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3554     D = DRE->getDecl();
3555   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3556     D = ME->getMemberDecl();
3557   }
3558 
3559   // If it's a field, require the containing struct to have a
3560   // complete definition so that we can compute the layout.
3561   //
3562   // This can happen in C++11 onwards, either by naming the member
3563   // in a way that is not transformed into a member access expression
3564   // (in an unevaluated operand, for instance), or by naming the member
3565   // in a trailing-return-type.
3566   //
3567   // For the record, since __alignof__ on expressions is a GCC
3568   // extension, GCC seems to permit this but always gives the
3569   // nonsensical answer 0.
3570   //
3571   // We don't really need the layout here --- we could instead just
3572   // directly check for all the appropriate alignment-lowing
3573   // attributes --- but that would require duplicating a lot of
3574   // logic that just isn't worth duplicating for such a marginal
3575   // use-case.
3576   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3577     // Fast path this check, since we at least know the record has a
3578     // definition if we can find a member of it.
3579     if (!FD->getParent()->isCompleteDefinition()) {
3580       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3581         << E->getSourceRange();
3582       return true;
3583     }
3584 
3585     // Otherwise, if it's a field, and the field doesn't have
3586     // reference type, then it must have a complete type (or be a
3587     // flexible array member, which we explicitly want to
3588     // white-list anyway), which makes the following checks trivial.
3589     if (!FD->getType()->isReferenceType())
3590       return false;
3591   }
3592 
3593   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3594 }
3595 
3596 bool Sema::CheckVecStepExpr(Expr *E) {
3597   E = E->IgnoreParens();
3598 
3599   // Cannot know anything else if the expression is dependent.
3600   if (E->isTypeDependent())
3601     return false;
3602 
3603   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3604 }
3605 
3606 /// \brief Build a sizeof or alignof expression given a type operand.
3607 ExprResult
3608 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3609                                      SourceLocation OpLoc,
3610                                      UnaryExprOrTypeTrait ExprKind,
3611                                      SourceRange R) {
3612   if (!TInfo)
3613     return ExprError();
3614 
3615   QualType T = TInfo->getType();
3616 
3617   if (!T->isDependentType() &&
3618       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3619     return ExprError();
3620 
3621   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3622   return new (Context) UnaryExprOrTypeTraitExpr(
3623       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3624 }
3625 
3626 /// \brief Build a sizeof or alignof expression given an expression
3627 /// operand.
3628 ExprResult
3629 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3630                                      UnaryExprOrTypeTrait ExprKind) {
3631   ExprResult PE = CheckPlaceholderExpr(E);
3632   if (PE.isInvalid())
3633     return ExprError();
3634 
3635   E = PE.get();
3636 
3637   // Verify that the operand is valid.
3638   bool isInvalid = false;
3639   if (E->isTypeDependent()) {
3640     // Delay type-checking for type-dependent expressions.
3641   } else if (ExprKind == UETT_AlignOf) {
3642     isInvalid = CheckAlignOfExpr(*this, E);
3643   } else if (ExprKind == UETT_VecStep) {
3644     isInvalid = CheckVecStepExpr(E);
3645   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3646     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3647     isInvalid = true;
3648   } else {
3649     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3650   }
3651 
3652   if (isInvalid)
3653     return ExprError();
3654 
3655   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3656     PE = TransformToPotentiallyEvaluated(E);
3657     if (PE.isInvalid()) return ExprError();
3658     E = PE.get();
3659   }
3660 
3661   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3662   return new (Context) UnaryExprOrTypeTraitExpr(
3663       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3664 }
3665 
3666 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3667 /// expr and the same for @c alignof and @c __alignof
3668 /// Note that the ArgRange is invalid if isType is false.
3669 ExprResult
3670 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3671                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3672                                     void *TyOrEx, const SourceRange &ArgRange) {
3673   // If error parsing type, ignore.
3674   if (!TyOrEx) return ExprError();
3675 
3676   if (IsType) {
3677     TypeSourceInfo *TInfo;
3678     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3679     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3680   }
3681 
3682   Expr *ArgEx = (Expr *)TyOrEx;
3683   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3684   return Result;
3685 }
3686 
3687 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3688                                      bool IsReal) {
3689   if (V.get()->isTypeDependent())
3690     return S.Context.DependentTy;
3691 
3692   // _Real and _Imag are only l-values for normal l-values.
3693   if (V.get()->getObjectKind() != OK_Ordinary) {
3694     V = S.DefaultLvalueConversion(V.get());
3695     if (V.isInvalid())
3696       return QualType();
3697   }
3698 
3699   // These operators return the element type of a complex type.
3700   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3701     return CT->getElementType();
3702 
3703   // Otherwise they pass through real integer and floating point types here.
3704   if (V.get()->getType()->isArithmeticType())
3705     return V.get()->getType();
3706 
3707   // Test for placeholders.
3708   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3709   if (PR.isInvalid()) return QualType();
3710   if (PR.get() != V.get()) {
3711     V = PR;
3712     return CheckRealImagOperand(S, V, Loc, IsReal);
3713   }
3714 
3715   // Reject anything else.
3716   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3717     << (IsReal ? "__real" : "__imag");
3718   return QualType();
3719 }
3720 
3721 
3722 
3723 ExprResult
3724 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3725                           tok::TokenKind Kind, Expr *Input) {
3726   UnaryOperatorKind Opc;
3727   switch (Kind) {
3728   default: llvm_unreachable("Unknown unary op!");
3729   case tok::plusplus:   Opc = UO_PostInc; break;
3730   case tok::minusminus: Opc = UO_PostDec; break;
3731   }
3732 
3733   // Since this might is a postfix expression, get rid of ParenListExprs.
3734   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3735   if (Result.isInvalid()) return ExprError();
3736   Input = Result.get();
3737 
3738   return BuildUnaryOp(S, OpLoc, Opc, Input);
3739 }
3740 
3741 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3742 ///
3743 /// \return true on error
3744 static bool checkArithmeticOnObjCPointer(Sema &S,
3745                                          SourceLocation opLoc,
3746                                          Expr *op) {
3747   assert(op->getType()->isObjCObjectPointerType());
3748   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3749       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3750     return false;
3751 
3752   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3753     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3754     << op->getSourceRange();
3755   return true;
3756 }
3757 
3758 ExprResult
3759 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3760                               Expr *idx, SourceLocation rbLoc) {
3761   // Since this might be a postfix expression, get rid of ParenListExprs.
3762   if (isa<ParenListExpr>(base)) {
3763     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3764     if (result.isInvalid()) return ExprError();
3765     base = result.get();
3766   }
3767 
3768   // Handle any non-overload placeholder types in the base and index
3769   // expressions.  We can't handle overloads here because the other
3770   // operand might be an overloadable type, in which case the overload
3771   // resolution for the operator overload should get the first crack
3772   // at the overload.
3773   if (base->getType()->isNonOverloadPlaceholderType()) {
3774     ExprResult result = CheckPlaceholderExpr(base);
3775     if (result.isInvalid()) return ExprError();
3776     base = result.get();
3777   }
3778   if (idx->getType()->isNonOverloadPlaceholderType()) {
3779     ExprResult result = CheckPlaceholderExpr(idx);
3780     if (result.isInvalid()) return ExprError();
3781     idx = result.get();
3782   }
3783 
3784   // Build an unanalyzed expression if either operand is type-dependent.
3785   if (getLangOpts().CPlusPlus &&
3786       (base->isTypeDependent() || idx->isTypeDependent())) {
3787     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3788                                             VK_LValue, OK_Ordinary, rbLoc);
3789   }
3790 
3791   // Use C++ overloaded-operator rules if either operand has record
3792   // type.  The spec says to do this if either type is *overloadable*,
3793   // but enum types can't declare subscript operators or conversion
3794   // operators, so there's nothing interesting for overload resolution
3795   // to do if there aren't any record types involved.
3796   //
3797   // ObjC pointers have their own subscripting logic that is not tied
3798   // to overload resolution and so should not take this path.
3799   if (getLangOpts().CPlusPlus &&
3800       (base->getType()->isRecordType() ||
3801        (!base->getType()->isObjCObjectPointerType() &&
3802         idx->getType()->isRecordType()))) {
3803     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3804   }
3805 
3806   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3807 }
3808 
3809 ExprResult
3810 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3811                                       Expr *Idx, SourceLocation RLoc) {
3812   Expr *LHSExp = Base;
3813   Expr *RHSExp = Idx;
3814 
3815   // Perform default conversions.
3816   if (!LHSExp->getType()->getAs<VectorType>()) {
3817     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3818     if (Result.isInvalid())
3819       return ExprError();
3820     LHSExp = Result.get();
3821   }
3822   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3823   if (Result.isInvalid())
3824     return ExprError();
3825   RHSExp = Result.get();
3826 
3827   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3828   ExprValueKind VK = VK_LValue;
3829   ExprObjectKind OK = OK_Ordinary;
3830 
3831   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3832   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3833   // in the subscript position. As a result, we need to derive the array base
3834   // and index from the expression types.
3835   Expr *BaseExpr, *IndexExpr;
3836   QualType ResultType;
3837   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3838     BaseExpr = LHSExp;
3839     IndexExpr = RHSExp;
3840     ResultType = Context.DependentTy;
3841   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3842     BaseExpr = LHSExp;
3843     IndexExpr = RHSExp;
3844     ResultType = PTy->getPointeeType();
3845   } else if (const ObjCObjectPointerType *PTy =
3846                LHSTy->getAs<ObjCObjectPointerType>()) {
3847     BaseExpr = LHSExp;
3848     IndexExpr = RHSExp;
3849 
3850     // Use custom logic if this should be the pseudo-object subscript
3851     // expression.
3852     if (!LangOpts.isSubscriptPointerArithmetic())
3853       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3854                                           nullptr);
3855 
3856     ResultType = PTy->getPointeeType();
3857   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3858      // Handle the uncommon case of "123[Ptr]".
3859     BaseExpr = RHSExp;
3860     IndexExpr = LHSExp;
3861     ResultType = PTy->getPointeeType();
3862   } else if (const ObjCObjectPointerType *PTy =
3863                RHSTy->getAs<ObjCObjectPointerType>()) {
3864      // Handle the uncommon case of "123[Ptr]".
3865     BaseExpr = RHSExp;
3866     IndexExpr = LHSExp;
3867     ResultType = PTy->getPointeeType();
3868     if (!LangOpts.isSubscriptPointerArithmetic()) {
3869       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3870         << ResultType << BaseExpr->getSourceRange();
3871       return ExprError();
3872     }
3873   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3874     BaseExpr = LHSExp;    // vectors: V[123]
3875     IndexExpr = RHSExp;
3876     VK = LHSExp->getValueKind();
3877     if (VK != VK_RValue)
3878       OK = OK_VectorComponent;
3879 
3880     // FIXME: need to deal with const...
3881     ResultType = VTy->getElementType();
3882   } else if (LHSTy->isArrayType()) {
3883     // If we see an array that wasn't promoted by
3884     // DefaultFunctionArrayLvalueConversion, it must be an array that
3885     // wasn't promoted because of the C90 rule that doesn't
3886     // allow promoting non-lvalue arrays.  Warn, then
3887     // force the promotion here.
3888     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3889         LHSExp->getSourceRange();
3890     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3891                                CK_ArrayToPointerDecay).get();
3892     LHSTy = LHSExp->getType();
3893 
3894     BaseExpr = LHSExp;
3895     IndexExpr = RHSExp;
3896     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3897   } else if (RHSTy->isArrayType()) {
3898     // Same as previous, except for 123[f().a] case
3899     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3900         RHSExp->getSourceRange();
3901     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3902                                CK_ArrayToPointerDecay).get();
3903     RHSTy = RHSExp->getType();
3904 
3905     BaseExpr = RHSExp;
3906     IndexExpr = LHSExp;
3907     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3908   } else {
3909     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3910        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3911   }
3912   // C99 6.5.2.1p1
3913   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3914     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3915                      << IndexExpr->getSourceRange());
3916 
3917   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3918        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3919          && !IndexExpr->isTypeDependent())
3920     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3921 
3922   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3923   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3924   // type. Note that Functions are not objects, and that (in C99 parlance)
3925   // incomplete types are not object types.
3926   if (ResultType->isFunctionType()) {
3927     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3928       << ResultType << BaseExpr->getSourceRange();
3929     return ExprError();
3930   }
3931 
3932   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3933     // GNU extension: subscripting on pointer to void
3934     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3935       << BaseExpr->getSourceRange();
3936 
3937     // C forbids expressions of unqualified void type from being l-values.
3938     // See IsCForbiddenLValueType.
3939     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3940   } else if (!ResultType->isDependentType() &&
3941       RequireCompleteType(LLoc, ResultType,
3942                           diag::err_subscript_incomplete_type, BaseExpr))
3943     return ExprError();
3944 
3945   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3946          !ResultType.isCForbiddenLValueType());
3947 
3948   return new (Context)
3949       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
3950 }
3951 
3952 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3953                                         FunctionDecl *FD,
3954                                         ParmVarDecl *Param) {
3955   if (Param->hasUnparsedDefaultArg()) {
3956     Diag(CallLoc,
3957          diag::err_use_of_default_argument_to_function_declared_later) <<
3958       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3959     Diag(UnparsedDefaultArgLocs[Param],
3960          diag::note_default_argument_declared_here);
3961     return ExprError();
3962   }
3963 
3964   if (Param->hasUninstantiatedDefaultArg()) {
3965     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3966 
3967     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3968                                                  Param);
3969 
3970     // Instantiate the expression.
3971     MultiLevelTemplateArgumentList MutiLevelArgList
3972       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
3973 
3974     InstantiatingTemplate Inst(*this, CallLoc, Param,
3975                                MutiLevelArgList.getInnermost());
3976     if (Inst.isInvalid())
3977       return ExprError();
3978 
3979     ExprResult Result;
3980     {
3981       // C++ [dcl.fct.default]p5:
3982       //   The names in the [default argument] expression are bound, and
3983       //   the semantic constraints are checked, at the point where the
3984       //   default argument expression appears.
3985       ContextRAII SavedContext(*this, FD);
3986       LocalInstantiationScope Local(*this);
3987       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3988     }
3989     if (Result.isInvalid())
3990       return ExprError();
3991 
3992     // Check the expression as an initializer for the parameter.
3993     InitializedEntity Entity
3994       = InitializedEntity::InitializeParameter(Context, Param);
3995     InitializationKind Kind
3996       = InitializationKind::CreateCopy(Param->getLocation(),
3997              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3998     Expr *ResultE = Result.getAs<Expr>();
3999 
4000     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4001     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4002     if (Result.isInvalid())
4003       return ExprError();
4004 
4005     Expr *Arg = Result.getAs<Expr>();
4006     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4007     // Build the default argument expression.
4008     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4009   }
4010 
4011   // If the default expression creates temporaries, we need to
4012   // push them to the current stack of expression temporaries so they'll
4013   // be properly destroyed.
4014   // FIXME: We should really be rebuilding the default argument with new
4015   // bound temporaries; see the comment in PR5810.
4016   // We don't need to do that with block decls, though, because
4017   // blocks in default argument expression can never capture anything.
4018   if (isa<ExprWithCleanups>(Param->getInit())) {
4019     // Set the "needs cleanups" bit regardless of whether there are
4020     // any explicit objects.
4021     ExprNeedsCleanups = true;
4022 
4023     // Append all the objects to the cleanup list.  Right now, this
4024     // should always be a no-op, because blocks in default argument
4025     // expressions should never be able to capture anything.
4026     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4027            "default argument expression has capturing blocks?");
4028   }
4029 
4030   // We already type-checked the argument, so we know it works.
4031   // Just mark all of the declarations in this potentially-evaluated expression
4032   // as being "referenced".
4033   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4034                                    /*SkipLocalVariables=*/true);
4035   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4036 }
4037 
4038 
4039 Sema::VariadicCallType
4040 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4041                           Expr *Fn) {
4042   if (Proto && Proto->isVariadic()) {
4043     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4044       return VariadicConstructor;
4045     else if (Fn && Fn->getType()->isBlockPointerType())
4046       return VariadicBlock;
4047     else if (FDecl) {
4048       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4049         if (Method->isInstance())
4050           return VariadicMethod;
4051     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4052       return VariadicMethod;
4053     return VariadicFunction;
4054   }
4055   return VariadicDoesNotApply;
4056 }
4057 
4058 namespace {
4059 class FunctionCallCCC : public FunctionCallFilterCCC {
4060 public:
4061   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4062                   unsigned NumArgs, MemberExpr *ME)
4063       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4064         FunctionName(FuncName) {}
4065 
4066   bool ValidateCandidate(const TypoCorrection &candidate) override {
4067     if (!candidate.getCorrectionSpecifier() ||
4068         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4069       return false;
4070     }
4071 
4072     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4073   }
4074 
4075 private:
4076   const IdentifierInfo *const FunctionName;
4077 };
4078 }
4079 
4080 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4081                                                FunctionDecl *FDecl,
4082                                                ArrayRef<Expr *> Args) {
4083   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4084   DeclarationName FuncName = FDecl->getDeclName();
4085   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4086   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4087 
4088   if (TypoCorrection Corrected = S.CorrectTypo(
4089           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4090           S.getScopeForContext(S.CurContext), nullptr, CCC,
4091           Sema::CTK_ErrorRecovery)) {
4092     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4093       if (Corrected.isOverloaded()) {
4094         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4095         OverloadCandidateSet::iterator Best;
4096         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4097                                            CDEnd = Corrected.end();
4098              CD != CDEnd; ++CD) {
4099           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4100             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4101                                    OCS);
4102         }
4103         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4104         case OR_Success:
4105           ND = Best->Function;
4106           Corrected.setCorrectionDecl(ND);
4107           break;
4108         default:
4109           break;
4110         }
4111       }
4112       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4113         return Corrected;
4114       }
4115     }
4116   }
4117   return TypoCorrection();
4118 }
4119 
4120 /// ConvertArgumentsForCall - Converts the arguments specified in
4121 /// Args/NumArgs to the parameter types of the function FDecl with
4122 /// function prototype Proto. Call is the call expression itself, and
4123 /// Fn is the function expression. For a C++ member function, this
4124 /// routine does not attempt to convert the object argument. Returns
4125 /// true if the call is ill-formed.
4126 bool
4127 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4128                               FunctionDecl *FDecl,
4129                               const FunctionProtoType *Proto,
4130                               ArrayRef<Expr *> Args,
4131                               SourceLocation RParenLoc,
4132                               bool IsExecConfig) {
4133   // Bail out early if calling a builtin with custom typechecking.
4134   // We don't need to do this in the
4135   if (FDecl)
4136     if (unsigned ID = FDecl->getBuiltinID())
4137       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4138         return false;
4139 
4140   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4141   // assignment, to the types of the corresponding parameter, ...
4142   unsigned NumParams = Proto->getNumParams();
4143   bool Invalid = false;
4144   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4145   unsigned FnKind = Fn->getType()->isBlockPointerType()
4146                        ? 1 /* block */
4147                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4148                                        : 0 /* function */);
4149 
4150   // If too few arguments are available (and we don't have default
4151   // arguments for the remaining parameters), don't make the call.
4152   if (Args.size() < NumParams) {
4153     if (Args.size() < MinArgs) {
4154       TypoCorrection TC;
4155       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4156         unsigned diag_id =
4157             MinArgs == NumParams && !Proto->isVariadic()
4158                 ? diag::err_typecheck_call_too_few_args_suggest
4159                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4160         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4161                                         << static_cast<unsigned>(Args.size())
4162                                         << TC.getCorrectionRange());
4163       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4164         Diag(RParenLoc,
4165              MinArgs == NumParams && !Proto->isVariadic()
4166                  ? diag::err_typecheck_call_too_few_args_one
4167                  : diag::err_typecheck_call_too_few_args_at_least_one)
4168             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4169       else
4170         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4171                             ? diag::err_typecheck_call_too_few_args
4172                             : diag::err_typecheck_call_too_few_args_at_least)
4173             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4174             << Fn->getSourceRange();
4175 
4176       // Emit the location of the prototype.
4177       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4178         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4179           << FDecl;
4180 
4181       return true;
4182     }
4183     Call->setNumArgs(Context, NumParams);
4184   }
4185 
4186   // If too many are passed and not variadic, error on the extras and drop
4187   // them.
4188   if (Args.size() > NumParams) {
4189     if (!Proto->isVariadic()) {
4190       TypoCorrection TC;
4191       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4192         unsigned diag_id =
4193             MinArgs == NumParams && !Proto->isVariadic()
4194                 ? diag::err_typecheck_call_too_many_args_suggest
4195                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4196         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4197                                         << static_cast<unsigned>(Args.size())
4198                                         << TC.getCorrectionRange());
4199       } else if (NumParams == 1 && FDecl &&
4200                  FDecl->getParamDecl(0)->getDeclName())
4201         Diag(Args[NumParams]->getLocStart(),
4202              MinArgs == NumParams
4203                  ? diag::err_typecheck_call_too_many_args_one
4204                  : diag::err_typecheck_call_too_many_args_at_most_one)
4205             << FnKind << FDecl->getParamDecl(0)
4206             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4207             << SourceRange(Args[NumParams]->getLocStart(),
4208                            Args.back()->getLocEnd());
4209       else
4210         Diag(Args[NumParams]->getLocStart(),
4211              MinArgs == NumParams
4212                  ? diag::err_typecheck_call_too_many_args
4213                  : diag::err_typecheck_call_too_many_args_at_most)
4214             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4215             << Fn->getSourceRange()
4216             << SourceRange(Args[NumParams]->getLocStart(),
4217                            Args.back()->getLocEnd());
4218 
4219       // Emit the location of the prototype.
4220       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4221         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4222           << FDecl;
4223 
4224       // This deletes the extra arguments.
4225       Call->setNumArgs(Context, NumParams);
4226       return true;
4227     }
4228   }
4229   SmallVector<Expr *, 8> AllArgs;
4230   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4231 
4232   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4233                                    Proto, 0, Args, AllArgs, CallType);
4234   if (Invalid)
4235     return true;
4236   unsigned TotalNumArgs = AllArgs.size();
4237   for (unsigned i = 0; i < TotalNumArgs; ++i)
4238     Call->setArg(i, AllArgs[i]);
4239 
4240   return false;
4241 }
4242 
4243 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4244                                   const FunctionProtoType *Proto,
4245                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4246                                   SmallVectorImpl<Expr *> &AllArgs,
4247                                   VariadicCallType CallType, bool AllowExplicit,
4248                                   bool IsListInitialization) {
4249   unsigned NumParams = Proto->getNumParams();
4250   bool Invalid = false;
4251   unsigned ArgIx = 0;
4252   // Continue to check argument types (even if we have too few/many args).
4253   for (unsigned i = FirstParam; i < NumParams; i++) {
4254     QualType ProtoArgType = Proto->getParamType(i);
4255 
4256     Expr *Arg;
4257     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4258     if (ArgIx < Args.size()) {
4259       Arg = Args[ArgIx++];
4260 
4261       if (RequireCompleteType(Arg->getLocStart(),
4262                               ProtoArgType,
4263                               diag::err_call_incomplete_argument, Arg))
4264         return true;
4265 
4266       // Strip the unbridged-cast placeholder expression off, if applicable.
4267       bool CFAudited = false;
4268       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4269           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4270           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4271         Arg = stripARCUnbridgedCast(Arg);
4272       else if (getLangOpts().ObjCAutoRefCount &&
4273                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4274                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4275         CFAudited = true;
4276 
4277       InitializedEntity Entity =
4278           Param ? InitializedEntity::InitializeParameter(Context, Param,
4279                                                          ProtoArgType)
4280                 : InitializedEntity::InitializeParameter(
4281                       Context, ProtoArgType, Proto->isParamConsumed(i));
4282 
4283       // Remember that parameter belongs to a CF audited API.
4284       if (CFAudited)
4285         Entity.setParameterCFAudited();
4286 
4287       ExprResult ArgE = PerformCopyInitialization(
4288           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4289       if (ArgE.isInvalid())
4290         return true;
4291 
4292       Arg = ArgE.getAs<Expr>();
4293     } else {
4294       assert(Param && "can't use default arguments without a known callee");
4295 
4296       ExprResult ArgExpr =
4297         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4298       if (ArgExpr.isInvalid())
4299         return true;
4300 
4301       Arg = ArgExpr.getAs<Expr>();
4302     }
4303 
4304     // Check for array bounds violations for each argument to the call. This
4305     // check only triggers warnings when the argument isn't a more complex Expr
4306     // with its own checking, such as a BinaryOperator.
4307     CheckArrayAccess(Arg);
4308 
4309     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4310     CheckStaticArrayArgument(CallLoc, Param, Arg);
4311 
4312     AllArgs.push_back(Arg);
4313   }
4314 
4315   // If this is a variadic call, handle args passed through "...".
4316   if (CallType != VariadicDoesNotApply) {
4317     // Assume that extern "C" functions with variadic arguments that
4318     // return __unknown_anytype aren't *really* variadic.
4319     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4320         FDecl->isExternC()) {
4321       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4322         QualType paramType; // ignored
4323         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4324         Invalid |= arg.isInvalid();
4325         AllArgs.push_back(arg.get());
4326       }
4327 
4328     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4329     } else {
4330       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4331         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4332                                                           FDecl);
4333         Invalid |= Arg.isInvalid();
4334         AllArgs.push_back(Arg.get());
4335       }
4336     }
4337 
4338     // Check for array bounds violations.
4339     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4340       CheckArrayAccess(Args[i]);
4341   }
4342   return Invalid;
4343 }
4344 
4345 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4346   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4347   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4348     TL = DTL.getOriginalLoc();
4349   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4350     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4351       << ATL.getLocalSourceRange();
4352 }
4353 
4354 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4355 /// array parameter, check that it is non-null, and that if it is formed by
4356 /// array-to-pointer decay, the underlying array is sufficiently large.
4357 ///
4358 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4359 /// array type derivation, then for each call to the function, the value of the
4360 /// corresponding actual argument shall provide access to the first element of
4361 /// an array with at least as many elements as specified by the size expression.
4362 void
4363 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4364                                ParmVarDecl *Param,
4365                                const Expr *ArgExpr) {
4366   // Static array parameters are not supported in C++.
4367   if (!Param || getLangOpts().CPlusPlus)
4368     return;
4369 
4370   QualType OrigTy = Param->getOriginalType();
4371 
4372   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4373   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4374     return;
4375 
4376   if (ArgExpr->isNullPointerConstant(Context,
4377                                      Expr::NPC_NeverValueDependent)) {
4378     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4379     DiagnoseCalleeStaticArrayParam(*this, Param);
4380     return;
4381   }
4382 
4383   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4384   if (!CAT)
4385     return;
4386 
4387   const ConstantArrayType *ArgCAT =
4388     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4389   if (!ArgCAT)
4390     return;
4391 
4392   if (ArgCAT->getSize().ult(CAT->getSize())) {
4393     Diag(CallLoc, diag::warn_static_array_too_small)
4394       << ArgExpr->getSourceRange()
4395       << (unsigned) ArgCAT->getSize().getZExtValue()
4396       << (unsigned) CAT->getSize().getZExtValue();
4397     DiagnoseCalleeStaticArrayParam(*this, Param);
4398   }
4399 }
4400 
4401 /// Given a function expression of unknown-any type, try to rebuild it
4402 /// to have a function type.
4403 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4404 
4405 /// Is the given type a placeholder that we need to lower out
4406 /// immediately during argument processing?
4407 static bool isPlaceholderToRemoveAsArg(QualType type) {
4408   // Placeholders are never sugared.
4409   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4410   if (!placeholder) return false;
4411 
4412   switch (placeholder->getKind()) {
4413   // Ignore all the non-placeholder types.
4414 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4415 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4416 #include "clang/AST/BuiltinTypes.def"
4417     return false;
4418 
4419   // We cannot lower out overload sets; they might validly be resolved
4420   // by the call machinery.
4421   case BuiltinType::Overload:
4422     return false;
4423 
4424   // Unbridged casts in ARC can be handled in some call positions and
4425   // should be left in place.
4426   case BuiltinType::ARCUnbridgedCast:
4427     return false;
4428 
4429   // Pseudo-objects should be converted as soon as possible.
4430   case BuiltinType::PseudoObject:
4431     return true;
4432 
4433   // The debugger mode could theoretically but currently does not try
4434   // to resolve unknown-typed arguments based on known parameter types.
4435   case BuiltinType::UnknownAny:
4436     return true;
4437 
4438   // These are always invalid as call arguments and should be reported.
4439   case BuiltinType::BoundMember:
4440   case BuiltinType::BuiltinFn:
4441     return true;
4442   }
4443   llvm_unreachable("bad builtin type kind");
4444 }
4445 
4446 /// Check an argument list for placeholders that we won't try to
4447 /// handle later.
4448 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4449   // Apply this processing to all the arguments at once instead of
4450   // dying at the first failure.
4451   bool hasInvalid = false;
4452   for (size_t i = 0, e = args.size(); i != e; i++) {
4453     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4454       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4455       if (result.isInvalid()) hasInvalid = true;
4456       else args[i] = result.get();
4457     }
4458   }
4459   return hasInvalid;
4460 }
4461 
4462 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4463 /// This provides the location of the left/right parens and a list of comma
4464 /// locations.
4465 ExprResult
4466 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4467                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4468                     Expr *ExecConfig, bool IsExecConfig) {
4469   // Since this might be a postfix expression, get rid of ParenListExprs.
4470   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4471   if (Result.isInvalid()) return ExprError();
4472   Fn = Result.get();
4473 
4474   if (checkArgsForPlaceholders(*this, ArgExprs))
4475     return ExprError();
4476 
4477   if (getLangOpts().CPlusPlus) {
4478     // If this is a pseudo-destructor expression, build the call immediately.
4479     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4480       if (!ArgExprs.empty()) {
4481         // Pseudo-destructor calls should not have any arguments.
4482         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4483           << FixItHint::CreateRemoval(
4484                                     SourceRange(ArgExprs[0]->getLocStart(),
4485                                                 ArgExprs.back()->getLocEnd()));
4486       }
4487 
4488       return new (Context)
4489           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4490     }
4491     if (Fn->getType() == Context.PseudoObjectTy) {
4492       ExprResult result = CheckPlaceholderExpr(Fn);
4493       if (result.isInvalid()) return ExprError();
4494       Fn = result.get();
4495     }
4496 
4497     // Determine whether this is a dependent call inside a C++ template,
4498     // in which case we won't do any semantic analysis now.
4499     // FIXME: Will need to cache the results of name lookup (including ADL) in
4500     // Fn.
4501     bool Dependent = false;
4502     if (Fn->isTypeDependent())
4503       Dependent = true;
4504     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4505       Dependent = true;
4506 
4507     if (Dependent) {
4508       if (ExecConfig) {
4509         return new (Context) CUDAKernelCallExpr(
4510             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4511             Context.DependentTy, VK_RValue, RParenLoc);
4512       } else {
4513         return new (Context) CallExpr(
4514             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4515       }
4516     }
4517 
4518     // Determine whether this is a call to an object (C++ [over.call.object]).
4519     if (Fn->getType()->isRecordType())
4520       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4521                                           RParenLoc);
4522 
4523     if (Fn->getType() == Context.UnknownAnyTy) {
4524       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4525       if (result.isInvalid()) return ExprError();
4526       Fn = result.get();
4527     }
4528 
4529     if (Fn->getType() == Context.BoundMemberTy) {
4530       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4531     }
4532   }
4533 
4534   // Check for overloaded calls.  This can happen even in C due to extensions.
4535   if (Fn->getType() == Context.OverloadTy) {
4536     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4537 
4538     // We aren't supposed to apply this logic for if there's an '&' involved.
4539     if (!find.HasFormOfMemberPointer) {
4540       OverloadExpr *ovl = find.Expression;
4541       if (isa<UnresolvedLookupExpr>(ovl)) {
4542         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4543         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4544                                        RParenLoc, ExecConfig);
4545       } else {
4546         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4547                                          RParenLoc);
4548       }
4549     }
4550   }
4551 
4552   // If we're directly calling a function, get the appropriate declaration.
4553   if (Fn->getType() == Context.UnknownAnyTy) {
4554     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4555     if (result.isInvalid()) return ExprError();
4556     Fn = result.get();
4557   }
4558 
4559   Expr *NakedFn = Fn->IgnoreParens();
4560 
4561   NamedDecl *NDecl = nullptr;
4562   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4563     if (UnOp->getOpcode() == UO_AddrOf)
4564       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4565 
4566   if (isa<DeclRefExpr>(NakedFn))
4567     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4568   else if (isa<MemberExpr>(NakedFn))
4569     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4570 
4571   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4572     if (FD->hasAttr<EnableIfAttr>()) {
4573       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4574         Diag(Fn->getLocStart(),
4575              isa<CXXMethodDecl>(FD) ?
4576                  diag::err_ovl_no_viable_member_function_in_call :
4577                  diag::err_ovl_no_viable_function_in_call)
4578           << FD << FD->getSourceRange();
4579         Diag(FD->getLocation(),
4580              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4581             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4582       }
4583     }
4584   }
4585 
4586   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4587                                ExecConfig, IsExecConfig);
4588 }
4589 
4590 ExprResult
4591 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4592                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4593   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4594   if (!ConfigDecl)
4595     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4596                           << "cudaConfigureCall");
4597   QualType ConfigQTy = ConfigDecl->getType();
4598 
4599   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4600       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4601   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4602 
4603   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
4604                        /*IsExecConfig=*/true);
4605 }
4606 
4607 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4608 ///
4609 /// __builtin_astype( value, dst type )
4610 ///
4611 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4612                                  SourceLocation BuiltinLoc,
4613                                  SourceLocation RParenLoc) {
4614   ExprValueKind VK = VK_RValue;
4615   ExprObjectKind OK = OK_Ordinary;
4616   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4617   QualType SrcTy = E->getType();
4618   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4619     return ExprError(Diag(BuiltinLoc,
4620                           diag::err_invalid_astype_of_different_size)
4621                      << DstTy
4622                      << SrcTy
4623                      << E->getSourceRange());
4624   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4625 }
4626 
4627 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4628 /// provided arguments.
4629 ///
4630 /// __builtin_convertvector( value, dst type )
4631 ///
4632 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4633                                         SourceLocation BuiltinLoc,
4634                                         SourceLocation RParenLoc) {
4635   TypeSourceInfo *TInfo;
4636   GetTypeFromParser(ParsedDestTy, &TInfo);
4637   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4638 }
4639 
4640 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4641 /// i.e. an expression not of \p OverloadTy.  The expression should
4642 /// unary-convert to an expression of function-pointer or
4643 /// block-pointer type.
4644 ///
4645 /// \param NDecl the declaration being called, if available
4646 ExprResult
4647 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4648                             SourceLocation LParenLoc,
4649                             ArrayRef<Expr *> Args,
4650                             SourceLocation RParenLoc,
4651                             Expr *Config, bool IsExecConfig) {
4652   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4653   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4654 
4655   // Promote the function operand.
4656   // We special-case function promotion here because we only allow promoting
4657   // builtin functions to function pointers in the callee of a call.
4658   ExprResult Result;
4659   if (BuiltinID &&
4660       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4661     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4662                                CK_BuiltinFnToFnPtr).get();
4663   } else {
4664     Result = CallExprUnaryConversions(Fn);
4665   }
4666   if (Result.isInvalid())
4667     return ExprError();
4668   Fn = Result.get();
4669 
4670   // Make the call expr early, before semantic checks.  This guarantees cleanup
4671   // of arguments and function on error.
4672   CallExpr *TheCall;
4673   if (Config)
4674     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4675                                                cast<CallExpr>(Config), Args,
4676                                                Context.BoolTy, VK_RValue,
4677                                                RParenLoc);
4678   else
4679     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4680                                      VK_RValue, RParenLoc);
4681 
4682   // Bail out early if calling a builtin with custom typechecking.
4683   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4684     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4685 
4686  retry:
4687   const FunctionType *FuncT;
4688   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4689     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4690     // have type pointer to function".
4691     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4692     if (!FuncT)
4693       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4694                          << Fn->getType() << Fn->getSourceRange());
4695   } else if (const BlockPointerType *BPT =
4696                Fn->getType()->getAs<BlockPointerType>()) {
4697     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4698   } else {
4699     // Handle calls to expressions of unknown-any type.
4700     if (Fn->getType() == Context.UnknownAnyTy) {
4701       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4702       if (rewrite.isInvalid()) return ExprError();
4703       Fn = rewrite.get();
4704       TheCall->setCallee(Fn);
4705       goto retry;
4706     }
4707 
4708     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4709       << Fn->getType() << Fn->getSourceRange());
4710   }
4711 
4712   if (getLangOpts().CUDA) {
4713     if (Config) {
4714       // CUDA: Kernel calls must be to global functions
4715       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4716         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4717             << FDecl->getName() << Fn->getSourceRange());
4718 
4719       // CUDA: Kernel function must have 'void' return type
4720       if (!FuncT->getReturnType()->isVoidType())
4721         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4722             << Fn->getType() << Fn->getSourceRange());
4723     } else {
4724       // CUDA: Calls to global functions must be configured
4725       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4726         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4727             << FDecl->getName() << Fn->getSourceRange());
4728     }
4729   }
4730 
4731   // Check for a valid return type
4732   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4733                           FDecl))
4734     return ExprError();
4735 
4736   // We know the result type of the call, set it.
4737   TheCall->setType(FuncT->getCallResultType(Context));
4738   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4739 
4740   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4741   if (Proto) {
4742     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4743                                 IsExecConfig))
4744       return ExprError();
4745   } else {
4746     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4747 
4748     if (FDecl) {
4749       // Check if we have too few/too many template arguments, based
4750       // on our knowledge of the function definition.
4751       const FunctionDecl *Def = nullptr;
4752       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4753         Proto = Def->getType()->getAs<FunctionProtoType>();
4754        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4755           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4756           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4757       }
4758 
4759       // If the function we're calling isn't a function prototype, but we have
4760       // a function prototype from a prior declaratiom, use that prototype.
4761       if (!FDecl->hasPrototype())
4762         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4763     }
4764 
4765     // Promote the arguments (C99 6.5.2.2p6).
4766     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4767       Expr *Arg = Args[i];
4768 
4769       if (Proto && i < Proto->getNumParams()) {
4770         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4771             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4772         ExprResult ArgE =
4773             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4774         if (ArgE.isInvalid())
4775           return true;
4776 
4777         Arg = ArgE.getAs<Expr>();
4778 
4779       } else {
4780         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4781 
4782         if (ArgE.isInvalid())
4783           return true;
4784 
4785         Arg = ArgE.getAs<Expr>();
4786       }
4787 
4788       if (RequireCompleteType(Arg->getLocStart(),
4789                               Arg->getType(),
4790                               diag::err_call_incomplete_argument, Arg))
4791         return ExprError();
4792 
4793       TheCall->setArg(i, Arg);
4794     }
4795   }
4796 
4797   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4798     if (!Method->isStatic())
4799       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4800         << Fn->getSourceRange());
4801 
4802   // Check for sentinels
4803   if (NDecl)
4804     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4805 
4806   // Do special checking on direct calls to functions.
4807   if (FDecl) {
4808     if (CheckFunctionCall(FDecl, TheCall, Proto))
4809       return ExprError();
4810 
4811     if (BuiltinID)
4812       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4813   } else if (NDecl) {
4814     if (CheckPointerCall(NDecl, TheCall, Proto))
4815       return ExprError();
4816   } else {
4817     if (CheckOtherCall(TheCall, Proto))
4818       return ExprError();
4819   }
4820 
4821   return MaybeBindToTemporary(TheCall);
4822 }
4823 
4824 ExprResult
4825 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4826                            SourceLocation RParenLoc, Expr *InitExpr) {
4827   assert(Ty && "ActOnCompoundLiteral(): missing type");
4828   // FIXME: put back this assert when initializers are worked out.
4829   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4830 
4831   TypeSourceInfo *TInfo;
4832   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4833   if (!TInfo)
4834     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4835 
4836   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4837 }
4838 
4839 ExprResult
4840 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4841                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4842   QualType literalType = TInfo->getType();
4843 
4844   if (literalType->isArrayType()) {
4845     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4846           diag::err_illegal_decl_array_incomplete_type,
4847           SourceRange(LParenLoc,
4848                       LiteralExpr->getSourceRange().getEnd())))
4849       return ExprError();
4850     if (literalType->isVariableArrayType())
4851       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4852         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4853   } else if (!literalType->isDependentType() &&
4854              RequireCompleteType(LParenLoc, literalType,
4855                diag::err_typecheck_decl_incomplete_type,
4856                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4857     return ExprError();
4858 
4859   InitializedEntity Entity
4860     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4861   InitializationKind Kind
4862     = InitializationKind::CreateCStyleCast(LParenLoc,
4863                                            SourceRange(LParenLoc, RParenLoc),
4864                                            /*InitList=*/true);
4865   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4866   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4867                                       &literalType);
4868   if (Result.isInvalid())
4869     return ExprError();
4870   LiteralExpr = Result.get();
4871 
4872   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4873   if (isFileScope &&
4874       !LiteralExpr->isTypeDependent() &&
4875       !LiteralExpr->isValueDependent() &&
4876       !literalType->isDependentType()) { // 6.5.2.5p3
4877     if (CheckForConstantInitializer(LiteralExpr, literalType))
4878       return ExprError();
4879   }
4880 
4881   // In C, compound literals are l-values for some reason.
4882   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4883 
4884   return MaybeBindToTemporary(
4885            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4886                                              VK, LiteralExpr, isFileScope));
4887 }
4888 
4889 ExprResult
4890 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4891                     SourceLocation RBraceLoc) {
4892   // Immediately handle non-overload placeholders.  Overloads can be
4893   // resolved contextually, but everything else here can't.
4894   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4895     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4896       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4897 
4898       // Ignore failures; dropping the entire initializer list because
4899       // of one failure would be terrible for indexing/etc.
4900       if (result.isInvalid()) continue;
4901 
4902       InitArgList[I] = result.get();
4903     }
4904   }
4905 
4906   // Semantic analysis for initializers is done by ActOnDeclarator() and
4907   // CheckInitializer() - it requires knowledge of the object being intialized.
4908 
4909   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4910                                                RBraceLoc);
4911   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4912   return E;
4913 }
4914 
4915 /// Do an explicit extend of the given block pointer if we're in ARC.
4916 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4917   assert(E.get()->getType()->isBlockPointerType());
4918   assert(E.get()->isRValue());
4919 
4920   // Only do this in an r-value context.
4921   if (!S.getLangOpts().ObjCAutoRefCount) return;
4922 
4923   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4924                                CK_ARCExtendBlockObject, E.get(),
4925                                /*base path*/ nullptr, VK_RValue);
4926   S.ExprNeedsCleanups = true;
4927 }
4928 
4929 /// Prepare a conversion of the given expression to an ObjC object
4930 /// pointer type.
4931 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4932   QualType type = E.get()->getType();
4933   if (type->isObjCObjectPointerType()) {
4934     return CK_BitCast;
4935   } else if (type->isBlockPointerType()) {
4936     maybeExtendBlockObject(*this, E);
4937     return CK_BlockPointerToObjCPointerCast;
4938   } else {
4939     assert(type->isPointerType());
4940     return CK_CPointerToObjCPointerCast;
4941   }
4942 }
4943 
4944 /// Prepares for a scalar cast, performing all the necessary stages
4945 /// except the final cast and returning the kind required.
4946 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4947   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4948   // Also, callers should have filtered out the invalid cases with
4949   // pointers.  Everything else should be possible.
4950 
4951   QualType SrcTy = Src.get()->getType();
4952   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4953     return CK_NoOp;
4954 
4955   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4956   case Type::STK_MemberPointer:
4957     llvm_unreachable("member pointer type in C");
4958 
4959   case Type::STK_CPointer:
4960   case Type::STK_BlockPointer:
4961   case Type::STK_ObjCObjectPointer:
4962     switch (DestTy->getScalarTypeKind()) {
4963     case Type::STK_CPointer: {
4964       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4965       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4966       if (SrcAS != DestAS)
4967         return CK_AddressSpaceConversion;
4968       return CK_BitCast;
4969     }
4970     case Type::STK_BlockPointer:
4971       return (SrcKind == Type::STK_BlockPointer
4972                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4973     case Type::STK_ObjCObjectPointer:
4974       if (SrcKind == Type::STK_ObjCObjectPointer)
4975         return CK_BitCast;
4976       if (SrcKind == Type::STK_CPointer)
4977         return CK_CPointerToObjCPointerCast;
4978       maybeExtendBlockObject(*this, Src);
4979       return CK_BlockPointerToObjCPointerCast;
4980     case Type::STK_Bool:
4981       return CK_PointerToBoolean;
4982     case Type::STK_Integral:
4983       return CK_PointerToIntegral;
4984     case Type::STK_Floating:
4985     case Type::STK_FloatingComplex:
4986     case Type::STK_IntegralComplex:
4987     case Type::STK_MemberPointer:
4988       llvm_unreachable("illegal cast from pointer");
4989     }
4990     llvm_unreachable("Should have returned before this");
4991 
4992   case Type::STK_Bool: // casting from bool is like casting from an integer
4993   case Type::STK_Integral:
4994     switch (DestTy->getScalarTypeKind()) {
4995     case Type::STK_CPointer:
4996     case Type::STK_ObjCObjectPointer:
4997     case Type::STK_BlockPointer:
4998       if (Src.get()->isNullPointerConstant(Context,
4999                                            Expr::NPC_ValueDependentIsNull))
5000         return CK_NullToPointer;
5001       return CK_IntegralToPointer;
5002     case Type::STK_Bool:
5003       return CK_IntegralToBoolean;
5004     case Type::STK_Integral:
5005       return CK_IntegralCast;
5006     case Type::STK_Floating:
5007       return CK_IntegralToFloating;
5008     case Type::STK_IntegralComplex:
5009       Src = ImpCastExprToType(Src.get(),
5010                               DestTy->castAs<ComplexType>()->getElementType(),
5011                               CK_IntegralCast);
5012       return CK_IntegralRealToComplex;
5013     case Type::STK_FloatingComplex:
5014       Src = ImpCastExprToType(Src.get(),
5015                               DestTy->castAs<ComplexType>()->getElementType(),
5016                               CK_IntegralToFloating);
5017       return CK_FloatingRealToComplex;
5018     case Type::STK_MemberPointer:
5019       llvm_unreachable("member pointer type in C");
5020     }
5021     llvm_unreachable("Should have returned before this");
5022 
5023   case Type::STK_Floating:
5024     switch (DestTy->getScalarTypeKind()) {
5025     case Type::STK_Floating:
5026       return CK_FloatingCast;
5027     case Type::STK_Bool:
5028       return CK_FloatingToBoolean;
5029     case Type::STK_Integral:
5030       return CK_FloatingToIntegral;
5031     case Type::STK_FloatingComplex:
5032       Src = ImpCastExprToType(Src.get(),
5033                               DestTy->castAs<ComplexType>()->getElementType(),
5034                               CK_FloatingCast);
5035       return CK_FloatingRealToComplex;
5036     case Type::STK_IntegralComplex:
5037       Src = ImpCastExprToType(Src.get(),
5038                               DestTy->castAs<ComplexType>()->getElementType(),
5039                               CK_FloatingToIntegral);
5040       return CK_IntegralRealToComplex;
5041     case Type::STK_CPointer:
5042     case Type::STK_ObjCObjectPointer:
5043     case Type::STK_BlockPointer:
5044       llvm_unreachable("valid float->pointer cast?");
5045     case Type::STK_MemberPointer:
5046       llvm_unreachable("member pointer type in C");
5047     }
5048     llvm_unreachable("Should have returned before this");
5049 
5050   case Type::STK_FloatingComplex:
5051     switch (DestTy->getScalarTypeKind()) {
5052     case Type::STK_FloatingComplex:
5053       return CK_FloatingComplexCast;
5054     case Type::STK_IntegralComplex:
5055       return CK_FloatingComplexToIntegralComplex;
5056     case Type::STK_Floating: {
5057       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5058       if (Context.hasSameType(ET, DestTy))
5059         return CK_FloatingComplexToReal;
5060       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5061       return CK_FloatingCast;
5062     }
5063     case Type::STK_Bool:
5064       return CK_FloatingComplexToBoolean;
5065     case Type::STK_Integral:
5066       Src = ImpCastExprToType(Src.get(),
5067                               SrcTy->castAs<ComplexType>()->getElementType(),
5068                               CK_FloatingComplexToReal);
5069       return CK_FloatingToIntegral;
5070     case Type::STK_CPointer:
5071     case Type::STK_ObjCObjectPointer:
5072     case Type::STK_BlockPointer:
5073       llvm_unreachable("valid complex float->pointer cast?");
5074     case Type::STK_MemberPointer:
5075       llvm_unreachable("member pointer type in C");
5076     }
5077     llvm_unreachable("Should have returned before this");
5078 
5079   case Type::STK_IntegralComplex:
5080     switch (DestTy->getScalarTypeKind()) {
5081     case Type::STK_FloatingComplex:
5082       return CK_IntegralComplexToFloatingComplex;
5083     case Type::STK_IntegralComplex:
5084       return CK_IntegralComplexCast;
5085     case Type::STK_Integral: {
5086       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5087       if (Context.hasSameType(ET, DestTy))
5088         return CK_IntegralComplexToReal;
5089       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5090       return CK_IntegralCast;
5091     }
5092     case Type::STK_Bool:
5093       return CK_IntegralComplexToBoolean;
5094     case Type::STK_Floating:
5095       Src = ImpCastExprToType(Src.get(),
5096                               SrcTy->castAs<ComplexType>()->getElementType(),
5097                               CK_IntegralComplexToReal);
5098       return CK_IntegralToFloating;
5099     case Type::STK_CPointer:
5100     case Type::STK_ObjCObjectPointer:
5101     case Type::STK_BlockPointer:
5102       llvm_unreachable("valid complex int->pointer cast?");
5103     case Type::STK_MemberPointer:
5104       llvm_unreachable("member pointer type in C");
5105     }
5106     llvm_unreachable("Should have returned before this");
5107   }
5108 
5109   llvm_unreachable("Unhandled scalar cast");
5110 }
5111 
5112 static bool breakDownVectorType(QualType type, uint64_t &len,
5113                                 QualType &eltType) {
5114   // Vectors are simple.
5115   if (const VectorType *vecType = type->getAs<VectorType>()) {
5116     len = vecType->getNumElements();
5117     eltType = vecType->getElementType();
5118     assert(eltType->isScalarType());
5119     return true;
5120   }
5121 
5122   // We allow lax conversion to and from non-vector types, but only if
5123   // they're real types (i.e. non-complex, non-pointer scalar types).
5124   if (!type->isRealType()) return false;
5125 
5126   len = 1;
5127   eltType = type;
5128   return true;
5129 }
5130 
5131 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5132   uint64_t srcLen, destLen;
5133   QualType srcElt, destElt;
5134   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5135   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5136 
5137   // ASTContext::getTypeSize will return the size rounded up to a
5138   // power of 2, so instead of using that, we need to use the raw
5139   // element size multiplied by the element count.
5140   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5141   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5142 
5143   return (srcLen * srcEltSize == destLen * destEltSize);
5144 }
5145 
5146 /// Is this a legal conversion between two known vector types?
5147 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5148   assert(destTy->isVectorType() || srcTy->isVectorType());
5149 
5150   if (!Context.getLangOpts().LaxVectorConversions)
5151     return false;
5152   return VectorTypesMatch(*this, srcTy, destTy);
5153 }
5154 
5155 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5156                            CastKind &Kind) {
5157   assert(VectorTy->isVectorType() && "Not a vector type!");
5158 
5159   if (Ty->isVectorType() || Ty->isIntegerType()) {
5160     if (!VectorTypesMatch(*this, Ty, VectorTy))
5161       return Diag(R.getBegin(),
5162                   Ty->isVectorType() ?
5163                   diag::err_invalid_conversion_between_vectors :
5164                   diag::err_invalid_conversion_between_vector_and_integer)
5165         << VectorTy << Ty << R;
5166   } else
5167     return Diag(R.getBegin(),
5168                 diag::err_invalid_conversion_between_vector_and_scalar)
5169       << VectorTy << Ty << R;
5170 
5171   Kind = CK_BitCast;
5172   return false;
5173 }
5174 
5175 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5176                                     Expr *CastExpr, CastKind &Kind) {
5177   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5178 
5179   QualType SrcTy = CastExpr->getType();
5180 
5181   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5182   // an ExtVectorType.
5183   // In OpenCL, casts between vectors of different types are not allowed.
5184   // (See OpenCL 6.2).
5185   if (SrcTy->isVectorType()) {
5186     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5187         || (getLangOpts().OpenCL &&
5188             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5189       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5190         << DestTy << SrcTy << R;
5191       return ExprError();
5192     }
5193     Kind = CK_BitCast;
5194     return CastExpr;
5195   }
5196 
5197   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5198   // conversion will take place first from scalar to elt type, and then
5199   // splat from elt type to vector.
5200   if (SrcTy->isPointerType())
5201     return Diag(R.getBegin(),
5202                 diag::err_invalid_conversion_between_vector_and_scalar)
5203       << DestTy << SrcTy << R;
5204 
5205   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5206   ExprResult CastExprRes = CastExpr;
5207   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5208   if (CastExprRes.isInvalid())
5209     return ExprError();
5210   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5211 
5212   Kind = CK_VectorSplat;
5213   return CastExpr;
5214 }
5215 
5216 ExprResult
5217 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5218                     Declarator &D, ParsedType &Ty,
5219                     SourceLocation RParenLoc, Expr *CastExpr) {
5220   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5221          "ActOnCastExpr(): missing type or expr");
5222 
5223   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5224   if (D.isInvalidType())
5225     return ExprError();
5226 
5227   if (getLangOpts().CPlusPlus) {
5228     // Check that there are no default arguments (C++ only).
5229     CheckExtraCXXDefaultArguments(D);
5230   }
5231 
5232   checkUnusedDeclAttributes(D);
5233 
5234   QualType castType = castTInfo->getType();
5235   Ty = CreateParsedType(castType, castTInfo);
5236 
5237   bool isVectorLiteral = false;
5238 
5239   // Check for an altivec or OpenCL literal,
5240   // i.e. all the elements are integer constants.
5241   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5242   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5243   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5244        && castType->isVectorType() && (PE || PLE)) {
5245     if (PLE && PLE->getNumExprs() == 0) {
5246       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5247       return ExprError();
5248     }
5249     if (PE || PLE->getNumExprs() == 1) {
5250       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5251       if (!E->getType()->isVectorType())
5252         isVectorLiteral = true;
5253     }
5254     else
5255       isVectorLiteral = true;
5256   }
5257 
5258   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5259   // then handle it as such.
5260   if (isVectorLiteral)
5261     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5262 
5263   // If the Expr being casted is a ParenListExpr, handle it specially.
5264   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5265   // sequence of BinOp comma operators.
5266   if (isa<ParenListExpr>(CastExpr)) {
5267     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5268     if (Result.isInvalid()) return ExprError();
5269     CastExpr = Result.get();
5270   }
5271 
5272   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5273       !getSourceManager().isInSystemMacro(LParenLoc))
5274     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5275 
5276   CheckTollFreeBridgeCast(castType, CastExpr);
5277 
5278   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5279 }
5280 
5281 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5282                                     SourceLocation RParenLoc, Expr *E,
5283                                     TypeSourceInfo *TInfo) {
5284   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5285          "Expected paren or paren list expression");
5286 
5287   Expr **exprs;
5288   unsigned numExprs;
5289   Expr *subExpr;
5290   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5291   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5292     LiteralLParenLoc = PE->getLParenLoc();
5293     LiteralRParenLoc = PE->getRParenLoc();
5294     exprs = PE->getExprs();
5295     numExprs = PE->getNumExprs();
5296   } else { // isa<ParenExpr> by assertion at function entrance
5297     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5298     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5299     subExpr = cast<ParenExpr>(E)->getSubExpr();
5300     exprs = &subExpr;
5301     numExprs = 1;
5302   }
5303 
5304   QualType Ty = TInfo->getType();
5305   assert(Ty->isVectorType() && "Expected vector type");
5306 
5307   SmallVector<Expr *, 8> initExprs;
5308   const VectorType *VTy = Ty->getAs<VectorType>();
5309   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5310 
5311   // '(...)' form of vector initialization in AltiVec: the number of
5312   // initializers must be one or must match the size of the vector.
5313   // If a single value is specified in the initializer then it will be
5314   // replicated to all the components of the vector
5315   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5316     // The number of initializers must be one or must match the size of the
5317     // vector. If a single value is specified in the initializer then it will
5318     // be replicated to all the components of the vector
5319     if (numExprs == 1) {
5320       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5321       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5322       if (Literal.isInvalid())
5323         return ExprError();
5324       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5325                                   PrepareScalarCast(Literal, ElemTy));
5326       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5327     }
5328     else if (numExprs < numElems) {
5329       Diag(E->getExprLoc(),
5330            diag::err_incorrect_number_of_vector_initializers);
5331       return ExprError();
5332     }
5333     else
5334       initExprs.append(exprs, exprs + numExprs);
5335   }
5336   else {
5337     // For OpenCL, when the number of initializers is a single value,
5338     // it will be replicated to all components of the vector.
5339     if (getLangOpts().OpenCL &&
5340         VTy->getVectorKind() == VectorType::GenericVector &&
5341         numExprs == 1) {
5342         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5343         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5344         if (Literal.isInvalid())
5345           return ExprError();
5346         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5347                                     PrepareScalarCast(Literal, ElemTy));
5348         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5349     }
5350 
5351     initExprs.append(exprs, exprs + numExprs);
5352   }
5353   // FIXME: This means that pretty-printing the final AST will produce curly
5354   // braces instead of the original commas.
5355   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5356                                                    initExprs, LiteralRParenLoc);
5357   initE->setType(Ty);
5358   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5359 }
5360 
5361 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5362 /// the ParenListExpr into a sequence of comma binary operators.
5363 ExprResult
5364 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5365   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5366   if (!E)
5367     return OrigExpr;
5368 
5369   ExprResult Result(E->getExpr(0));
5370 
5371   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5372     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5373                         E->getExpr(i));
5374 
5375   if (Result.isInvalid()) return ExprError();
5376 
5377   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5378 }
5379 
5380 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5381                                     SourceLocation R,
5382                                     MultiExprArg Val) {
5383   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5384   return expr;
5385 }
5386 
5387 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5388 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5389 /// emitted.
5390 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5391                                       SourceLocation QuestionLoc) {
5392   Expr *NullExpr = LHSExpr;
5393   Expr *NonPointerExpr = RHSExpr;
5394   Expr::NullPointerConstantKind NullKind =
5395       NullExpr->isNullPointerConstant(Context,
5396                                       Expr::NPC_ValueDependentIsNotNull);
5397 
5398   if (NullKind == Expr::NPCK_NotNull) {
5399     NullExpr = RHSExpr;
5400     NonPointerExpr = LHSExpr;
5401     NullKind =
5402         NullExpr->isNullPointerConstant(Context,
5403                                         Expr::NPC_ValueDependentIsNotNull);
5404   }
5405 
5406   if (NullKind == Expr::NPCK_NotNull)
5407     return false;
5408 
5409   if (NullKind == Expr::NPCK_ZeroExpression)
5410     return false;
5411 
5412   if (NullKind == Expr::NPCK_ZeroLiteral) {
5413     // In this case, check to make sure that we got here from a "NULL"
5414     // string in the source code.
5415     NullExpr = NullExpr->IgnoreParenImpCasts();
5416     SourceLocation loc = NullExpr->getExprLoc();
5417     if (!findMacroSpelling(loc, "NULL"))
5418       return false;
5419   }
5420 
5421   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5422   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5423       << NonPointerExpr->getType() << DiagType
5424       << NonPointerExpr->getSourceRange();
5425   return true;
5426 }
5427 
5428 /// \brief Return false if the condition expression is valid, true otherwise.
5429 static bool checkCondition(Sema &S, Expr *Cond) {
5430   QualType CondTy = Cond->getType();
5431 
5432   // C99 6.5.15p2
5433   if (CondTy->isScalarType()) return false;
5434 
5435   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5436   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5437     return false;
5438 
5439   // Emit the proper error message.
5440   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5441                               diag::err_typecheck_cond_expect_scalar :
5442                               diag::err_typecheck_cond_expect_scalar_or_vector)
5443     << CondTy;
5444   return true;
5445 }
5446 
5447 /// \brief Return false if the two expressions can be converted to a vector,
5448 /// true otherwise
5449 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5450                                                     ExprResult &RHS,
5451                                                     QualType CondTy) {
5452   // Both operands should be of scalar type.
5453   if (!LHS.get()->getType()->isScalarType()) {
5454     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5455       << CondTy;
5456     return true;
5457   }
5458   if (!RHS.get()->getType()->isScalarType()) {
5459     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5460       << CondTy;
5461     return true;
5462   }
5463 
5464   // Implicity convert these scalars to the type of the condition.
5465   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5466   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5467   return false;
5468 }
5469 
5470 /// \brief Handle when one or both operands are void type.
5471 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5472                                          ExprResult &RHS) {
5473     Expr *LHSExpr = LHS.get();
5474     Expr *RHSExpr = RHS.get();
5475 
5476     if (!LHSExpr->getType()->isVoidType())
5477       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5478         << RHSExpr->getSourceRange();
5479     if (!RHSExpr->getType()->isVoidType())
5480       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5481         << LHSExpr->getSourceRange();
5482     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5483     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5484     return S.Context.VoidTy;
5485 }
5486 
5487 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5488 /// true otherwise.
5489 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5490                                         QualType PointerTy) {
5491   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5492       !NullExpr.get()->isNullPointerConstant(S.Context,
5493                                             Expr::NPC_ValueDependentIsNull))
5494     return true;
5495 
5496   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5497   return false;
5498 }
5499 
5500 /// \brief Checks compatibility between two pointers and return the resulting
5501 /// type.
5502 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5503                                                      ExprResult &RHS,
5504                                                      SourceLocation Loc) {
5505   QualType LHSTy = LHS.get()->getType();
5506   QualType RHSTy = RHS.get()->getType();
5507 
5508   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5509     // Two identical pointers types are always compatible.
5510     return LHSTy;
5511   }
5512 
5513   QualType lhptee, rhptee;
5514 
5515   // Get the pointee types.
5516   bool IsBlockPointer = false;
5517   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5518     lhptee = LHSBTy->getPointeeType();
5519     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5520     IsBlockPointer = true;
5521   } else {
5522     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5523     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5524   }
5525 
5526   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5527   // differently qualified versions of compatible types, the result type is
5528   // a pointer to an appropriately qualified version of the composite
5529   // type.
5530 
5531   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5532   // clause doesn't make sense for our extensions. E.g. address space 2 should
5533   // be incompatible with address space 3: they may live on different devices or
5534   // anything.
5535   Qualifiers lhQual = lhptee.getQualifiers();
5536   Qualifiers rhQual = rhptee.getQualifiers();
5537 
5538   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5539   lhQual.removeCVRQualifiers();
5540   rhQual.removeCVRQualifiers();
5541 
5542   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5543   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5544 
5545   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5546 
5547   if (CompositeTy.isNull()) {
5548     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5549       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5550       << RHS.get()->getSourceRange();
5551     // In this situation, we assume void* type. No especially good
5552     // reason, but this is what gcc does, and we do have to pick
5553     // to get a consistent AST.
5554     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5555     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5556     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5557     return incompatTy;
5558   }
5559 
5560   // The pointer types are compatible.
5561   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5562   if (IsBlockPointer)
5563     ResultTy = S.Context.getBlockPointerType(ResultTy);
5564   else
5565     ResultTy = S.Context.getPointerType(ResultTy);
5566 
5567   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5568   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5569   return ResultTy;
5570 }
5571 
5572 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5573 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5574 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5575 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5576   if (QT->isObjCIdType())
5577     return true;
5578 
5579   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5580   if (!OPT)
5581     return false;
5582 
5583   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5584     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5585       return false;
5586 
5587   ObjCProtocolDecl* PNSCopying =
5588     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5589   ObjCProtocolDecl* PNSObject =
5590     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5591 
5592   for (auto *Proto : OPT->quals()) {
5593     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5594         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5595       ;
5596     else
5597       return false;
5598   }
5599   return true;
5600 }
5601 
5602 /// \brief Return the resulting type when the operands are both block pointers.
5603 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5604                                                           ExprResult &LHS,
5605                                                           ExprResult &RHS,
5606                                                           SourceLocation Loc) {
5607   QualType LHSTy = LHS.get()->getType();
5608   QualType RHSTy = RHS.get()->getType();
5609 
5610   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5611     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5612       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5613       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5614       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5615       return destType;
5616     }
5617     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5618       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5619       << RHS.get()->getSourceRange();
5620     return QualType();
5621   }
5622 
5623   // We have 2 block pointer types.
5624   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5625 }
5626 
5627 /// \brief Return the resulting type when the operands are both pointers.
5628 static QualType
5629 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5630                                             ExprResult &RHS,
5631                                             SourceLocation Loc) {
5632   // get the pointer types
5633   QualType LHSTy = LHS.get()->getType();
5634   QualType RHSTy = RHS.get()->getType();
5635 
5636   // get the "pointed to" types
5637   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5638   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5639 
5640   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5641   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5642     // Figure out necessary qualifiers (C99 6.5.15p6)
5643     QualType destPointee
5644       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5645     QualType destType = S.Context.getPointerType(destPointee);
5646     // Add qualifiers if necessary.
5647     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5648     // Promote to void*.
5649     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5650     return destType;
5651   }
5652   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5653     QualType destPointee
5654       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5655     QualType destType = S.Context.getPointerType(destPointee);
5656     // Add qualifiers if necessary.
5657     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5658     // Promote to void*.
5659     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5660     return destType;
5661   }
5662 
5663   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5664 }
5665 
5666 /// \brief Return false if the first expression is not an integer and the second
5667 /// expression is not a pointer, true otherwise.
5668 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5669                                         Expr* PointerExpr, SourceLocation Loc,
5670                                         bool IsIntFirstExpr) {
5671   if (!PointerExpr->getType()->isPointerType() ||
5672       !Int.get()->getType()->isIntegerType())
5673     return false;
5674 
5675   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5676   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5677 
5678   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5679     << Expr1->getType() << Expr2->getType()
5680     << Expr1->getSourceRange() << Expr2->getSourceRange();
5681   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5682                             CK_IntegralToPointer);
5683   return true;
5684 }
5685 
5686 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5687 /// In that case, LHS = cond.
5688 /// C99 6.5.15
5689 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5690                                         ExprResult &RHS, ExprValueKind &VK,
5691                                         ExprObjectKind &OK,
5692                                         SourceLocation QuestionLoc) {
5693 
5694   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5695   if (!LHSResult.isUsable()) return QualType();
5696   LHS = LHSResult;
5697 
5698   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5699   if (!RHSResult.isUsable()) return QualType();
5700   RHS = RHSResult;
5701 
5702   // C++ is sufficiently different to merit its own checker.
5703   if (getLangOpts().CPlusPlus)
5704     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5705 
5706   VK = VK_RValue;
5707   OK = OK_Ordinary;
5708 
5709   // First, check the condition.
5710   Cond = UsualUnaryConversions(Cond.get());
5711   if (Cond.isInvalid())
5712     return QualType();
5713   if (checkCondition(*this, Cond.get()))
5714     return QualType();
5715 
5716   // Now check the two expressions.
5717   if (LHS.get()->getType()->isVectorType() ||
5718       RHS.get()->getType()->isVectorType())
5719     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5720 
5721   UsualArithmeticConversions(LHS, RHS);
5722   if (LHS.isInvalid() || RHS.isInvalid())
5723     return QualType();
5724 
5725   QualType CondTy = Cond.get()->getType();
5726   QualType LHSTy = LHS.get()->getType();
5727   QualType RHSTy = RHS.get()->getType();
5728 
5729   // If the condition is a vector, and both operands are scalar,
5730   // attempt to implicity convert them to the vector type to act like the
5731   // built in select. (OpenCL v1.1 s6.3.i)
5732   if (getLangOpts().OpenCL && CondTy->isVectorType())
5733     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5734       return QualType();
5735 
5736   // If both operands have arithmetic type, do the usual arithmetic conversions
5737   // to find a common type: C99 6.5.15p3,5.
5738   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5739     return LHS.get()->getType();
5740 
5741   // If both operands are the same structure or union type, the result is that
5742   // type.
5743   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5744     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5745       if (LHSRT->getDecl() == RHSRT->getDecl())
5746         // "If both the operands have structure or union type, the result has
5747         // that type."  This implies that CV qualifiers are dropped.
5748         return LHSTy.getUnqualifiedType();
5749     // FIXME: Type of conditional expression must be complete in C mode.
5750   }
5751 
5752   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5753   // The following || allows only one side to be void (a GCC-ism).
5754   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5755     return checkConditionalVoidType(*this, LHS, RHS);
5756   }
5757 
5758   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5759   // the type of the other operand."
5760   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5761   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5762 
5763   // All objective-c pointer type analysis is done here.
5764   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5765                                                         QuestionLoc);
5766   if (LHS.isInvalid() || RHS.isInvalid())
5767     return QualType();
5768   if (!compositeType.isNull())
5769     return compositeType;
5770 
5771 
5772   // Handle block pointer types.
5773   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5774     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5775                                                      QuestionLoc);
5776 
5777   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5778   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5779     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5780                                                        QuestionLoc);
5781 
5782   // GCC compatibility: soften pointer/integer mismatch.  Note that
5783   // null pointers have been filtered out by this point.
5784   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5785       /*isIntFirstExpr=*/true))
5786     return RHSTy;
5787   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5788       /*isIntFirstExpr=*/false))
5789     return LHSTy;
5790 
5791   // Emit a better diagnostic if one of the expressions is a null pointer
5792   // constant and the other is not a pointer type. In this case, the user most
5793   // likely forgot to take the address of the other expression.
5794   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5795     return QualType();
5796 
5797   // Otherwise, the operands are not compatible.
5798   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5799     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5800     << RHS.get()->getSourceRange();
5801   return QualType();
5802 }
5803 
5804 /// FindCompositeObjCPointerType - Helper method to find composite type of
5805 /// two objective-c pointer types of the two input expressions.
5806 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5807                                             SourceLocation QuestionLoc) {
5808   QualType LHSTy = LHS.get()->getType();
5809   QualType RHSTy = RHS.get()->getType();
5810 
5811   // Handle things like Class and struct objc_class*.  Here we case the result
5812   // to the pseudo-builtin, because that will be implicitly cast back to the
5813   // redefinition type if an attempt is made to access its fields.
5814   if (LHSTy->isObjCClassType() &&
5815       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5816     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5817     return LHSTy;
5818   }
5819   if (RHSTy->isObjCClassType() &&
5820       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5821     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5822     return RHSTy;
5823   }
5824   // And the same for struct objc_object* / id
5825   if (LHSTy->isObjCIdType() &&
5826       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5827     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5828     return LHSTy;
5829   }
5830   if (RHSTy->isObjCIdType() &&
5831       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5832     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5833     return RHSTy;
5834   }
5835   // And the same for struct objc_selector* / SEL
5836   if (Context.isObjCSelType(LHSTy) &&
5837       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5838     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5839     return LHSTy;
5840   }
5841   if (Context.isObjCSelType(RHSTy) &&
5842       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5843     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5844     return RHSTy;
5845   }
5846   // Check constraints for Objective-C object pointers types.
5847   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5848 
5849     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5850       // Two identical object pointer types are always compatible.
5851       return LHSTy;
5852     }
5853     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5854     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5855     QualType compositeType = LHSTy;
5856 
5857     // If both operands are interfaces and either operand can be
5858     // assigned to the other, use that type as the composite
5859     // type. This allows
5860     //   xxx ? (A*) a : (B*) b
5861     // where B is a subclass of A.
5862     //
5863     // Additionally, as for assignment, if either type is 'id'
5864     // allow silent coercion. Finally, if the types are
5865     // incompatible then make sure to use 'id' as the composite
5866     // type so the result is acceptable for sending messages to.
5867 
5868     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5869     // It could return the composite type.
5870     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5871       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5872     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5873       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5874     } else if ((LHSTy->isObjCQualifiedIdType() ||
5875                 RHSTy->isObjCQualifiedIdType()) &&
5876                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5877       // Need to handle "id<xx>" explicitly.
5878       // GCC allows qualified id and any Objective-C type to devolve to
5879       // id. Currently localizing to here until clear this should be
5880       // part of ObjCQualifiedIdTypesAreCompatible.
5881       compositeType = Context.getObjCIdType();
5882     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5883       compositeType = Context.getObjCIdType();
5884     } else if (!(compositeType =
5885                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5886       ;
5887     else {
5888       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5889       << LHSTy << RHSTy
5890       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5891       QualType incompatTy = Context.getObjCIdType();
5892       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5893       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5894       return incompatTy;
5895     }
5896     // The object pointer types are compatible.
5897     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5898     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5899     return compositeType;
5900   }
5901   // Check Objective-C object pointer types and 'void *'
5902   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5903     if (getLangOpts().ObjCAutoRefCount) {
5904       // ARC forbids the implicit conversion of object pointers to 'void *',
5905       // so these types are not compatible.
5906       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5907           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5908       LHS = RHS = true;
5909       return QualType();
5910     }
5911     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5912     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5913     QualType destPointee
5914     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5915     QualType destType = Context.getPointerType(destPointee);
5916     // Add qualifiers if necessary.
5917     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5918     // Promote to void*.
5919     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5920     return destType;
5921   }
5922   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5923     if (getLangOpts().ObjCAutoRefCount) {
5924       // ARC forbids the implicit conversion of object pointers to 'void *',
5925       // so these types are not compatible.
5926       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5927           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5928       LHS = RHS = true;
5929       return QualType();
5930     }
5931     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5932     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5933     QualType destPointee
5934     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5935     QualType destType = Context.getPointerType(destPointee);
5936     // Add qualifiers if necessary.
5937     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5938     // Promote to void*.
5939     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5940     return destType;
5941   }
5942   return QualType();
5943 }
5944 
5945 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5946 /// ParenRange in parentheses.
5947 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5948                                const PartialDiagnostic &Note,
5949                                SourceRange ParenRange) {
5950   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5951   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5952       EndLoc.isValid()) {
5953     Self.Diag(Loc, Note)
5954       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5955       << FixItHint::CreateInsertion(EndLoc, ")");
5956   } else {
5957     // We can't display the parentheses, so just show the bare note.
5958     Self.Diag(Loc, Note) << ParenRange;
5959   }
5960 }
5961 
5962 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5963   return Opc >= BO_Mul && Opc <= BO_Shr;
5964 }
5965 
5966 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5967 /// expression, either using a built-in or overloaded operator,
5968 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5969 /// expression.
5970 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5971                                    Expr **RHSExprs) {
5972   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5973   E = E->IgnoreImpCasts();
5974   E = E->IgnoreConversionOperator();
5975   E = E->IgnoreImpCasts();
5976 
5977   // Built-in binary operator.
5978   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5979     if (IsArithmeticOp(OP->getOpcode())) {
5980       *Opcode = OP->getOpcode();
5981       *RHSExprs = OP->getRHS();
5982       return true;
5983     }
5984   }
5985 
5986   // Overloaded operator.
5987   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5988     if (Call->getNumArgs() != 2)
5989       return false;
5990 
5991     // Make sure this is really a binary operator that is safe to pass into
5992     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5993     OverloadedOperatorKind OO = Call->getOperator();
5994     if (OO < OO_Plus || OO > OO_Arrow ||
5995         OO == OO_PlusPlus || OO == OO_MinusMinus)
5996       return false;
5997 
5998     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5999     if (IsArithmeticOp(OpKind)) {
6000       *Opcode = OpKind;
6001       *RHSExprs = Call->getArg(1);
6002       return true;
6003     }
6004   }
6005 
6006   return false;
6007 }
6008 
6009 static bool IsLogicOp(BinaryOperatorKind Opc) {
6010   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6011 }
6012 
6013 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6014 /// or is a logical expression such as (x==y) which has int type, but is
6015 /// commonly interpreted as boolean.
6016 static bool ExprLooksBoolean(Expr *E) {
6017   E = E->IgnoreParenImpCasts();
6018 
6019   if (E->getType()->isBooleanType())
6020     return true;
6021   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6022     return IsLogicOp(OP->getOpcode());
6023   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6024     return OP->getOpcode() == UO_LNot;
6025 
6026   return false;
6027 }
6028 
6029 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6030 /// and binary operator are mixed in a way that suggests the programmer assumed
6031 /// the conditional operator has higher precedence, for example:
6032 /// "int x = a + someBinaryCondition ? 1 : 2".
6033 static void DiagnoseConditionalPrecedence(Sema &Self,
6034                                           SourceLocation OpLoc,
6035                                           Expr *Condition,
6036                                           Expr *LHSExpr,
6037                                           Expr *RHSExpr) {
6038   BinaryOperatorKind CondOpcode;
6039   Expr *CondRHS;
6040 
6041   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6042     return;
6043   if (!ExprLooksBoolean(CondRHS))
6044     return;
6045 
6046   // The condition is an arithmetic binary expression, with a right-
6047   // hand side that looks boolean, so warn.
6048 
6049   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6050       << Condition->getSourceRange()
6051       << BinaryOperator::getOpcodeStr(CondOpcode);
6052 
6053   SuggestParentheses(Self, OpLoc,
6054     Self.PDiag(diag::note_precedence_silence)
6055       << BinaryOperator::getOpcodeStr(CondOpcode),
6056     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6057 
6058   SuggestParentheses(Self, OpLoc,
6059     Self.PDiag(diag::note_precedence_conditional_first),
6060     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6061 }
6062 
6063 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6064 /// in the case of a the GNU conditional expr extension.
6065 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6066                                     SourceLocation ColonLoc,
6067                                     Expr *CondExpr, Expr *LHSExpr,
6068                                     Expr *RHSExpr) {
6069   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6070   // was the condition.
6071   OpaqueValueExpr *opaqueValue = nullptr;
6072   Expr *commonExpr = nullptr;
6073   if (!LHSExpr) {
6074     commonExpr = CondExpr;
6075     // Lower out placeholder types first.  This is important so that we don't
6076     // try to capture a placeholder. This happens in few cases in C++; such
6077     // as Objective-C++'s dictionary subscripting syntax.
6078     if (commonExpr->hasPlaceholderType()) {
6079       ExprResult result = CheckPlaceholderExpr(commonExpr);
6080       if (!result.isUsable()) return ExprError();
6081       commonExpr = result.get();
6082     }
6083     // We usually want to apply unary conversions *before* saving, except
6084     // in the special case of a C++ l-value conditional.
6085     if (!(getLangOpts().CPlusPlus
6086           && !commonExpr->isTypeDependent()
6087           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6088           && commonExpr->isGLValue()
6089           && commonExpr->isOrdinaryOrBitFieldObject()
6090           && RHSExpr->isOrdinaryOrBitFieldObject()
6091           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6092       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6093       if (commonRes.isInvalid())
6094         return ExprError();
6095       commonExpr = commonRes.get();
6096     }
6097 
6098     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6099                                                 commonExpr->getType(),
6100                                                 commonExpr->getValueKind(),
6101                                                 commonExpr->getObjectKind(),
6102                                                 commonExpr);
6103     LHSExpr = CondExpr = opaqueValue;
6104   }
6105 
6106   ExprValueKind VK = VK_RValue;
6107   ExprObjectKind OK = OK_Ordinary;
6108   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6109   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6110                                              VK, OK, QuestionLoc);
6111   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6112       RHS.isInvalid())
6113     return ExprError();
6114 
6115   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6116                                 RHS.get());
6117 
6118   if (!commonExpr)
6119     return new (Context)
6120         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6121                             RHS.get(), result, VK, OK);
6122 
6123   return new (Context) BinaryConditionalOperator(
6124       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6125       ColonLoc, result, VK, OK);
6126 }
6127 
6128 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6129 // being closely modeled after the C99 spec:-). The odd characteristic of this
6130 // routine is it effectively iqnores the qualifiers on the top level pointee.
6131 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6132 // FIXME: add a couple examples in this comment.
6133 static Sema::AssignConvertType
6134 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6135   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6136   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6137 
6138   // get the "pointed to" type (ignoring qualifiers at the top level)
6139   const Type *lhptee, *rhptee;
6140   Qualifiers lhq, rhq;
6141   std::tie(lhptee, lhq) =
6142       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6143   std::tie(rhptee, rhq) =
6144       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6145 
6146   Sema::AssignConvertType ConvTy = Sema::Compatible;
6147 
6148   // C99 6.5.16.1p1: This following citation is common to constraints
6149   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6150   // qualifiers of the type *pointed to* by the right;
6151 
6152   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6153   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6154       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6155     // Ignore lifetime for further calculation.
6156     lhq.removeObjCLifetime();
6157     rhq.removeObjCLifetime();
6158   }
6159 
6160   if (!lhq.compatiblyIncludes(rhq)) {
6161     // Treat address-space mismatches as fatal.  TODO: address subspaces
6162     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6163       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6164 
6165     // It's okay to add or remove GC or lifetime qualifiers when converting to
6166     // and from void*.
6167     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6168                         .compatiblyIncludes(
6169                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6170              && (lhptee->isVoidType() || rhptee->isVoidType()))
6171       ; // keep old
6172 
6173     // Treat lifetime mismatches as fatal.
6174     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6175       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6176 
6177     // For GCC compatibility, other qualifier mismatches are treated
6178     // as still compatible in C.
6179     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6180   }
6181 
6182   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6183   // incomplete type and the other is a pointer to a qualified or unqualified
6184   // version of void...
6185   if (lhptee->isVoidType()) {
6186     if (rhptee->isIncompleteOrObjectType())
6187       return ConvTy;
6188 
6189     // As an extension, we allow cast to/from void* to function pointer.
6190     assert(rhptee->isFunctionType());
6191     return Sema::FunctionVoidPointer;
6192   }
6193 
6194   if (rhptee->isVoidType()) {
6195     if (lhptee->isIncompleteOrObjectType())
6196       return ConvTy;
6197 
6198     // As an extension, we allow cast to/from void* to function pointer.
6199     assert(lhptee->isFunctionType());
6200     return Sema::FunctionVoidPointer;
6201   }
6202 
6203   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6204   // unqualified versions of compatible types, ...
6205   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6206   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6207     // Check if the pointee types are compatible ignoring the sign.
6208     // We explicitly check for char so that we catch "char" vs
6209     // "unsigned char" on systems where "char" is unsigned.
6210     if (lhptee->isCharType())
6211       ltrans = S.Context.UnsignedCharTy;
6212     else if (lhptee->hasSignedIntegerRepresentation())
6213       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6214 
6215     if (rhptee->isCharType())
6216       rtrans = S.Context.UnsignedCharTy;
6217     else if (rhptee->hasSignedIntegerRepresentation())
6218       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6219 
6220     if (ltrans == rtrans) {
6221       // Types are compatible ignoring the sign. Qualifier incompatibility
6222       // takes priority over sign incompatibility because the sign
6223       // warning can be disabled.
6224       if (ConvTy != Sema::Compatible)
6225         return ConvTy;
6226 
6227       return Sema::IncompatiblePointerSign;
6228     }
6229 
6230     // If we are a multi-level pointer, it's possible that our issue is simply
6231     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6232     // the eventual target type is the same and the pointers have the same
6233     // level of indirection, this must be the issue.
6234     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6235       do {
6236         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6237         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6238       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6239 
6240       if (lhptee == rhptee)
6241         return Sema::IncompatibleNestedPointerQualifiers;
6242     }
6243 
6244     // General pointer incompatibility takes priority over qualifiers.
6245     return Sema::IncompatiblePointer;
6246   }
6247   if (!S.getLangOpts().CPlusPlus &&
6248       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6249     return Sema::IncompatiblePointer;
6250   return ConvTy;
6251 }
6252 
6253 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6254 /// block pointer types are compatible or whether a block and normal pointer
6255 /// are compatible. It is more restrict than comparing two function pointer
6256 // types.
6257 static Sema::AssignConvertType
6258 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6259                                     QualType RHSType) {
6260   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6261   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6262 
6263   QualType lhptee, rhptee;
6264 
6265   // get the "pointed to" type (ignoring qualifiers at the top level)
6266   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6267   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6268 
6269   // In C++, the types have to match exactly.
6270   if (S.getLangOpts().CPlusPlus)
6271     return Sema::IncompatibleBlockPointer;
6272 
6273   Sema::AssignConvertType ConvTy = Sema::Compatible;
6274 
6275   // For blocks we enforce that qualifiers are identical.
6276   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6277     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6278 
6279   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6280     return Sema::IncompatibleBlockPointer;
6281 
6282   return ConvTy;
6283 }
6284 
6285 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6286 /// for assignment compatibility.
6287 static Sema::AssignConvertType
6288 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6289                                    QualType RHSType) {
6290   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6291   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6292 
6293   if (LHSType->isObjCBuiltinType()) {
6294     // Class is not compatible with ObjC object pointers.
6295     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6296         !RHSType->isObjCQualifiedClassType())
6297       return Sema::IncompatiblePointer;
6298     return Sema::Compatible;
6299   }
6300   if (RHSType->isObjCBuiltinType()) {
6301     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6302         !LHSType->isObjCQualifiedClassType())
6303       return Sema::IncompatiblePointer;
6304     return Sema::Compatible;
6305   }
6306   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6307   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6308 
6309   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6310       // make an exception for id<P>
6311       !LHSType->isObjCQualifiedIdType())
6312     return Sema::CompatiblePointerDiscardsQualifiers;
6313 
6314   if (S.Context.typesAreCompatible(LHSType, RHSType))
6315     return Sema::Compatible;
6316   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6317     return Sema::IncompatibleObjCQualifiedId;
6318   return Sema::IncompatiblePointer;
6319 }
6320 
6321 Sema::AssignConvertType
6322 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6323                                  QualType LHSType, QualType RHSType) {
6324   // Fake up an opaque expression.  We don't actually care about what
6325   // cast operations are required, so if CheckAssignmentConstraints
6326   // adds casts to this they'll be wasted, but fortunately that doesn't
6327   // usually happen on valid code.
6328   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6329   ExprResult RHSPtr = &RHSExpr;
6330   CastKind K = CK_Invalid;
6331 
6332   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6333 }
6334 
6335 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6336 /// has code to accommodate several GCC extensions when type checking
6337 /// pointers. Here are some objectionable examples that GCC considers warnings:
6338 ///
6339 ///  int a, *pint;
6340 ///  short *pshort;
6341 ///  struct foo *pfoo;
6342 ///
6343 ///  pint = pshort; // warning: assignment from incompatible pointer type
6344 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6345 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6346 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6347 ///
6348 /// As a result, the code for dealing with pointers is more complex than the
6349 /// C99 spec dictates.
6350 ///
6351 /// Sets 'Kind' for any result kind except Incompatible.
6352 Sema::AssignConvertType
6353 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6354                                  CastKind &Kind) {
6355   QualType RHSType = RHS.get()->getType();
6356   QualType OrigLHSType = LHSType;
6357 
6358   // Get canonical types.  We're not formatting these types, just comparing
6359   // them.
6360   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6361   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6362 
6363   // Common case: no conversion required.
6364   if (LHSType == RHSType) {
6365     Kind = CK_NoOp;
6366     return Compatible;
6367   }
6368 
6369   // If we have an atomic type, try a non-atomic assignment, then just add an
6370   // atomic qualification step.
6371   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6372     Sema::AssignConvertType result =
6373       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6374     if (result != Compatible)
6375       return result;
6376     if (Kind != CK_NoOp)
6377       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6378     Kind = CK_NonAtomicToAtomic;
6379     return Compatible;
6380   }
6381 
6382   // If the left-hand side is a reference type, then we are in a
6383   // (rare!) case where we've allowed the use of references in C,
6384   // e.g., as a parameter type in a built-in function. In this case,
6385   // just make sure that the type referenced is compatible with the
6386   // right-hand side type. The caller is responsible for adjusting
6387   // LHSType so that the resulting expression does not have reference
6388   // type.
6389   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6390     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6391       Kind = CK_LValueBitCast;
6392       return Compatible;
6393     }
6394     return Incompatible;
6395   }
6396 
6397   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6398   // to the same ExtVector type.
6399   if (LHSType->isExtVectorType()) {
6400     if (RHSType->isExtVectorType())
6401       return Incompatible;
6402     if (RHSType->isArithmeticType()) {
6403       // CK_VectorSplat does T -> vector T, so first cast to the
6404       // element type.
6405       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6406       if (elType != RHSType) {
6407         Kind = PrepareScalarCast(RHS, elType);
6408         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6409       }
6410       Kind = CK_VectorSplat;
6411       return Compatible;
6412     }
6413   }
6414 
6415   // Conversions to or from vector type.
6416   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6417     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6418       // Allow assignments of an AltiVec vector type to an equivalent GCC
6419       // vector type and vice versa
6420       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6421         Kind = CK_BitCast;
6422         return Compatible;
6423       }
6424 
6425       // If we are allowing lax vector conversions, and LHS and RHS are both
6426       // vectors, the total size only needs to be the same. This is a bitcast;
6427       // no bits are changed but the result type is different.
6428       if (isLaxVectorConversion(RHSType, LHSType)) {
6429         Kind = CK_BitCast;
6430         return IncompatibleVectors;
6431       }
6432     }
6433     return Incompatible;
6434   }
6435 
6436   // Arithmetic conversions.
6437   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6438       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6439     Kind = PrepareScalarCast(RHS, LHSType);
6440     return Compatible;
6441   }
6442 
6443   // Conversions to normal pointers.
6444   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6445     // U* -> T*
6446     if (isa<PointerType>(RHSType)) {
6447       Kind = CK_BitCast;
6448       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6449     }
6450 
6451     // int -> T*
6452     if (RHSType->isIntegerType()) {
6453       Kind = CK_IntegralToPointer; // FIXME: null?
6454       return IntToPointer;
6455     }
6456 
6457     // C pointers are not compatible with ObjC object pointers,
6458     // with two exceptions:
6459     if (isa<ObjCObjectPointerType>(RHSType)) {
6460       //  - conversions to void*
6461       if (LHSPointer->getPointeeType()->isVoidType()) {
6462         Kind = CK_BitCast;
6463         return Compatible;
6464       }
6465 
6466       //  - conversions from 'Class' to the redefinition type
6467       if (RHSType->isObjCClassType() &&
6468           Context.hasSameType(LHSType,
6469                               Context.getObjCClassRedefinitionType())) {
6470         Kind = CK_BitCast;
6471         return Compatible;
6472       }
6473 
6474       Kind = CK_BitCast;
6475       return IncompatiblePointer;
6476     }
6477 
6478     // U^ -> void*
6479     if (RHSType->getAs<BlockPointerType>()) {
6480       if (LHSPointer->getPointeeType()->isVoidType()) {
6481         Kind = CK_BitCast;
6482         return Compatible;
6483       }
6484     }
6485 
6486     return Incompatible;
6487   }
6488 
6489   // Conversions to block pointers.
6490   if (isa<BlockPointerType>(LHSType)) {
6491     // U^ -> T^
6492     if (RHSType->isBlockPointerType()) {
6493       Kind = CK_BitCast;
6494       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6495     }
6496 
6497     // int or null -> T^
6498     if (RHSType->isIntegerType()) {
6499       Kind = CK_IntegralToPointer; // FIXME: null
6500       return IntToBlockPointer;
6501     }
6502 
6503     // id -> T^
6504     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6505       Kind = CK_AnyPointerToBlockPointerCast;
6506       return Compatible;
6507     }
6508 
6509     // void* -> T^
6510     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6511       if (RHSPT->getPointeeType()->isVoidType()) {
6512         Kind = CK_AnyPointerToBlockPointerCast;
6513         return Compatible;
6514       }
6515 
6516     return Incompatible;
6517   }
6518 
6519   // Conversions to Objective-C pointers.
6520   if (isa<ObjCObjectPointerType>(LHSType)) {
6521     // A* -> B*
6522     if (RHSType->isObjCObjectPointerType()) {
6523       Kind = CK_BitCast;
6524       Sema::AssignConvertType result =
6525         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6526       if (getLangOpts().ObjCAutoRefCount &&
6527           result == Compatible &&
6528           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6529         result = IncompatibleObjCWeakRef;
6530       return result;
6531     }
6532 
6533     // int or null -> A*
6534     if (RHSType->isIntegerType()) {
6535       Kind = CK_IntegralToPointer; // FIXME: null
6536       return IntToPointer;
6537     }
6538 
6539     // In general, C pointers are not compatible with ObjC object pointers,
6540     // with two exceptions:
6541     if (isa<PointerType>(RHSType)) {
6542       Kind = CK_CPointerToObjCPointerCast;
6543 
6544       //  - conversions from 'void*'
6545       if (RHSType->isVoidPointerType()) {
6546         return Compatible;
6547       }
6548 
6549       //  - conversions to 'Class' from its redefinition type
6550       if (LHSType->isObjCClassType() &&
6551           Context.hasSameType(RHSType,
6552                               Context.getObjCClassRedefinitionType())) {
6553         return Compatible;
6554       }
6555 
6556       return IncompatiblePointer;
6557     }
6558 
6559     // Only under strict condition T^ is compatible with an Objective-C pointer.
6560     if (RHSType->isBlockPointerType() &&
6561         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6562       maybeExtendBlockObject(*this, RHS);
6563       Kind = CK_BlockPointerToObjCPointerCast;
6564       return Compatible;
6565     }
6566 
6567     return Incompatible;
6568   }
6569 
6570   // Conversions from pointers that are not covered by the above.
6571   if (isa<PointerType>(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   // Conversions from Objective-C pointers that are not covered by the above.
6588   if (isa<ObjCObjectPointerType>(RHSType)) {
6589     // T* -> _Bool
6590     if (LHSType == Context.BoolTy) {
6591       Kind = CK_PointerToBoolean;
6592       return Compatible;
6593     }
6594 
6595     // T* -> int
6596     if (LHSType->isIntegerType()) {
6597       Kind = CK_PointerToIntegral;
6598       return PointerToInt;
6599     }
6600 
6601     return Incompatible;
6602   }
6603 
6604   // struct A -> struct B
6605   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6606     if (Context.typesAreCompatible(LHSType, RHSType)) {
6607       Kind = CK_NoOp;
6608       return Compatible;
6609     }
6610   }
6611 
6612   return Incompatible;
6613 }
6614 
6615 /// \brief Constructs a transparent union from an expression that is
6616 /// used to initialize the transparent union.
6617 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6618                                       ExprResult &EResult, QualType UnionType,
6619                                       FieldDecl *Field) {
6620   // Build an initializer list that designates the appropriate member
6621   // of the transparent union.
6622   Expr *E = EResult.get();
6623   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6624                                                    E, SourceLocation());
6625   Initializer->setType(UnionType);
6626   Initializer->setInitializedFieldInUnion(Field);
6627 
6628   // Build a compound literal constructing a value of the transparent
6629   // union type from this initializer list.
6630   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6631   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6632                                         VK_RValue, Initializer, false);
6633 }
6634 
6635 Sema::AssignConvertType
6636 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6637                                                ExprResult &RHS) {
6638   QualType RHSType = RHS.get()->getType();
6639 
6640   // If the ArgType is a Union type, we want to handle a potential
6641   // transparent_union GCC extension.
6642   const RecordType *UT = ArgType->getAsUnionType();
6643   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6644     return Incompatible;
6645 
6646   // The field to initialize within the transparent union.
6647   RecordDecl *UD = UT->getDecl();
6648   FieldDecl *InitField = nullptr;
6649   // It's compatible if the expression matches any of the fields.
6650   for (auto *it : UD->fields()) {
6651     if (it->getType()->isPointerType()) {
6652       // If the transparent union contains a pointer type, we allow:
6653       // 1) void pointer
6654       // 2) null pointer constant
6655       if (RHSType->isPointerType())
6656         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6657           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6658           InitField = it;
6659           break;
6660         }
6661 
6662       if (RHS.get()->isNullPointerConstant(Context,
6663                                            Expr::NPC_ValueDependentIsNull)) {
6664         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6665                                 CK_NullToPointer);
6666         InitField = it;
6667         break;
6668       }
6669     }
6670 
6671     CastKind Kind = CK_Invalid;
6672     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6673           == Compatible) {
6674       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6675       InitField = it;
6676       break;
6677     }
6678   }
6679 
6680   if (!InitField)
6681     return Incompatible;
6682 
6683   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6684   return Compatible;
6685 }
6686 
6687 Sema::AssignConvertType
6688 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6689                                        bool Diagnose,
6690                                        bool DiagnoseCFAudited) {
6691   if (getLangOpts().CPlusPlus) {
6692     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6693       // C++ 5.17p3: If the left operand is not of class type, the
6694       // expression is implicitly converted (C++ 4) to the
6695       // cv-unqualified type of the left operand.
6696       ExprResult Res;
6697       if (Diagnose) {
6698         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6699                                         AA_Assigning);
6700       } else {
6701         ImplicitConversionSequence ICS =
6702             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6703                                   /*SuppressUserConversions=*/false,
6704                                   /*AllowExplicit=*/false,
6705                                   /*InOverloadResolution=*/false,
6706                                   /*CStyle=*/false,
6707                                   /*AllowObjCWritebackConversion=*/false);
6708         if (ICS.isFailure())
6709           return Incompatible;
6710         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6711                                         ICS, AA_Assigning);
6712       }
6713       if (Res.isInvalid())
6714         return Incompatible;
6715       Sema::AssignConvertType result = Compatible;
6716       if (getLangOpts().ObjCAutoRefCount &&
6717           !CheckObjCARCUnavailableWeakConversion(LHSType,
6718                                                  RHS.get()->getType()))
6719         result = IncompatibleObjCWeakRef;
6720       RHS = Res;
6721       return result;
6722     }
6723 
6724     // FIXME: Currently, we fall through and treat C++ classes like C
6725     // structures.
6726     // FIXME: We also fall through for atomics; not sure what should
6727     // happen there, though.
6728   }
6729 
6730   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6731   // a null pointer constant.
6732   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6733        LHSType->isBlockPointerType()) &&
6734       RHS.get()->isNullPointerConstant(Context,
6735                                        Expr::NPC_ValueDependentIsNull)) {
6736     CastKind Kind;
6737     CXXCastPath Path;
6738     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6739     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6740     return Compatible;
6741   }
6742 
6743   // This check seems unnatural, however it is necessary to ensure the proper
6744   // conversion of functions/arrays. If the conversion were done for all
6745   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6746   // expressions that suppress this implicit conversion (&, sizeof).
6747   //
6748   // Suppress this for references: C++ 8.5.3p5.
6749   if (!LHSType->isReferenceType()) {
6750     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6751     if (RHS.isInvalid())
6752       return Incompatible;
6753   }
6754 
6755   CastKind Kind = CK_Invalid;
6756   Sema::AssignConvertType result =
6757     CheckAssignmentConstraints(LHSType, RHS, Kind);
6758 
6759   // C99 6.5.16.1p2: The value of the right operand is converted to the
6760   // type of the assignment expression.
6761   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6762   // so that we can use references in built-in functions even in C.
6763   // The getNonReferenceType() call makes sure that the resulting expression
6764   // does not have reference type.
6765   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6766     QualType Ty = LHSType.getNonLValueExprType(Context);
6767     Expr *E = RHS.get();
6768     if (getLangOpts().ObjCAutoRefCount)
6769       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6770                              DiagnoseCFAudited);
6771     if (getLangOpts().ObjC1 &&
6772         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6773                                           LHSType, E->getType(), E) ||
6774          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6775       RHS = E;
6776       return Compatible;
6777     }
6778 
6779     RHS = ImpCastExprToType(E, Ty, Kind);
6780   }
6781   return result;
6782 }
6783 
6784 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6785                                ExprResult &RHS) {
6786   Diag(Loc, diag::err_typecheck_invalid_operands)
6787     << LHS.get()->getType() << RHS.get()->getType()
6788     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6789   return QualType();
6790 }
6791 
6792 /// Try to convert a value of non-vector type to a vector type by converting
6793 /// the type to the element type of the vector and then performing a splat.
6794 /// If the language is OpenCL, we only use conversions that promote scalar
6795 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6796 /// for float->int.
6797 ///
6798 /// \param scalar - if non-null, actually perform the conversions
6799 /// \return true if the operation fails (but without diagnosing the failure)
6800 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6801                                      QualType scalarTy,
6802                                      QualType vectorEltTy,
6803                                      QualType vectorTy) {
6804   // The conversion to apply to the scalar before splatting it,
6805   // if necessary.
6806   CastKind scalarCast = CK_Invalid;
6807 
6808   if (vectorEltTy->isIntegralType(S.Context)) {
6809     if (!scalarTy->isIntegralType(S.Context))
6810       return true;
6811     if (S.getLangOpts().OpenCL &&
6812         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6813       return true;
6814     scalarCast = CK_IntegralCast;
6815   } else if (vectorEltTy->isRealFloatingType()) {
6816     if (scalarTy->isRealFloatingType()) {
6817       if (S.getLangOpts().OpenCL &&
6818           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6819         return true;
6820       scalarCast = CK_FloatingCast;
6821     }
6822     else if (scalarTy->isIntegralType(S.Context))
6823       scalarCast = CK_IntegralToFloating;
6824     else
6825       return true;
6826   } else {
6827     return true;
6828   }
6829 
6830   // Adjust scalar if desired.
6831   if (scalar) {
6832     if (scalarCast != CK_Invalid)
6833       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6834     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6835   }
6836   return false;
6837 }
6838 
6839 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6840                                    SourceLocation Loc, bool IsCompAssign) {
6841   if (!IsCompAssign) {
6842     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6843     if (LHS.isInvalid())
6844       return QualType();
6845   }
6846   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6847   if (RHS.isInvalid())
6848     return QualType();
6849 
6850   // For conversion purposes, we ignore any qualifiers.
6851   // For example, "const float" and "float" are equivalent.
6852   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6853   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6854 
6855   // If the vector types are identical, return.
6856   if (Context.hasSameType(LHSType, RHSType))
6857     return LHSType;
6858 
6859   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6860   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6861   assert(LHSVecType || RHSVecType);
6862 
6863   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6864   if (LHSVecType && RHSVecType &&
6865       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6866     if (isa<ExtVectorType>(LHSVecType)) {
6867       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6868       return LHSType;
6869     }
6870 
6871     if (!IsCompAssign)
6872       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6873     return RHSType;
6874   }
6875 
6876   // If there's an ext-vector type and a scalar, try to convert the scalar to
6877   // the vector element type and splat.
6878   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6879     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6880                                   LHSVecType->getElementType(), LHSType))
6881       return LHSType;
6882   }
6883   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6884     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6885                                   LHSType, RHSVecType->getElementType(),
6886                                   RHSType))
6887       return RHSType;
6888   }
6889 
6890   // If we're allowing lax vector conversions, only the total (data) size
6891   // needs to be the same.
6892   // FIXME: Should we really be allowing this?
6893   // FIXME: We really just pick the LHS type arbitrarily?
6894   if (isLaxVectorConversion(RHSType, LHSType)) {
6895     QualType resultType = LHSType;
6896     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
6897     return resultType;
6898   }
6899 
6900   // Okay, the expression is invalid.
6901 
6902   // If there's a non-vector, non-real operand, diagnose that.
6903   if ((!RHSVecType && !RHSType->isRealType()) ||
6904       (!LHSVecType && !LHSType->isRealType())) {
6905     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6906       << LHSType << RHSType
6907       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6908     return QualType();
6909   }
6910 
6911   // Otherwise, use the generic diagnostic.
6912   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6913     << LHSType << RHSType
6914     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6915   return QualType();
6916 }
6917 
6918 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6919 // expression.  These are mainly cases where the null pointer is used as an
6920 // integer instead of a pointer.
6921 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6922                                 SourceLocation Loc, bool IsCompare) {
6923   // The canonical way to check for a GNU null is with isNullPointerConstant,
6924   // but we use a bit of a hack here for speed; this is a relatively
6925   // hot path, and isNullPointerConstant is slow.
6926   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6927   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6928 
6929   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6930 
6931   // Avoid analyzing cases where the result will either be invalid (and
6932   // diagnosed as such) or entirely valid and not something to warn about.
6933   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6934       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6935     return;
6936 
6937   // Comparison operations would not make sense with a null pointer no matter
6938   // what the other expression is.
6939   if (!IsCompare) {
6940     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6941         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6942         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6943     return;
6944   }
6945 
6946   // The rest of the operations only make sense with a null pointer
6947   // if the other expression is a pointer.
6948   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6949       NonNullType->canDecayToPointerType())
6950     return;
6951 
6952   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6953       << LHSNull /* LHS is NULL */ << NonNullType
6954       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6955 }
6956 
6957 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6958                                            SourceLocation Loc,
6959                                            bool IsCompAssign, bool IsDiv) {
6960   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6961 
6962   if (LHS.get()->getType()->isVectorType() ||
6963       RHS.get()->getType()->isVectorType())
6964     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6965 
6966   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6967   if (LHS.isInvalid() || RHS.isInvalid())
6968     return QualType();
6969 
6970 
6971   if (compType.isNull() || !compType->isArithmeticType())
6972     return InvalidOperands(Loc, LHS, RHS);
6973 
6974   // Check for division by zero.
6975   llvm::APSInt RHSValue;
6976   if (IsDiv && !RHS.get()->isValueDependent() &&
6977       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6978     DiagRuntimeBehavior(Loc, RHS.get(),
6979                         PDiag(diag::warn_division_by_zero)
6980                           << RHS.get()->getSourceRange());
6981 
6982   return compType;
6983 }
6984 
6985 QualType Sema::CheckRemainderOperands(
6986   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6987   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6988 
6989   if (LHS.get()->getType()->isVectorType() ||
6990       RHS.get()->getType()->isVectorType()) {
6991     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6992         RHS.get()->getType()->hasIntegerRepresentation())
6993       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6994     return InvalidOperands(Loc, LHS, RHS);
6995   }
6996 
6997   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6998   if (LHS.isInvalid() || RHS.isInvalid())
6999     return QualType();
7000 
7001   if (compType.isNull() || !compType->isIntegerType())
7002     return InvalidOperands(Loc, LHS, RHS);
7003 
7004   // Check for remainder by zero.
7005   llvm::APSInt RHSValue;
7006   if (!RHS.get()->isValueDependent() &&
7007       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7008     DiagRuntimeBehavior(Loc, RHS.get(),
7009                         PDiag(diag::warn_remainder_by_zero)
7010                           << RHS.get()->getSourceRange());
7011 
7012   return compType;
7013 }
7014 
7015 /// \brief Diagnose invalid arithmetic on two void pointers.
7016 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7017                                                 Expr *LHSExpr, Expr *RHSExpr) {
7018   S.Diag(Loc, S.getLangOpts().CPlusPlus
7019                 ? diag::err_typecheck_pointer_arith_void_type
7020                 : diag::ext_gnu_void_ptr)
7021     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7022                             << RHSExpr->getSourceRange();
7023 }
7024 
7025 /// \brief Diagnose invalid arithmetic on a void pointer.
7026 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7027                                             Expr *Pointer) {
7028   S.Diag(Loc, S.getLangOpts().CPlusPlus
7029                 ? diag::err_typecheck_pointer_arith_void_type
7030                 : diag::ext_gnu_void_ptr)
7031     << 0 /* one pointer */ << Pointer->getSourceRange();
7032 }
7033 
7034 /// \brief Diagnose invalid arithmetic on two function pointers.
7035 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7036                                                     Expr *LHS, Expr *RHS) {
7037   assert(LHS->getType()->isAnyPointerType());
7038   assert(RHS->getType()->isAnyPointerType());
7039   S.Diag(Loc, S.getLangOpts().CPlusPlus
7040                 ? diag::err_typecheck_pointer_arith_function_type
7041                 : diag::ext_gnu_ptr_func_arith)
7042     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7043     // We only show the second type if it differs from the first.
7044     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7045                                                    RHS->getType())
7046     << RHS->getType()->getPointeeType()
7047     << LHS->getSourceRange() << RHS->getSourceRange();
7048 }
7049 
7050 /// \brief Diagnose invalid arithmetic on a function pointer.
7051 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7052                                                 Expr *Pointer) {
7053   assert(Pointer->getType()->isAnyPointerType());
7054   S.Diag(Loc, S.getLangOpts().CPlusPlus
7055                 ? diag::err_typecheck_pointer_arith_function_type
7056                 : diag::ext_gnu_ptr_func_arith)
7057     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7058     << 0 /* one pointer, so only one type */
7059     << Pointer->getSourceRange();
7060 }
7061 
7062 /// \brief Emit error if Operand is incomplete pointer type
7063 ///
7064 /// \returns True if pointer has incomplete type
7065 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7066                                                  Expr *Operand) {
7067   assert(Operand->getType()->isAnyPointerType() &&
7068          !Operand->getType()->isDependentType());
7069   QualType PointeeTy = Operand->getType()->getPointeeType();
7070   return S.RequireCompleteType(Loc, PointeeTy,
7071                                diag::err_typecheck_arithmetic_incomplete_type,
7072                                PointeeTy, Operand->getSourceRange());
7073 }
7074 
7075 /// \brief Check the validity of an arithmetic pointer operand.
7076 ///
7077 /// If the operand has pointer type, this code will check for pointer types
7078 /// which are invalid in arithmetic operations. These will be diagnosed
7079 /// appropriately, including whether or not the use is supported as an
7080 /// extension.
7081 ///
7082 /// \returns True when the operand is valid to use (even if as an extension).
7083 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7084                                             Expr *Operand) {
7085   if (!Operand->getType()->isAnyPointerType()) return true;
7086 
7087   QualType PointeeTy = Operand->getType()->getPointeeType();
7088   if (PointeeTy->isVoidType()) {
7089     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7090     return !S.getLangOpts().CPlusPlus;
7091   }
7092   if (PointeeTy->isFunctionType()) {
7093     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7094     return !S.getLangOpts().CPlusPlus;
7095   }
7096 
7097   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7098 
7099   return true;
7100 }
7101 
7102 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7103 /// operands.
7104 ///
7105 /// This routine will diagnose any invalid arithmetic on pointer operands much
7106 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7107 /// for emitting a single diagnostic even for operations where both LHS and RHS
7108 /// are (potentially problematic) pointers.
7109 ///
7110 /// \returns True when the operand is valid to use (even if as an extension).
7111 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7112                                                 Expr *LHSExpr, Expr *RHSExpr) {
7113   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7114   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7115   if (!isLHSPointer && !isRHSPointer) return true;
7116 
7117   QualType LHSPointeeTy, RHSPointeeTy;
7118   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7119   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7120 
7121   // Check for arithmetic on pointers to incomplete types.
7122   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7123   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7124   if (isLHSVoidPtr || isRHSVoidPtr) {
7125     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7126     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7127     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7128 
7129     return !S.getLangOpts().CPlusPlus;
7130   }
7131 
7132   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7133   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7134   if (isLHSFuncPtr || isRHSFuncPtr) {
7135     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7136     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7137                                                                 RHSExpr);
7138     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7139 
7140     return !S.getLangOpts().CPlusPlus;
7141   }
7142 
7143   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7144     return false;
7145   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7146     return false;
7147 
7148   return true;
7149 }
7150 
7151 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7152 /// literal.
7153 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7154                                   Expr *LHSExpr, Expr *RHSExpr) {
7155   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7156   Expr* IndexExpr = RHSExpr;
7157   if (!StrExpr) {
7158     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7159     IndexExpr = LHSExpr;
7160   }
7161 
7162   bool IsStringPlusInt = StrExpr &&
7163       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7164   if (!IsStringPlusInt)
7165     return;
7166 
7167   llvm::APSInt index;
7168   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7169     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7170     if (index.isNonNegative() &&
7171         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7172                               index.isUnsigned()))
7173       return;
7174   }
7175 
7176   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7177   Self.Diag(OpLoc, diag::warn_string_plus_int)
7178       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7179 
7180   // Only print a fixit for "str" + int, not for int + "str".
7181   if (IndexExpr == RHSExpr) {
7182     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7183     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7184         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7185         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7186         << FixItHint::CreateInsertion(EndLoc, "]");
7187   } else
7188     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7189 }
7190 
7191 /// \brief Emit a warning when adding a char literal to a string.
7192 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7193                                    Expr *LHSExpr, Expr *RHSExpr) {
7194   const DeclRefExpr *StringRefExpr =
7195       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7196   const CharacterLiteral *CharExpr =
7197       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7198   if (!StringRefExpr) {
7199     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7200     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7201   }
7202 
7203   if (!CharExpr || !StringRefExpr)
7204     return;
7205 
7206   const QualType StringType = StringRefExpr->getType();
7207 
7208   // Return if not a PointerType.
7209   if (!StringType->isAnyPointerType())
7210     return;
7211 
7212   // Return if not a CharacterType.
7213   if (!StringType->getPointeeType()->isAnyCharacterType())
7214     return;
7215 
7216   ASTContext &Ctx = Self.getASTContext();
7217   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7218 
7219   const QualType CharType = CharExpr->getType();
7220   if (!CharType->isAnyCharacterType() &&
7221       CharType->isIntegerType() &&
7222       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7223     Self.Diag(OpLoc, diag::warn_string_plus_char)
7224         << DiagRange << Ctx.CharTy;
7225   } else {
7226     Self.Diag(OpLoc, diag::warn_string_plus_char)
7227         << DiagRange << CharExpr->getType();
7228   }
7229 
7230   // Only print a fixit for str + char, not for char + str.
7231   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7232     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7233     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7234         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7235         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7236         << FixItHint::CreateInsertion(EndLoc, "]");
7237   } else {
7238     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7239   }
7240 }
7241 
7242 /// \brief Emit error when two pointers are incompatible.
7243 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7244                                            Expr *LHSExpr, Expr *RHSExpr) {
7245   assert(LHSExpr->getType()->isAnyPointerType());
7246   assert(RHSExpr->getType()->isAnyPointerType());
7247   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7248     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7249     << RHSExpr->getSourceRange();
7250 }
7251 
7252 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7253     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7254     QualType* CompLHSTy) {
7255   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7256 
7257   if (LHS.get()->getType()->isVectorType() ||
7258       RHS.get()->getType()->isVectorType()) {
7259     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7260     if (CompLHSTy) *CompLHSTy = compType;
7261     return compType;
7262   }
7263 
7264   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7265   if (LHS.isInvalid() || RHS.isInvalid())
7266     return QualType();
7267 
7268   // Diagnose "string literal" '+' int and string '+' "char literal".
7269   if (Opc == BO_Add) {
7270     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7271     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7272   }
7273 
7274   // handle the common case first (both operands are arithmetic).
7275   if (!compType.isNull() && compType->isArithmeticType()) {
7276     if (CompLHSTy) *CompLHSTy = compType;
7277     return compType;
7278   }
7279 
7280   // Type-checking.  Ultimately the pointer's going to be in PExp;
7281   // note that we bias towards the LHS being the pointer.
7282   Expr *PExp = LHS.get(), *IExp = RHS.get();
7283 
7284   bool isObjCPointer;
7285   if (PExp->getType()->isPointerType()) {
7286     isObjCPointer = false;
7287   } else if (PExp->getType()->isObjCObjectPointerType()) {
7288     isObjCPointer = true;
7289   } else {
7290     std::swap(PExp, IExp);
7291     if (PExp->getType()->isPointerType()) {
7292       isObjCPointer = false;
7293     } else if (PExp->getType()->isObjCObjectPointerType()) {
7294       isObjCPointer = true;
7295     } else {
7296       return InvalidOperands(Loc, LHS, RHS);
7297     }
7298   }
7299   assert(PExp->getType()->isAnyPointerType());
7300 
7301   if (!IExp->getType()->isIntegerType())
7302     return InvalidOperands(Loc, LHS, RHS);
7303 
7304   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7305     return QualType();
7306 
7307   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7308     return QualType();
7309 
7310   // Check array bounds for pointer arithemtic
7311   CheckArrayAccess(PExp, IExp);
7312 
7313   if (CompLHSTy) {
7314     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7315     if (LHSTy.isNull()) {
7316       LHSTy = LHS.get()->getType();
7317       if (LHSTy->isPromotableIntegerType())
7318         LHSTy = Context.getPromotedIntegerType(LHSTy);
7319     }
7320     *CompLHSTy = LHSTy;
7321   }
7322 
7323   return PExp->getType();
7324 }
7325 
7326 // C99 6.5.6
7327 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7328                                         SourceLocation Loc,
7329                                         QualType* CompLHSTy) {
7330   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7331 
7332   if (LHS.get()->getType()->isVectorType() ||
7333       RHS.get()->getType()->isVectorType()) {
7334     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7335     if (CompLHSTy) *CompLHSTy = compType;
7336     return compType;
7337   }
7338 
7339   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7340   if (LHS.isInvalid() || RHS.isInvalid())
7341     return QualType();
7342 
7343   // Enforce type constraints: C99 6.5.6p3.
7344 
7345   // Handle the common case first (both operands are arithmetic).
7346   if (!compType.isNull() && compType->isArithmeticType()) {
7347     if (CompLHSTy) *CompLHSTy = compType;
7348     return compType;
7349   }
7350 
7351   // Either ptr - int   or   ptr - ptr.
7352   if (LHS.get()->getType()->isAnyPointerType()) {
7353     QualType lpointee = LHS.get()->getType()->getPointeeType();
7354 
7355     // Diagnose bad cases where we step over interface counts.
7356     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7357         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7358       return QualType();
7359 
7360     // The result type of a pointer-int computation is the pointer type.
7361     if (RHS.get()->getType()->isIntegerType()) {
7362       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7363         return QualType();
7364 
7365       // Check array bounds for pointer arithemtic
7366       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7367                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7368 
7369       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7370       return LHS.get()->getType();
7371     }
7372 
7373     // Handle pointer-pointer subtractions.
7374     if (const PointerType *RHSPTy
7375           = RHS.get()->getType()->getAs<PointerType>()) {
7376       QualType rpointee = RHSPTy->getPointeeType();
7377 
7378       if (getLangOpts().CPlusPlus) {
7379         // Pointee types must be the same: C++ [expr.add]
7380         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7381           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7382         }
7383       } else {
7384         // Pointee types must be compatible C99 6.5.6p3
7385         if (!Context.typesAreCompatible(
7386                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7387                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7388           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7389           return QualType();
7390         }
7391       }
7392 
7393       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7394                                                LHS.get(), RHS.get()))
7395         return QualType();
7396 
7397       // The pointee type may have zero size.  As an extension, a structure or
7398       // union may have zero size or an array may have zero length.  In this
7399       // case subtraction does not make sense.
7400       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7401         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7402         if (ElementSize.isZero()) {
7403           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7404             << rpointee.getUnqualifiedType()
7405             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7406         }
7407       }
7408 
7409       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7410       return Context.getPointerDiffType();
7411     }
7412   }
7413 
7414   return InvalidOperands(Loc, LHS, RHS);
7415 }
7416 
7417 static bool isScopedEnumerationType(QualType T) {
7418   if (const EnumType *ET = dyn_cast<EnumType>(T))
7419     return ET->getDecl()->isScoped();
7420   return false;
7421 }
7422 
7423 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7424                                    SourceLocation Loc, unsigned Opc,
7425                                    QualType LHSType) {
7426   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7427   // so skip remaining warnings as we don't want to modify values within Sema.
7428   if (S.getLangOpts().OpenCL)
7429     return;
7430 
7431   llvm::APSInt Right;
7432   // Check right/shifter operand
7433   if (RHS.get()->isValueDependent() ||
7434       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7435     return;
7436 
7437   if (Right.isNegative()) {
7438     S.DiagRuntimeBehavior(Loc, RHS.get(),
7439                           S.PDiag(diag::warn_shift_negative)
7440                             << RHS.get()->getSourceRange());
7441     return;
7442   }
7443   llvm::APInt LeftBits(Right.getBitWidth(),
7444                        S.Context.getTypeSize(LHS.get()->getType()));
7445   if (Right.uge(LeftBits)) {
7446     S.DiagRuntimeBehavior(Loc, RHS.get(),
7447                           S.PDiag(diag::warn_shift_gt_typewidth)
7448                             << RHS.get()->getSourceRange());
7449     return;
7450   }
7451   if (Opc != BO_Shl)
7452     return;
7453 
7454   // When left shifting an ICE which is signed, we can check for overflow which
7455   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7456   // integers have defined behavior modulo one more than the maximum value
7457   // representable in the result type, so never warn for those.
7458   llvm::APSInt Left;
7459   if (LHS.get()->isValueDependent() ||
7460       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7461       LHSType->hasUnsignedIntegerRepresentation())
7462     return;
7463   llvm::APInt ResultBits =
7464       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7465   if (LeftBits.uge(ResultBits))
7466     return;
7467   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7468   Result = Result.shl(Right);
7469 
7470   // Print the bit representation of the signed integer as an unsigned
7471   // hexadecimal number.
7472   SmallString<40> HexResult;
7473   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7474 
7475   // If we are only missing a sign bit, this is less likely to result in actual
7476   // bugs -- if the result is cast back to an unsigned type, it will have the
7477   // expected value. Thus we place this behind a different warning that can be
7478   // turned off separately if needed.
7479   if (LeftBits == ResultBits - 1) {
7480     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7481         << HexResult.str() << LHSType
7482         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7483     return;
7484   }
7485 
7486   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7487     << HexResult.str() << Result.getMinSignedBits() << LHSType
7488     << Left.getBitWidth() << LHS.get()->getSourceRange()
7489     << RHS.get()->getSourceRange();
7490 }
7491 
7492 // C99 6.5.7
7493 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7494                                   SourceLocation Loc, unsigned Opc,
7495                                   bool IsCompAssign) {
7496   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7497 
7498   // Vector shifts promote their scalar inputs to vector type.
7499   if (LHS.get()->getType()->isVectorType() ||
7500       RHS.get()->getType()->isVectorType())
7501     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7502 
7503   // Shifts don't perform usual arithmetic conversions, they just do integer
7504   // promotions on each operand. C99 6.5.7p3
7505 
7506   // For the LHS, do usual unary conversions, but then reset them away
7507   // if this is a compound assignment.
7508   ExprResult OldLHS = LHS;
7509   LHS = UsualUnaryConversions(LHS.get());
7510   if (LHS.isInvalid())
7511     return QualType();
7512   QualType LHSType = LHS.get()->getType();
7513   if (IsCompAssign) LHS = OldLHS;
7514 
7515   // The RHS is simpler.
7516   RHS = UsualUnaryConversions(RHS.get());
7517   if (RHS.isInvalid())
7518     return QualType();
7519   QualType RHSType = RHS.get()->getType();
7520 
7521   // C99 6.5.7p2: Each of the operands shall have integer type.
7522   if (!LHSType->hasIntegerRepresentation() ||
7523       !RHSType->hasIntegerRepresentation())
7524     return InvalidOperands(Loc, LHS, RHS);
7525 
7526   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7527   // hasIntegerRepresentation() above instead of this.
7528   if (isScopedEnumerationType(LHSType) ||
7529       isScopedEnumerationType(RHSType)) {
7530     return InvalidOperands(Loc, LHS, RHS);
7531   }
7532   // Sanity-check shift operands
7533   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7534 
7535   // "The type of the result is that of the promoted left operand."
7536   return LHSType;
7537 }
7538 
7539 static bool IsWithinTemplateSpecialization(Decl *D) {
7540   if (DeclContext *DC = D->getDeclContext()) {
7541     if (isa<ClassTemplateSpecializationDecl>(DC))
7542       return true;
7543     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7544       return FD->isFunctionTemplateSpecialization();
7545   }
7546   return false;
7547 }
7548 
7549 /// If two different enums are compared, raise a warning.
7550 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7551                                 Expr *RHS) {
7552   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7553   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7554 
7555   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7556   if (!LHSEnumType)
7557     return;
7558   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7559   if (!RHSEnumType)
7560     return;
7561 
7562   // Ignore anonymous enums.
7563   if (!LHSEnumType->getDecl()->getIdentifier())
7564     return;
7565   if (!RHSEnumType->getDecl()->getIdentifier())
7566     return;
7567 
7568   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7569     return;
7570 
7571   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7572       << LHSStrippedType << RHSStrippedType
7573       << LHS->getSourceRange() << RHS->getSourceRange();
7574 }
7575 
7576 /// \brief Diagnose bad pointer comparisons.
7577 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7578                                               ExprResult &LHS, ExprResult &RHS,
7579                                               bool IsError) {
7580   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7581                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7582     << LHS.get()->getType() << RHS.get()->getType()
7583     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7584 }
7585 
7586 /// \brief Returns false if the pointers are converted to a composite type,
7587 /// true otherwise.
7588 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7589                                            ExprResult &LHS, ExprResult &RHS) {
7590   // C++ [expr.rel]p2:
7591   //   [...] Pointer conversions (4.10) and qualification
7592   //   conversions (4.4) are performed on pointer operands (or on
7593   //   a pointer operand and a null pointer constant) to bring
7594   //   them to their composite pointer type. [...]
7595   //
7596   // C++ [expr.eq]p1 uses the same notion for (in)equality
7597   // comparisons of pointers.
7598 
7599   // C++ [expr.eq]p2:
7600   //   In addition, pointers to members can be compared, or a pointer to
7601   //   member and a null pointer constant. Pointer to member conversions
7602   //   (4.11) and qualification conversions (4.4) are performed to bring
7603   //   them to a common type. If one operand is a null pointer constant,
7604   //   the common type is the type of the other operand. Otherwise, the
7605   //   common type is a pointer to member type similar (4.4) to the type
7606   //   of one of the operands, with a cv-qualification signature (4.4)
7607   //   that is the union of the cv-qualification signatures of the operand
7608   //   types.
7609 
7610   QualType LHSType = LHS.get()->getType();
7611   QualType RHSType = RHS.get()->getType();
7612   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7613          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7614 
7615   bool NonStandardCompositeType = false;
7616   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7617   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7618   if (T.isNull()) {
7619     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7620     return true;
7621   }
7622 
7623   if (NonStandardCompositeType)
7624     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7625       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7626       << RHS.get()->getSourceRange();
7627 
7628   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7629   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7630   return false;
7631 }
7632 
7633 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7634                                                     ExprResult &LHS,
7635                                                     ExprResult &RHS,
7636                                                     bool IsError) {
7637   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7638                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7639     << LHS.get()->getType() << RHS.get()->getType()
7640     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7641 }
7642 
7643 static bool isObjCObjectLiteral(ExprResult &E) {
7644   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7645   case Stmt::ObjCArrayLiteralClass:
7646   case Stmt::ObjCDictionaryLiteralClass:
7647   case Stmt::ObjCStringLiteralClass:
7648   case Stmt::ObjCBoxedExprClass:
7649     return true;
7650   default:
7651     // Note that ObjCBoolLiteral is NOT an object literal!
7652     return false;
7653   }
7654 }
7655 
7656 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7657   const ObjCObjectPointerType *Type =
7658     LHS->getType()->getAs<ObjCObjectPointerType>();
7659 
7660   // If this is not actually an Objective-C object, bail out.
7661   if (!Type)
7662     return false;
7663 
7664   // Get the LHS object's interface type.
7665   QualType InterfaceType = Type->getPointeeType();
7666   if (const ObjCObjectType *iQFaceTy =
7667       InterfaceType->getAsObjCQualifiedInterfaceType())
7668     InterfaceType = iQFaceTy->getBaseType();
7669 
7670   // If the RHS isn't an Objective-C object, bail out.
7671   if (!RHS->getType()->isObjCObjectPointerType())
7672     return false;
7673 
7674   // Try to find the -isEqual: method.
7675   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7676   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7677                                                       InterfaceType,
7678                                                       /*instance=*/true);
7679   if (!Method) {
7680     if (Type->isObjCIdType()) {
7681       // For 'id', just check the global pool.
7682       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7683                                                   /*receiverId=*/true,
7684                                                   /*warn=*/false);
7685     } else {
7686       // Check protocols.
7687       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7688                                              /*instance=*/true);
7689     }
7690   }
7691 
7692   if (!Method)
7693     return false;
7694 
7695   QualType T = Method->param_begin()[0]->getType();
7696   if (!T->isObjCObjectPointerType())
7697     return false;
7698 
7699   QualType R = Method->getReturnType();
7700   if (!R->isScalarType())
7701     return false;
7702 
7703   return true;
7704 }
7705 
7706 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7707   FromE = FromE->IgnoreParenImpCasts();
7708   switch (FromE->getStmtClass()) {
7709     default:
7710       break;
7711     case Stmt::ObjCStringLiteralClass:
7712       // "string literal"
7713       return LK_String;
7714     case Stmt::ObjCArrayLiteralClass:
7715       // "array literal"
7716       return LK_Array;
7717     case Stmt::ObjCDictionaryLiteralClass:
7718       // "dictionary literal"
7719       return LK_Dictionary;
7720     case Stmt::BlockExprClass:
7721       return LK_Block;
7722     case Stmt::ObjCBoxedExprClass: {
7723       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7724       switch (Inner->getStmtClass()) {
7725         case Stmt::IntegerLiteralClass:
7726         case Stmt::FloatingLiteralClass:
7727         case Stmt::CharacterLiteralClass:
7728         case Stmt::ObjCBoolLiteralExprClass:
7729         case Stmt::CXXBoolLiteralExprClass:
7730           // "numeric literal"
7731           return LK_Numeric;
7732         case Stmt::ImplicitCastExprClass: {
7733           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7734           // Boolean literals can be represented by implicit casts.
7735           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7736             return LK_Numeric;
7737           break;
7738         }
7739         default:
7740           break;
7741       }
7742       return LK_Boxed;
7743     }
7744   }
7745   return LK_None;
7746 }
7747 
7748 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7749                                           ExprResult &LHS, ExprResult &RHS,
7750                                           BinaryOperator::Opcode Opc){
7751   Expr *Literal;
7752   Expr *Other;
7753   if (isObjCObjectLiteral(LHS)) {
7754     Literal = LHS.get();
7755     Other = RHS.get();
7756   } else {
7757     Literal = RHS.get();
7758     Other = LHS.get();
7759   }
7760 
7761   // Don't warn on comparisons against nil.
7762   Other = Other->IgnoreParenCasts();
7763   if (Other->isNullPointerConstant(S.getASTContext(),
7764                                    Expr::NPC_ValueDependentIsNotNull))
7765     return;
7766 
7767   // This should be kept in sync with warn_objc_literal_comparison.
7768   // LK_String should always be after the other literals, since it has its own
7769   // warning flag.
7770   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7771   assert(LiteralKind != Sema::LK_Block);
7772   if (LiteralKind == Sema::LK_None) {
7773     llvm_unreachable("Unknown Objective-C object literal kind");
7774   }
7775 
7776   if (LiteralKind == Sema::LK_String)
7777     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7778       << Literal->getSourceRange();
7779   else
7780     S.Diag(Loc, diag::warn_objc_literal_comparison)
7781       << LiteralKind << Literal->getSourceRange();
7782 
7783   if (BinaryOperator::isEqualityOp(Opc) &&
7784       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7785     SourceLocation Start = LHS.get()->getLocStart();
7786     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7787     CharSourceRange OpRange =
7788       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7789 
7790     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7791       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7792       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7793       << FixItHint::CreateInsertion(End, "]");
7794   }
7795 }
7796 
7797 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7798                                                 ExprResult &RHS,
7799                                                 SourceLocation Loc,
7800                                                 unsigned OpaqueOpc) {
7801   // This checking requires bools.
7802   if (!S.getLangOpts().Bool) return;
7803 
7804   // Check that left hand side is !something.
7805   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7806   if (!UO || UO->getOpcode() != UO_LNot) return;
7807 
7808   // Only check if the right hand side is non-bool arithmetic type.
7809   if (RHS.get()->getType()->isBooleanType()) return;
7810 
7811   // Make sure that the something in !something is not bool.
7812   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7813   if (SubExpr->getType()->isBooleanType()) return;
7814 
7815   // Emit warning.
7816   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7817       << Loc;
7818 
7819   // First note suggest !(x < y)
7820   SourceLocation FirstOpen = SubExpr->getLocStart();
7821   SourceLocation FirstClose = RHS.get()->getLocEnd();
7822   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7823   if (FirstClose.isInvalid())
7824     FirstOpen = SourceLocation();
7825   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7826       << FixItHint::CreateInsertion(FirstOpen, "(")
7827       << FixItHint::CreateInsertion(FirstClose, ")");
7828 
7829   // Second note suggests (!x) < y
7830   SourceLocation SecondOpen = LHS.get()->getLocStart();
7831   SourceLocation SecondClose = LHS.get()->getLocEnd();
7832   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7833   if (SecondClose.isInvalid())
7834     SecondOpen = SourceLocation();
7835   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7836       << FixItHint::CreateInsertion(SecondOpen, "(")
7837       << FixItHint::CreateInsertion(SecondClose, ")");
7838 }
7839 
7840 // Get the decl for a simple expression: a reference to a variable,
7841 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7842 static ValueDecl *getCompareDecl(Expr *E) {
7843   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7844     return DR->getDecl();
7845   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7846     if (Ivar->isFreeIvar())
7847       return Ivar->getDecl();
7848   }
7849   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7850     if (Mem->isImplicitAccess())
7851       return Mem->getMemberDecl();
7852   }
7853   return nullptr;
7854 }
7855 
7856 // C99 6.5.8, C++ [expr.rel]
7857 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7858                                     SourceLocation Loc, unsigned OpaqueOpc,
7859                                     bool IsRelational) {
7860   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7861 
7862   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7863 
7864   // Handle vector comparisons separately.
7865   if (LHS.get()->getType()->isVectorType() ||
7866       RHS.get()->getType()->isVectorType())
7867     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7868 
7869   QualType LHSType = LHS.get()->getType();
7870   QualType RHSType = RHS.get()->getType();
7871 
7872   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7873   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7874 
7875   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7876   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7877 
7878   if (!LHSType->hasFloatingRepresentation() &&
7879       !(LHSType->isBlockPointerType() && IsRelational) &&
7880       !LHS.get()->getLocStart().isMacroID() &&
7881       !RHS.get()->getLocStart().isMacroID() &&
7882       ActiveTemplateInstantiations.empty()) {
7883     // For non-floating point types, check for self-comparisons of the form
7884     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7885     // often indicate logic errors in the program.
7886     //
7887     // NOTE: Don't warn about comparison expressions resulting from macro
7888     // expansion. Also don't warn about comparisons which are only self
7889     // comparisons within a template specialization. The warnings should catch
7890     // obvious cases in the definition of the template anyways. The idea is to
7891     // warn when the typed comparison operator will always evaluate to the same
7892     // result.
7893     ValueDecl *DL = getCompareDecl(LHSStripped);
7894     ValueDecl *DR = getCompareDecl(RHSStripped);
7895     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7896       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7897                           << 0 // self-
7898                           << (Opc == BO_EQ
7899                               || Opc == BO_LE
7900                               || Opc == BO_GE));
7901     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7902                !DL->getType()->isReferenceType() &&
7903                !DR->getType()->isReferenceType()) {
7904         // what is it always going to eval to?
7905         char always_evals_to;
7906         switch(Opc) {
7907         case BO_EQ: // e.g. array1 == array2
7908           always_evals_to = 0; // false
7909           break;
7910         case BO_NE: // e.g. array1 != array2
7911           always_evals_to = 1; // true
7912           break;
7913         default:
7914           // best we can say is 'a constant'
7915           always_evals_to = 2; // e.g. array1 <= array2
7916           break;
7917         }
7918         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7919                             << 1 // array
7920                             << always_evals_to);
7921     }
7922 
7923     if (isa<CastExpr>(LHSStripped))
7924       LHSStripped = LHSStripped->IgnoreParenCasts();
7925     if (isa<CastExpr>(RHSStripped))
7926       RHSStripped = RHSStripped->IgnoreParenCasts();
7927 
7928     // Warn about comparisons against a string constant (unless the other
7929     // operand is null), the user probably wants strcmp.
7930     Expr *literalString = nullptr;
7931     Expr *literalStringStripped = nullptr;
7932     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7933         !RHSStripped->isNullPointerConstant(Context,
7934                                             Expr::NPC_ValueDependentIsNull)) {
7935       literalString = LHS.get();
7936       literalStringStripped = LHSStripped;
7937     } else if ((isa<StringLiteral>(RHSStripped) ||
7938                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7939                !LHSStripped->isNullPointerConstant(Context,
7940                                             Expr::NPC_ValueDependentIsNull)) {
7941       literalString = RHS.get();
7942       literalStringStripped = RHSStripped;
7943     }
7944 
7945     if (literalString) {
7946       DiagRuntimeBehavior(Loc, nullptr,
7947         PDiag(diag::warn_stringcompare)
7948           << isa<ObjCEncodeExpr>(literalStringStripped)
7949           << literalString->getSourceRange());
7950     }
7951   }
7952 
7953   // C99 6.5.8p3 / C99 6.5.9p4
7954   UsualArithmeticConversions(LHS, RHS);
7955   if (LHS.isInvalid() || RHS.isInvalid())
7956     return QualType();
7957 
7958   LHSType = LHS.get()->getType();
7959   RHSType = RHS.get()->getType();
7960 
7961   // The result of comparisons is 'bool' in C++, 'int' in C.
7962   QualType ResultTy = Context.getLogicalOperationType();
7963 
7964   if (IsRelational) {
7965     if (LHSType->isRealType() && RHSType->isRealType())
7966       return ResultTy;
7967   } else {
7968     // Check for comparisons of floating point operands using != and ==.
7969     if (LHSType->hasFloatingRepresentation())
7970       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7971 
7972     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7973       return ResultTy;
7974   }
7975 
7976   const Expr::NullPointerConstantKind LHSNullKind =
7977       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7978   const Expr::NullPointerConstantKind RHSNullKind =
7979       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7980   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7981   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7982 
7983   if (!IsRelational && LHSIsNull != RHSIsNull) {
7984     bool IsEquality = Opc == BO_EQ;
7985     if (RHSIsNull)
7986       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7987                                    RHS.get()->getSourceRange());
7988     else
7989       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7990                                    LHS.get()->getSourceRange());
7991   }
7992 
7993   // All of the following pointer-related warnings are GCC extensions, except
7994   // when handling null pointer constants.
7995   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7996     QualType LCanPointeeTy =
7997       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7998     QualType RCanPointeeTy =
7999       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8000 
8001     if (getLangOpts().CPlusPlus) {
8002       if (LCanPointeeTy == RCanPointeeTy)
8003         return ResultTy;
8004       if (!IsRelational &&
8005           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8006         // Valid unless comparison between non-null pointer and function pointer
8007         // This is a gcc extension compatibility comparison.
8008         // In a SFINAE context, we treat this as a hard error to maintain
8009         // conformance with the C++ standard.
8010         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8011             && !LHSIsNull && !RHSIsNull) {
8012           diagnoseFunctionPointerToVoidComparison(
8013               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8014 
8015           if (isSFINAEContext())
8016             return QualType();
8017 
8018           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8019           return ResultTy;
8020         }
8021       }
8022 
8023       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8024         return QualType();
8025       else
8026         return ResultTy;
8027     }
8028     // C99 6.5.9p2 and C99 6.5.8p2
8029     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8030                                    RCanPointeeTy.getUnqualifiedType())) {
8031       // Valid unless a relational comparison of function pointers
8032       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8033         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8034           << LHSType << RHSType << LHS.get()->getSourceRange()
8035           << RHS.get()->getSourceRange();
8036       }
8037     } else if (!IsRelational &&
8038                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8039       // Valid unless comparison between non-null pointer and function pointer
8040       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8041           && !LHSIsNull && !RHSIsNull)
8042         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8043                                                 /*isError*/false);
8044     } else {
8045       // Invalid
8046       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8047     }
8048     if (LCanPointeeTy != RCanPointeeTy) {
8049       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8050       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8051       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8052                                                : CK_BitCast;
8053       if (LHSIsNull && !RHSIsNull)
8054         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8055       else
8056         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8057     }
8058     return ResultTy;
8059   }
8060 
8061   if (getLangOpts().CPlusPlus) {
8062     // Comparison of nullptr_t with itself.
8063     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8064       return ResultTy;
8065 
8066     // Comparison of pointers with null pointer constants and equality
8067     // comparisons of member pointers to null pointer constants.
8068     if (RHSIsNull &&
8069         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8070          (!IsRelational &&
8071           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8072       RHS = ImpCastExprToType(RHS.get(), LHSType,
8073                         LHSType->isMemberPointerType()
8074                           ? CK_NullToMemberPointer
8075                           : CK_NullToPointer);
8076       return ResultTy;
8077     }
8078     if (LHSIsNull &&
8079         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8080          (!IsRelational &&
8081           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8082       LHS = ImpCastExprToType(LHS.get(), RHSType,
8083                         RHSType->isMemberPointerType()
8084                           ? CK_NullToMemberPointer
8085                           : CK_NullToPointer);
8086       return ResultTy;
8087     }
8088 
8089     // Comparison of member pointers.
8090     if (!IsRelational &&
8091         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8092       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8093         return QualType();
8094       else
8095         return ResultTy;
8096     }
8097 
8098     // Handle scoped enumeration types specifically, since they don't promote
8099     // to integers.
8100     if (LHS.get()->getType()->isEnumeralType() &&
8101         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8102                                        RHS.get()->getType()))
8103       return ResultTy;
8104   }
8105 
8106   // Handle block pointer types.
8107   if (!IsRelational && LHSType->isBlockPointerType() &&
8108       RHSType->isBlockPointerType()) {
8109     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8110     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8111 
8112     if (!LHSIsNull && !RHSIsNull &&
8113         !Context.typesAreCompatible(lpointee, rpointee)) {
8114       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8115         << LHSType << RHSType << LHS.get()->getSourceRange()
8116         << RHS.get()->getSourceRange();
8117     }
8118     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8119     return ResultTy;
8120   }
8121 
8122   // Allow block pointers to be compared with null pointer constants.
8123   if (!IsRelational
8124       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8125           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8126     if (!LHSIsNull && !RHSIsNull) {
8127       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8128              ->getPointeeType()->isVoidType())
8129             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8130                 ->getPointeeType()->isVoidType())))
8131         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8132           << LHSType << RHSType << LHS.get()->getSourceRange()
8133           << RHS.get()->getSourceRange();
8134     }
8135     if (LHSIsNull && !RHSIsNull)
8136       LHS = ImpCastExprToType(LHS.get(), RHSType,
8137                               RHSType->isPointerType() ? CK_BitCast
8138                                 : CK_AnyPointerToBlockPointerCast);
8139     else
8140       RHS = ImpCastExprToType(RHS.get(), LHSType,
8141                               LHSType->isPointerType() ? CK_BitCast
8142                                 : CK_AnyPointerToBlockPointerCast);
8143     return ResultTy;
8144   }
8145 
8146   if (LHSType->isObjCObjectPointerType() ||
8147       RHSType->isObjCObjectPointerType()) {
8148     const PointerType *LPT = LHSType->getAs<PointerType>();
8149     const PointerType *RPT = RHSType->getAs<PointerType>();
8150     if (LPT || RPT) {
8151       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8152       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8153 
8154       if (!LPtrToVoid && !RPtrToVoid &&
8155           !Context.typesAreCompatible(LHSType, RHSType)) {
8156         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8157                                           /*isError*/false);
8158       }
8159       if (LHSIsNull && !RHSIsNull) {
8160         Expr *E = LHS.get();
8161         if (getLangOpts().ObjCAutoRefCount)
8162           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8163         LHS = ImpCastExprToType(E, RHSType,
8164                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8165       }
8166       else {
8167         Expr *E = RHS.get();
8168         if (getLangOpts().ObjCAutoRefCount)
8169           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8170                                  Opc);
8171         RHS = ImpCastExprToType(E, LHSType,
8172                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8173       }
8174       return ResultTy;
8175     }
8176     if (LHSType->isObjCObjectPointerType() &&
8177         RHSType->isObjCObjectPointerType()) {
8178       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8179         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8180                                           /*isError*/false);
8181       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8182         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8183 
8184       if (LHSIsNull && !RHSIsNull)
8185         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8186       else
8187         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8188       return ResultTy;
8189     }
8190   }
8191   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8192       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8193     unsigned DiagID = 0;
8194     bool isError = false;
8195     if (LangOpts.DebuggerSupport) {
8196       // Under a debugger, allow the comparison of pointers to integers,
8197       // since users tend to want to compare addresses.
8198     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8199         (RHSIsNull && RHSType->isIntegerType())) {
8200       if (IsRelational && !getLangOpts().CPlusPlus)
8201         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8202     } else if (IsRelational && !getLangOpts().CPlusPlus)
8203       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8204     else if (getLangOpts().CPlusPlus) {
8205       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8206       isError = true;
8207     } else
8208       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8209 
8210     if (DiagID) {
8211       Diag(Loc, DiagID)
8212         << LHSType << RHSType << LHS.get()->getSourceRange()
8213         << RHS.get()->getSourceRange();
8214       if (isError)
8215         return QualType();
8216     }
8217 
8218     if (LHSType->isIntegerType())
8219       LHS = ImpCastExprToType(LHS.get(), RHSType,
8220                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8221     else
8222       RHS = ImpCastExprToType(RHS.get(), LHSType,
8223                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8224     return ResultTy;
8225   }
8226 
8227   // Handle block pointers.
8228   if (!IsRelational && RHSIsNull
8229       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8230     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8231     return ResultTy;
8232   }
8233   if (!IsRelational && LHSIsNull
8234       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8235     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8236     return ResultTy;
8237   }
8238 
8239   return InvalidOperands(Loc, LHS, RHS);
8240 }
8241 
8242 
8243 // Return a signed type that is of identical size and number of elements.
8244 // For floating point vectors, return an integer type of identical size
8245 // and number of elements.
8246 QualType Sema::GetSignedVectorType(QualType V) {
8247   const VectorType *VTy = V->getAs<VectorType>();
8248   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8249   if (TypeSize == Context.getTypeSize(Context.CharTy))
8250     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8251   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8252     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8253   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8254     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8255   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8256     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8257   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8258          "Unhandled vector element size in vector compare");
8259   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8260 }
8261 
8262 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8263 /// operates on extended vector types.  Instead of producing an IntTy result,
8264 /// like a scalar comparison, a vector comparison produces a vector of integer
8265 /// types.
8266 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8267                                           SourceLocation Loc,
8268                                           bool IsRelational) {
8269   // Check to make sure we're operating on vectors of the same type and width,
8270   // Allowing one side to be a scalar of element type.
8271   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8272   if (vType.isNull())
8273     return vType;
8274 
8275   QualType LHSType = LHS.get()->getType();
8276 
8277   // If AltiVec, the comparison results in a numeric type, i.e.
8278   // bool for C++, int for C
8279   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8280     return Context.getLogicalOperationType();
8281 
8282   // For non-floating point types, check for self-comparisons of the form
8283   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8284   // often indicate logic errors in the program.
8285   if (!LHSType->hasFloatingRepresentation() &&
8286       ActiveTemplateInstantiations.empty()) {
8287     if (DeclRefExpr* DRL
8288           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8289       if (DeclRefExpr* DRR
8290             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8291         if (DRL->getDecl() == DRR->getDecl())
8292           DiagRuntimeBehavior(Loc, nullptr,
8293                               PDiag(diag::warn_comparison_always)
8294                                 << 0 // self-
8295                                 << 2 // "a constant"
8296                               );
8297   }
8298 
8299   // Check for comparisons of floating point operands using != and ==.
8300   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8301     assert (RHS.get()->getType()->hasFloatingRepresentation());
8302     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8303   }
8304 
8305   // Return a signed type for the vector.
8306   return GetSignedVectorType(LHSType);
8307 }
8308 
8309 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8310                                           SourceLocation Loc) {
8311   // Ensure that either both operands are of the same vector type, or
8312   // one operand is of a vector type and the other is of its element type.
8313   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8314   if (vType.isNull())
8315     return InvalidOperands(Loc, LHS, RHS);
8316   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8317       vType->hasFloatingRepresentation())
8318     return InvalidOperands(Loc, LHS, RHS);
8319 
8320   return GetSignedVectorType(LHS.get()->getType());
8321 }
8322 
8323 inline QualType Sema::CheckBitwiseOperands(
8324   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8325   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8326 
8327   if (LHS.get()->getType()->isVectorType() ||
8328       RHS.get()->getType()->isVectorType()) {
8329     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8330         RHS.get()->getType()->hasIntegerRepresentation())
8331       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8332 
8333     return InvalidOperands(Loc, LHS, RHS);
8334   }
8335 
8336   ExprResult LHSResult = LHS, RHSResult = RHS;
8337   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8338                                                  IsCompAssign);
8339   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8340     return QualType();
8341   LHS = LHSResult.get();
8342   RHS = RHSResult.get();
8343 
8344   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8345     return compType;
8346   return InvalidOperands(Loc, LHS, RHS);
8347 }
8348 
8349 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8350   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8351 
8352   // Check vector operands differently.
8353   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8354     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8355 
8356   // Diagnose cases where the user write a logical and/or but probably meant a
8357   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8358   // is a constant.
8359   if (LHS.get()->getType()->isIntegerType() &&
8360       !LHS.get()->getType()->isBooleanType() &&
8361       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8362       // Don't warn in macros or template instantiations.
8363       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8364     // If the RHS can be constant folded, and if it constant folds to something
8365     // that isn't 0 or 1 (which indicate a potential logical operation that
8366     // happened to fold to true/false) then warn.
8367     // Parens on the RHS are ignored.
8368     llvm::APSInt Result;
8369     if (RHS.get()->EvaluateAsInt(Result, Context))
8370       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8371            !RHS.get()->getExprLoc().isMacroID()) ||
8372           (Result != 0 && Result != 1)) {
8373         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8374           << RHS.get()->getSourceRange()
8375           << (Opc == BO_LAnd ? "&&" : "||");
8376         // Suggest replacing the logical operator with the bitwise version
8377         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8378             << (Opc == BO_LAnd ? "&" : "|")
8379             << FixItHint::CreateReplacement(SourceRange(
8380                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8381                                                 getLangOpts())),
8382                                             Opc == BO_LAnd ? "&" : "|");
8383         if (Opc == BO_LAnd)
8384           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8385           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8386               << FixItHint::CreateRemoval(
8387                   SourceRange(
8388                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8389                                                  0, getSourceManager(),
8390                                                  getLangOpts()),
8391                       RHS.get()->getLocEnd()));
8392       }
8393   }
8394 
8395   if (!Context.getLangOpts().CPlusPlus) {
8396     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8397     // not operate on the built-in scalar and vector float types.
8398     if (Context.getLangOpts().OpenCL &&
8399         Context.getLangOpts().OpenCLVersion < 120) {
8400       if (LHS.get()->getType()->isFloatingType() ||
8401           RHS.get()->getType()->isFloatingType())
8402         return InvalidOperands(Loc, LHS, RHS);
8403     }
8404 
8405     LHS = UsualUnaryConversions(LHS.get());
8406     if (LHS.isInvalid())
8407       return QualType();
8408 
8409     RHS = UsualUnaryConversions(RHS.get());
8410     if (RHS.isInvalid())
8411       return QualType();
8412 
8413     if (!LHS.get()->getType()->isScalarType() ||
8414         !RHS.get()->getType()->isScalarType())
8415       return InvalidOperands(Loc, LHS, RHS);
8416 
8417     return Context.IntTy;
8418   }
8419 
8420   // The following is safe because we only use this method for
8421   // non-overloadable operands.
8422 
8423   // C++ [expr.log.and]p1
8424   // C++ [expr.log.or]p1
8425   // The operands are both contextually converted to type bool.
8426   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8427   if (LHSRes.isInvalid())
8428     return InvalidOperands(Loc, LHS, RHS);
8429   LHS = LHSRes;
8430 
8431   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8432   if (RHSRes.isInvalid())
8433     return InvalidOperands(Loc, LHS, RHS);
8434   RHS = RHSRes;
8435 
8436   // C++ [expr.log.and]p2
8437   // C++ [expr.log.or]p2
8438   // The result is a bool.
8439   return Context.BoolTy;
8440 }
8441 
8442 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8443   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8444   if (!ME) return false;
8445   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8446   ObjCMessageExpr *Base =
8447     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8448   if (!Base) return false;
8449   return Base->getMethodDecl() != nullptr;
8450 }
8451 
8452 /// Is the given expression (which must be 'const') a reference to a
8453 /// variable which was originally non-const, but which has become
8454 /// 'const' due to being captured within a block?
8455 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8456 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8457   assert(E->isLValue() && E->getType().isConstQualified());
8458   E = E->IgnoreParens();
8459 
8460   // Must be a reference to a declaration from an enclosing scope.
8461   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8462   if (!DRE) return NCCK_None;
8463   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8464 
8465   // The declaration must be a variable which is not declared 'const'.
8466   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8467   if (!var) return NCCK_None;
8468   if (var->getType().isConstQualified()) return NCCK_None;
8469   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8470 
8471   // Decide whether the first capture was for a block or a lambda.
8472   DeclContext *DC = S.CurContext, *Prev = nullptr;
8473   while (DC != var->getDeclContext()) {
8474     Prev = DC;
8475     DC = DC->getParent();
8476   }
8477   // Unless we have an init-capture, we've gone one step too far.
8478   if (!var->isInitCapture())
8479     DC = Prev;
8480   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8481 }
8482 
8483 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8484 /// emit an error and return true.  If so, return false.
8485 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8486   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8487   SourceLocation OrigLoc = Loc;
8488   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8489                                                               &Loc);
8490   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8491     IsLV = Expr::MLV_InvalidMessageExpression;
8492   if (IsLV == Expr::MLV_Valid)
8493     return false;
8494 
8495   unsigned Diag = 0;
8496   bool NeedType = false;
8497   switch (IsLV) { // C99 6.5.16p2
8498   case Expr::MLV_ConstQualified:
8499     Diag = diag::err_typecheck_assign_const;
8500 
8501     // Use a specialized diagnostic when we're assigning to an object
8502     // from an enclosing function or block.
8503     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8504       if (NCCK == NCCK_Block)
8505         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8506       else
8507         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8508       break;
8509     }
8510 
8511     // In ARC, use some specialized diagnostics for occasions where we
8512     // infer 'const'.  These are always pseudo-strong variables.
8513     if (S.getLangOpts().ObjCAutoRefCount) {
8514       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8515       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8516         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8517 
8518         // Use the normal diagnostic if it's pseudo-__strong but the
8519         // user actually wrote 'const'.
8520         if (var->isARCPseudoStrong() &&
8521             (!var->getTypeSourceInfo() ||
8522              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8523           // There are two pseudo-strong cases:
8524           //  - self
8525           ObjCMethodDecl *method = S.getCurMethodDecl();
8526           if (method && var == method->getSelfDecl())
8527             Diag = method->isClassMethod()
8528               ? diag::err_typecheck_arc_assign_self_class_method
8529               : diag::err_typecheck_arc_assign_self;
8530 
8531           //  - fast enumeration variables
8532           else
8533             Diag = diag::err_typecheck_arr_assign_enumeration;
8534 
8535           SourceRange Assign;
8536           if (Loc != OrigLoc)
8537             Assign = SourceRange(OrigLoc, OrigLoc);
8538           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8539           // We need to preserve the AST regardless, so migration tool
8540           // can do its job.
8541           return false;
8542         }
8543       }
8544     }
8545 
8546     break;
8547   case Expr::MLV_ArrayType:
8548   case Expr::MLV_ArrayTemporary:
8549     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8550     NeedType = true;
8551     break;
8552   case Expr::MLV_NotObjectType:
8553     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8554     NeedType = true;
8555     break;
8556   case Expr::MLV_LValueCast:
8557     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8558     break;
8559   case Expr::MLV_Valid:
8560     llvm_unreachable("did not take early return for MLV_Valid");
8561   case Expr::MLV_InvalidExpression:
8562   case Expr::MLV_MemberFunction:
8563   case Expr::MLV_ClassTemporary:
8564     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8565     break;
8566   case Expr::MLV_IncompleteType:
8567   case Expr::MLV_IncompleteVoidType:
8568     return S.RequireCompleteType(Loc, E->getType(),
8569              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8570   case Expr::MLV_DuplicateVectorComponents:
8571     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8572     break;
8573   case Expr::MLV_NoSetterProperty:
8574     llvm_unreachable("readonly properties should be processed differently");
8575   case Expr::MLV_InvalidMessageExpression:
8576     Diag = diag::error_readonly_message_assignment;
8577     break;
8578   case Expr::MLV_SubObjCPropertySetting:
8579     Diag = diag::error_no_subobject_property_setting;
8580     break;
8581   }
8582 
8583   SourceRange Assign;
8584   if (Loc != OrigLoc)
8585     Assign = SourceRange(OrigLoc, OrigLoc);
8586   if (NeedType)
8587     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8588   else
8589     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8590   return true;
8591 }
8592 
8593 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8594                                          SourceLocation Loc,
8595                                          Sema &Sema) {
8596   // C / C++ fields
8597   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8598   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8599   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8600     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8601       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8602   }
8603 
8604   // Objective-C instance variables
8605   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8606   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8607   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8608     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8609     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8610     if (RL && RR && RL->getDecl() == RR->getDecl())
8611       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8612   }
8613 }
8614 
8615 // C99 6.5.16.1
8616 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8617                                        SourceLocation Loc,
8618                                        QualType CompoundType) {
8619   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8620 
8621   // Verify that LHS is a modifiable lvalue, and emit error if not.
8622   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8623     return QualType();
8624 
8625   QualType LHSType = LHSExpr->getType();
8626   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8627                                              CompoundType;
8628   AssignConvertType ConvTy;
8629   if (CompoundType.isNull()) {
8630     Expr *RHSCheck = RHS.get();
8631 
8632     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8633 
8634     QualType LHSTy(LHSType);
8635     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8636     if (RHS.isInvalid())
8637       return QualType();
8638     // Special case of NSObject attributes on c-style pointer types.
8639     if (ConvTy == IncompatiblePointer &&
8640         ((Context.isObjCNSObjectType(LHSType) &&
8641           RHSType->isObjCObjectPointerType()) ||
8642          (Context.isObjCNSObjectType(RHSType) &&
8643           LHSType->isObjCObjectPointerType())))
8644       ConvTy = Compatible;
8645 
8646     if (ConvTy == Compatible &&
8647         LHSType->isObjCObjectType())
8648         Diag(Loc, diag::err_objc_object_assignment)
8649           << LHSType;
8650 
8651     // If the RHS is a unary plus or minus, check to see if they = and + are
8652     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8653     // instead of "x += 4".
8654     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8655       RHSCheck = ICE->getSubExpr();
8656     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8657       if ((UO->getOpcode() == UO_Plus ||
8658            UO->getOpcode() == UO_Minus) &&
8659           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8660           // Only if the two operators are exactly adjacent.
8661           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8662           // And there is a space or other character before the subexpr of the
8663           // unary +/-.  We don't want to warn on "x=-1".
8664           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8665           UO->getSubExpr()->getLocStart().isFileID()) {
8666         Diag(Loc, diag::warn_not_compound_assign)
8667           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8668           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8669       }
8670     }
8671 
8672     if (ConvTy == Compatible) {
8673       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8674         // Warn about retain cycles where a block captures the LHS, but
8675         // not if the LHS is a simple variable into which the block is
8676         // being stored...unless that variable can be captured by reference!
8677         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8678         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8679         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8680           checkRetainCycles(LHSExpr, RHS.get());
8681 
8682         // It is safe to assign a weak reference into a strong variable.
8683         // Although this code can still have problems:
8684         //   id x = self.weakProp;
8685         //   id y = self.weakProp;
8686         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8687         // paths through the function. This should be revisited if
8688         // -Wrepeated-use-of-weak is made flow-sensitive.
8689         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8690                              RHS.get()->getLocStart()))
8691           getCurFunction()->markSafeWeakUse(RHS.get());
8692 
8693       } else if (getLangOpts().ObjCAutoRefCount) {
8694         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8695       }
8696     }
8697   } else {
8698     // Compound assignment "x += y"
8699     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8700   }
8701 
8702   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8703                                RHS.get(), AA_Assigning))
8704     return QualType();
8705 
8706   CheckForNullPointerDereference(*this, LHSExpr);
8707 
8708   // C99 6.5.16p3: The type of an assignment expression is the type of the
8709   // left operand unless the left operand has qualified type, in which case
8710   // it is the unqualified version of the type of the left operand.
8711   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8712   // is converted to the type of the assignment expression (above).
8713   // C++ 5.17p1: the type of the assignment expression is that of its left
8714   // operand.
8715   return (getLangOpts().CPlusPlus
8716           ? LHSType : LHSType.getUnqualifiedType());
8717 }
8718 
8719 // C99 6.5.17
8720 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8721                                    SourceLocation Loc) {
8722   LHS = S.CheckPlaceholderExpr(LHS.get());
8723   RHS = S.CheckPlaceholderExpr(RHS.get());
8724   if (LHS.isInvalid() || RHS.isInvalid())
8725     return QualType();
8726 
8727   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8728   // operands, but not unary promotions.
8729   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8730 
8731   // So we treat the LHS as a ignored value, and in C++ we allow the
8732   // containing site to determine what should be done with the RHS.
8733   LHS = S.IgnoredValueConversions(LHS.get());
8734   if (LHS.isInvalid())
8735     return QualType();
8736 
8737   S.DiagnoseUnusedExprResult(LHS.get());
8738 
8739   if (!S.getLangOpts().CPlusPlus) {
8740     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8741     if (RHS.isInvalid())
8742       return QualType();
8743     if (!RHS.get()->getType()->isVoidType())
8744       S.RequireCompleteType(Loc, RHS.get()->getType(),
8745                             diag::err_incomplete_type);
8746   }
8747 
8748   return RHS.get()->getType();
8749 }
8750 
8751 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8752 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8753 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8754                                                ExprValueKind &VK,
8755                                                SourceLocation OpLoc,
8756                                                bool IsInc, bool IsPrefix) {
8757   if (Op->isTypeDependent())
8758     return S.Context.DependentTy;
8759 
8760   QualType ResType = Op->getType();
8761   // Atomic types can be used for increment / decrement where the non-atomic
8762   // versions can, so ignore the _Atomic() specifier for the purpose of
8763   // checking.
8764   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8765     ResType = ResAtomicType->getValueType();
8766 
8767   assert(!ResType.isNull() && "no type for increment/decrement expression");
8768 
8769   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8770     // Decrement of bool is not allowed.
8771     if (!IsInc) {
8772       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8773       return QualType();
8774     }
8775     // Increment of bool sets it to true, but is deprecated.
8776     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8777   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8778     // Error on enum increments and decrements in C++ mode
8779     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8780     return QualType();
8781   } else if (ResType->isRealType()) {
8782     // OK!
8783   } else if (ResType->isPointerType()) {
8784     // C99 6.5.2.4p2, 6.5.6p2
8785     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8786       return QualType();
8787   } else if (ResType->isObjCObjectPointerType()) {
8788     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8789     // Otherwise, we just need a complete type.
8790     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8791         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8792       return QualType();
8793   } else if (ResType->isAnyComplexType()) {
8794     // C99 does not support ++/-- on complex types, we allow as an extension.
8795     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8796       << ResType << Op->getSourceRange();
8797   } else if (ResType->isPlaceholderType()) {
8798     ExprResult PR = S.CheckPlaceholderExpr(Op);
8799     if (PR.isInvalid()) return QualType();
8800     return CheckIncrementDecrementOperand(S, PR.get(), VK, OpLoc,
8801                                           IsInc, IsPrefix);
8802   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8803     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8804   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8805             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8806     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8807   } else {
8808     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8809       << ResType << int(IsInc) << Op->getSourceRange();
8810     return QualType();
8811   }
8812   // At this point, we know we have a real, complex or pointer type.
8813   // Now make sure the operand is a modifiable lvalue.
8814   if (CheckForModifiableLvalue(Op, OpLoc, S))
8815     return QualType();
8816   // In C++, a prefix increment is the same type as the operand. Otherwise
8817   // (in C or with postfix), the increment is the unqualified type of the
8818   // operand.
8819   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8820     VK = VK_LValue;
8821     return ResType;
8822   } else {
8823     VK = VK_RValue;
8824     return ResType.getUnqualifiedType();
8825   }
8826 }
8827 
8828 
8829 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8830 /// This routine allows us to typecheck complex/recursive expressions
8831 /// where the declaration is needed for type checking. We only need to
8832 /// handle cases when the expression references a function designator
8833 /// or is an lvalue. Here are some examples:
8834 ///  - &(x) => x
8835 ///  - &*****f => f for f a function designator.
8836 ///  - &s.xx => s
8837 ///  - &s.zz[1].yy -> s, if zz is an array
8838 ///  - *(x + 1) -> x, if x is an array
8839 ///  - &"123"[2] -> 0
8840 ///  - & __real__ x -> x
8841 static ValueDecl *getPrimaryDecl(Expr *E) {
8842   switch (E->getStmtClass()) {
8843   case Stmt::DeclRefExprClass:
8844     return cast<DeclRefExpr>(E)->getDecl();
8845   case Stmt::MemberExprClass:
8846     // If this is an arrow operator, the address is an offset from
8847     // the base's value, so the object the base refers to is
8848     // irrelevant.
8849     if (cast<MemberExpr>(E)->isArrow())
8850       return nullptr;
8851     // Otherwise, the expression refers to a part of the base
8852     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8853   case Stmt::ArraySubscriptExprClass: {
8854     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8855     // promotion of register arrays earlier.
8856     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8857     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8858       if (ICE->getSubExpr()->getType()->isArrayType())
8859         return getPrimaryDecl(ICE->getSubExpr());
8860     }
8861     return nullptr;
8862   }
8863   case Stmt::UnaryOperatorClass: {
8864     UnaryOperator *UO = cast<UnaryOperator>(E);
8865 
8866     switch(UO->getOpcode()) {
8867     case UO_Real:
8868     case UO_Imag:
8869     case UO_Extension:
8870       return getPrimaryDecl(UO->getSubExpr());
8871     default:
8872       return nullptr;
8873     }
8874   }
8875   case Stmt::ParenExprClass:
8876     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8877   case Stmt::ImplicitCastExprClass:
8878     // If the result of an implicit cast is an l-value, we care about
8879     // the sub-expression; otherwise, the result here doesn't matter.
8880     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8881   default:
8882     return nullptr;
8883   }
8884 }
8885 
8886 namespace {
8887   enum {
8888     AO_Bit_Field = 0,
8889     AO_Vector_Element = 1,
8890     AO_Property_Expansion = 2,
8891     AO_Register_Variable = 3,
8892     AO_No_Error = 4
8893   };
8894 }
8895 /// \brief Diagnose invalid operand for address of operations.
8896 ///
8897 /// \param Type The type of operand which cannot have its address taken.
8898 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8899                                          Expr *E, unsigned Type) {
8900   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8901 }
8902 
8903 /// CheckAddressOfOperand - The operand of & must be either a function
8904 /// designator or an lvalue designating an object. If it is an lvalue, the
8905 /// object cannot be declared with storage class register or be a bit field.
8906 /// Note: The usual conversions are *not* applied to the operand of the &
8907 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8908 /// In C++, the operand might be an overloaded function name, in which case
8909 /// we allow the '&' but retain the overloaded-function type.
8910 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8911   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8912     if (PTy->getKind() == BuiltinType::Overload) {
8913       Expr *E = OrigOp.get()->IgnoreParens();
8914       if (!isa<OverloadExpr>(E)) {
8915         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8916         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8917           << OrigOp.get()->getSourceRange();
8918         return QualType();
8919       }
8920 
8921       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8922       if (isa<UnresolvedMemberExpr>(Ovl))
8923         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8924           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8925             << OrigOp.get()->getSourceRange();
8926           return QualType();
8927         }
8928 
8929       return Context.OverloadTy;
8930     }
8931 
8932     if (PTy->getKind() == BuiltinType::UnknownAny)
8933       return Context.UnknownAnyTy;
8934 
8935     if (PTy->getKind() == BuiltinType::BoundMember) {
8936       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8937         << OrigOp.get()->getSourceRange();
8938       return QualType();
8939     }
8940 
8941     OrigOp = CheckPlaceholderExpr(OrigOp.get());
8942     if (OrigOp.isInvalid()) return QualType();
8943   }
8944 
8945   if (OrigOp.get()->isTypeDependent())
8946     return Context.DependentTy;
8947 
8948   assert(!OrigOp.get()->getType()->isPlaceholderType());
8949 
8950   // Make sure to ignore parentheses in subsequent checks
8951   Expr *op = OrigOp.get()->IgnoreParens();
8952 
8953   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8954   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8955     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8956     return QualType();
8957   }
8958 
8959   if (getLangOpts().C99) {
8960     // Implement C99-only parts of addressof rules.
8961     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8962       if (uOp->getOpcode() == UO_Deref)
8963         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8964         // (assuming the deref expression is valid).
8965         return uOp->getSubExpr()->getType();
8966     }
8967     // Technically, there should be a check for array subscript
8968     // expressions here, but the result of one is always an lvalue anyway.
8969   }
8970   ValueDecl *dcl = getPrimaryDecl(op);
8971   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8972   unsigned AddressOfError = AO_No_Error;
8973 
8974   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8975     bool sfinae = (bool)isSFINAEContext();
8976     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8977                                   : diag::ext_typecheck_addrof_temporary)
8978       << op->getType() << op->getSourceRange();
8979     if (sfinae)
8980       return QualType();
8981     // Materialize the temporary as an lvalue so that we can take its address.
8982     OrigOp = op = new (Context)
8983         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
8984   } else if (isa<ObjCSelectorExpr>(op)) {
8985     return Context.getPointerType(op->getType());
8986   } else if (lval == Expr::LV_MemberFunction) {
8987     // If it's an instance method, make a member pointer.
8988     // The expression must have exactly the form &A::foo.
8989 
8990     // If the underlying expression isn't a decl ref, give up.
8991     if (!isa<DeclRefExpr>(op)) {
8992       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8993         << OrigOp.get()->getSourceRange();
8994       return QualType();
8995     }
8996     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8997     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8998 
8999     // The id-expression was parenthesized.
9000     if (OrigOp.get() != DRE) {
9001       Diag(OpLoc, diag::err_parens_pointer_member_function)
9002         << OrigOp.get()->getSourceRange();
9003 
9004     // The method was named without a qualifier.
9005     } else if (!DRE->getQualifier()) {
9006       if (MD->getParent()->getName().empty())
9007         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9008           << op->getSourceRange();
9009       else {
9010         SmallString<32> Str;
9011         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9012         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9013           << op->getSourceRange()
9014           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9015       }
9016     }
9017 
9018     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9019     if (isa<CXXDestructorDecl>(MD))
9020       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9021 
9022     QualType MPTy = Context.getMemberPointerType(
9023         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9024     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9025       RequireCompleteType(OpLoc, MPTy, 0);
9026     return MPTy;
9027   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9028     // C99 6.5.3.2p1
9029     // The operand must be either an l-value or a function designator
9030     if (!op->getType()->isFunctionType()) {
9031       // Use a special diagnostic for loads from property references.
9032       if (isa<PseudoObjectExpr>(op)) {
9033         AddressOfError = AO_Property_Expansion;
9034       } else {
9035         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9036           << op->getType() << op->getSourceRange();
9037         return QualType();
9038       }
9039     }
9040   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9041     // The operand cannot be a bit-field
9042     AddressOfError = AO_Bit_Field;
9043   } else if (op->getObjectKind() == OK_VectorComponent) {
9044     // The operand cannot be an element of a vector
9045     AddressOfError = AO_Vector_Element;
9046   } else if (dcl) { // C99 6.5.3.2p1
9047     // We have an lvalue with a decl. Make sure the decl is not declared
9048     // with the register storage-class specifier.
9049     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9050       // in C++ it is not error to take address of a register
9051       // variable (c++03 7.1.1P3)
9052       if (vd->getStorageClass() == SC_Register &&
9053           !getLangOpts().CPlusPlus) {
9054         AddressOfError = AO_Register_Variable;
9055       }
9056     } else if (isa<FunctionTemplateDecl>(dcl)) {
9057       return Context.OverloadTy;
9058     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9059       // Okay: we can take the address of a field.
9060       // Could be a pointer to member, though, if there is an explicit
9061       // scope qualifier for the class.
9062       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9063         DeclContext *Ctx = dcl->getDeclContext();
9064         if (Ctx && Ctx->isRecord()) {
9065           if (dcl->getType()->isReferenceType()) {
9066             Diag(OpLoc,
9067                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9068               << dcl->getDeclName() << dcl->getType();
9069             return QualType();
9070           }
9071 
9072           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9073             Ctx = Ctx->getParent();
9074 
9075           QualType MPTy = Context.getMemberPointerType(
9076               op->getType(),
9077               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9078           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9079             RequireCompleteType(OpLoc, MPTy, 0);
9080           return MPTy;
9081         }
9082       }
9083     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9084       llvm_unreachable("Unknown/unexpected decl type");
9085   }
9086 
9087   if (AddressOfError != AO_No_Error) {
9088     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9089     return QualType();
9090   }
9091 
9092   if (lval == Expr::LV_IncompleteVoidType) {
9093     // Taking the address of a void variable is technically illegal, but we
9094     // allow it in cases which are otherwise valid.
9095     // Example: "extern void x; void* y = &x;".
9096     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9097   }
9098 
9099   // If the operand has type "type", the result has type "pointer to type".
9100   if (op->getType()->isObjCObjectType())
9101     return Context.getObjCObjectPointerType(op->getType());
9102   return Context.getPointerType(op->getType());
9103 }
9104 
9105 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9106 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9107                                         SourceLocation OpLoc) {
9108   if (Op->isTypeDependent())
9109     return S.Context.DependentTy;
9110 
9111   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9112   if (ConvResult.isInvalid())
9113     return QualType();
9114   Op = ConvResult.get();
9115   QualType OpTy = Op->getType();
9116   QualType Result;
9117 
9118   if (isa<CXXReinterpretCastExpr>(Op)) {
9119     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9120     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9121                                      Op->getSourceRange());
9122   }
9123 
9124   if (const PointerType *PT = OpTy->getAs<PointerType>())
9125     Result = PT->getPointeeType();
9126   else if (const ObjCObjectPointerType *OPT =
9127              OpTy->getAs<ObjCObjectPointerType>())
9128     Result = OPT->getPointeeType();
9129   else {
9130     ExprResult PR = S.CheckPlaceholderExpr(Op);
9131     if (PR.isInvalid()) return QualType();
9132     if (PR.get() != Op)
9133       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9134   }
9135 
9136   if (Result.isNull()) {
9137     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9138       << OpTy << Op->getSourceRange();
9139     return QualType();
9140   }
9141 
9142   // Note that per both C89 and C99, indirection is always legal, even if Result
9143   // is an incomplete type or void.  It would be possible to warn about
9144   // dereferencing a void pointer, but it's completely well-defined, and such a
9145   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9146   // for pointers to 'void' but is fine for any other pointer type:
9147   //
9148   // C++ [expr.unary.op]p1:
9149   //   [...] the expression to which [the unary * operator] is applied shall
9150   //   be a pointer to an object type, or a pointer to a function type
9151   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9152     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9153       << OpTy << Op->getSourceRange();
9154 
9155   // Dereferences are usually l-values...
9156   VK = VK_LValue;
9157 
9158   // ...except that certain expressions are never l-values in C.
9159   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9160     VK = VK_RValue;
9161 
9162   return Result;
9163 }
9164 
9165 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9166   tok::TokenKind Kind) {
9167   BinaryOperatorKind Opc;
9168   switch (Kind) {
9169   default: llvm_unreachable("Unknown binop!");
9170   case tok::periodstar:           Opc = BO_PtrMemD; break;
9171   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9172   case tok::star:                 Opc = BO_Mul; break;
9173   case tok::slash:                Opc = BO_Div; break;
9174   case tok::percent:              Opc = BO_Rem; break;
9175   case tok::plus:                 Opc = BO_Add; break;
9176   case tok::minus:                Opc = BO_Sub; break;
9177   case tok::lessless:             Opc = BO_Shl; break;
9178   case tok::greatergreater:       Opc = BO_Shr; break;
9179   case tok::lessequal:            Opc = BO_LE; break;
9180   case tok::less:                 Opc = BO_LT; break;
9181   case tok::greaterequal:         Opc = BO_GE; break;
9182   case tok::greater:              Opc = BO_GT; break;
9183   case tok::exclaimequal:         Opc = BO_NE; break;
9184   case tok::equalequal:           Opc = BO_EQ; break;
9185   case tok::amp:                  Opc = BO_And; break;
9186   case tok::caret:                Opc = BO_Xor; break;
9187   case tok::pipe:                 Opc = BO_Or; break;
9188   case tok::ampamp:               Opc = BO_LAnd; break;
9189   case tok::pipepipe:             Opc = BO_LOr; break;
9190   case tok::equal:                Opc = BO_Assign; break;
9191   case tok::starequal:            Opc = BO_MulAssign; break;
9192   case tok::slashequal:           Opc = BO_DivAssign; break;
9193   case tok::percentequal:         Opc = BO_RemAssign; break;
9194   case tok::plusequal:            Opc = BO_AddAssign; break;
9195   case tok::minusequal:           Opc = BO_SubAssign; break;
9196   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9197   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9198   case tok::ampequal:             Opc = BO_AndAssign; break;
9199   case tok::caretequal:           Opc = BO_XorAssign; break;
9200   case tok::pipeequal:            Opc = BO_OrAssign; break;
9201   case tok::comma:                Opc = BO_Comma; break;
9202   }
9203   return Opc;
9204 }
9205 
9206 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9207   tok::TokenKind Kind) {
9208   UnaryOperatorKind Opc;
9209   switch (Kind) {
9210   default: llvm_unreachable("Unknown unary op!");
9211   case tok::plusplus:     Opc = UO_PreInc; break;
9212   case tok::minusminus:   Opc = UO_PreDec; break;
9213   case tok::amp:          Opc = UO_AddrOf; break;
9214   case tok::star:         Opc = UO_Deref; break;
9215   case tok::plus:         Opc = UO_Plus; break;
9216   case tok::minus:        Opc = UO_Minus; break;
9217   case tok::tilde:        Opc = UO_Not; break;
9218   case tok::exclaim:      Opc = UO_LNot; break;
9219   case tok::kw___real:    Opc = UO_Real; break;
9220   case tok::kw___imag:    Opc = UO_Imag; break;
9221   case tok::kw___extension__: Opc = UO_Extension; break;
9222   }
9223   return Opc;
9224 }
9225 
9226 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9227 /// This warning is only emitted for builtin assignment operations. It is also
9228 /// suppressed in the event of macro expansions.
9229 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9230                                    SourceLocation OpLoc) {
9231   if (!S.ActiveTemplateInstantiations.empty())
9232     return;
9233   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9234     return;
9235   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9236   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9237   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9238   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9239   if (!LHSDeclRef || !RHSDeclRef ||
9240       LHSDeclRef->getLocation().isMacroID() ||
9241       RHSDeclRef->getLocation().isMacroID())
9242     return;
9243   const ValueDecl *LHSDecl =
9244     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9245   const ValueDecl *RHSDecl =
9246     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9247   if (LHSDecl != RHSDecl)
9248     return;
9249   if (LHSDecl->getType().isVolatileQualified())
9250     return;
9251   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9252     if (RefTy->getPointeeType().isVolatileQualified())
9253       return;
9254 
9255   S.Diag(OpLoc, diag::warn_self_assignment)
9256       << LHSDeclRef->getType()
9257       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9258 }
9259 
9260 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9261 /// is usually indicative of introspection within the Objective-C pointer.
9262 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9263                                           SourceLocation OpLoc) {
9264   if (!S.getLangOpts().ObjC1)
9265     return;
9266 
9267   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9268   const Expr *LHS = L.get();
9269   const Expr *RHS = R.get();
9270 
9271   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9272     ObjCPointerExpr = LHS;
9273     OtherExpr = RHS;
9274   }
9275   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9276     ObjCPointerExpr = RHS;
9277     OtherExpr = LHS;
9278   }
9279 
9280   // This warning is deliberately made very specific to reduce false
9281   // positives with logic that uses '&' for hashing.  This logic mainly
9282   // looks for code trying to introspect into tagged pointers, which
9283   // code should generally never do.
9284   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9285     unsigned Diag = diag::warn_objc_pointer_masking;
9286     // Determine if we are introspecting the result of performSelectorXXX.
9287     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9288     // Special case messages to -performSelector and friends, which
9289     // can return non-pointer values boxed in a pointer value.
9290     // Some clients may wish to silence warnings in this subcase.
9291     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9292       Selector S = ME->getSelector();
9293       StringRef SelArg0 = S.getNameForSlot(0);
9294       if (SelArg0.startswith("performSelector"))
9295         Diag = diag::warn_objc_pointer_masking_performSelector;
9296     }
9297 
9298     S.Diag(OpLoc, Diag)
9299       << ObjCPointerExpr->getSourceRange();
9300   }
9301 }
9302 
9303 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9304 /// operator @p Opc at location @c TokLoc. This routine only supports
9305 /// built-in operations; ActOnBinOp handles overloaded operators.
9306 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9307                                     BinaryOperatorKind Opc,
9308                                     Expr *LHSExpr, Expr *RHSExpr) {
9309   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9310     // The syntax only allows initializer lists on the RHS of assignment,
9311     // so we don't need to worry about accepting invalid code for
9312     // non-assignment operators.
9313     // C++11 5.17p9:
9314     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9315     //   of x = {} is x = T().
9316     InitializationKind Kind =
9317         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9318     InitializedEntity Entity =
9319         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9320     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9321     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9322     if (Init.isInvalid())
9323       return Init;
9324     RHSExpr = Init.get();
9325   }
9326 
9327   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9328   QualType ResultTy;     // Result type of the binary operator.
9329   // The following two variables are used for compound assignment operators
9330   QualType CompLHSTy;    // Type of LHS after promotions for computation
9331   QualType CompResultTy; // Type of computation result
9332   ExprValueKind VK = VK_RValue;
9333   ExprObjectKind OK = OK_Ordinary;
9334 
9335   switch (Opc) {
9336   case BO_Assign:
9337     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9338     if (getLangOpts().CPlusPlus &&
9339         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9340       VK = LHS.get()->getValueKind();
9341       OK = LHS.get()->getObjectKind();
9342     }
9343     if (!ResultTy.isNull())
9344       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9345     break;
9346   case BO_PtrMemD:
9347   case BO_PtrMemI:
9348     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9349                                             Opc == BO_PtrMemI);
9350     break;
9351   case BO_Mul:
9352   case BO_Div:
9353     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9354                                            Opc == BO_Div);
9355     break;
9356   case BO_Rem:
9357     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9358     break;
9359   case BO_Add:
9360     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9361     break;
9362   case BO_Sub:
9363     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9364     break;
9365   case BO_Shl:
9366   case BO_Shr:
9367     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9368     break;
9369   case BO_LE:
9370   case BO_LT:
9371   case BO_GE:
9372   case BO_GT:
9373     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9374     break;
9375   case BO_EQ:
9376   case BO_NE:
9377     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9378     break;
9379   case BO_And:
9380     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9381   case BO_Xor:
9382   case BO_Or:
9383     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9384     break;
9385   case BO_LAnd:
9386   case BO_LOr:
9387     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9388     break;
9389   case BO_MulAssign:
9390   case BO_DivAssign:
9391     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9392                                                Opc == BO_DivAssign);
9393     CompLHSTy = CompResultTy;
9394     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9395       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9396     break;
9397   case BO_RemAssign:
9398     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, 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_AddAssign:
9404     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9405     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9406       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9407     break;
9408   case BO_SubAssign:
9409     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9410     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9411       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9412     break;
9413   case BO_ShlAssign:
9414   case BO_ShrAssign:
9415     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9416     CompLHSTy = CompResultTy;
9417     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9418       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9419     break;
9420   case BO_AndAssign:
9421   case BO_OrAssign: // fallthrough
9422 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9423   case BO_XorAssign:
9424     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9425     CompLHSTy = CompResultTy;
9426     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9427       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9428     break;
9429   case BO_Comma:
9430     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9431     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9432       VK = RHS.get()->getValueKind();
9433       OK = RHS.get()->getObjectKind();
9434     }
9435     break;
9436   }
9437   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9438     return ExprError();
9439 
9440   // Check for array bounds violations for both sides of the BinaryOperator
9441   CheckArrayAccess(LHS.get());
9442   CheckArrayAccess(RHS.get());
9443 
9444   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9445     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9446                                                  &Context.Idents.get("object_setClass"),
9447                                                  SourceLocation(), LookupOrdinaryName);
9448     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9449       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9450       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9451       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9452       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9453       FixItHint::CreateInsertion(RHSLocEnd, ")");
9454     }
9455     else
9456       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9457   }
9458   else if (const ObjCIvarRefExpr *OIRE =
9459            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9460     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9461 
9462   if (CompResultTy.isNull())
9463     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9464                                         OK, OpLoc, FPFeatures.fp_contract);
9465   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9466       OK_ObjCProperty) {
9467     VK = VK_LValue;
9468     OK = LHS.get()->getObjectKind();
9469   }
9470   return new (Context) CompoundAssignOperator(
9471       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9472       OpLoc, FPFeatures.fp_contract);
9473 }
9474 
9475 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9476 /// operators are mixed in a way that suggests that the programmer forgot that
9477 /// comparison operators have higher precedence. The most typical example of
9478 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9479 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9480                                       SourceLocation OpLoc, Expr *LHSExpr,
9481                                       Expr *RHSExpr) {
9482   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9483   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9484 
9485   // Check that one of the sides is a comparison operator.
9486   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9487   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9488   if (!isLeftComp && !isRightComp)
9489     return;
9490 
9491   // Bitwise operations are sometimes used as eager logical ops.
9492   // Don't diagnose this.
9493   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9494   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9495   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9496     return;
9497 
9498   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9499                                                    OpLoc)
9500                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9501   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9502   SourceRange ParensRange = isLeftComp ?
9503       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9504     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9505 
9506   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9507     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9508   SuggestParentheses(Self, OpLoc,
9509     Self.PDiag(diag::note_precedence_silence) << OpStr,
9510     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9511   SuggestParentheses(Self, OpLoc,
9512     Self.PDiag(diag::note_precedence_bitwise_first)
9513       << BinaryOperator::getOpcodeStr(Opc),
9514     ParensRange);
9515 }
9516 
9517 /// \brief It accepts a '&' expr that is inside a '|' one.
9518 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9519 /// in parentheses.
9520 static void
9521 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9522                                        BinaryOperator *Bop) {
9523   assert(Bop->getOpcode() == BO_And);
9524   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9525       << Bop->getSourceRange() << OpLoc;
9526   SuggestParentheses(Self, Bop->getOperatorLoc(),
9527     Self.PDiag(diag::note_precedence_silence)
9528       << Bop->getOpcodeStr(),
9529     Bop->getSourceRange());
9530 }
9531 
9532 /// \brief It accepts a '&&' expr that is inside a '||' one.
9533 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9534 /// in parentheses.
9535 static void
9536 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9537                                        BinaryOperator *Bop) {
9538   assert(Bop->getOpcode() == BO_LAnd);
9539   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9540       << Bop->getSourceRange() << OpLoc;
9541   SuggestParentheses(Self, Bop->getOperatorLoc(),
9542     Self.PDiag(diag::note_precedence_silence)
9543       << Bop->getOpcodeStr(),
9544     Bop->getSourceRange());
9545 }
9546 
9547 /// \brief Returns true if the given expression can be evaluated as a constant
9548 /// 'true'.
9549 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9550   bool Res;
9551   return !E->isValueDependent() &&
9552          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9553 }
9554 
9555 /// \brief Returns true if the given expression can be evaluated as a constant
9556 /// 'false'.
9557 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9558   bool Res;
9559   return !E->isValueDependent() &&
9560          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9561 }
9562 
9563 /// \brief Look for '&&' in the left hand of a '||' expr.
9564 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9565                                              Expr *LHSExpr, Expr *RHSExpr) {
9566   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9567     if (Bop->getOpcode() == BO_LAnd) {
9568       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9569       if (EvaluatesAsFalse(S, RHSExpr))
9570         return;
9571       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9572       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9573         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9574     } else if (Bop->getOpcode() == BO_LOr) {
9575       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9576         // If it's "a || b && 1 || c" we didn't warn earlier for
9577         // "a || b && 1", but warn now.
9578         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9579           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9580       }
9581     }
9582   }
9583 }
9584 
9585 /// \brief Look for '&&' in the right hand of a '||' expr.
9586 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9587                                              Expr *LHSExpr, Expr *RHSExpr) {
9588   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9589     if (Bop->getOpcode() == BO_LAnd) {
9590       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9591       if (EvaluatesAsFalse(S, LHSExpr))
9592         return;
9593       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9594       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9595         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9596     }
9597   }
9598 }
9599 
9600 /// \brief Look for '&' in the left or right hand of a '|' expr.
9601 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9602                                              Expr *OrArg) {
9603   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9604     if (Bop->getOpcode() == BO_And)
9605       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9606   }
9607 }
9608 
9609 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9610                                     Expr *SubExpr, StringRef Shift) {
9611   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9612     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9613       StringRef Op = Bop->getOpcodeStr();
9614       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9615           << Bop->getSourceRange() << OpLoc << Shift << Op;
9616       SuggestParentheses(S, Bop->getOperatorLoc(),
9617           S.PDiag(diag::note_precedence_silence) << Op,
9618           Bop->getSourceRange());
9619     }
9620   }
9621 }
9622 
9623 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9624                                  Expr *LHSExpr, Expr *RHSExpr) {
9625   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9626   if (!OCE)
9627     return;
9628 
9629   FunctionDecl *FD = OCE->getDirectCallee();
9630   if (!FD || !FD->isOverloadedOperator())
9631     return;
9632 
9633   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9634   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9635     return;
9636 
9637   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9638       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9639       << (Kind == OO_LessLess);
9640   SuggestParentheses(S, OCE->getOperatorLoc(),
9641                      S.PDiag(diag::note_precedence_silence)
9642                          << (Kind == OO_LessLess ? "<<" : ">>"),
9643                      OCE->getSourceRange());
9644   SuggestParentheses(S, OpLoc,
9645                      S.PDiag(diag::note_evaluate_comparison_first),
9646                      SourceRange(OCE->getArg(1)->getLocStart(),
9647                                  RHSExpr->getLocEnd()));
9648 }
9649 
9650 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9651 /// precedence.
9652 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9653                                     SourceLocation OpLoc, Expr *LHSExpr,
9654                                     Expr *RHSExpr){
9655   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9656   if (BinaryOperator::isBitwiseOp(Opc))
9657     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9658 
9659   // Diagnose "arg1 & arg2 | arg3"
9660   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9661     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9662     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9663   }
9664 
9665   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9666   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9667   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9668     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9669     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9670   }
9671 
9672   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9673       || Opc == BO_Shr) {
9674     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9675     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9676     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9677   }
9678 
9679   // Warn on overloaded shift operators and comparisons, such as:
9680   // cout << 5 == 4;
9681   if (BinaryOperator::isComparisonOp(Opc))
9682     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9683 }
9684 
9685 // Binary Operators.  'Tok' is the token for the operator.
9686 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9687                             tok::TokenKind Kind,
9688                             Expr *LHSExpr, Expr *RHSExpr) {
9689   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9690   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9691   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9692 
9693   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9694   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9695 
9696   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9697 }
9698 
9699 /// Build an overloaded binary operator expression in the given scope.
9700 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9701                                        BinaryOperatorKind Opc,
9702                                        Expr *LHS, Expr *RHS) {
9703   // Find all of the overloaded operators visible from this
9704   // point. We perform both an operator-name lookup from the local
9705   // scope and an argument-dependent lookup based on the types of
9706   // the arguments.
9707   UnresolvedSet<16> Functions;
9708   OverloadedOperatorKind OverOp
9709     = BinaryOperator::getOverloadedOperator(Opc);
9710   if (Sc && OverOp != OO_None)
9711     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9712                                    RHS->getType(), Functions);
9713 
9714   // Build the (potentially-overloaded, potentially-dependent)
9715   // binary operation.
9716   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9717 }
9718 
9719 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9720                             BinaryOperatorKind Opc,
9721                             Expr *LHSExpr, Expr *RHSExpr) {
9722   // We want to end up calling one of checkPseudoObjectAssignment
9723   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9724   // both expressions are overloadable or either is type-dependent),
9725   // or CreateBuiltinBinOp (in any other case).  We also want to get
9726   // any placeholder types out of the way.
9727 
9728   // Handle pseudo-objects in the LHS.
9729   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9730     // Assignments with a pseudo-object l-value need special analysis.
9731     if (pty->getKind() == BuiltinType::PseudoObject &&
9732         BinaryOperator::isAssignmentOp(Opc))
9733       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9734 
9735     // Don't resolve overloads if the other type is overloadable.
9736     if (pty->getKind() == BuiltinType::Overload) {
9737       // We can't actually test that if we still have a placeholder,
9738       // though.  Fortunately, none of the exceptions we see in that
9739       // code below are valid when the LHS is an overload set.  Note
9740       // that an overload set can be dependently-typed, but it never
9741       // instantiates to having an overloadable type.
9742       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9743       if (resolvedRHS.isInvalid()) return ExprError();
9744       RHSExpr = resolvedRHS.get();
9745 
9746       if (RHSExpr->isTypeDependent() ||
9747           RHSExpr->getType()->isOverloadableType())
9748         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9749     }
9750 
9751     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9752     if (LHS.isInvalid()) return ExprError();
9753     LHSExpr = LHS.get();
9754   }
9755 
9756   // Handle pseudo-objects in the RHS.
9757   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9758     // An overload in the RHS can potentially be resolved by the type
9759     // being assigned to.
9760     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9761       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9762         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9763 
9764       if (LHSExpr->getType()->isOverloadableType())
9765         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9766 
9767       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9768     }
9769 
9770     // Don't resolve overloads if the other type is overloadable.
9771     if (pty->getKind() == BuiltinType::Overload &&
9772         LHSExpr->getType()->isOverloadableType())
9773       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9774 
9775     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9776     if (!resolvedRHS.isUsable()) return ExprError();
9777     RHSExpr = resolvedRHS.get();
9778   }
9779 
9780   if (getLangOpts().CPlusPlus) {
9781     // If either expression is type-dependent, always build an
9782     // overloaded op.
9783     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9784       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9785 
9786     // Otherwise, build an overloaded op if either expression has an
9787     // overloadable type.
9788     if (LHSExpr->getType()->isOverloadableType() ||
9789         RHSExpr->getType()->isOverloadableType())
9790       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9791   }
9792 
9793   // Build a built-in binary operation.
9794   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9795 }
9796 
9797 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9798                                       UnaryOperatorKind Opc,
9799                                       Expr *InputExpr) {
9800   ExprResult Input = InputExpr;
9801   ExprValueKind VK = VK_RValue;
9802   ExprObjectKind OK = OK_Ordinary;
9803   QualType resultType;
9804   switch (Opc) {
9805   case UO_PreInc:
9806   case UO_PreDec:
9807   case UO_PostInc:
9808   case UO_PostDec:
9809     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9810                                                 Opc == UO_PreInc ||
9811                                                 Opc == UO_PostInc,
9812                                                 Opc == UO_PreInc ||
9813                                                 Opc == UO_PreDec);
9814     break;
9815   case UO_AddrOf:
9816     resultType = CheckAddressOfOperand(Input, OpLoc);
9817     break;
9818   case UO_Deref: {
9819     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9820     if (Input.isInvalid()) return ExprError();
9821     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9822     break;
9823   }
9824   case UO_Plus:
9825   case UO_Minus:
9826     Input = UsualUnaryConversions(Input.get());
9827     if (Input.isInvalid()) return ExprError();
9828     resultType = Input.get()->getType();
9829     if (resultType->isDependentType())
9830       break;
9831     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9832         resultType->isVectorType())
9833       break;
9834     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9835              Opc == UO_Plus &&
9836              resultType->isPointerType())
9837       break;
9838 
9839     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9840       << resultType << Input.get()->getSourceRange());
9841 
9842   case UO_Not: // bitwise complement
9843     Input = UsualUnaryConversions(Input.get());
9844     if (Input.isInvalid())
9845       return ExprError();
9846     resultType = Input.get()->getType();
9847     if (resultType->isDependentType())
9848       break;
9849     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9850     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9851       // C99 does not support '~' for complex conjugation.
9852       Diag(OpLoc, diag::ext_integer_complement_complex)
9853           << resultType << Input.get()->getSourceRange();
9854     else if (resultType->hasIntegerRepresentation())
9855       break;
9856     else if (resultType->isExtVectorType()) {
9857       if (Context.getLangOpts().OpenCL) {
9858         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9859         // on vector float types.
9860         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9861         if (!T->isIntegerType())
9862           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9863                            << resultType << Input.get()->getSourceRange());
9864       }
9865       break;
9866     } else {
9867       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9868                        << resultType << Input.get()->getSourceRange());
9869     }
9870     break;
9871 
9872   case UO_LNot: // logical negation
9873     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9874     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9875     if (Input.isInvalid()) return ExprError();
9876     resultType = Input.get()->getType();
9877 
9878     // Though we still have to promote half FP to float...
9879     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9880       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9881       resultType = Context.FloatTy;
9882     }
9883 
9884     if (resultType->isDependentType())
9885       break;
9886     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9887       // C99 6.5.3.3p1: ok, fallthrough;
9888       if (Context.getLangOpts().CPlusPlus) {
9889         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9890         // operand contextually converted to bool.
9891         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
9892                                   ScalarTypeToBooleanCastKind(resultType));
9893       } else if (Context.getLangOpts().OpenCL &&
9894                  Context.getLangOpts().OpenCLVersion < 120) {
9895         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9896         // operate on scalar float types.
9897         if (!resultType->isIntegerType())
9898           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9899                            << resultType << Input.get()->getSourceRange());
9900       }
9901     } else if (resultType->isExtVectorType()) {
9902       if (Context.getLangOpts().OpenCL &&
9903           Context.getLangOpts().OpenCLVersion < 120) {
9904         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9905         // operate on vector float types.
9906         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9907         if (!T->isIntegerType())
9908           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9909                            << resultType << Input.get()->getSourceRange());
9910       }
9911       // Vector logical not returns the signed variant of the operand type.
9912       resultType = GetSignedVectorType(resultType);
9913       break;
9914     } else {
9915       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9916         << resultType << Input.get()->getSourceRange());
9917     }
9918 
9919     // LNot always has type int. C99 6.5.3.3p5.
9920     // In C++, it's bool. C++ 5.3.1p8
9921     resultType = Context.getLogicalOperationType();
9922     break;
9923   case UO_Real:
9924   case UO_Imag:
9925     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9926     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9927     // complex l-values to ordinary l-values and all other values to r-values.
9928     if (Input.isInvalid()) return ExprError();
9929     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9930       if (Input.get()->getValueKind() != VK_RValue &&
9931           Input.get()->getObjectKind() == OK_Ordinary)
9932         VK = Input.get()->getValueKind();
9933     } else if (!getLangOpts().CPlusPlus) {
9934       // In C, a volatile scalar is read by __imag. In C++, it is not.
9935       Input = DefaultLvalueConversion(Input.get());
9936     }
9937     break;
9938   case UO_Extension:
9939     resultType = Input.get()->getType();
9940     VK = Input.get()->getValueKind();
9941     OK = Input.get()->getObjectKind();
9942     break;
9943   }
9944   if (resultType.isNull() || Input.isInvalid())
9945     return ExprError();
9946 
9947   // Check for array bounds violations in the operand of the UnaryOperator,
9948   // except for the '*' and '&' operators that have to be handled specially
9949   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9950   // that are explicitly defined as valid by the standard).
9951   if (Opc != UO_AddrOf && Opc != UO_Deref)
9952     CheckArrayAccess(Input.get());
9953 
9954   return new (Context)
9955       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
9956 }
9957 
9958 /// \brief Determine whether the given expression is a qualified member
9959 /// access expression, of a form that could be turned into a pointer to member
9960 /// with the address-of operator.
9961 static bool isQualifiedMemberAccess(Expr *E) {
9962   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9963     if (!DRE->getQualifier())
9964       return false;
9965 
9966     ValueDecl *VD = DRE->getDecl();
9967     if (!VD->isCXXClassMember())
9968       return false;
9969 
9970     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9971       return true;
9972     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9973       return Method->isInstance();
9974 
9975     return false;
9976   }
9977 
9978   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9979     if (!ULE->getQualifier())
9980       return false;
9981 
9982     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9983                                            DEnd = ULE->decls_end();
9984          D != DEnd; ++D) {
9985       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9986         if (Method->isInstance())
9987           return true;
9988       } else {
9989         // Overload set does not contain methods.
9990         break;
9991       }
9992     }
9993 
9994     return false;
9995   }
9996 
9997   return false;
9998 }
9999 
10000 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10001                               UnaryOperatorKind Opc, Expr *Input) {
10002   // First things first: handle placeholders so that the
10003   // overloaded-operator check considers the right type.
10004   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10005     // Increment and decrement of pseudo-object references.
10006     if (pty->getKind() == BuiltinType::PseudoObject &&
10007         UnaryOperator::isIncrementDecrementOp(Opc))
10008       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10009 
10010     // extension is always a builtin operator.
10011     if (Opc == UO_Extension)
10012       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10013 
10014     // & gets special logic for several kinds of placeholder.
10015     // The builtin code knows what to do.
10016     if (Opc == UO_AddrOf &&
10017         (pty->getKind() == BuiltinType::Overload ||
10018          pty->getKind() == BuiltinType::UnknownAny ||
10019          pty->getKind() == BuiltinType::BoundMember))
10020       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10021 
10022     // Anything else needs to be handled now.
10023     ExprResult Result = CheckPlaceholderExpr(Input);
10024     if (Result.isInvalid()) return ExprError();
10025     Input = Result.get();
10026   }
10027 
10028   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10029       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10030       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10031     // Find all of the overloaded operators visible from this
10032     // point. We perform both an operator-name lookup from the local
10033     // scope and an argument-dependent lookup based on the types of
10034     // the arguments.
10035     UnresolvedSet<16> Functions;
10036     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10037     if (S && OverOp != OO_None)
10038       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10039                                    Functions);
10040 
10041     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10042   }
10043 
10044   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10045 }
10046 
10047 // Unary Operators.  'Tok' is the token for the operator.
10048 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10049                               tok::TokenKind Op, Expr *Input) {
10050   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10051 }
10052 
10053 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10054 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10055                                 LabelDecl *TheDecl) {
10056   TheDecl->markUsed(Context);
10057   // Create the AST node.  The address of a label always has type 'void*'.
10058   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10059                                      Context.getPointerType(Context.VoidTy));
10060 }
10061 
10062 /// Given the last statement in a statement-expression, check whether
10063 /// the result is a producing expression (like a call to an
10064 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10065 /// release out of the full-expression.  Otherwise, return null.
10066 /// Cannot fail.
10067 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10068   // Should always be wrapped with one of these.
10069   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10070   if (!cleanups) return nullptr;
10071 
10072   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10073   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10074     return nullptr;
10075 
10076   // Splice out the cast.  This shouldn't modify any interesting
10077   // features of the statement.
10078   Expr *producer = cast->getSubExpr();
10079   assert(producer->getType() == cast->getType());
10080   assert(producer->getValueKind() == cast->getValueKind());
10081   cleanups->setSubExpr(producer);
10082   return cleanups;
10083 }
10084 
10085 void Sema::ActOnStartStmtExpr() {
10086   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10087 }
10088 
10089 void Sema::ActOnStmtExprError() {
10090   // Note that function is also called by TreeTransform when leaving a
10091   // StmtExpr scope without rebuilding anything.
10092 
10093   DiscardCleanupsInEvaluationContext();
10094   PopExpressionEvaluationContext();
10095 }
10096 
10097 ExprResult
10098 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10099                     SourceLocation RPLoc) { // "({..})"
10100   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10101   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10102 
10103   if (hasAnyUnrecoverableErrorsInThisFunction())
10104     DiscardCleanupsInEvaluationContext();
10105   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10106   PopExpressionEvaluationContext();
10107 
10108   bool isFileScope
10109     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10110   if (isFileScope)
10111     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10112 
10113   // FIXME: there are a variety of strange constraints to enforce here, for
10114   // example, it is not possible to goto into a stmt expression apparently.
10115   // More semantic analysis is needed.
10116 
10117   // If there are sub-stmts in the compound stmt, take the type of the last one
10118   // as the type of the stmtexpr.
10119   QualType Ty = Context.VoidTy;
10120   bool StmtExprMayBindToTemp = false;
10121   if (!Compound->body_empty()) {
10122     Stmt *LastStmt = Compound->body_back();
10123     LabelStmt *LastLabelStmt = nullptr;
10124     // If LastStmt is a label, skip down through into the body.
10125     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10126       LastLabelStmt = Label;
10127       LastStmt = Label->getSubStmt();
10128     }
10129 
10130     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10131       // Do function/array conversion on the last expression, but not
10132       // lvalue-to-rvalue.  However, initialize an unqualified type.
10133       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10134       if (LastExpr.isInvalid())
10135         return ExprError();
10136       Ty = LastExpr.get()->getType().getUnqualifiedType();
10137 
10138       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10139         // In ARC, if the final expression ends in a consume, splice
10140         // the consume out and bind it later.  In the alternate case
10141         // (when dealing with a retainable type), the result
10142         // initialization will create a produce.  In both cases the
10143         // result will be +1, and we'll need to balance that out with
10144         // a bind.
10145         if (Expr *rebuiltLastStmt
10146               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10147           LastExpr = rebuiltLastStmt;
10148         } else {
10149           LastExpr = PerformCopyInitialization(
10150                             InitializedEntity::InitializeResult(LPLoc,
10151                                                                 Ty,
10152                                                                 false),
10153                                                    SourceLocation(),
10154                                                LastExpr);
10155         }
10156 
10157         if (LastExpr.isInvalid())
10158           return ExprError();
10159         if (LastExpr.get() != nullptr) {
10160           if (!LastLabelStmt)
10161             Compound->setLastStmt(LastExpr.get());
10162           else
10163             LastLabelStmt->setSubStmt(LastExpr.get());
10164           StmtExprMayBindToTemp = true;
10165         }
10166       }
10167     }
10168   }
10169 
10170   // FIXME: Check that expression type is complete/non-abstract; statement
10171   // expressions are not lvalues.
10172   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10173   if (StmtExprMayBindToTemp)
10174     return MaybeBindToTemporary(ResStmtExpr);
10175   return ResStmtExpr;
10176 }
10177 
10178 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10179                                       TypeSourceInfo *TInfo,
10180                                       OffsetOfComponent *CompPtr,
10181                                       unsigned NumComponents,
10182                                       SourceLocation RParenLoc) {
10183   QualType ArgTy = TInfo->getType();
10184   bool Dependent = ArgTy->isDependentType();
10185   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10186 
10187   // We must have at least one component that refers to the type, and the first
10188   // one is known to be a field designator.  Verify that the ArgTy represents
10189   // a struct/union/class.
10190   if (!Dependent && !ArgTy->isRecordType())
10191     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10192                        << ArgTy << TypeRange);
10193 
10194   // Type must be complete per C99 7.17p3 because a declaring a variable
10195   // with an incomplete type would be ill-formed.
10196   if (!Dependent
10197       && RequireCompleteType(BuiltinLoc, ArgTy,
10198                              diag::err_offsetof_incomplete_type, TypeRange))
10199     return ExprError();
10200 
10201   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10202   // GCC extension, diagnose them.
10203   // FIXME: This diagnostic isn't actually visible because the location is in
10204   // a system header!
10205   if (NumComponents != 1)
10206     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10207       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10208 
10209   bool DidWarnAboutNonPOD = false;
10210   QualType CurrentType = ArgTy;
10211   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10212   SmallVector<OffsetOfNode, 4> Comps;
10213   SmallVector<Expr*, 4> Exprs;
10214   for (unsigned i = 0; i != NumComponents; ++i) {
10215     const OffsetOfComponent &OC = CompPtr[i];
10216     if (OC.isBrackets) {
10217       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10218       if (!CurrentType->isDependentType()) {
10219         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10220         if(!AT)
10221           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10222                            << CurrentType);
10223         CurrentType = AT->getElementType();
10224       } else
10225         CurrentType = Context.DependentTy;
10226 
10227       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10228       if (IdxRval.isInvalid())
10229         return ExprError();
10230       Expr *Idx = IdxRval.get();
10231 
10232       // The expression must be an integral expression.
10233       // FIXME: An integral constant expression?
10234       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10235           !Idx->getType()->isIntegerType())
10236         return ExprError(Diag(Idx->getLocStart(),
10237                               diag::err_typecheck_subscript_not_integer)
10238                          << Idx->getSourceRange());
10239 
10240       // Record this array index.
10241       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10242       Exprs.push_back(Idx);
10243       continue;
10244     }
10245 
10246     // Offset of a field.
10247     if (CurrentType->isDependentType()) {
10248       // We have the offset of a field, but we can't look into the dependent
10249       // type. Just record the identifier of the field.
10250       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10251       CurrentType = Context.DependentTy;
10252       continue;
10253     }
10254 
10255     // We need to have a complete type to look into.
10256     if (RequireCompleteType(OC.LocStart, CurrentType,
10257                             diag::err_offsetof_incomplete_type))
10258       return ExprError();
10259 
10260     // Look for the designated field.
10261     const RecordType *RC = CurrentType->getAs<RecordType>();
10262     if (!RC)
10263       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10264                        << CurrentType);
10265     RecordDecl *RD = RC->getDecl();
10266 
10267     // C++ [lib.support.types]p5:
10268     //   The macro offsetof accepts a restricted set of type arguments in this
10269     //   International Standard. type shall be a POD structure or a POD union
10270     //   (clause 9).
10271     // C++11 [support.types]p4:
10272     //   If type is not a standard-layout class (Clause 9), the results are
10273     //   undefined.
10274     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10275       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10276       unsigned DiagID =
10277         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10278                             : diag::warn_offsetof_non_pod_type;
10279 
10280       if (!IsSafe && !DidWarnAboutNonPOD &&
10281           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10282                               PDiag(DiagID)
10283                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10284                               << CurrentType))
10285         DidWarnAboutNonPOD = true;
10286     }
10287 
10288     // Look for the field.
10289     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10290     LookupQualifiedName(R, RD);
10291     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10292     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10293     if (!MemberDecl) {
10294       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10295         MemberDecl = IndirectMemberDecl->getAnonField();
10296     }
10297 
10298     if (!MemberDecl)
10299       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10300                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10301                                                               OC.LocEnd));
10302 
10303     // C99 7.17p3:
10304     //   (If the specified member is a bit-field, the behavior is undefined.)
10305     //
10306     // We diagnose this as an error.
10307     if (MemberDecl->isBitField()) {
10308       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10309         << MemberDecl->getDeclName()
10310         << SourceRange(BuiltinLoc, RParenLoc);
10311       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10312       return ExprError();
10313     }
10314 
10315     RecordDecl *Parent = MemberDecl->getParent();
10316     if (IndirectMemberDecl)
10317       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10318 
10319     // If the member was found in a base class, introduce OffsetOfNodes for
10320     // the base class indirections.
10321     CXXBasePaths Paths;
10322     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10323       if (Paths.getDetectedVirtual()) {
10324         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10325           << MemberDecl->getDeclName()
10326           << SourceRange(BuiltinLoc, RParenLoc);
10327         return ExprError();
10328       }
10329 
10330       CXXBasePath &Path = Paths.front();
10331       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10332            B != BEnd; ++B)
10333         Comps.push_back(OffsetOfNode(B->Base));
10334     }
10335 
10336     if (IndirectMemberDecl) {
10337       for (auto *FI : IndirectMemberDecl->chain()) {
10338         assert(isa<FieldDecl>(FI));
10339         Comps.push_back(OffsetOfNode(OC.LocStart,
10340                                      cast<FieldDecl>(FI), OC.LocEnd));
10341       }
10342     } else
10343       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10344 
10345     CurrentType = MemberDecl->getType().getNonReferenceType();
10346   }
10347 
10348   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10349                               Comps, Exprs, RParenLoc);
10350 }
10351 
10352 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10353                                       SourceLocation BuiltinLoc,
10354                                       SourceLocation TypeLoc,
10355                                       ParsedType ParsedArgTy,
10356                                       OffsetOfComponent *CompPtr,
10357                                       unsigned NumComponents,
10358                                       SourceLocation RParenLoc) {
10359 
10360   TypeSourceInfo *ArgTInfo;
10361   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10362   if (ArgTy.isNull())
10363     return ExprError();
10364 
10365   if (!ArgTInfo)
10366     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10367 
10368   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10369                               RParenLoc);
10370 }
10371 
10372 
10373 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10374                                  Expr *CondExpr,
10375                                  Expr *LHSExpr, Expr *RHSExpr,
10376                                  SourceLocation RPLoc) {
10377   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10378 
10379   ExprValueKind VK = VK_RValue;
10380   ExprObjectKind OK = OK_Ordinary;
10381   QualType resType;
10382   bool ValueDependent = false;
10383   bool CondIsTrue = false;
10384   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10385     resType = Context.DependentTy;
10386     ValueDependent = true;
10387   } else {
10388     // The conditional expression is required to be a constant expression.
10389     llvm::APSInt condEval(32);
10390     ExprResult CondICE
10391       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10392           diag::err_typecheck_choose_expr_requires_constant, false);
10393     if (CondICE.isInvalid())
10394       return ExprError();
10395     CondExpr = CondICE.get();
10396     CondIsTrue = condEval.getZExtValue();
10397 
10398     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10399     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10400 
10401     resType = ActiveExpr->getType();
10402     ValueDependent = ActiveExpr->isValueDependent();
10403     VK = ActiveExpr->getValueKind();
10404     OK = ActiveExpr->getObjectKind();
10405   }
10406 
10407   return new (Context)
10408       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10409                  CondIsTrue, resType->isDependentType(), ValueDependent);
10410 }
10411 
10412 //===----------------------------------------------------------------------===//
10413 // Clang Extensions.
10414 //===----------------------------------------------------------------------===//
10415 
10416 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10417 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10418   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10419 
10420   if (LangOpts.CPlusPlus) {
10421     Decl *ManglingContextDecl;
10422     if (MangleNumberingContext *MCtx =
10423             getCurrentMangleNumberContext(Block->getDeclContext(),
10424                                           ManglingContextDecl)) {
10425       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10426       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10427     }
10428   }
10429 
10430   PushBlockScope(CurScope, Block);
10431   CurContext->addDecl(Block);
10432   if (CurScope)
10433     PushDeclContext(CurScope, Block);
10434   else
10435     CurContext = Block;
10436 
10437   getCurBlock()->HasImplicitReturnType = true;
10438 
10439   // Enter a new evaluation context to insulate the block from any
10440   // cleanups from the enclosing full-expression.
10441   PushExpressionEvaluationContext(PotentiallyEvaluated);
10442 }
10443 
10444 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10445                                Scope *CurScope) {
10446   assert(ParamInfo.getIdentifier() == nullptr &&
10447          "block-id should have no identifier!");
10448   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10449   BlockScopeInfo *CurBlock = getCurBlock();
10450 
10451   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10452   QualType T = Sig->getType();
10453 
10454   // FIXME: We should allow unexpanded parameter packs here, but that would,
10455   // in turn, make the block expression contain unexpanded parameter packs.
10456   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10457     // Drop the parameters.
10458     FunctionProtoType::ExtProtoInfo EPI;
10459     EPI.HasTrailingReturn = false;
10460     EPI.TypeQuals |= DeclSpec::TQ_const;
10461     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10462     Sig = Context.getTrivialTypeSourceInfo(T);
10463   }
10464 
10465   // GetTypeForDeclarator always produces a function type for a block
10466   // literal signature.  Furthermore, it is always a FunctionProtoType
10467   // unless the function was written with a typedef.
10468   assert(T->isFunctionType() &&
10469          "GetTypeForDeclarator made a non-function block signature");
10470 
10471   // Look for an explicit signature in that function type.
10472   FunctionProtoTypeLoc ExplicitSignature;
10473 
10474   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10475   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10476 
10477     // Check whether that explicit signature was synthesized by
10478     // GetTypeForDeclarator.  If so, don't save that as part of the
10479     // written signature.
10480     if (ExplicitSignature.getLocalRangeBegin() ==
10481         ExplicitSignature.getLocalRangeEnd()) {
10482       // This would be much cheaper if we stored TypeLocs instead of
10483       // TypeSourceInfos.
10484       TypeLoc Result = ExplicitSignature.getReturnLoc();
10485       unsigned Size = Result.getFullDataSize();
10486       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10487       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10488 
10489       ExplicitSignature = FunctionProtoTypeLoc();
10490     }
10491   }
10492 
10493   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10494   CurBlock->FunctionType = T;
10495 
10496   const FunctionType *Fn = T->getAs<FunctionType>();
10497   QualType RetTy = Fn->getReturnType();
10498   bool isVariadic =
10499     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10500 
10501   CurBlock->TheDecl->setIsVariadic(isVariadic);
10502 
10503   // Context.DependentTy is used as a placeholder for a missing block
10504   // return type.  TODO:  what should we do with declarators like:
10505   //   ^ * { ... }
10506   // If the answer is "apply template argument deduction"....
10507   if (RetTy != Context.DependentTy) {
10508     CurBlock->ReturnType = RetTy;
10509     CurBlock->TheDecl->setBlockMissingReturnType(false);
10510     CurBlock->HasImplicitReturnType = false;
10511   }
10512 
10513   // Push block parameters from the declarator if we had them.
10514   SmallVector<ParmVarDecl*, 8> Params;
10515   if (ExplicitSignature) {
10516     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10517       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10518       if (Param->getIdentifier() == nullptr &&
10519           !Param->isImplicit() &&
10520           !Param->isInvalidDecl() &&
10521           !getLangOpts().CPlusPlus)
10522         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10523       Params.push_back(Param);
10524     }
10525 
10526   // Fake up parameter variables if we have a typedef, like
10527   //   ^ fntype { ... }
10528   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10529     for (const auto &I : Fn->param_types()) {
10530       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10531           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10532       Params.push_back(Param);
10533     }
10534   }
10535 
10536   // Set the parameters on the block decl.
10537   if (!Params.empty()) {
10538     CurBlock->TheDecl->setParams(Params);
10539     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10540                              CurBlock->TheDecl->param_end(),
10541                              /*CheckParameterNames=*/false);
10542   }
10543 
10544   // Finally we can process decl attributes.
10545   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10546 
10547   // Put the parameter variables in scope.
10548   for (auto AI : CurBlock->TheDecl->params()) {
10549     AI->setOwningFunction(CurBlock->TheDecl);
10550 
10551     // If this has an identifier, add it to the scope stack.
10552     if (AI->getIdentifier()) {
10553       CheckShadow(CurBlock->TheScope, AI);
10554 
10555       PushOnScopeChains(AI, CurBlock->TheScope);
10556     }
10557   }
10558 }
10559 
10560 /// ActOnBlockError - If there is an error parsing a block, this callback
10561 /// is invoked to pop the information about the block from the action impl.
10562 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10563   // Leave the expression-evaluation context.
10564   DiscardCleanupsInEvaluationContext();
10565   PopExpressionEvaluationContext();
10566 
10567   // Pop off CurBlock, handle nested blocks.
10568   PopDeclContext();
10569   PopFunctionScopeInfo();
10570 }
10571 
10572 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10573 /// literal was successfully completed.  ^(int x){...}
10574 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10575                                     Stmt *Body, Scope *CurScope) {
10576   // If blocks are disabled, emit an error.
10577   if (!LangOpts.Blocks)
10578     Diag(CaretLoc, diag::err_blocks_disable);
10579 
10580   // Leave the expression-evaluation context.
10581   if (hasAnyUnrecoverableErrorsInThisFunction())
10582     DiscardCleanupsInEvaluationContext();
10583   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10584   PopExpressionEvaluationContext();
10585 
10586   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10587 
10588   if (BSI->HasImplicitReturnType)
10589     deduceClosureReturnType(*BSI);
10590 
10591   PopDeclContext();
10592 
10593   QualType RetTy = Context.VoidTy;
10594   if (!BSI->ReturnType.isNull())
10595     RetTy = BSI->ReturnType;
10596 
10597   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10598   QualType BlockTy;
10599 
10600   // Set the captured variables on the block.
10601   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10602   SmallVector<BlockDecl::Capture, 4> Captures;
10603   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10604     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10605     if (Cap.isThisCapture())
10606       continue;
10607     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10608                               Cap.isNested(), Cap.getInitExpr());
10609     Captures.push_back(NewCap);
10610   }
10611   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10612                             BSI->CXXThisCaptureIndex != 0);
10613 
10614   // If the user wrote a function type in some form, try to use that.
10615   if (!BSI->FunctionType.isNull()) {
10616     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10617 
10618     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10619     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10620 
10621     // Turn protoless block types into nullary block types.
10622     if (isa<FunctionNoProtoType>(FTy)) {
10623       FunctionProtoType::ExtProtoInfo EPI;
10624       EPI.ExtInfo = Ext;
10625       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10626 
10627     // Otherwise, if we don't need to change anything about the function type,
10628     // preserve its sugar structure.
10629     } else if (FTy->getReturnType() == RetTy &&
10630                (!NoReturn || FTy->getNoReturnAttr())) {
10631       BlockTy = BSI->FunctionType;
10632 
10633     // Otherwise, make the minimal modifications to the function type.
10634     } else {
10635       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10636       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10637       EPI.TypeQuals = 0; // FIXME: silently?
10638       EPI.ExtInfo = Ext;
10639       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10640     }
10641 
10642   // If we don't have a function type, just build one from nothing.
10643   } else {
10644     FunctionProtoType::ExtProtoInfo EPI;
10645     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10646     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10647   }
10648 
10649   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10650                            BSI->TheDecl->param_end());
10651   BlockTy = Context.getBlockPointerType(BlockTy);
10652 
10653   // If needed, diagnose invalid gotos and switches in the block.
10654   if (getCurFunction()->NeedsScopeChecking() &&
10655       !PP.isCodeCompletionEnabled())
10656     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10657 
10658   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10659 
10660   // Try to apply the named return value optimization. We have to check again
10661   // if we can do this, though, because blocks keep return statements around
10662   // to deduce an implicit return type.
10663   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10664       !BSI->TheDecl->isDependentContext())
10665     computeNRVO(Body, BSI);
10666 
10667   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10668   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10669   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10670 
10671   // If the block isn't obviously global, i.e. it captures anything at
10672   // all, then we need to do a few things in the surrounding context:
10673   if (Result->getBlockDecl()->hasCaptures()) {
10674     // First, this expression has a new cleanup object.
10675     ExprCleanupObjects.push_back(Result->getBlockDecl());
10676     ExprNeedsCleanups = true;
10677 
10678     // It also gets a branch-protected scope if any of the captured
10679     // variables needs destruction.
10680     for (const auto &CI : Result->getBlockDecl()->captures()) {
10681       const VarDecl *var = CI.getVariable();
10682       if (var->getType().isDestructedType() != QualType::DK_none) {
10683         getCurFunction()->setHasBranchProtectedScope();
10684         break;
10685       }
10686     }
10687   }
10688 
10689   return Result;
10690 }
10691 
10692 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10693                                         Expr *E, ParsedType Ty,
10694                                         SourceLocation RPLoc) {
10695   TypeSourceInfo *TInfo;
10696   GetTypeFromParser(Ty, &TInfo);
10697   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10698 }
10699 
10700 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10701                                 Expr *E, TypeSourceInfo *TInfo,
10702                                 SourceLocation RPLoc) {
10703   Expr *OrigExpr = E;
10704 
10705   // Get the va_list type
10706   QualType VaListType = Context.getBuiltinVaListType();
10707   if (VaListType->isArrayType()) {
10708     // Deal with implicit array decay; for example, on x86-64,
10709     // va_list is an array, but it's supposed to decay to
10710     // a pointer for va_arg.
10711     VaListType = Context.getArrayDecayedType(VaListType);
10712     // Make sure the input expression also decays appropriately.
10713     ExprResult Result = UsualUnaryConversions(E);
10714     if (Result.isInvalid())
10715       return ExprError();
10716     E = Result.get();
10717   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10718     // If va_list is a record type and we are compiling in C++ mode,
10719     // check the argument using reference binding.
10720     InitializedEntity Entity
10721       = InitializedEntity::InitializeParameter(Context,
10722           Context.getLValueReferenceType(VaListType), false);
10723     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10724     if (Init.isInvalid())
10725       return ExprError();
10726     E = Init.getAs<Expr>();
10727   } else {
10728     // Otherwise, the va_list argument must be an l-value because
10729     // it is modified by va_arg.
10730     if (!E->isTypeDependent() &&
10731         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10732       return ExprError();
10733   }
10734 
10735   if (!E->isTypeDependent() &&
10736       !Context.hasSameType(VaListType, E->getType())) {
10737     return ExprError(Diag(E->getLocStart(),
10738                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10739       << OrigExpr->getType() << E->getSourceRange());
10740   }
10741 
10742   if (!TInfo->getType()->isDependentType()) {
10743     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10744                             diag::err_second_parameter_to_va_arg_incomplete,
10745                             TInfo->getTypeLoc()))
10746       return ExprError();
10747 
10748     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10749                                TInfo->getType(),
10750                                diag::err_second_parameter_to_va_arg_abstract,
10751                                TInfo->getTypeLoc()))
10752       return ExprError();
10753 
10754     if (!TInfo->getType().isPODType(Context)) {
10755       Diag(TInfo->getTypeLoc().getBeginLoc(),
10756            TInfo->getType()->isObjCLifetimeType()
10757              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10758              : diag::warn_second_parameter_to_va_arg_not_pod)
10759         << TInfo->getType()
10760         << TInfo->getTypeLoc().getSourceRange();
10761     }
10762 
10763     // Check for va_arg where arguments of the given type will be promoted
10764     // (i.e. this va_arg is guaranteed to have undefined behavior).
10765     QualType PromoteType;
10766     if (TInfo->getType()->isPromotableIntegerType()) {
10767       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10768       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10769         PromoteType = QualType();
10770     }
10771     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10772       PromoteType = Context.DoubleTy;
10773     if (!PromoteType.isNull())
10774       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10775                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10776                           << TInfo->getType()
10777                           << PromoteType
10778                           << TInfo->getTypeLoc().getSourceRange());
10779   }
10780 
10781   QualType T = TInfo->getType().getNonLValueExprType(Context);
10782   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10783 }
10784 
10785 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10786   // The type of __null will be int or long, depending on the size of
10787   // pointers on the target.
10788   QualType Ty;
10789   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10790   if (pw == Context.getTargetInfo().getIntWidth())
10791     Ty = Context.IntTy;
10792   else if (pw == Context.getTargetInfo().getLongWidth())
10793     Ty = Context.LongTy;
10794   else if (pw == Context.getTargetInfo().getLongLongWidth())
10795     Ty = Context.LongLongTy;
10796   else {
10797     llvm_unreachable("I don't know size of pointer!");
10798   }
10799 
10800   return new (Context) GNUNullExpr(Ty, TokenLoc);
10801 }
10802 
10803 bool
10804 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10805   if (!getLangOpts().ObjC1)
10806     return false;
10807 
10808   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10809   if (!PT)
10810     return false;
10811 
10812   if (!PT->isObjCIdType()) {
10813     // Check if the destination is the 'NSString' interface.
10814     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10815     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10816       return false;
10817   }
10818 
10819   // Ignore any parens, implicit casts (should only be
10820   // array-to-pointer decays), and not-so-opaque values.  The last is
10821   // important for making this trigger for property assignments.
10822   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10823   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10824     if (OV->getSourceExpr())
10825       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10826 
10827   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10828   if (!SL || !SL->isAscii())
10829     return false;
10830   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10831     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10832   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10833   return true;
10834 }
10835 
10836 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10837                                     SourceLocation Loc,
10838                                     QualType DstType, QualType SrcType,
10839                                     Expr *SrcExpr, AssignmentAction Action,
10840                                     bool *Complained) {
10841   if (Complained)
10842     *Complained = false;
10843 
10844   // Decode the result (notice that AST's are still created for extensions).
10845   bool CheckInferredResultType = false;
10846   bool isInvalid = false;
10847   unsigned DiagKind = 0;
10848   FixItHint Hint;
10849   ConversionFixItGenerator ConvHints;
10850   bool MayHaveConvFixit = false;
10851   bool MayHaveFunctionDiff = false;
10852   const ObjCInterfaceDecl *IFace = nullptr;
10853   const ObjCProtocolDecl *PDecl = nullptr;
10854 
10855   switch (ConvTy) {
10856   case Compatible:
10857       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10858       return false;
10859 
10860   case PointerToInt:
10861     DiagKind = diag::ext_typecheck_convert_pointer_int;
10862     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10863     MayHaveConvFixit = true;
10864     break;
10865   case IntToPointer:
10866     DiagKind = diag::ext_typecheck_convert_int_pointer;
10867     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10868     MayHaveConvFixit = true;
10869     break;
10870   case IncompatiblePointer:
10871       DiagKind =
10872         (Action == AA_Passing_CFAudited ?
10873           diag::err_arc_typecheck_convert_incompatible_pointer :
10874           diag::ext_typecheck_convert_incompatible_pointer);
10875     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10876       SrcType->isObjCObjectPointerType();
10877     if (Hint.isNull() && !CheckInferredResultType) {
10878       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10879     }
10880     else if (CheckInferredResultType) {
10881       SrcType = SrcType.getUnqualifiedType();
10882       DstType = DstType.getUnqualifiedType();
10883     }
10884     MayHaveConvFixit = true;
10885     break;
10886   case IncompatiblePointerSign:
10887     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10888     break;
10889   case FunctionVoidPointer:
10890     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10891     break;
10892   case IncompatiblePointerDiscardsQualifiers: {
10893     // Perform array-to-pointer decay if necessary.
10894     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10895 
10896     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10897     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10898     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10899       DiagKind = diag::err_typecheck_incompatible_address_space;
10900       break;
10901 
10902 
10903     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10904       DiagKind = diag::err_typecheck_incompatible_ownership;
10905       break;
10906     }
10907 
10908     llvm_unreachable("unknown error case for discarding qualifiers!");
10909     // fallthrough
10910   }
10911   case CompatiblePointerDiscardsQualifiers:
10912     // If the qualifiers lost were because we were applying the
10913     // (deprecated) C++ conversion from a string literal to a char*
10914     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10915     // Ideally, this check would be performed in
10916     // checkPointerTypesForAssignment. However, that would require a
10917     // bit of refactoring (so that the second argument is an
10918     // expression, rather than a type), which should be done as part
10919     // of a larger effort to fix checkPointerTypesForAssignment for
10920     // C++ semantics.
10921     if (getLangOpts().CPlusPlus &&
10922         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10923       return false;
10924     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10925     break;
10926   case IncompatibleNestedPointerQualifiers:
10927     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10928     break;
10929   case IntToBlockPointer:
10930     DiagKind = diag::err_int_to_block_pointer;
10931     break;
10932   case IncompatibleBlockPointer:
10933     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10934     break;
10935   case IncompatibleObjCQualifiedId: {
10936     if (SrcType->isObjCQualifiedIdType()) {
10937       const ObjCObjectPointerType *srcOPT =
10938                 SrcType->getAs<ObjCObjectPointerType>();
10939       for (auto *srcProto : srcOPT->quals()) {
10940         PDecl = srcProto;
10941         break;
10942       }
10943       if (const ObjCInterfaceType *IFaceT =
10944             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10945         IFace = IFaceT->getDecl();
10946     }
10947     else if (DstType->isObjCQualifiedIdType()) {
10948       const ObjCObjectPointerType *dstOPT =
10949         DstType->getAs<ObjCObjectPointerType>();
10950       for (auto *dstProto : dstOPT->quals()) {
10951         PDecl = dstProto;
10952         break;
10953       }
10954       if (const ObjCInterfaceType *IFaceT =
10955             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10956         IFace = IFaceT->getDecl();
10957     }
10958     DiagKind = diag::warn_incompatible_qualified_id;
10959     break;
10960   }
10961   case IncompatibleVectors:
10962     DiagKind = diag::warn_incompatible_vectors;
10963     break;
10964   case IncompatibleObjCWeakRef:
10965     DiagKind = diag::err_arc_weak_unavailable_assign;
10966     break;
10967   case Incompatible:
10968     DiagKind = diag::err_typecheck_convert_incompatible;
10969     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10970     MayHaveConvFixit = true;
10971     isInvalid = true;
10972     MayHaveFunctionDiff = true;
10973     break;
10974   }
10975 
10976   QualType FirstType, SecondType;
10977   switch (Action) {
10978   case AA_Assigning:
10979   case AA_Initializing:
10980     // The destination type comes first.
10981     FirstType = DstType;
10982     SecondType = SrcType;
10983     break;
10984 
10985   case AA_Returning:
10986   case AA_Passing:
10987   case AA_Passing_CFAudited:
10988   case AA_Converting:
10989   case AA_Sending:
10990   case AA_Casting:
10991     // The source type comes first.
10992     FirstType = SrcType;
10993     SecondType = DstType;
10994     break;
10995   }
10996 
10997   PartialDiagnostic FDiag = PDiag(DiagKind);
10998   if (Action == AA_Passing_CFAudited)
10999     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
11000   else
11001     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11002 
11003   // If we can fix the conversion, suggest the FixIts.
11004   assert(ConvHints.isNull() || Hint.isNull());
11005   if (!ConvHints.isNull()) {
11006     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11007          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11008       FDiag << *HI;
11009   } else {
11010     FDiag << Hint;
11011   }
11012   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11013 
11014   if (MayHaveFunctionDiff)
11015     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11016 
11017   Diag(Loc, FDiag);
11018   if (DiagKind == diag::warn_incompatible_qualified_id &&
11019       PDecl && IFace && !IFace->hasDefinition())
11020       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11021         << IFace->getName() << PDecl->getName();
11022 
11023   if (SecondType == Context.OverloadTy)
11024     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11025                               FirstType);
11026 
11027   if (CheckInferredResultType)
11028     EmitRelatedResultTypeNote(SrcExpr);
11029 
11030   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11031     EmitRelatedResultTypeNoteForReturn(DstType);
11032 
11033   if (Complained)
11034     *Complained = true;
11035   return isInvalid;
11036 }
11037 
11038 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11039                                                  llvm::APSInt *Result) {
11040   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11041   public:
11042     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11043       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11044     }
11045   } Diagnoser;
11046 
11047   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11048 }
11049 
11050 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11051                                                  llvm::APSInt *Result,
11052                                                  unsigned DiagID,
11053                                                  bool AllowFold) {
11054   class IDDiagnoser : public VerifyICEDiagnoser {
11055     unsigned DiagID;
11056 
11057   public:
11058     IDDiagnoser(unsigned DiagID)
11059       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11060 
11061     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11062       S.Diag(Loc, DiagID) << SR;
11063     }
11064   } Diagnoser(DiagID);
11065 
11066   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11067 }
11068 
11069 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11070                                             SourceRange SR) {
11071   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11072 }
11073 
11074 ExprResult
11075 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11076                                       VerifyICEDiagnoser &Diagnoser,
11077                                       bool AllowFold) {
11078   SourceLocation DiagLoc = E->getLocStart();
11079 
11080   if (getLangOpts().CPlusPlus11) {
11081     // C++11 [expr.const]p5:
11082     //   If an expression of literal class type is used in a context where an
11083     //   integral constant expression is required, then that class type shall
11084     //   have a single non-explicit conversion function to an integral or
11085     //   unscoped enumeration type
11086     ExprResult Converted;
11087     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11088     public:
11089       CXX11ConvertDiagnoser(bool Silent)
11090           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11091                                 Silent, true) {}
11092 
11093       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11094                                            QualType T) override {
11095         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11096       }
11097 
11098       SemaDiagnosticBuilder diagnoseIncomplete(
11099           Sema &S, SourceLocation Loc, QualType T) override {
11100         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11101       }
11102 
11103       SemaDiagnosticBuilder diagnoseExplicitConv(
11104           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11105         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11106       }
11107 
11108       SemaDiagnosticBuilder noteExplicitConv(
11109           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11110         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11111                  << ConvTy->isEnumeralType() << ConvTy;
11112       }
11113 
11114       SemaDiagnosticBuilder diagnoseAmbiguous(
11115           Sema &S, SourceLocation Loc, QualType T) override {
11116         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11117       }
11118 
11119       SemaDiagnosticBuilder noteAmbiguous(
11120           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11121         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11122                  << ConvTy->isEnumeralType() << ConvTy;
11123       }
11124 
11125       SemaDiagnosticBuilder diagnoseConversion(
11126           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11127         llvm_unreachable("conversion functions are permitted");
11128       }
11129     } ConvertDiagnoser(Diagnoser.Suppress);
11130 
11131     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11132                                                     ConvertDiagnoser);
11133     if (Converted.isInvalid())
11134       return Converted;
11135     E = Converted.get();
11136     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11137       return ExprError();
11138   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11139     // An ICE must be of integral or unscoped enumeration type.
11140     if (!Diagnoser.Suppress)
11141       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11142     return ExprError();
11143   }
11144 
11145   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11146   // in the non-ICE case.
11147   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11148     if (Result)
11149       *Result = E->EvaluateKnownConstInt(Context);
11150     return E;
11151   }
11152 
11153   Expr::EvalResult EvalResult;
11154   SmallVector<PartialDiagnosticAt, 8> Notes;
11155   EvalResult.Diag = &Notes;
11156 
11157   // Try to evaluate the expression, and produce diagnostics explaining why it's
11158   // not a constant expression as a side-effect.
11159   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11160                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11161 
11162   // In C++11, we can rely on diagnostics being produced for any expression
11163   // which is not a constant expression. If no diagnostics were produced, then
11164   // this is a constant expression.
11165   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11166     if (Result)
11167       *Result = EvalResult.Val.getInt();
11168     return E;
11169   }
11170 
11171   // If our only note is the usual "invalid subexpression" note, just point
11172   // the caret at its location rather than producing an essentially
11173   // redundant note.
11174   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11175         diag::note_invalid_subexpr_in_const_expr) {
11176     DiagLoc = Notes[0].first;
11177     Notes.clear();
11178   }
11179 
11180   if (!Folded || !AllowFold) {
11181     if (!Diagnoser.Suppress) {
11182       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11183       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11184         Diag(Notes[I].first, Notes[I].second);
11185     }
11186 
11187     return ExprError();
11188   }
11189 
11190   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11191   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11192     Diag(Notes[I].first, Notes[I].second);
11193 
11194   if (Result)
11195     *Result = EvalResult.Val.getInt();
11196   return E;
11197 }
11198 
11199 namespace {
11200   // Handle the case where we conclude a expression which we speculatively
11201   // considered to be unevaluated is actually evaluated.
11202   class TransformToPE : public TreeTransform<TransformToPE> {
11203     typedef TreeTransform<TransformToPE> BaseTransform;
11204 
11205   public:
11206     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11207 
11208     // Make sure we redo semantic analysis
11209     bool AlwaysRebuild() { return true; }
11210 
11211     // Make sure we handle LabelStmts correctly.
11212     // FIXME: This does the right thing, but maybe we need a more general
11213     // fix to TreeTransform?
11214     StmtResult TransformLabelStmt(LabelStmt *S) {
11215       S->getDecl()->setStmt(nullptr);
11216       return BaseTransform::TransformLabelStmt(S);
11217     }
11218 
11219     // We need to special-case DeclRefExprs referring to FieldDecls which
11220     // are not part of a member pointer formation; normal TreeTransforming
11221     // doesn't catch this case because of the way we represent them in the AST.
11222     // FIXME: This is a bit ugly; is it really the best way to handle this
11223     // case?
11224     //
11225     // Error on DeclRefExprs referring to FieldDecls.
11226     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11227       if (isa<FieldDecl>(E->getDecl()) &&
11228           !SemaRef.isUnevaluatedContext())
11229         return SemaRef.Diag(E->getLocation(),
11230                             diag::err_invalid_non_static_member_use)
11231             << E->getDecl() << E->getSourceRange();
11232 
11233       return BaseTransform::TransformDeclRefExpr(E);
11234     }
11235 
11236     // Exception: filter out member pointer formation
11237     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11238       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11239         return E;
11240 
11241       return BaseTransform::TransformUnaryOperator(E);
11242     }
11243 
11244     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11245       // Lambdas never need to be transformed.
11246       return E;
11247     }
11248   };
11249 }
11250 
11251 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11252   assert(isUnevaluatedContext() &&
11253          "Should only transform unevaluated expressions");
11254   ExprEvalContexts.back().Context =
11255       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11256   if (isUnevaluatedContext())
11257     return E;
11258   return TransformToPE(*this).TransformExpr(E);
11259 }
11260 
11261 void
11262 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11263                                       Decl *LambdaContextDecl,
11264                                       bool IsDecltype) {
11265   ExprEvalContexts.push_back(
11266              ExpressionEvaluationContextRecord(NewContext,
11267                                                ExprCleanupObjects.size(),
11268                                                ExprNeedsCleanups,
11269                                                LambdaContextDecl,
11270                                                IsDecltype));
11271   ExprNeedsCleanups = false;
11272   if (!MaybeODRUseExprs.empty())
11273     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11274 }
11275 
11276 void
11277 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11278                                       ReuseLambdaContextDecl_t,
11279                                       bool IsDecltype) {
11280   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11281   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11282 }
11283 
11284 void Sema::PopExpressionEvaluationContext() {
11285   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11286 
11287   if (!Rec.Lambdas.empty()) {
11288     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11289       unsigned D;
11290       if (Rec.isUnevaluated()) {
11291         // C++11 [expr.prim.lambda]p2:
11292         //   A lambda-expression shall not appear in an unevaluated operand
11293         //   (Clause 5).
11294         D = diag::err_lambda_unevaluated_operand;
11295       } else {
11296         // C++1y [expr.const]p2:
11297         //   A conditional-expression e is a core constant expression unless the
11298         //   evaluation of e, following the rules of the abstract machine, would
11299         //   evaluate [...] a lambda-expression.
11300         D = diag::err_lambda_in_constant_expression;
11301       }
11302       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11303         Diag(Rec.Lambdas[I]->getLocStart(), D);
11304     } else {
11305       // Mark the capture expressions odr-used. This was deferred
11306       // during lambda expression creation.
11307       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11308         LambdaExpr *Lambda = Rec.Lambdas[I];
11309         for (LambdaExpr::capture_init_iterator
11310                   C = Lambda->capture_init_begin(),
11311                CEnd = Lambda->capture_init_end();
11312              C != CEnd; ++C) {
11313           MarkDeclarationsReferencedInExpr(*C);
11314         }
11315       }
11316     }
11317   }
11318 
11319   // When are coming out of an unevaluated context, clear out any
11320   // temporaries that we may have created as part of the evaluation of
11321   // the expression in that context: they aren't relevant because they
11322   // will never be constructed.
11323   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11324     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11325                              ExprCleanupObjects.end());
11326     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11327     CleanupVarDeclMarking();
11328     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11329   // Otherwise, merge the contexts together.
11330   } else {
11331     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11332     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11333                             Rec.SavedMaybeODRUseExprs.end());
11334   }
11335 
11336   // Pop the current expression evaluation context off the stack.
11337   ExprEvalContexts.pop_back();
11338 }
11339 
11340 void Sema::DiscardCleanupsInEvaluationContext() {
11341   ExprCleanupObjects.erase(
11342          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11343          ExprCleanupObjects.end());
11344   ExprNeedsCleanups = false;
11345   MaybeODRUseExprs.clear();
11346 }
11347 
11348 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11349   if (!E->getType()->isVariablyModifiedType())
11350     return E;
11351   return TransformToPotentiallyEvaluated(E);
11352 }
11353 
11354 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11355   // Do not mark anything as "used" within a dependent context; wait for
11356   // an instantiation.
11357   if (SemaRef.CurContext->isDependentContext())
11358     return false;
11359 
11360   switch (SemaRef.ExprEvalContexts.back().Context) {
11361     case Sema::Unevaluated:
11362     case Sema::UnevaluatedAbstract:
11363       // We are in an expression that is not potentially evaluated; do nothing.
11364       // (Depending on how you read the standard, we actually do need to do
11365       // something here for null pointer constants, but the standard's
11366       // definition of a null pointer constant is completely crazy.)
11367       return false;
11368 
11369     case Sema::ConstantEvaluated:
11370     case Sema::PotentiallyEvaluated:
11371       // We are in a potentially evaluated expression (or a constant-expression
11372       // in C++03); we need to do implicit template instantiation, implicitly
11373       // define class members, and mark most declarations as used.
11374       return true;
11375 
11376     case Sema::PotentiallyEvaluatedIfUsed:
11377       // Referenced declarations will only be used if the construct in the
11378       // containing expression is used.
11379       return false;
11380   }
11381   llvm_unreachable("Invalid context");
11382 }
11383 
11384 /// \brief Mark a function referenced, and check whether it is odr-used
11385 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11386 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11387   assert(Func && "No function?");
11388 
11389   Func->setReferenced();
11390 
11391   // C++11 [basic.def.odr]p3:
11392   //   A function whose name appears as a potentially-evaluated expression is
11393   //   odr-used if it is the unique lookup result or the selected member of a
11394   //   set of overloaded functions [...].
11395   //
11396   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11397   // can just check that here. Skip the rest of this function if we've already
11398   // marked the function as used.
11399   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11400     // C++11 [temp.inst]p3:
11401     //   Unless a function template specialization has been explicitly
11402     //   instantiated or explicitly specialized, the function template
11403     //   specialization is implicitly instantiated when the specialization is
11404     //   referenced in a context that requires a function definition to exist.
11405     //
11406     // We consider constexpr function templates to be referenced in a context
11407     // that requires a definition to exist whenever they are referenced.
11408     //
11409     // FIXME: This instantiates constexpr functions too frequently. If this is
11410     // really an unevaluated context (and we're not just in the definition of a
11411     // function template or overload resolution or other cases which we
11412     // incorrectly consider to be unevaluated contexts), and we're not in a
11413     // subexpression which we actually need to evaluate (for instance, a
11414     // template argument, array bound or an expression in a braced-init-list),
11415     // we are not permitted to instantiate this constexpr function definition.
11416     //
11417     // FIXME: This also implicitly defines special members too frequently. They
11418     // are only supposed to be implicitly defined if they are odr-used, but they
11419     // are not odr-used from constant expressions in unevaluated contexts.
11420     // However, they cannot be referenced if they are deleted, and they are
11421     // deleted whenever the implicit definition of the special member would
11422     // fail.
11423     if (!Func->isConstexpr() || Func->getBody())
11424       return;
11425     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11426     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11427       return;
11428   }
11429 
11430   // Note that this declaration has been used.
11431   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11432     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11433     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11434       if (Constructor->isDefaultConstructor()) {
11435         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11436           return;
11437         DefineImplicitDefaultConstructor(Loc, Constructor);
11438       } else if (Constructor->isCopyConstructor()) {
11439         DefineImplicitCopyConstructor(Loc, Constructor);
11440       } else if (Constructor->isMoveConstructor()) {
11441         DefineImplicitMoveConstructor(Loc, Constructor);
11442       }
11443     } else if (Constructor->getInheritedConstructor()) {
11444       DefineInheritingConstructor(Loc, Constructor);
11445     }
11446 
11447     MarkVTableUsed(Loc, Constructor->getParent());
11448   } else if (CXXDestructorDecl *Destructor =
11449                  dyn_cast<CXXDestructorDecl>(Func)) {
11450     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11451     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11452       DefineImplicitDestructor(Loc, Destructor);
11453     if (Destructor->isVirtual())
11454       MarkVTableUsed(Loc, Destructor->getParent());
11455   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11456     if (MethodDecl->isOverloadedOperator() &&
11457         MethodDecl->getOverloadedOperator() == OO_Equal) {
11458       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11459       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11460         if (MethodDecl->isCopyAssignmentOperator())
11461           DefineImplicitCopyAssignment(Loc, MethodDecl);
11462         else
11463           DefineImplicitMoveAssignment(Loc, MethodDecl);
11464       }
11465     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11466                MethodDecl->getParent()->isLambda()) {
11467       CXXConversionDecl *Conversion =
11468           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11469       if (Conversion->isLambdaToBlockPointerConversion())
11470         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11471       else
11472         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11473     } else if (MethodDecl->isVirtual())
11474       MarkVTableUsed(Loc, MethodDecl->getParent());
11475   }
11476 
11477   // Recursive functions should be marked when used from another function.
11478   // FIXME: Is this really right?
11479   if (CurContext == Func) return;
11480 
11481   // Resolve the exception specification for any function which is
11482   // used: CodeGen will need it.
11483   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11484   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11485     ResolveExceptionSpec(Loc, FPT);
11486 
11487   // Implicit instantiation of function templates and member functions of
11488   // class templates.
11489   if (Func->isImplicitlyInstantiable()) {
11490     bool AlreadyInstantiated = false;
11491     SourceLocation PointOfInstantiation = Loc;
11492     if (FunctionTemplateSpecializationInfo *SpecInfo
11493                               = Func->getTemplateSpecializationInfo()) {
11494       if (SpecInfo->getPointOfInstantiation().isInvalid())
11495         SpecInfo->setPointOfInstantiation(Loc);
11496       else if (SpecInfo->getTemplateSpecializationKind()
11497                  == TSK_ImplicitInstantiation) {
11498         AlreadyInstantiated = true;
11499         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11500       }
11501     } else if (MemberSpecializationInfo *MSInfo
11502                                 = Func->getMemberSpecializationInfo()) {
11503       if (MSInfo->getPointOfInstantiation().isInvalid())
11504         MSInfo->setPointOfInstantiation(Loc);
11505       else if (MSInfo->getTemplateSpecializationKind()
11506                  == TSK_ImplicitInstantiation) {
11507         AlreadyInstantiated = true;
11508         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11509       }
11510     }
11511 
11512     if (!AlreadyInstantiated || Func->isConstexpr()) {
11513       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11514           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11515           ActiveTemplateInstantiations.size())
11516         PendingLocalImplicitInstantiations.push_back(
11517             std::make_pair(Func, PointOfInstantiation));
11518       else if (Func->isConstexpr())
11519         // Do not defer instantiations of constexpr functions, to avoid the
11520         // expression evaluator needing to call back into Sema if it sees a
11521         // call to such a function.
11522         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11523       else {
11524         PendingInstantiations.push_back(std::make_pair(Func,
11525                                                        PointOfInstantiation));
11526         // Notify the consumer that a function was implicitly instantiated.
11527         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11528       }
11529     }
11530   } else {
11531     // Walk redefinitions, as some of them may be instantiable.
11532     for (auto i : Func->redecls()) {
11533       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11534         MarkFunctionReferenced(Loc, i);
11535     }
11536   }
11537 
11538   // Keep track of used but undefined functions.
11539   if (!Func->isDefined()) {
11540     if (mightHaveNonExternalLinkage(Func))
11541       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11542     else if (Func->getMostRecentDecl()->isInlined() &&
11543              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11544              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11545       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11546   }
11547 
11548   // Normally the most current decl is marked used while processing the use and
11549   // any subsequent decls are marked used by decl merging. This fails with
11550   // template instantiation since marking can happen at the end of the file
11551   // and, because of the two phase lookup, this function is called with at
11552   // decl in the middle of a decl chain. We loop to maintain the invariant
11553   // that once a decl is used, all decls after it are also used.
11554   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11555     F->markUsed(Context);
11556     if (F == Func)
11557       break;
11558   }
11559 }
11560 
11561 static void
11562 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11563                                    VarDecl *var, DeclContext *DC) {
11564   DeclContext *VarDC = var->getDeclContext();
11565 
11566   //  If the parameter still belongs to the translation unit, then
11567   //  we're actually just using one parameter in the declaration of
11568   //  the next.
11569   if (isa<ParmVarDecl>(var) &&
11570       isa<TranslationUnitDecl>(VarDC))
11571     return;
11572 
11573   // For C code, don't diagnose about capture if we're not actually in code
11574   // right now; it's impossible to write a non-constant expression outside of
11575   // function context, so we'll get other (more useful) diagnostics later.
11576   //
11577   // For C++, things get a bit more nasty... it would be nice to suppress this
11578   // diagnostic for certain cases like using a local variable in an array bound
11579   // for a member of a local class, but the correct predicate is not obvious.
11580   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11581     return;
11582 
11583   if (isa<CXXMethodDecl>(VarDC) &&
11584       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11585     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11586       << var->getIdentifier();
11587   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11588     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11589       << var->getIdentifier() << fn->getDeclName();
11590   } else if (isa<BlockDecl>(VarDC)) {
11591     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11592       << var->getIdentifier();
11593   } else {
11594     // FIXME: Is there any other context where a local variable can be
11595     // declared?
11596     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11597       << var->getIdentifier();
11598   }
11599 
11600   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11601       << var->getIdentifier();
11602 
11603   // FIXME: Add additional diagnostic info about class etc. which prevents
11604   // capture.
11605 }
11606 
11607 
11608 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11609                                       bool &SubCapturesAreNested,
11610                                       QualType &CaptureType,
11611                                       QualType &DeclRefType) {
11612    // Check whether we've already captured it.
11613   if (CSI->CaptureMap.count(Var)) {
11614     // If we found a capture, any subcaptures are nested.
11615     SubCapturesAreNested = true;
11616 
11617     // Retrieve the capture type for this variable.
11618     CaptureType = CSI->getCapture(Var).getCaptureType();
11619 
11620     // Compute the type of an expression that refers to this variable.
11621     DeclRefType = CaptureType.getNonReferenceType();
11622 
11623     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11624     if (Cap.isCopyCapture() &&
11625         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11626       DeclRefType.addConst();
11627     return true;
11628   }
11629   return false;
11630 }
11631 
11632 // Only block literals, captured statements, and lambda expressions can
11633 // capture; other scopes don't work.
11634 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11635                                  SourceLocation Loc,
11636                                  const bool Diagnose, Sema &S) {
11637   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11638     return getLambdaAwareParentOfDeclContext(DC);
11639   else {
11640     if (Diagnose)
11641        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11642   }
11643   return nullptr;
11644 }
11645 
11646 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11647 // certain types of variables (unnamed, variably modified types etc.)
11648 // so check for eligibility.
11649 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11650                                  SourceLocation Loc,
11651                                  const bool Diagnose, Sema &S) {
11652 
11653   bool IsBlock = isa<BlockScopeInfo>(CSI);
11654   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11655 
11656   // Lambdas are not allowed to capture unnamed variables
11657   // (e.g. anonymous unions).
11658   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11659   // assuming that's the intent.
11660   if (IsLambda && !Var->getDeclName()) {
11661     if (Diagnose) {
11662       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11663       S.Diag(Var->getLocation(), diag::note_declared_at);
11664     }
11665     return false;
11666   }
11667 
11668   // Prohibit variably-modified types; they're difficult to deal with.
11669   if (Var->getType()->isVariablyModifiedType()) {
11670     if (Diagnose) {
11671       if (IsBlock)
11672         S.Diag(Loc, diag::err_ref_vm_type);
11673       else
11674         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11675       S.Diag(Var->getLocation(), diag::note_previous_decl)
11676         << Var->getDeclName();
11677     }
11678     return false;
11679   }
11680   // Prohibit structs with flexible array members too.
11681   // We cannot capture what is in the tail end of the struct.
11682   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11683     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11684       if (Diagnose) {
11685         if (IsBlock)
11686           S.Diag(Loc, diag::err_ref_flexarray_type);
11687         else
11688           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11689             << Var->getDeclName();
11690         S.Diag(Var->getLocation(), diag::note_previous_decl)
11691           << Var->getDeclName();
11692       }
11693       return false;
11694     }
11695   }
11696   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11697   // Lambdas and captured statements are not allowed to capture __block
11698   // variables; they don't support the expected semantics.
11699   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11700     if (Diagnose) {
11701       S.Diag(Loc, diag::err_capture_block_variable)
11702         << Var->getDeclName() << !IsLambda;
11703       S.Diag(Var->getLocation(), diag::note_previous_decl)
11704         << Var->getDeclName();
11705     }
11706     return false;
11707   }
11708 
11709   return true;
11710 }
11711 
11712 // Returns true if the capture by block was successful.
11713 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11714                                  SourceLocation Loc,
11715                                  const bool BuildAndDiagnose,
11716                                  QualType &CaptureType,
11717                                  QualType &DeclRefType,
11718                                  const bool Nested,
11719                                  Sema &S) {
11720   Expr *CopyExpr = nullptr;
11721   bool ByRef = false;
11722 
11723   // Blocks are not allowed to capture arrays.
11724   if (CaptureType->isArrayType()) {
11725     if (BuildAndDiagnose) {
11726       S.Diag(Loc, diag::err_ref_array_type);
11727       S.Diag(Var->getLocation(), diag::note_previous_decl)
11728       << Var->getDeclName();
11729     }
11730     return false;
11731   }
11732 
11733   // Forbid the block-capture of autoreleasing variables.
11734   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11735     if (BuildAndDiagnose) {
11736       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11737         << /*block*/ 0;
11738       S.Diag(Var->getLocation(), diag::note_previous_decl)
11739         << Var->getDeclName();
11740     }
11741     return false;
11742   }
11743   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11744   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11745     // Block capture by reference does not change the capture or
11746     // declaration reference types.
11747     ByRef = true;
11748   } else {
11749     // Block capture by copy introduces 'const'.
11750     CaptureType = CaptureType.getNonReferenceType().withConst();
11751     DeclRefType = CaptureType;
11752 
11753     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11754       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11755         // The capture logic needs the destructor, so make sure we mark it.
11756         // Usually this is unnecessary because most local variables have
11757         // their destructors marked at declaration time, but parameters are
11758         // an exception because it's technically only the call site that
11759         // actually requires the destructor.
11760         if (isa<ParmVarDecl>(Var))
11761           S.FinalizeVarWithDestructor(Var, Record);
11762 
11763         // Enter a new evaluation context to insulate the copy
11764         // full-expression.
11765         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11766 
11767         // According to the blocks spec, the capture of a variable from
11768         // the stack requires a const copy constructor.  This is not true
11769         // of the copy/move done to move a __block variable to the heap.
11770         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11771                                                   DeclRefType.withConst(),
11772                                                   VK_LValue, Loc);
11773 
11774         ExprResult Result
11775           = S.PerformCopyInitialization(
11776               InitializedEntity::InitializeBlock(Var->getLocation(),
11777                                                   CaptureType, false),
11778               Loc, DeclRef);
11779 
11780         // Build a full-expression copy expression if initialization
11781         // succeeded and used a non-trivial constructor.  Recover from
11782         // errors by pretending that the copy isn't necessary.
11783         if (!Result.isInvalid() &&
11784             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11785                 ->isTrivial()) {
11786           Result = S.MaybeCreateExprWithCleanups(Result);
11787           CopyExpr = Result.get();
11788         }
11789       }
11790     }
11791   }
11792 
11793   // Actually capture the variable.
11794   if (BuildAndDiagnose)
11795     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11796                     SourceLocation(), CaptureType, CopyExpr);
11797 
11798   return true;
11799 
11800 }
11801 
11802 
11803 /// \brief Capture the given variable in the captured region.
11804 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11805                                     VarDecl *Var,
11806                                     SourceLocation Loc,
11807                                     const bool BuildAndDiagnose,
11808                                     QualType &CaptureType,
11809                                     QualType &DeclRefType,
11810                                     const bool RefersToEnclosingLocal,
11811                                     Sema &S) {
11812 
11813   // By default, capture variables by reference.
11814   bool ByRef = true;
11815   // Using an LValue reference type is consistent with Lambdas (see below).
11816   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11817   Expr *CopyExpr = nullptr;
11818   if (BuildAndDiagnose) {
11819     // The current implementation assumes that all variables are captured
11820     // by references. Since there is no capture by copy, no expression
11821     // evaluation will be needed.
11822     RecordDecl *RD = RSI->TheRecordDecl;
11823 
11824     FieldDecl *Field
11825       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11826                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11827                           nullptr, false, ICIS_NoInit);
11828     Field->setImplicit(true);
11829     Field->setAccess(AS_private);
11830     RD->addDecl(Field);
11831 
11832     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11833                                             DeclRefType, VK_LValue, Loc);
11834     Var->setReferenced(true);
11835     Var->markUsed(S.Context);
11836   }
11837 
11838   // Actually capture the variable.
11839   if (BuildAndDiagnose)
11840     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11841                     SourceLocation(), CaptureType, CopyExpr);
11842 
11843 
11844   return true;
11845 }
11846 
11847 /// \brief Create a field within the lambda class for the variable
11848 ///  being captured.  Handle Array captures.
11849 static ExprResult addAsFieldToClosureType(Sema &S,
11850                                  LambdaScopeInfo *LSI,
11851                                   VarDecl *Var, QualType FieldType,
11852                                   QualType DeclRefType,
11853                                   SourceLocation Loc,
11854                                   bool RefersToEnclosingLocal) {
11855   CXXRecordDecl *Lambda = LSI->Lambda;
11856 
11857   // Build the non-static data member.
11858   FieldDecl *Field
11859     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11860                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11861                         nullptr, false, ICIS_NoInit);
11862   Field->setImplicit(true);
11863   Field->setAccess(AS_private);
11864   Lambda->addDecl(Field);
11865 
11866   // C++11 [expr.prim.lambda]p21:
11867   //   When the lambda-expression is evaluated, the entities that
11868   //   are captured by copy are used to direct-initialize each
11869   //   corresponding non-static data member of the resulting closure
11870   //   object. (For array members, the array elements are
11871   //   direct-initialized in increasing subscript order.) These
11872   //   initializations are performed in the (unspecified) order in
11873   //   which the non-static data members are declared.
11874 
11875   // Introduce a new evaluation context for the initialization, so
11876   // that temporaries introduced as part of the capture are retained
11877   // to be re-"exported" from the lambda expression itself.
11878   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11879 
11880   // C++ [expr.prim.labda]p12:
11881   //   An entity captured by a lambda-expression is odr-used (3.2) in
11882   //   the scope containing the lambda-expression.
11883   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11884                                           DeclRefType, VK_LValue, Loc);
11885   Var->setReferenced(true);
11886   Var->markUsed(S.Context);
11887 
11888   // When the field has array type, create index variables for each
11889   // dimension of the array. We use these index variables to subscript
11890   // the source array, and other clients (e.g., CodeGen) will perform
11891   // the necessary iteration with these index variables.
11892   SmallVector<VarDecl *, 4> IndexVariables;
11893   QualType BaseType = FieldType;
11894   QualType SizeType = S.Context.getSizeType();
11895   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11896   while (const ConstantArrayType *Array
11897                         = S.Context.getAsConstantArrayType(BaseType)) {
11898     // Create the iteration variable for this array index.
11899     IdentifierInfo *IterationVarName = nullptr;
11900     {
11901       SmallString<8> Str;
11902       llvm::raw_svector_ostream OS(Str);
11903       OS << "__i" << IndexVariables.size();
11904       IterationVarName = &S.Context.Idents.get(OS.str());
11905     }
11906     VarDecl *IterationVar
11907       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11908                         IterationVarName, SizeType,
11909                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11910                         SC_None);
11911     IndexVariables.push_back(IterationVar);
11912     LSI->ArrayIndexVars.push_back(IterationVar);
11913 
11914     // Create a reference to the iteration variable.
11915     ExprResult IterationVarRef
11916       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11917     assert(!IterationVarRef.isInvalid() &&
11918            "Reference to invented variable cannot fail!");
11919     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11920     assert(!IterationVarRef.isInvalid() &&
11921            "Conversion of invented variable cannot fail!");
11922 
11923     // Subscript the array with this iteration variable.
11924     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11925                              Ref, Loc, IterationVarRef.get(), Loc);
11926     if (Subscript.isInvalid()) {
11927       S.CleanupVarDeclMarking();
11928       S.DiscardCleanupsInEvaluationContext();
11929       return ExprError();
11930     }
11931 
11932     Ref = Subscript.get();
11933     BaseType = Array->getElementType();
11934   }
11935 
11936   // Construct the entity that we will be initializing. For an array, this
11937   // will be first element in the array, which may require several levels
11938   // of array-subscript entities.
11939   SmallVector<InitializedEntity, 4> Entities;
11940   Entities.reserve(1 + IndexVariables.size());
11941   Entities.push_back(
11942     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11943         Field->getType(), Loc));
11944   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11945     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11946                                                             0,
11947                                                             Entities.back()));
11948 
11949   InitializationKind InitKind
11950     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11951   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11952   ExprResult Result(true);
11953   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11954     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11955 
11956   // If this initialization requires any cleanups (e.g., due to a
11957   // default argument to a copy constructor), note that for the
11958   // lambda.
11959   if (S.ExprNeedsCleanups)
11960     LSI->ExprNeedsCleanups = true;
11961 
11962   // Exit the expression evaluation context used for the capture.
11963   S.CleanupVarDeclMarking();
11964   S.DiscardCleanupsInEvaluationContext();
11965   return Result;
11966 }
11967 
11968 
11969 
11970 /// \brief Capture the given variable in the lambda.
11971 static bool captureInLambda(LambdaScopeInfo *LSI,
11972                             VarDecl *Var,
11973                             SourceLocation Loc,
11974                             const bool BuildAndDiagnose,
11975                             QualType &CaptureType,
11976                             QualType &DeclRefType,
11977                             const bool RefersToEnclosingLocal,
11978                             const Sema::TryCaptureKind Kind,
11979                             SourceLocation EllipsisLoc,
11980                             const bool IsTopScope,
11981                             Sema &S) {
11982 
11983   // Determine whether we are capturing by reference or by value.
11984   bool ByRef = false;
11985   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11986     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11987   } else {
11988     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11989   }
11990 
11991   // Compute the type of the field that will capture this variable.
11992   if (ByRef) {
11993     // C++11 [expr.prim.lambda]p15:
11994     //   An entity is captured by reference if it is implicitly or
11995     //   explicitly captured but not captured by copy. It is
11996     //   unspecified whether additional unnamed non-static data
11997     //   members are declared in the closure type for entities
11998     //   captured by reference.
11999     //
12000     // FIXME: It is not clear whether we want to build an lvalue reference
12001     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12002     // to do the former, while EDG does the latter. Core issue 1249 will
12003     // clarify, but for now we follow GCC because it's a more permissive and
12004     // easily defensible position.
12005     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12006   } else {
12007     // C++11 [expr.prim.lambda]p14:
12008     //   For each entity captured by copy, an unnamed non-static
12009     //   data member is declared in the closure type. The
12010     //   declaration order of these members is unspecified. The type
12011     //   of such a data member is the type of the corresponding
12012     //   captured entity if the entity is not a reference to an
12013     //   object, or the referenced type otherwise. [Note: If the
12014     //   captured entity is a reference to a function, the
12015     //   corresponding data member is also a reference to a
12016     //   function. - end note ]
12017     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12018       if (!RefType->getPointeeType()->isFunctionType())
12019         CaptureType = RefType->getPointeeType();
12020     }
12021 
12022     // Forbid the lambda copy-capture of autoreleasing variables.
12023     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12024       if (BuildAndDiagnose) {
12025         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12026         S.Diag(Var->getLocation(), diag::note_previous_decl)
12027           << Var->getDeclName();
12028       }
12029       return false;
12030     }
12031 
12032     // Make sure that by-copy captures are of a complete and non-abstract type.
12033     if (BuildAndDiagnose) {
12034       if (!CaptureType->isDependentType() &&
12035           S.RequireCompleteType(Loc, CaptureType,
12036                                 diag::err_capture_of_incomplete_type,
12037                                 Var->getDeclName()))
12038         return false;
12039 
12040       if (S.RequireNonAbstractType(Loc, CaptureType,
12041                                    diag::err_capture_of_abstract_type))
12042         return false;
12043     }
12044   }
12045 
12046   // Capture this variable in the lambda.
12047   Expr *CopyExpr = nullptr;
12048   if (BuildAndDiagnose) {
12049     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12050                                         CaptureType, DeclRefType, Loc,
12051                                         RefersToEnclosingLocal);
12052     if (!Result.isInvalid())
12053       CopyExpr = Result.get();
12054   }
12055 
12056   // Compute the type of a reference to this captured variable.
12057   if (ByRef)
12058     DeclRefType = CaptureType.getNonReferenceType();
12059   else {
12060     // C++ [expr.prim.lambda]p5:
12061     //   The closure type for a lambda-expression has a public inline
12062     //   function call operator [...]. This function call operator is
12063     //   declared const (9.3.1) if and only if the lambda-expression’s
12064     //   parameter-declaration-clause is not followed by mutable.
12065     DeclRefType = CaptureType.getNonReferenceType();
12066     if (!LSI->Mutable && !CaptureType->isReferenceType())
12067       DeclRefType.addConst();
12068   }
12069 
12070   // Add the capture.
12071   if (BuildAndDiagnose)
12072     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12073                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12074 
12075   return true;
12076 }
12077 
12078 
12079 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12080                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12081                               bool BuildAndDiagnose,
12082                               QualType &CaptureType,
12083                               QualType &DeclRefType,
12084 						                const unsigned *const FunctionScopeIndexToStopAt) {
12085   bool Nested = false;
12086 
12087   DeclContext *DC = CurContext;
12088   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12089       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12090   // We need to sync up the Declaration Context with the
12091   // FunctionScopeIndexToStopAt
12092   if (FunctionScopeIndexToStopAt) {
12093     unsigned FSIndex = FunctionScopes.size() - 1;
12094     while (FSIndex != MaxFunctionScopesIndex) {
12095       DC = getLambdaAwareParentOfDeclContext(DC);
12096       --FSIndex;
12097     }
12098   }
12099 
12100 
12101   // If the variable is declared in the current context (and is not an
12102   // init-capture), there is no need to capture it.
12103   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12104   if (!Var->hasLocalStorage()) return true;
12105 
12106   // Walk up the stack to determine whether we can capture the variable,
12107   // performing the "simple" checks that don't depend on type. We stop when
12108   // we've either hit the declared scope of the variable or find an existing
12109   // capture of that variable.  We start from the innermost capturing-entity
12110   // (the DC) and ensure that all intervening capturing-entities
12111   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12112   // declcontext can either capture the variable or have already captured
12113   // the variable.
12114   CaptureType = Var->getType();
12115   DeclRefType = CaptureType.getNonReferenceType();
12116   bool Explicit = (Kind != TryCapture_Implicit);
12117   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12118   do {
12119     // Only block literals, captured statements, and lambda expressions can
12120     // capture; other scopes don't work.
12121     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12122                                                               ExprLoc,
12123                                                               BuildAndDiagnose,
12124                                                               *this);
12125     if (!ParentDC) return true;
12126 
12127     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12128     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12129 
12130 
12131     // Check whether we've already captured it.
12132     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12133                                              DeclRefType))
12134       break;
12135     // If we are instantiating a generic lambda call operator body,
12136     // we do not want to capture new variables.  What was captured
12137     // during either a lambdas transformation or initial parsing
12138     // should be used.
12139     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12140       if (BuildAndDiagnose) {
12141         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12142         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12143           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12144           Diag(Var->getLocation(), diag::note_previous_decl)
12145              << Var->getDeclName();
12146           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12147         } else
12148           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12149       }
12150       return true;
12151     }
12152     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12153     // certain types of variables (unnamed, variably modified types etc.)
12154     // so check for eligibility.
12155     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12156        return true;
12157 
12158     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12159       // No capture-default, and this is not an explicit capture
12160       // so cannot capture this variable.
12161       if (BuildAndDiagnose) {
12162         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12163         Diag(Var->getLocation(), diag::note_previous_decl)
12164           << Var->getDeclName();
12165         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12166              diag::note_lambda_decl);
12167         // FIXME: If we error out because an outer lambda can not implicitly
12168         // capture a variable that an inner lambda explicitly captures, we
12169         // should have the inner lambda do the explicit capture - because
12170         // it makes for cleaner diagnostics later.  This would purely be done
12171         // so that the diagnostic does not misleadingly claim that a variable
12172         // can not be captured by a lambda implicitly even though it is captured
12173         // explicitly.  Suggestion:
12174         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12175         //    at the function head
12176         //  - cache the StartingDeclContext - this must be a lambda
12177         //  - captureInLambda in the innermost lambda the variable.
12178       }
12179       return true;
12180     }
12181 
12182     FunctionScopesIndex--;
12183     DC = ParentDC;
12184     Explicit = false;
12185   } while (!Var->getDeclContext()->Equals(DC));
12186 
12187   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12188   // computing the type of the capture at each step, checking type-specific
12189   // requirements, and adding captures if requested.
12190   // If the variable had already been captured previously, we start capturing
12191   // at the lambda nested within that one.
12192   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12193        ++I) {
12194     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12195 
12196     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12197       if (!captureInBlock(BSI, Var, ExprLoc,
12198                           BuildAndDiagnose, CaptureType,
12199                           DeclRefType, Nested, *this))
12200         return true;
12201       Nested = true;
12202     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12203       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12204                                    BuildAndDiagnose, CaptureType,
12205                                    DeclRefType, Nested, *this))
12206         return true;
12207       Nested = true;
12208     } else {
12209       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12210       if (!captureInLambda(LSI, Var, ExprLoc,
12211                            BuildAndDiagnose, CaptureType,
12212                            DeclRefType, Nested, Kind, EllipsisLoc,
12213                             /*IsTopScope*/I == N - 1, *this))
12214         return true;
12215       Nested = true;
12216     }
12217   }
12218   return false;
12219 }
12220 
12221 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12222                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12223   QualType CaptureType;
12224   QualType DeclRefType;
12225   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12226                             /*BuildAndDiagnose=*/true, CaptureType,
12227                             DeclRefType, nullptr);
12228 }
12229 
12230 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12231   QualType CaptureType;
12232   QualType DeclRefType;
12233 
12234   // Determine whether we can capture this variable.
12235   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12236                          /*BuildAndDiagnose=*/false, CaptureType,
12237                          DeclRefType, nullptr))
12238     return QualType();
12239 
12240   return DeclRefType;
12241 }
12242 
12243 
12244 
12245 // If either the type of the variable or the initializer is dependent,
12246 // return false. Otherwise, determine whether the variable is a constant
12247 // expression. Use this if you need to know if a variable that might or
12248 // might not be dependent is truly a constant expression.
12249 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12250     ASTContext &Context) {
12251 
12252   if (Var->getType()->isDependentType())
12253     return false;
12254   const VarDecl *DefVD = nullptr;
12255   Var->getAnyInitializer(DefVD);
12256   if (!DefVD)
12257     return false;
12258   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12259   Expr *Init = cast<Expr>(Eval->Value);
12260   if (Init->isValueDependent())
12261     return false;
12262   return IsVariableAConstantExpression(Var, Context);
12263 }
12264 
12265 
12266 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12267   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12268   // an object that satisfies the requirements for appearing in a
12269   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12270   // is immediately applied."  This function handles the lvalue-to-rvalue
12271   // conversion part.
12272   MaybeODRUseExprs.erase(E->IgnoreParens());
12273 
12274   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12275   // to a variable that is a constant expression, and if so, identify it as
12276   // a reference to a variable that does not involve an odr-use of that
12277   // variable.
12278   if (LambdaScopeInfo *LSI = getCurLambda()) {
12279     Expr *SansParensExpr = E->IgnoreParens();
12280     VarDecl *Var = nullptr;
12281     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12282       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12283     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12284       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12285 
12286     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12287       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12288   }
12289 }
12290 
12291 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12292   if (!Res.isUsable())
12293     return Res;
12294 
12295   // If a constant-expression is a reference to a variable where we delay
12296   // deciding whether it is an odr-use, just assume we will apply the
12297   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12298   // (a non-type template argument), we have special handling anyway.
12299   UpdateMarkingForLValueToRValue(Res.get());
12300   return Res;
12301 }
12302 
12303 void Sema::CleanupVarDeclMarking() {
12304   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12305                                         e = MaybeODRUseExprs.end();
12306        i != e; ++i) {
12307     VarDecl *Var;
12308     SourceLocation Loc;
12309     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12310       Var = cast<VarDecl>(DRE->getDecl());
12311       Loc = DRE->getLocation();
12312     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12313       Var = cast<VarDecl>(ME->getMemberDecl());
12314       Loc = ME->getMemberLoc();
12315     } else {
12316       llvm_unreachable("Unexpcted expression");
12317     }
12318 
12319     MarkVarDeclODRUsed(Var, Loc, *this,
12320                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12321   }
12322 
12323   MaybeODRUseExprs.clear();
12324 }
12325 
12326 
12327 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12328                                     VarDecl *Var, Expr *E) {
12329   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12330          "Invalid Expr argument to DoMarkVarDeclReferenced");
12331   Var->setReferenced();
12332 
12333   // If the context is not potentially evaluated, this is not an odr-use and
12334   // does not trigger instantiation.
12335   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12336     if (SemaRef.isUnevaluatedContext())
12337       return;
12338 
12339     // If we don't yet know whether this context is going to end up being an
12340     // evaluated context, and we're referencing a variable from an enclosing
12341     // scope, add a potential capture.
12342     //
12343     // FIXME: Is this necessary? These contexts are only used for default
12344     // arguments, where local variables can't be used.
12345     const bool RefersToEnclosingScope =
12346         (SemaRef.CurContext != Var->getDeclContext() &&
12347          Var->getDeclContext()->isFunctionOrMethod() &&
12348          Var->hasLocalStorage());
12349     if (!RefersToEnclosingScope)
12350       return;
12351 
12352     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12353       // If a variable could potentially be odr-used, defer marking it so
12354       // until we finish analyzing the full expression for any lvalue-to-rvalue
12355       // or discarded value conversions that would obviate odr-use.
12356       // Add it to the list of potential captures that will be analyzed
12357       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12358       // unless the variable is a reference that was initialized by a constant
12359       // expression (this will never need to be captured or odr-used).
12360       assert(E && "Capture variable should be used in an expression.");
12361       if (!Var->getType()->isReferenceType() ||
12362           !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12363         LSI->addPotentialCapture(E->IgnoreParens());
12364     }
12365     return;
12366   }
12367 
12368   VarTemplateSpecializationDecl *VarSpec =
12369       dyn_cast<VarTemplateSpecializationDecl>(Var);
12370   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12371          "Can't instantiate a partial template specialization.");
12372 
12373   // Perform implicit instantiation of static data members, static data member
12374   // templates of class templates, and variable template specializations. Delay
12375   // instantiations of variable templates, except for those that could be used
12376   // in a constant expression.
12377   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12378   if (isTemplateInstantiation(TSK)) {
12379     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12380 
12381     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12382       if (Var->getPointOfInstantiation().isInvalid()) {
12383         // This is a modification of an existing AST node. Notify listeners.
12384         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12385           L->StaticDataMemberInstantiated(Var);
12386       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12387         // Don't bother trying to instantiate it again, unless we might need
12388         // its initializer before we get to the end of the TU.
12389         TryInstantiating = false;
12390     }
12391 
12392     if (Var->getPointOfInstantiation().isInvalid())
12393       Var->setTemplateSpecializationKind(TSK, Loc);
12394 
12395     if (TryInstantiating) {
12396       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12397       bool InstantiationDependent = false;
12398       bool IsNonDependent =
12399           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12400                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12401                   : true;
12402 
12403       // Do not instantiate specializations that are still type-dependent.
12404       if (IsNonDependent) {
12405         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12406           // Do not defer instantiations of variables which could be used in a
12407           // constant expression.
12408           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12409         } else {
12410           SemaRef.PendingInstantiations
12411               .push_back(std::make_pair(Var, PointOfInstantiation));
12412         }
12413       }
12414     }
12415   }
12416 
12417   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12418   // the requirements for appearing in a constant expression (5.19) and, if
12419   // it is an object, the lvalue-to-rvalue conversion (4.1)
12420   // is immediately applied."  We check the first part here, and
12421   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12422   // Note that we use the C++11 definition everywhere because nothing in
12423   // C++03 depends on whether we get the C++03 version correct. The second
12424   // part does not apply to references, since they are not objects.
12425   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12426     // A reference initialized by a constant expression can never be
12427     // odr-used, so simply ignore it.
12428     if (!Var->getType()->isReferenceType())
12429       SemaRef.MaybeODRUseExprs.insert(E);
12430   } else
12431     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12432                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12433 }
12434 
12435 /// \brief Mark a variable referenced, and check whether it is odr-used
12436 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12437 /// used directly for normal expressions referring to VarDecl.
12438 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12439   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12440 }
12441 
12442 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12443                                Decl *D, Expr *E, bool OdrUse) {
12444   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12445     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12446     return;
12447   }
12448 
12449   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12450 
12451   // If this is a call to a method via a cast, also mark the method in the
12452   // derived class used in case codegen can devirtualize the call.
12453   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12454   if (!ME)
12455     return;
12456   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12457   if (!MD)
12458     return;
12459   const Expr *Base = ME->getBase();
12460   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12461   if (!MostDerivedClassDecl)
12462     return;
12463   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12464   if (!DM || DM->isPure())
12465     return;
12466   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12467 }
12468 
12469 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12470 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12471   // TODO: update this with DR# once a defect report is filed.
12472   // C++11 defect. The address of a pure member should not be an ODR use, even
12473   // if it's a qualified reference.
12474   bool OdrUse = true;
12475   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12476     if (Method->isVirtual())
12477       OdrUse = false;
12478   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12479 }
12480 
12481 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12482 void Sema::MarkMemberReferenced(MemberExpr *E) {
12483   // C++11 [basic.def.odr]p2:
12484   //   A non-overloaded function whose name appears as a potentially-evaluated
12485   //   expression or a member of a set of candidate functions, if selected by
12486   //   overload resolution when referred to from a potentially-evaluated
12487   //   expression, is odr-used, unless it is a pure virtual function and its
12488   //   name is not explicitly qualified.
12489   bool OdrUse = true;
12490   if (!E->hasQualifier()) {
12491     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12492       if (Method->isPure())
12493         OdrUse = false;
12494   }
12495   SourceLocation Loc = E->getMemberLoc().isValid() ?
12496                             E->getMemberLoc() : E->getLocStart();
12497   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12498 }
12499 
12500 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12501 /// marks the declaration referenced, and performs odr-use checking for
12502 /// functions and variables. This method should not be used when building a
12503 /// normal expression which refers to a variable.
12504 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12505   if (OdrUse) {
12506     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12507       MarkVariableReferenced(Loc, VD);
12508       return;
12509     }
12510     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12511       MarkFunctionReferenced(Loc, FD);
12512       return;
12513     }
12514   }
12515   D->setReferenced();
12516 }
12517 
12518 namespace {
12519   // Mark all of the declarations referenced
12520   // FIXME: Not fully implemented yet! We need to have a better understanding
12521   // of when we're entering
12522   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12523     Sema &S;
12524     SourceLocation Loc;
12525 
12526   public:
12527     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12528 
12529     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12530 
12531     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12532     bool TraverseRecordType(RecordType *T);
12533   };
12534 }
12535 
12536 bool MarkReferencedDecls::TraverseTemplateArgument(
12537     const TemplateArgument &Arg) {
12538   if (Arg.getKind() == TemplateArgument::Declaration) {
12539     if (Decl *D = Arg.getAsDecl())
12540       S.MarkAnyDeclReferenced(Loc, D, true);
12541   }
12542 
12543   return Inherited::TraverseTemplateArgument(Arg);
12544 }
12545 
12546 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12547   if (ClassTemplateSpecializationDecl *Spec
12548                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12549     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12550     return TraverseTemplateArguments(Args.data(), Args.size());
12551   }
12552 
12553   return true;
12554 }
12555 
12556 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12557   MarkReferencedDecls Marker(*this, Loc);
12558   Marker.TraverseType(Context.getCanonicalType(T));
12559 }
12560 
12561 namespace {
12562   /// \brief Helper class that marks all of the declarations referenced by
12563   /// potentially-evaluated subexpressions as "referenced".
12564   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12565     Sema &S;
12566     bool SkipLocalVariables;
12567 
12568   public:
12569     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12570 
12571     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12572       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12573 
12574     void VisitDeclRefExpr(DeclRefExpr *E) {
12575       // If we were asked not to visit local variables, don't.
12576       if (SkipLocalVariables) {
12577         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12578           if (VD->hasLocalStorage())
12579             return;
12580       }
12581 
12582       S.MarkDeclRefReferenced(E);
12583     }
12584 
12585     void VisitMemberExpr(MemberExpr *E) {
12586       S.MarkMemberReferenced(E);
12587       Inherited::VisitMemberExpr(E);
12588     }
12589 
12590     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12591       S.MarkFunctionReferenced(E->getLocStart(),
12592             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12593       Visit(E->getSubExpr());
12594     }
12595 
12596     void VisitCXXNewExpr(CXXNewExpr *E) {
12597       if (E->getOperatorNew())
12598         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12599       if (E->getOperatorDelete())
12600         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12601       Inherited::VisitCXXNewExpr(E);
12602     }
12603 
12604     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12605       if (E->getOperatorDelete())
12606         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12607       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12608       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12609         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12610         S.MarkFunctionReferenced(E->getLocStart(),
12611                                     S.LookupDestructor(Record));
12612       }
12613 
12614       Inherited::VisitCXXDeleteExpr(E);
12615     }
12616 
12617     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12618       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12619       Inherited::VisitCXXConstructExpr(E);
12620     }
12621 
12622     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12623       Visit(E->getExpr());
12624     }
12625 
12626     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12627       Inherited::VisitImplicitCastExpr(E);
12628 
12629       if (E->getCastKind() == CK_LValueToRValue)
12630         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12631     }
12632   };
12633 }
12634 
12635 /// \brief Mark any declarations that appear within this expression or any
12636 /// potentially-evaluated subexpressions as "referenced".
12637 ///
12638 /// \param SkipLocalVariables If true, don't mark local variables as
12639 /// 'referenced'.
12640 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12641                                             bool SkipLocalVariables) {
12642   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12643 }
12644 
12645 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12646 /// of the program being compiled.
12647 ///
12648 /// This routine emits the given diagnostic when the code currently being
12649 /// type-checked is "potentially evaluated", meaning that there is a
12650 /// possibility that the code will actually be executable. Code in sizeof()
12651 /// expressions, code used only during overload resolution, etc., are not
12652 /// potentially evaluated. This routine will suppress such diagnostics or,
12653 /// in the absolutely nutty case of potentially potentially evaluated
12654 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12655 /// later.
12656 ///
12657 /// This routine should be used for all diagnostics that describe the run-time
12658 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12659 /// Failure to do so will likely result in spurious diagnostics or failures
12660 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12661 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12662                                const PartialDiagnostic &PD) {
12663   switch (ExprEvalContexts.back().Context) {
12664   case Unevaluated:
12665   case UnevaluatedAbstract:
12666     // The argument will never be evaluated, so don't complain.
12667     break;
12668 
12669   case ConstantEvaluated:
12670     // Relevant diagnostics should be produced by constant evaluation.
12671     break;
12672 
12673   case PotentiallyEvaluated:
12674   case PotentiallyEvaluatedIfUsed:
12675     if (Statement && getCurFunctionOrMethodDecl()) {
12676       FunctionScopes.back()->PossiblyUnreachableDiags.
12677         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12678     }
12679     else
12680       Diag(Loc, PD);
12681 
12682     return true;
12683   }
12684 
12685   return false;
12686 }
12687 
12688 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12689                                CallExpr *CE, FunctionDecl *FD) {
12690   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12691     return false;
12692 
12693   // If we're inside a decltype's expression, don't check for a valid return
12694   // type or construct temporaries until we know whether this is the last call.
12695   if (ExprEvalContexts.back().IsDecltype) {
12696     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12697     return false;
12698   }
12699 
12700   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12701     FunctionDecl *FD;
12702     CallExpr *CE;
12703 
12704   public:
12705     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12706       : FD(FD), CE(CE) { }
12707 
12708     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12709       if (!FD) {
12710         S.Diag(Loc, diag::err_call_incomplete_return)
12711           << T << CE->getSourceRange();
12712         return;
12713       }
12714 
12715       S.Diag(Loc, diag::err_call_function_incomplete_return)
12716         << CE->getSourceRange() << FD->getDeclName() << T;
12717       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12718           << FD->getDeclName();
12719     }
12720   } Diagnoser(FD, CE);
12721 
12722   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12723     return true;
12724 
12725   return false;
12726 }
12727 
12728 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12729 // will prevent this condition from triggering, which is what we want.
12730 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12731   SourceLocation Loc;
12732 
12733   unsigned diagnostic = diag::warn_condition_is_assignment;
12734   bool IsOrAssign = false;
12735 
12736   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12737     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12738       return;
12739 
12740     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12741 
12742     // Greylist some idioms by putting them into a warning subcategory.
12743     if (ObjCMessageExpr *ME
12744           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12745       Selector Sel = ME->getSelector();
12746 
12747       // self = [<foo> init...]
12748       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12749         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12750 
12751       // <foo> = [<bar> nextObject]
12752       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12753         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12754     }
12755 
12756     Loc = Op->getOperatorLoc();
12757   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12758     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12759       return;
12760 
12761     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12762     Loc = Op->getOperatorLoc();
12763   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12764     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12765   else {
12766     // Not an assignment.
12767     return;
12768   }
12769 
12770   Diag(Loc, diagnostic) << E->getSourceRange();
12771 
12772   SourceLocation Open = E->getLocStart();
12773   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12774   Diag(Loc, diag::note_condition_assign_silence)
12775         << FixItHint::CreateInsertion(Open, "(")
12776         << FixItHint::CreateInsertion(Close, ")");
12777 
12778   if (IsOrAssign)
12779     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12780       << FixItHint::CreateReplacement(Loc, "!=");
12781   else
12782     Diag(Loc, diag::note_condition_assign_to_comparison)
12783       << FixItHint::CreateReplacement(Loc, "==");
12784 }
12785 
12786 /// \brief Redundant parentheses over an equality comparison can indicate
12787 /// that the user intended an assignment used as condition.
12788 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12789   // Don't warn if the parens came from a macro.
12790   SourceLocation parenLoc = ParenE->getLocStart();
12791   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12792     return;
12793   // Don't warn for dependent expressions.
12794   if (ParenE->isTypeDependent())
12795     return;
12796 
12797   Expr *E = ParenE->IgnoreParens();
12798 
12799   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12800     if (opE->getOpcode() == BO_EQ &&
12801         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12802                                                            == Expr::MLV_Valid) {
12803       SourceLocation Loc = opE->getOperatorLoc();
12804 
12805       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12806       SourceRange ParenERange = ParenE->getSourceRange();
12807       Diag(Loc, diag::note_equality_comparison_silence)
12808         << FixItHint::CreateRemoval(ParenERange.getBegin())
12809         << FixItHint::CreateRemoval(ParenERange.getEnd());
12810       Diag(Loc, diag::note_equality_comparison_to_assign)
12811         << FixItHint::CreateReplacement(Loc, "=");
12812     }
12813 }
12814 
12815 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12816   DiagnoseAssignmentAsCondition(E);
12817   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12818     DiagnoseEqualityWithExtraParens(parenE);
12819 
12820   ExprResult result = CheckPlaceholderExpr(E);
12821   if (result.isInvalid()) return ExprError();
12822   E = result.get();
12823 
12824   if (!E->isTypeDependent()) {
12825     if (getLangOpts().CPlusPlus)
12826       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12827 
12828     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12829     if (ERes.isInvalid())
12830       return ExprError();
12831     E = ERes.get();
12832 
12833     QualType T = E->getType();
12834     if (!T->isScalarType()) { // C99 6.8.4.1p1
12835       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12836         << T << E->getSourceRange();
12837       return ExprError();
12838     }
12839   }
12840 
12841   return E;
12842 }
12843 
12844 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12845                                        Expr *SubExpr) {
12846   if (!SubExpr)
12847     return ExprError();
12848 
12849   return CheckBooleanCondition(SubExpr, Loc);
12850 }
12851 
12852 namespace {
12853   /// A visitor for rebuilding a call to an __unknown_any expression
12854   /// to have an appropriate type.
12855   struct RebuildUnknownAnyFunction
12856     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12857 
12858     Sema &S;
12859 
12860     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12861 
12862     ExprResult VisitStmt(Stmt *S) {
12863       llvm_unreachable("unexpected statement!");
12864     }
12865 
12866     ExprResult VisitExpr(Expr *E) {
12867       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12868         << E->getSourceRange();
12869       return ExprError();
12870     }
12871 
12872     /// Rebuild an expression which simply semantically wraps another
12873     /// expression which it shares the type and value kind of.
12874     template <class T> ExprResult rebuildSugarExpr(T *E) {
12875       ExprResult SubResult = Visit(E->getSubExpr());
12876       if (SubResult.isInvalid()) return ExprError();
12877 
12878       Expr *SubExpr = SubResult.get();
12879       E->setSubExpr(SubExpr);
12880       E->setType(SubExpr->getType());
12881       E->setValueKind(SubExpr->getValueKind());
12882       assert(E->getObjectKind() == OK_Ordinary);
12883       return E;
12884     }
12885 
12886     ExprResult VisitParenExpr(ParenExpr *E) {
12887       return rebuildSugarExpr(E);
12888     }
12889 
12890     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12891       return rebuildSugarExpr(E);
12892     }
12893 
12894     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12895       ExprResult SubResult = Visit(E->getSubExpr());
12896       if (SubResult.isInvalid()) return ExprError();
12897 
12898       Expr *SubExpr = SubResult.get();
12899       E->setSubExpr(SubExpr);
12900       E->setType(S.Context.getPointerType(SubExpr->getType()));
12901       assert(E->getValueKind() == VK_RValue);
12902       assert(E->getObjectKind() == OK_Ordinary);
12903       return E;
12904     }
12905 
12906     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12907       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12908 
12909       E->setType(VD->getType());
12910 
12911       assert(E->getValueKind() == VK_RValue);
12912       if (S.getLangOpts().CPlusPlus &&
12913           !(isa<CXXMethodDecl>(VD) &&
12914             cast<CXXMethodDecl>(VD)->isInstance()))
12915         E->setValueKind(VK_LValue);
12916 
12917       return E;
12918     }
12919 
12920     ExprResult VisitMemberExpr(MemberExpr *E) {
12921       return resolveDecl(E, E->getMemberDecl());
12922     }
12923 
12924     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12925       return resolveDecl(E, E->getDecl());
12926     }
12927   };
12928 }
12929 
12930 /// Given a function expression of unknown-any type, try to rebuild it
12931 /// to have a function type.
12932 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12933   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12934   if (Result.isInvalid()) return ExprError();
12935   return S.DefaultFunctionArrayConversion(Result.get());
12936 }
12937 
12938 namespace {
12939   /// A visitor for rebuilding an expression of type __unknown_anytype
12940   /// into one which resolves the type directly on the referring
12941   /// expression.  Strict preservation of the original source
12942   /// structure is not a goal.
12943   struct RebuildUnknownAnyExpr
12944     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12945 
12946     Sema &S;
12947 
12948     /// The current destination type.
12949     QualType DestType;
12950 
12951     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12952       : S(S), DestType(CastType) {}
12953 
12954     ExprResult VisitStmt(Stmt *S) {
12955       llvm_unreachable("unexpected statement!");
12956     }
12957 
12958     ExprResult VisitExpr(Expr *E) {
12959       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12960         << E->getSourceRange();
12961       return ExprError();
12962     }
12963 
12964     ExprResult VisitCallExpr(CallExpr *E);
12965     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12966 
12967     /// Rebuild an expression which simply semantically wraps another
12968     /// expression which it shares the type and value kind of.
12969     template <class T> ExprResult rebuildSugarExpr(T *E) {
12970       ExprResult SubResult = Visit(E->getSubExpr());
12971       if (SubResult.isInvalid()) return ExprError();
12972       Expr *SubExpr = SubResult.get();
12973       E->setSubExpr(SubExpr);
12974       E->setType(SubExpr->getType());
12975       E->setValueKind(SubExpr->getValueKind());
12976       assert(E->getObjectKind() == OK_Ordinary);
12977       return E;
12978     }
12979 
12980     ExprResult VisitParenExpr(ParenExpr *E) {
12981       return rebuildSugarExpr(E);
12982     }
12983 
12984     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12985       return rebuildSugarExpr(E);
12986     }
12987 
12988     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12989       const PointerType *Ptr = DestType->getAs<PointerType>();
12990       if (!Ptr) {
12991         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12992           << E->getSourceRange();
12993         return ExprError();
12994       }
12995       assert(E->getValueKind() == VK_RValue);
12996       assert(E->getObjectKind() == OK_Ordinary);
12997       E->setType(DestType);
12998 
12999       // Build the sub-expression as if it were an object of the pointee type.
13000       DestType = Ptr->getPointeeType();
13001       ExprResult SubResult = Visit(E->getSubExpr());
13002       if (SubResult.isInvalid()) return ExprError();
13003       E->setSubExpr(SubResult.get());
13004       return E;
13005     }
13006 
13007     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13008 
13009     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13010 
13011     ExprResult VisitMemberExpr(MemberExpr *E) {
13012       return resolveDecl(E, E->getMemberDecl());
13013     }
13014 
13015     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13016       return resolveDecl(E, E->getDecl());
13017     }
13018   };
13019 }
13020 
13021 /// Rebuilds a call expression which yielded __unknown_anytype.
13022 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13023   Expr *CalleeExpr = E->getCallee();
13024 
13025   enum FnKind {
13026     FK_MemberFunction,
13027     FK_FunctionPointer,
13028     FK_BlockPointer
13029   };
13030 
13031   FnKind Kind;
13032   QualType CalleeType = CalleeExpr->getType();
13033   if (CalleeType == S.Context.BoundMemberTy) {
13034     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13035     Kind = FK_MemberFunction;
13036     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13037   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13038     CalleeType = Ptr->getPointeeType();
13039     Kind = FK_FunctionPointer;
13040   } else {
13041     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13042     Kind = FK_BlockPointer;
13043   }
13044   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13045 
13046   // Verify that this is a legal result type of a function.
13047   if (DestType->isArrayType() || DestType->isFunctionType()) {
13048     unsigned diagID = diag::err_func_returning_array_function;
13049     if (Kind == FK_BlockPointer)
13050       diagID = diag::err_block_returning_array_function;
13051 
13052     S.Diag(E->getExprLoc(), diagID)
13053       << DestType->isFunctionType() << DestType;
13054     return ExprError();
13055   }
13056 
13057   // Otherwise, go ahead and set DestType as the call's result.
13058   E->setType(DestType.getNonLValueExprType(S.Context));
13059   E->setValueKind(Expr::getValueKindForType(DestType));
13060   assert(E->getObjectKind() == OK_Ordinary);
13061 
13062   // Rebuild the function type, replacing the result type with DestType.
13063   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13064   if (Proto) {
13065     // __unknown_anytype(...) is a special case used by the debugger when
13066     // it has no idea what a function's signature is.
13067     //
13068     // We want to build this call essentially under the K&R
13069     // unprototyped rules, but making a FunctionNoProtoType in C++
13070     // would foul up all sorts of assumptions.  However, we cannot
13071     // simply pass all arguments as variadic arguments, nor can we
13072     // portably just call the function under a non-variadic type; see
13073     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13074     // However, it turns out that in practice it is generally safe to
13075     // call a function declared as "A foo(B,C,D);" under the prototype
13076     // "A foo(B,C,D,...);".  The only known exception is with the
13077     // Windows ABI, where any variadic function is implicitly cdecl
13078     // regardless of its normal CC.  Therefore we change the parameter
13079     // types to match the types of the arguments.
13080     //
13081     // This is a hack, but it is far superior to moving the
13082     // corresponding target-specific code from IR-gen to Sema/AST.
13083 
13084     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13085     SmallVector<QualType, 8> ArgTypes;
13086     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13087       ArgTypes.reserve(E->getNumArgs());
13088       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13089         Expr *Arg = E->getArg(i);
13090         QualType ArgType = Arg->getType();
13091         if (E->isLValue()) {
13092           ArgType = S.Context.getLValueReferenceType(ArgType);
13093         } else if (E->isXValue()) {
13094           ArgType = S.Context.getRValueReferenceType(ArgType);
13095         }
13096         ArgTypes.push_back(ArgType);
13097       }
13098       ParamTypes = ArgTypes;
13099     }
13100     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13101                                          Proto->getExtProtoInfo());
13102   } else {
13103     DestType = S.Context.getFunctionNoProtoType(DestType,
13104                                                 FnType->getExtInfo());
13105   }
13106 
13107   // Rebuild the appropriate pointer-to-function type.
13108   switch (Kind) {
13109   case FK_MemberFunction:
13110     // Nothing to do.
13111     break;
13112 
13113   case FK_FunctionPointer:
13114     DestType = S.Context.getPointerType(DestType);
13115     break;
13116 
13117   case FK_BlockPointer:
13118     DestType = S.Context.getBlockPointerType(DestType);
13119     break;
13120   }
13121 
13122   // Finally, we can recurse.
13123   ExprResult CalleeResult = Visit(CalleeExpr);
13124   if (!CalleeResult.isUsable()) return ExprError();
13125   E->setCallee(CalleeResult.get());
13126 
13127   // Bind a temporary if necessary.
13128   return S.MaybeBindToTemporary(E);
13129 }
13130 
13131 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13132   // Verify that this is a legal result type of a call.
13133   if (DestType->isArrayType() || DestType->isFunctionType()) {
13134     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13135       << DestType->isFunctionType() << DestType;
13136     return ExprError();
13137   }
13138 
13139   // Rewrite the method result type if available.
13140   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13141     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13142     Method->setReturnType(DestType);
13143   }
13144 
13145   // Change the type of the message.
13146   E->setType(DestType.getNonReferenceType());
13147   E->setValueKind(Expr::getValueKindForType(DestType));
13148 
13149   return S.MaybeBindToTemporary(E);
13150 }
13151 
13152 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13153   // The only case we should ever see here is a function-to-pointer decay.
13154   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13155     assert(E->getValueKind() == VK_RValue);
13156     assert(E->getObjectKind() == OK_Ordinary);
13157 
13158     E->setType(DestType);
13159 
13160     // Rebuild the sub-expression as the pointee (function) type.
13161     DestType = DestType->castAs<PointerType>()->getPointeeType();
13162 
13163     ExprResult Result = Visit(E->getSubExpr());
13164     if (!Result.isUsable()) return ExprError();
13165 
13166     E->setSubExpr(Result.get());
13167     return E;
13168   } else if (E->getCastKind() == CK_LValueToRValue) {
13169     assert(E->getValueKind() == VK_RValue);
13170     assert(E->getObjectKind() == OK_Ordinary);
13171 
13172     assert(isa<BlockPointerType>(E->getType()));
13173 
13174     E->setType(DestType);
13175 
13176     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13177     DestType = S.Context.getLValueReferenceType(DestType);
13178 
13179     ExprResult Result = Visit(E->getSubExpr());
13180     if (!Result.isUsable()) return ExprError();
13181 
13182     E->setSubExpr(Result.get());
13183     return E;
13184   } else {
13185     llvm_unreachable("Unhandled cast type!");
13186   }
13187 }
13188 
13189 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13190   ExprValueKind ValueKind = VK_LValue;
13191   QualType Type = DestType;
13192 
13193   // We know how to make this work for certain kinds of decls:
13194 
13195   //  - functions
13196   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13197     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13198       DestType = Ptr->getPointeeType();
13199       ExprResult Result = resolveDecl(E, VD);
13200       if (Result.isInvalid()) return ExprError();
13201       return S.ImpCastExprToType(Result.get(), Type,
13202                                  CK_FunctionToPointerDecay, VK_RValue);
13203     }
13204 
13205     if (!Type->isFunctionType()) {
13206       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13207         << VD << E->getSourceRange();
13208       return ExprError();
13209     }
13210 
13211     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13212       if (MD->isInstance()) {
13213         ValueKind = VK_RValue;
13214         Type = S.Context.BoundMemberTy;
13215       }
13216 
13217     // Function references aren't l-values in C.
13218     if (!S.getLangOpts().CPlusPlus)
13219       ValueKind = VK_RValue;
13220 
13221   //  - variables
13222   } else if (isa<VarDecl>(VD)) {
13223     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13224       Type = RefTy->getPointeeType();
13225     } else if (Type->isFunctionType()) {
13226       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13227         << VD << E->getSourceRange();
13228       return ExprError();
13229     }
13230 
13231   //  - nothing else
13232   } else {
13233     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13234       << VD << E->getSourceRange();
13235     return ExprError();
13236   }
13237 
13238   // Modifying the declaration like this is friendly to IR-gen but
13239   // also really dangerous.
13240   VD->setType(DestType);
13241   E->setType(Type);
13242   E->setValueKind(ValueKind);
13243   return E;
13244 }
13245 
13246 /// Check a cast of an unknown-any type.  We intentionally only
13247 /// trigger this for C-style casts.
13248 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13249                                      Expr *CastExpr, CastKind &CastKind,
13250                                      ExprValueKind &VK, CXXCastPath &Path) {
13251   // Rewrite the casted expression from scratch.
13252   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13253   if (!result.isUsable()) return ExprError();
13254 
13255   CastExpr = result.get();
13256   VK = CastExpr->getValueKind();
13257   CastKind = CK_NoOp;
13258 
13259   return CastExpr;
13260 }
13261 
13262 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13263   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13264 }
13265 
13266 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13267                                     Expr *arg, QualType &paramType) {
13268   // If the syntactic form of the argument is not an explicit cast of
13269   // any sort, just do default argument promotion.
13270   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13271   if (!castArg) {
13272     ExprResult result = DefaultArgumentPromotion(arg);
13273     if (result.isInvalid()) return ExprError();
13274     paramType = result.get()->getType();
13275     return result;
13276   }
13277 
13278   // Otherwise, use the type that was written in the explicit cast.
13279   assert(!arg->hasPlaceholderType());
13280   paramType = castArg->getTypeAsWritten();
13281 
13282   // Copy-initialize a parameter of that type.
13283   InitializedEntity entity =
13284     InitializedEntity::InitializeParameter(Context, paramType,
13285                                            /*consumed*/ false);
13286   return PerformCopyInitialization(entity, callLoc, arg);
13287 }
13288 
13289 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13290   Expr *orig = E;
13291   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13292   while (true) {
13293     E = E->IgnoreParenImpCasts();
13294     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13295       E = call->getCallee();
13296       diagID = diag::err_uncasted_call_of_unknown_any;
13297     } else {
13298       break;
13299     }
13300   }
13301 
13302   SourceLocation loc;
13303   NamedDecl *d;
13304   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13305     loc = ref->getLocation();
13306     d = ref->getDecl();
13307   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13308     loc = mem->getMemberLoc();
13309     d = mem->getMemberDecl();
13310   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13311     diagID = diag::err_uncasted_call_of_unknown_any;
13312     loc = msg->getSelectorStartLoc();
13313     d = msg->getMethodDecl();
13314     if (!d) {
13315       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13316         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13317         << orig->getSourceRange();
13318       return ExprError();
13319     }
13320   } else {
13321     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13322       << E->getSourceRange();
13323     return ExprError();
13324   }
13325 
13326   S.Diag(loc, diagID) << d << orig->getSourceRange();
13327 
13328   // Never recoverable.
13329   return ExprError();
13330 }
13331 
13332 /// Check for operands with placeholder types and complain if found.
13333 /// Returns true if there was an error and no recovery was possible.
13334 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13335   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13336   if (!placeholderType) return E;
13337 
13338   switch (placeholderType->getKind()) {
13339 
13340   // Overloaded expressions.
13341   case BuiltinType::Overload: {
13342     // Try to resolve a single function template specialization.
13343     // This is obligatory.
13344     ExprResult result = E;
13345     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13346       return result;
13347 
13348     // If that failed, try to recover with a call.
13349     } else {
13350       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13351                            /*complain*/ true);
13352       return result;
13353     }
13354   }
13355 
13356   // Bound member functions.
13357   case BuiltinType::BoundMember: {
13358     ExprResult result = E;
13359     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13360                          /*complain*/ true);
13361     return result;
13362   }
13363 
13364   // ARC unbridged casts.
13365   case BuiltinType::ARCUnbridgedCast: {
13366     Expr *realCast = stripARCUnbridgedCast(E);
13367     diagnoseARCUnbridgedCast(realCast);
13368     return realCast;
13369   }
13370 
13371   // Expressions of unknown type.
13372   case BuiltinType::UnknownAny:
13373     return diagnoseUnknownAnyExpr(*this, E);
13374 
13375   // Pseudo-objects.
13376   case BuiltinType::PseudoObject:
13377     return checkPseudoObjectRValue(E);
13378 
13379   case BuiltinType::BuiltinFn:
13380     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13381     return ExprError();
13382 
13383   // Everything else should be impossible.
13384 #define BUILTIN_TYPE(Id, SingletonId) \
13385   case BuiltinType::Id:
13386 #define PLACEHOLDER_TYPE(Id, SingletonId)
13387 #include "clang/AST/BuiltinTypes.def"
13388     break;
13389   }
13390 
13391   llvm_unreachable("invalid placeholder type!");
13392 }
13393 
13394 bool Sema::CheckCaseExpression(Expr *E) {
13395   if (E->isTypeDependent())
13396     return true;
13397   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13398     return E->getType()->isIntegralOrEnumerationType();
13399   return false;
13400 }
13401 
13402 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13403 ExprResult
13404 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13405   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13406          "Unknown Objective-C Boolean value!");
13407   QualType BoolT = Context.ObjCBuiltinBoolTy;
13408   if (!Context.getBOOLDecl()) {
13409     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13410                         Sema::LookupOrdinaryName);
13411     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13412       NamedDecl *ND = Result.getFoundDecl();
13413       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13414         Context.setBOOLDecl(TD);
13415     }
13416   }
13417   if (Context.getBOOLDecl())
13418     BoolT = Context.getBOOLType();
13419   return new (Context)
13420       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13421 }
13422