1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/Support/ConvertUTF.h"
46 using namespace clang;
47 using namespace sema;
48 
49 /// \brief Determine whether the use of this declaration is valid, without
50 /// emitting diagnostics.
51 bool Sema::CanUseDecl(NamedDecl *D) {
52   // See if this is an auto-typed variable whose initializer we are parsing.
53   if (ParsingInitForAutoVars.count(D))
54     return false;
55 
56   // See if this is a deleted function.
57   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
58     if (FD->isDeleted())
59       return false;
60 
61     // If the function has a deduced return type, and we can't deduce it,
62     // then we can't use it either.
63     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
64         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
65       return false;
66   }
67 
68   // See if this function is unavailable.
69   if (D->getAvailability() == AR_Unavailable &&
70       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
71     return false;
72 
73   return true;
74 }
75 
76 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
77   // Warn if this is used but marked unused.
78   if (D->hasAttr<UnusedAttr>()) {
79     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
80     if (!DC->hasAttr<UnusedAttr>())
81       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
82   }
83 }
84 
85 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
86                               NamedDecl *D, SourceLocation Loc,
87                               const ObjCInterfaceDecl *UnknownObjCClass,
88                               bool ObjCPropertyAccess) {
89   // See if this declaration is unavailable or deprecated.
90   std::string Message;
91 
92   // Forward class declarations get their attributes from their definition.
93   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
94     if (IDecl->getDefinition())
95       D = IDecl->getDefinition();
96   }
97   AvailabilityResult Result = D->getAvailability(&Message);
98   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
99     if (Result == AR_Available) {
100       const DeclContext *DC = ECD->getDeclContext();
101       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
102         Result = TheEnumDecl->getAvailability(&Message);
103     }
104 
105   const ObjCPropertyDecl *ObjCPDecl = nullptr;
106   if (Result == AR_Deprecated || Result == AR_Unavailable) {
107     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
108       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
109         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
110         if (PDeclResult == Result)
111           ObjCPDecl = PD;
112       }
113     }
114   }
115 
116   switch (Result) {
117     case AR_Available:
118     case AR_NotYetIntroduced:
119       break;
120 
121     case AR_Deprecated:
122       if (S.getCurContextAvailability() != AR_Deprecated)
123         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
124                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
125                                   ObjCPropertyAccess);
126       break;
127 
128     case AR_Unavailable:
129       if (S.getCurContextAvailability() != AR_Unavailable)
130         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
131                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
132                                   ObjCPropertyAccess);
133       break;
134 
135     }
136     return Result;
137 }
138 
139 /// \brief Emit a note explaining that this function is deleted.
140 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
141   assert(Decl->isDeleted());
142 
143   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
144 
145   if (Method && Method->isDeleted() && Method->isDefaulted()) {
146     // If the method was explicitly defaulted, point at that declaration.
147     if (!Method->isImplicit())
148       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
149 
150     // Try to diagnose why this special member function was implicitly
151     // deleted. This might fail, if that reason no longer applies.
152     CXXSpecialMember CSM = getSpecialMember(Method);
153     if (CSM != CXXInvalid)
154       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
155 
156     return;
157   }
158 
159   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
160     if (CXXConstructorDecl *BaseCD =
161             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
162       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
163       if (BaseCD->isDeleted()) {
164         NoteDeletedFunction(BaseCD);
165       } else {
166         // FIXME: An explanation of why exactly it can't be inherited
167         // would be nice.
168         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
169       }
170       return;
171     }
172   }
173 
174   Diag(Decl->getLocation(), diag::note_availability_specified_here)
175     << Decl << true;
176 }
177 
178 /// \brief Determine whether a FunctionDecl was ever declared with an
179 /// explicit storage class.
180 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
181   for (auto I : D->redecls()) {
182     if (I->getStorageClass() != SC_None)
183       return true;
184   }
185   return false;
186 }
187 
188 /// \brief Check whether we're in an extern inline function and referring to a
189 /// variable or function with internal linkage (C11 6.7.4p3).
190 ///
191 /// This is only a warning because we used to silently accept this code, but
192 /// in many cases it will not behave correctly. This is not enabled in C++ mode
193 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
194 /// and so while there may still be user mistakes, most of the time we can't
195 /// prove that there are errors.
196 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
197                                                       const NamedDecl *D,
198                                                       SourceLocation Loc) {
199   // This is disabled under C++; there are too many ways for this to fire in
200   // contexts where the warning is a false positive, or where it is technically
201   // correct but benign.
202   if (S.getLangOpts().CPlusPlus)
203     return;
204 
205   // Check if this is an inlined function or method.
206   FunctionDecl *Current = S.getCurFunctionDecl();
207   if (!Current)
208     return;
209   if (!Current->isInlined())
210     return;
211   if (!Current->isExternallyVisible())
212     return;
213 
214   // Check if the decl has internal linkage.
215   if (D->getFormalLinkage() != InternalLinkage)
216     return;
217 
218   // Downgrade from ExtWarn to Extension if
219   //  (1) the supposedly external inline function is in the main file,
220   //      and probably won't be included anywhere else.
221   //  (2) the thing we're referencing is a pure function.
222   //  (3) the thing we're referencing is another inline function.
223   // This last can give us false negatives, but it's better than warning on
224   // wrappers for simple C library functions.
225   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
226   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
227   if (!DowngradeWarning && UsedFn)
228     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
229 
230   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
231                                : diag::ext_internal_in_extern_inline)
232     << /*IsVar=*/!UsedFn << D;
233 
234   S.MaybeSuggestAddingStaticToDecl(Current);
235 
236   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
237       << D;
238 }
239 
240 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
241   const FunctionDecl *First = Cur->getFirstDecl();
242 
243   // Suggest "static" on the function, if possible.
244   if (!hasAnyExplicitStorageClass(First)) {
245     SourceLocation DeclBegin = First->getSourceRange().getBegin();
246     Diag(DeclBegin, diag::note_convert_inline_to_static)
247       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
248   }
249 }
250 
251 /// \brief Determine whether the use of this declaration is valid, and
252 /// emit any corresponding diagnostics.
253 ///
254 /// This routine diagnoses various problems with referencing
255 /// declarations that can occur when using a declaration. For example,
256 /// it might warn if a deprecated or unavailable declaration is being
257 /// used, or produce an error (and return true) if a C++0x deleted
258 /// function is being used.
259 ///
260 /// \returns true if there was an error (this declaration cannot be
261 /// referenced), false otherwise.
262 ///
263 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
264                              const ObjCInterfaceDecl *UnknownObjCClass,
265                              bool ObjCPropertyAccess) {
266   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
267     // If there were any diagnostics suppressed by template argument deduction,
268     // emit them now.
269     SuppressedDiagnosticsMap::iterator
270       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
271     if (Pos != SuppressedDiagnostics.end()) {
272       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
273       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
274         Diag(Suppressed[I].first, Suppressed[I].second);
275 
276       // Clear out the list of suppressed diagnostics, so that we don't emit
277       // them again for this specialization. However, we don't obsolete this
278       // entry from the table, because we want to avoid ever emitting these
279       // diagnostics again.
280       Suppressed.clear();
281     }
282 
283     // C++ [basic.start.main]p3:
284     //   The function 'main' shall not be used within a program.
285     if (cast<FunctionDecl>(D)->isMain())
286       Diag(Loc, diag::ext_main_used);
287   }
288 
289   // See if this is an auto-typed variable whose initializer we are parsing.
290   if (ParsingInitForAutoVars.count(D)) {
291     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
292       << D->getDeclName();
293     return true;
294   }
295 
296   // See if this is a deleted function.
297   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
298     if (FD->isDeleted()) {
299       Diag(Loc, diag::err_deleted_function_use);
300       NoteDeletedFunction(FD);
301       return true;
302     }
303 
304     // If the function has a deduced return type, and we can't deduce it,
305     // then we can't use it either.
306     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307         DeduceReturnType(FD, Loc))
308       return true;
309   }
310   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
311 
312   DiagnoseUnusedOfDecl(*this, D, Loc);
313 
314   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
315 
316   return false;
317 }
318 
319 /// \brief Retrieve the message suffix that should be added to a
320 /// diagnostic complaining about the given function being deleted or
321 /// unavailable.
322 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
323   std::string Message;
324   if (FD->getAvailability(&Message))
325     return ": " + Message;
326 
327   return std::string();
328 }
329 
330 /// DiagnoseSentinelCalls - This routine checks whether a call or
331 /// message-send is to a declaration with the sentinel attribute, and
332 /// if so, it checks that the requirements of the sentinel are
333 /// satisfied.
334 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
335                                  ArrayRef<Expr *> Args) {
336   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
337   if (!attr)
338     return;
339 
340   // The number of formal parameters of the declaration.
341   unsigned numFormalParams;
342 
343   // The kind of declaration.  This is also an index into a %select in
344   // the diagnostic.
345   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
346 
347   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
348     numFormalParams = MD->param_size();
349     calleeType = CT_Method;
350   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
351     numFormalParams = FD->param_size();
352     calleeType = CT_Function;
353   } else if (isa<VarDecl>(D)) {
354     QualType type = cast<ValueDecl>(D)->getType();
355     const FunctionType *fn = nullptr;
356     if (const PointerType *ptr = type->getAs<PointerType>()) {
357       fn = ptr->getPointeeType()->getAs<FunctionType>();
358       if (!fn) return;
359       calleeType = CT_Function;
360     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
361       fn = ptr->getPointeeType()->castAs<FunctionType>();
362       calleeType = CT_Block;
363     } else {
364       return;
365     }
366 
367     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
368       numFormalParams = proto->getNumParams();
369     } else {
370       numFormalParams = 0;
371     }
372   } else {
373     return;
374   }
375 
376   // "nullPos" is the number of formal parameters at the end which
377   // effectively count as part of the variadic arguments.  This is
378   // useful if you would prefer to not have *any* formal parameters,
379   // but the language forces you to have at least one.
380   unsigned nullPos = attr->getNullPos();
381   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
382   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
383 
384   // The number of arguments which should follow the sentinel.
385   unsigned numArgsAfterSentinel = attr->getSentinel();
386 
387   // If there aren't enough arguments for all the formal parameters,
388   // the sentinel, and the args after the sentinel, complain.
389   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
390     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
391     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
392     return;
393   }
394 
395   // Otherwise, find the sentinel expression.
396   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
397   if (!sentinelExpr) return;
398   if (sentinelExpr->isValueDependent()) return;
399   if (Context.isSentinelNullExpr(sentinelExpr)) return;
400 
401   // Pick a reasonable string to insert.  Optimistically use 'nil' or
402   // 'NULL' if those are actually defined in the context.  Only use
403   // 'nil' for ObjC methods, where it's much more likely that the
404   // variadic arguments form a list of object pointers.
405   SourceLocation MissingNilLoc
406     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
407   std::string NullValue;
408   if (calleeType == CT_Method &&
409       PP.getIdentifierInfo("nil")->hasMacroDefinition())
410     NullValue = "nil";
411   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
412     NullValue = "NULL";
413   else
414     NullValue = "(void*) 0";
415 
416   if (MissingNilLoc.isInvalid())
417     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
418   else
419     Diag(MissingNilLoc, diag::warn_missing_sentinel)
420       << int(calleeType)
421       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
422   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
423 }
424 
425 SourceRange Sema::getExprRange(Expr *E) const {
426   return E ? E->getSourceRange() : SourceRange();
427 }
428 
429 //===----------------------------------------------------------------------===//
430 //  Standard Promotions and Conversions
431 //===----------------------------------------------------------------------===//
432 
433 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
434 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
435   // Handle any placeholder expressions which made it here.
436   if (E->getType()->isPlaceholderType()) {
437     ExprResult result = CheckPlaceholderExpr(E);
438     if (result.isInvalid()) return ExprError();
439     E = result.get();
440   }
441 
442   QualType Ty = E->getType();
443   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
444 
445   if (Ty->isFunctionType()) {
446     // If we are here, we are not calling a function but taking
447     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
448     if (getLangOpts().OpenCL) {
449       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
450       return ExprError();
451     }
452     E = ImpCastExprToType(E, Context.getPointerType(Ty),
453                           CK_FunctionToPointerDecay).get();
454   } else if (Ty->isArrayType()) {
455     // In C90 mode, arrays only promote to pointers if the array expression is
456     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
457     // type 'array of type' is converted to an expression that has type 'pointer
458     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
459     // that has type 'array of type' ...".  The relevant change is "an lvalue"
460     // (C90) to "an expression" (C99).
461     //
462     // C++ 4.2p1:
463     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
464     // T" can be converted to an rvalue of type "pointer to T".
465     //
466     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
467       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
468                             CK_ArrayToPointerDecay).get();
469   }
470   return E;
471 }
472 
473 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
474   // Check to see if we are dereferencing a null pointer.  If so,
475   // and if not volatile-qualified, this is undefined behavior that the
476   // optimizer will delete, so warn about it.  People sometimes try to use this
477   // to get a deterministic trap and are surprised by clang's behavior.  This
478   // only handles the pattern "*null", which is a very syntactic check.
479   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
480     if (UO->getOpcode() == UO_Deref &&
481         UO->getSubExpr()->IgnoreParenCasts()->
482           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
483         !UO->getType().isVolatileQualified()) {
484     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
485                           S.PDiag(diag::warn_indirection_through_null)
486                             << UO->getSubExpr()->getSourceRange());
487     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
488                         S.PDiag(diag::note_indirection_through_null));
489   }
490 }
491 
492 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
493                                     SourceLocation AssignLoc,
494                                     const Expr* RHS) {
495   const ObjCIvarDecl *IV = OIRE->getDecl();
496   if (!IV)
497     return;
498 
499   DeclarationName MemberName = IV->getDeclName();
500   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
501   if (!Member || !Member->isStr("isa"))
502     return;
503 
504   const Expr *Base = OIRE->getBase();
505   QualType BaseType = Base->getType();
506   if (OIRE->isArrow())
507     BaseType = BaseType->getPointeeType();
508   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
509     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
510       ObjCInterfaceDecl *ClassDeclared = nullptr;
511       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
512       if (!ClassDeclared->getSuperClass()
513           && (*ClassDeclared->ivar_begin()) == IV) {
514         if (RHS) {
515           NamedDecl *ObjectSetClass =
516             S.LookupSingleName(S.TUScope,
517                                &S.Context.Idents.get("object_setClass"),
518                                SourceLocation(), S.LookupOrdinaryName);
519           if (ObjectSetClass) {
520             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
521             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
522             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
523             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
524                                                      AssignLoc), ",") <<
525             FixItHint::CreateInsertion(RHSLocEnd, ")");
526           }
527           else
528             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
529         } else {
530           NamedDecl *ObjectGetClass =
531             S.LookupSingleName(S.TUScope,
532                                &S.Context.Idents.get("object_getClass"),
533                                SourceLocation(), S.LookupOrdinaryName);
534           if (ObjectGetClass)
535             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
536             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
537             FixItHint::CreateReplacement(
538                                          SourceRange(OIRE->getOpLoc(),
539                                                      OIRE->getLocEnd()), ")");
540           else
541             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
542         }
543         S.Diag(IV->getLocation(), diag::note_ivar_decl);
544       }
545     }
546 }
547 
548 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
549   // Handle any placeholder expressions which made it here.
550   if (E->getType()->isPlaceholderType()) {
551     ExprResult result = CheckPlaceholderExpr(E);
552     if (result.isInvalid()) return ExprError();
553     E = result.get();
554   }
555 
556   // C++ [conv.lval]p1:
557   //   A glvalue of a non-function, non-array type T can be
558   //   converted to a prvalue.
559   if (!E->isGLValue()) return E;
560 
561   QualType T = E->getType();
562   assert(!T.isNull() && "r-value conversion on typeless expression?");
563 
564   // We don't want to throw lvalue-to-rvalue casts on top of
565   // expressions of certain types in C++.
566   if (getLangOpts().CPlusPlus &&
567       (E->getType() == Context.OverloadTy ||
568        T->isDependentType() ||
569        T->isRecordType()))
570     return E;
571 
572   // The C standard is actually really unclear on this point, and
573   // DR106 tells us what the result should be but not why.  It's
574   // generally best to say that void types just doesn't undergo
575   // lvalue-to-rvalue at all.  Note that expressions of unqualified
576   // 'void' type are never l-values, but qualified void can be.
577   if (T->isVoidType())
578     return E;
579 
580   // OpenCL usually rejects direct accesses to values of 'half' type.
581   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
582       T->isHalfType()) {
583     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
584       << 0 << T;
585     return ExprError();
586   }
587 
588   CheckForNullPointerDereference(*this, E);
589   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
590     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
591                                      &Context.Idents.get("object_getClass"),
592                                      SourceLocation(), LookupOrdinaryName);
593     if (ObjectGetClass)
594       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
595         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
596         FixItHint::CreateReplacement(
597                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
598     else
599       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
600   }
601   else if (const ObjCIvarRefExpr *OIRE =
602             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
603     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
604 
605   // C++ [conv.lval]p1:
606   //   [...] If T is a non-class type, the type of the prvalue is the
607   //   cv-unqualified version of T. Otherwise, the type of the
608   //   rvalue is T.
609   //
610   // C99 6.3.2.1p2:
611   //   If the lvalue has qualified type, the value has the unqualified
612   //   version of the type of the lvalue; otherwise, the value has the
613   //   type of the lvalue.
614   if (T.hasQualifiers())
615     T = T.getUnqualifiedType();
616 
617   UpdateMarkingForLValueToRValue(E);
618 
619   // Loading a __weak object implicitly retains the value, so we need a cleanup to
620   // balance that.
621   if (getLangOpts().ObjCAutoRefCount &&
622       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
623     ExprNeedsCleanups = true;
624 
625   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
626                                             nullptr, VK_RValue);
627 
628   // C11 6.3.2.1p2:
629   //   ... if the lvalue has atomic type, the value has the non-atomic version
630   //   of the type of the lvalue ...
631   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
632     T = Atomic->getValueType().getUnqualifiedType();
633     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
634                                    nullptr, VK_RValue);
635   }
636 
637   return Res;
638 }
639 
640 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
641   ExprResult Res = DefaultFunctionArrayConversion(E);
642   if (Res.isInvalid())
643     return ExprError();
644   Res = DefaultLvalueConversion(Res.get());
645   if (Res.isInvalid())
646     return ExprError();
647   return Res;
648 }
649 
650 /// CallExprUnaryConversions - a special case of an unary conversion
651 /// performed on a function designator of a call expression.
652 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
653   QualType Ty = E->getType();
654   ExprResult Res = E;
655   // Only do implicit cast for a function type, but not for a pointer
656   // to function type.
657   if (Ty->isFunctionType()) {
658     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
659                             CK_FunctionToPointerDecay).get();
660     if (Res.isInvalid())
661       return ExprError();
662   }
663   Res = DefaultLvalueConversion(Res.get());
664   if (Res.isInvalid())
665     return ExprError();
666   return Res.get();
667 }
668 
669 /// UsualUnaryConversions - Performs various conversions that are common to most
670 /// operators (C99 6.3). The conversions of array and function types are
671 /// sometimes suppressed. For example, the array->pointer conversion doesn't
672 /// apply if the array is an argument to the sizeof or address (&) operators.
673 /// In these instances, this routine should *not* be called.
674 ExprResult Sema::UsualUnaryConversions(Expr *E) {
675   // First, convert to an r-value.
676   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
677   if (Res.isInvalid())
678     return ExprError();
679   E = Res.get();
680 
681   QualType Ty = E->getType();
682   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
683 
684   // Half FP have to be promoted to float unless it is natively supported
685   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
686     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
687 
688   // Try to perform integral promotions if the object has a theoretically
689   // promotable type.
690   if (Ty->isIntegralOrUnscopedEnumerationType()) {
691     // C99 6.3.1.1p2:
692     //
693     //   The following may be used in an expression wherever an int or
694     //   unsigned int may be used:
695     //     - an object or expression with an integer type whose integer
696     //       conversion rank is less than or equal to the rank of int
697     //       and unsigned int.
698     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
699     //
700     //   If an int can represent all values of the original type, the
701     //   value is converted to an int; otherwise, it is converted to an
702     //   unsigned int. These are called the integer promotions. All
703     //   other types are unchanged by the integer promotions.
704 
705     QualType PTy = Context.isPromotableBitField(E);
706     if (!PTy.isNull()) {
707       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
708       return E;
709     }
710     if (Ty->isPromotableIntegerType()) {
711       QualType PT = Context.getPromotedIntegerType(Ty);
712       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
713       return E;
714     }
715   }
716   return E;
717 }
718 
719 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
720 /// do not have a prototype. Arguments that have type float or __fp16
721 /// are promoted to double. All other argument types are converted by
722 /// UsualUnaryConversions().
723 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
724   QualType Ty = E->getType();
725   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
726 
727   ExprResult Res = UsualUnaryConversions(E);
728   if (Res.isInvalid())
729     return ExprError();
730   E = Res.get();
731 
732   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
733   // double.
734   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
735   if (BTy && (BTy->getKind() == BuiltinType::Half ||
736               BTy->getKind() == BuiltinType::Float))
737     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
738 
739   // C++ performs lvalue-to-rvalue conversion as a default argument
740   // promotion, even on class types, but note:
741   //   C++11 [conv.lval]p2:
742   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
743   //     operand or a subexpression thereof the value contained in the
744   //     referenced object is not accessed. Otherwise, if the glvalue
745   //     has a class type, the conversion copy-initializes a temporary
746   //     of type T from the glvalue and the result of the conversion
747   //     is a prvalue for the temporary.
748   // FIXME: add some way to gate this entire thing for correctness in
749   // potentially potentially evaluated contexts.
750   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
751     ExprResult Temp = PerformCopyInitialization(
752                        InitializedEntity::InitializeTemporary(E->getType()),
753                                                 E->getExprLoc(), E);
754     if (Temp.isInvalid())
755       return ExprError();
756     E = Temp.get();
757   }
758 
759   return E;
760 }
761 
762 /// Determine the degree of POD-ness for an expression.
763 /// Incomplete types are considered POD, since this check can be performed
764 /// when we're in an unevaluated context.
765 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
766   if (Ty->isIncompleteType()) {
767     // C++11 [expr.call]p7:
768     //   After these conversions, if the argument does not have arithmetic,
769     //   enumeration, pointer, pointer to member, or class type, the program
770     //   is ill-formed.
771     //
772     // Since we've already performed array-to-pointer and function-to-pointer
773     // decay, the only such type in C++ is cv void. This also handles
774     // initializer lists as variadic arguments.
775     if (Ty->isVoidType())
776       return VAK_Invalid;
777 
778     if (Ty->isObjCObjectType())
779       return VAK_Invalid;
780     return VAK_Valid;
781   }
782 
783   if (Ty.isCXX98PODType(Context))
784     return VAK_Valid;
785 
786   // C++11 [expr.call]p7:
787   //   Passing a potentially-evaluated argument of class type (Clause 9)
788   //   having a non-trivial copy constructor, a non-trivial move constructor,
789   //   or a non-trivial destructor, with no corresponding parameter,
790   //   is conditionally-supported with implementation-defined semantics.
791   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
792     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
793       if (!Record->hasNonTrivialCopyConstructor() &&
794           !Record->hasNonTrivialMoveConstructor() &&
795           !Record->hasNonTrivialDestructor())
796         return VAK_ValidInCXX11;
797 
798   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
799     return VAK_Valid;
800 
801   if (Ty->isObjCObjectType())
802     return VAK_Invalid;
803 
804   if (getLangOpts().MSVCCompat)
805     return VAK_MSVCUndefined;
806 
807   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
808   // permitted to reject them. We should consider doing so.
809   return VAK_Undefined;
810 }
811 
812 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
813   // Don't allow one to pass an Objective-C interface to a vararg.
814   const QualType &Ty = E->getType();
815   VarArgKind VAK = isValidVarArgType(Ty);
816 
817   // Complain about passing non-POD types through varargs.
818   switch (VAK) {
819   case VAK_ValidInCXX11:
820     DiagRuntimeBehavior(
821         E->getLocStart(), nullptr,
822         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
823           << Ty << CT);
824     // Fall through.
825   case VAK_Valid:
826     if (Ty->isRecordType()) {
827       // This is unlikely to be what the user intended. If the class has a
828       // 'c_str' member function, the user probably meant to call that.
829       DiagRuntimeBehavior(E->getLocStart(), nullptr,
830                           PDiag(diag::warn_pass_class_arg_to_vararg)
831                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
832     }
833     break;
834 
835   case VAK_Undefined:
836   case VAK_MSVCUndefined:
837     DiagRuntimeBehavior(
838         E->getLocStart(), nullptr,
839         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
840           << getLangOpts().CPlusPlus11 << Ty << CT);
841     break;
842 
843   case VAK_Invalid:
844     if (Ty->isObjCObjectType())
845       DiagRuntimeBehavior(
846           E->getLocStart(), nullptr,
847           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
848             << Ty << CT);
849     else
850       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
851         << isa<InitListExpr>(E) << Ty << CT;
852     break;
853   }
854 }
855 
856 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
857 /// will create a trap if the resulting type is not a POD type.
858 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
859                                                   FunctionDecl *FDecl) {
860   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
861     // Strip the unbridged-cast placeholder expression off, if applicable.
862     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
863         (CT == VariadicMethod ||
864          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
865       E = stripARCUnbridgedCast(E);
866 
867     // Otherwise, do normal placeholder checking.
868     } else {
869       ExprResult ExprRes = CheckPlaceholderExpr(E);
870       if (ExprRes.isInvalid())
871         return ExprError();
872       E = ExprRes.get();
873     }
874   }
875 
876   ExprResult ExprRes = DefaultArgumentPromotion(E);
877   if (ExprRes.isInvalid())
878     return ExprError();
879   E = ExprRes.get();
880 
881   // Diagnostics regarding non-POD argument types are
882   // emitted along with format string checking in Sema::CheckFunctionCall().
883   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
884     // Turn this into a trap.
885     CXXScopeSpec SS;
886     SourceLocation TemplateKWLoc;
887     UnqualifiedId Name;
888     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
889                        E->getLocStart());
890     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
891                                           Name, true, false);
892     if (TrapFn.isInvalid())
893       return ExprError();
894 
895     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
896                                     E->getLocStart(), None,
897                                     E->getLocEnd());
898     if (Call.isInvalid())
899       return ExprError();
900 
901     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
902                                   Call.get(), E);
903     if (Comma.isInvalid())
904       return ExprError();
905     return Comma.get();
906   }
907 
908   if (!getLangOpts().CPlusPlus &&
909       RequireCompleteType(E->getExprLoc(), E->getType(),
910                           diag::err_call_incomplete_argument))
911     return ExprError();
912 
913   return E;
914 }
915 
916 /// \brief Converts an integer to complex float type.  Helper function of
917 /// UsualArithmeticConversions()
918 ///
919 /// \return false if the integer expression is an integer type and is
920 /// successfully converted to the complex type.
921 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
922                                                   ExprResult &ComplexExpr,
923                                                   QualType IntTy,
924                                                   QualType ComplexTy,
925                                                   bool SkipCast) {
926   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
927   if (SkipCast) return false;
928   if (IntTy->isIntegerType()) {
929     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
930     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
931     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
932                                   CK_FloatingRealToComplex);
933   } else {
934     assert(IntTy->isComplexIntegerType());
935     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
936                                   CK_IntegralComplexToFloatingComplex);
937   }
938   return false;
939 }
940 
941 /// \brief Handle arithmetic conversion with complex types.  Helper function of
942 /// UsualArithmeticConversions()
943 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
944                                              ExprResult &RHS, QualType LHSType,
945                                              QualType RHSType,
946                                              bool IsCompAssign) {
947   // if we have an integer operand, the result is the complex type.
948   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
949                                              /*skipCast*/false))
950     return LHSType;
951   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
952                                              /*skipCast*/IsCompAssign))
953     return RHSType;
954 
955   // This handles complex/complex, complex/float, or float/complex.
956   // When both operands are complex, the shorter operand is converted to the
957   // type of the longer, and that is the type of the result. This corresponds
958   // to what is done when combining two real floating-point operands.
959   // The fun begins when size promotion occur across type domains.
960   // From H&S 6.3.4: When one operand is complex and the other is a real
961   // floating-point type, the less precise type is converted, within it's
962   // real or complex domain, to the precision of the other type. For example,
963   // when combining a "long double" with a "double _Complex", the
964   // "double _Complex" is promoted to "long double _Complex".
965 
966   // Compute the rank of the two types, regardless of whether they are complex.
967   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
968 
969   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
970   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
971   QualType LHSElementType =
972       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
973   QualType RHSElementType =
974       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
975 
976   QualType ResultType = S.Context.getComplexType(LHSElementType);
977   if (Order < 0) {
978     // Promote the precision of the LHS if not an assignment.
979     ResultType = S.Context.getComplexType(RHSElementType);
980     if (!IsCompAssign) {
981       if (LHSComplexType)
982         LHS =
983             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
984       else
985         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
986     }
987   } else if (Order > 0) {
988     // Promote the precision of the RHS.
989     if (RHSComplexType)
990       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
991     else
992       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
993   }
994   return ResultType;
995 }
996 
997 /// \brief Hande arithmetic conversion from integer to float.  Helper function
998 /// of UsualArithmeticConversions()
999 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1000                                            ExprResult &IntExpr,
1001                                            QualType FloatTy, QualType IntTy,
1002                                            bool ConvertFloat, bool ConvertInt) {
1003   if (IntTy->isIntegerType()) {
1004     if (ConvertInt)
1005       // Convert intExpr to the lhs floating point type.
1006       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1007                                     CK_IntegralToFloating);
1008     return FloatTy;
1009   }
1010 
1011   // Convert both sides to the appropriate complex float.
1012   assert(IntTy->isComplexIntegerType());
1013   QualType result = S.Context.getComplexType(FloatTy);
1014 
1015   // _Complex int -> _Complex float
1016   if (ConvertInt)
1017     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1018                                   CK_IntegralComplexToFloatingComplex);
1019 
1020   // float -> _Complex float
1021   if (ConvertFloat)
1022     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1023                                     CK_FloatingRealToComplex);
1024 
1025   return result;
1026 }
1027 
1028 /// \brief Handle arithmethic conversion with floating point types.  Helper
1029 /// function of UsualArithmeticConversions()
1030 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1031                                       ExprResult &RHS, QualType LHSType,
1032                                       QualType RHSType, bool IsCompAssign) {
1033   bool LHSFloat = LHSType->isRealFloatingType();
1034   bool RHSFloat = RHSType->isRealFloatingType();
1035 
1036   // If we have two real floating types, convert the smaller operand
1037   // to the bigger result.
1038   if (LHSFloat && RHSFloat) {
1039     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1040     if (order > 0) {
1041       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1042       return LHSType;
1043     }
1044 
1045     assert(order < 0 && "illegal float comparison");
1046     if (!IsCompAssign)
1047       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1048     return RHSType;
1049   }
1050 
1051   if (LHSFloat)
1052     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1053                                       /*convertFloat=*/!IsCompAssign,
1054                                       /*convertInt=*/ true);
1055   assert(RHSFloat);
1056   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1057                                     /*convertInt=*/ true,
1058                                     /*convertFloat=*/!IsCompAssign);
1059 }
1060 
1061 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1062 
1063 namespace {
1064 /// These helper callbacks are placed in an anonymous namespace to
1065 /// permit their use as function template parameters.
1066 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1067   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1068 }
1069 
1070 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1071   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1072                              CK_IntegralComplexCast);
1073 }
1074 }
1075 
1076 /// \brief Handle integer arithmetic conversions.  Helper function of
1077 /// UsualArithmeticConversions()
1078 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1079 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1080                                         ExprResult &RHS, QualType LHSType,
1081                                         QualType RHSType, bool IsCompAssign) {
1082   // The rules for this case are in C99 6.3.1.8
1083   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1084   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1085   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1086   if (LHSSigned == RHSSigned) {
1087     // Same signedness; use the higher-ranked type
1088     if (order >= 0) {
1089       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1090       return LHSType;
1091     } else if (!IsCompAssign)
1092       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1093     return RHSType;
1094   } else if (order != (LHSSigned ? 1 : -1)) {
1095     // The unsigned type has greater than or equal rank to the
1096     // signed type, so use the unsigned type
1097     if (RHSSigned) {
1098       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1099       return LHSType;
1100     } else if (!IsCompAssign)
1101       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1102     return RHSType;
1103   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1104     // The two types are different widths; if we are here, that
1105     // means the signed type is larger than the unsigned type, so
1106     // use the signed type.
1107     if (LHSSigned) {
1108       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1109       return LHSType;
1110     } else if (!IsCompAssign)
1111       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1112     return RHSType;
1113   } else {
1114     // The signed type is higher-ranked than the unsigned type,
1115     // but isn't actually any bigger (like unsigned int and long
1116     // on most 32-bit systems).  Use the unsigned type corresponding
1117     // to the signed type.
1118     QualType result =
1119       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1120     RHS = (*doRHSCast)(S, RHS.get(), result);
1121     if (!IsCompAssign)
1122       LHS = (*doLHSCast)(S, LHS.get(), result);
1123     return result;
1124   }
1125 }
1126 
1127 /// \brief Handle conversions with GCC complex int extension.  Helper function
1128 /// of UsualArithmeticConversions()
1129 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1130                                            ExprResult &RHS, QualType LHSType,
1131                                            QualType RHSType,
1132                                            bool IsCompAssign) {
1133   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1134   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1135 
1136   if (LHSComplexInt && RHSComplexInt) {
1137     QualType LHSEltType = LHSComplexInt->getElementType();
1138     QualType RHSEltType = RHSComplexInt->getElementType();
1139     QualType ScalarType =
1140       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1141         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1142 
1143     return S.Context.getComplexType(ScalarType);
1144   }
1145 
1146   if (LHSComplexInt) {
1147     QualType LHSEltType = LHSComplexInt->getElementType();
1148     QualType ScalarType =
1149       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1150         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1151     QualType ComplexType = S.Context.getComplexType(ScalarType);
1152     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1153                               CK_IntegralRealToComplex);
1154 
1155     return ComplexType;
1156   }
1157 
1158   assert(RHSComplexInt);
1159 
1160   QualType RHSEltType = RHSComplexInt->getElementType();
1161   QualType ScalarType =
1162     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1163       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1164   QualType ComplexType = S.Context.getComplexType(ScalarType);
1165 
1166   if (!IsCompAssign)
1167     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1168                               CK_IntegralRealToComplex);
1169   return ComplexType;
1170 }
1171 
1172 /// UsualArithmeticConversions - Performs various conversions that are common to
1173 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1174 /// routine returns the first non-arithmetic type found. The client is
1175 /// responsible for emitting appropriate error diagnostics.
1176 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1177                                           bool IsCompAssign) {
1178   if (!IsCompAssign) {
1179     LHS = UsualUnaryConversions(LHS.get());
1180     if (LHS.isInvalid())
1181       return QualType();
1182   }
1183 
1184   RHS = UsualUnaryConversions(RHS.get());
1185   if (RHS.isInvalid())
1186     return QualType();
1187 
1188   // For conversion purposes, we ignore any qualifiers.
1189   // For example, "const float" and "float" are equivalent.
1190   QualType LHSType =
1191     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1192   QualType RHSType =
1193     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1194 
1195   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1196   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1197     LHSType = AtomicLHS->getValueType();
1198 
1199   // If both types are identical, no conversion is needed.
1200   if (LHSType == RHSType)
1201     return LHSType;
1202 
1203   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1204   // The caller can deal with this (e.g. pointer + int).
1205   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1206     return QualType();
1207 
1208   // Apply unary and bitfield promotions to the LHS's type.
1209   QualType LHSUnpromotedType = LHSType;
1210   if (LHSType->isPromotableIntegerType())
1211     LHSType = Context.getPromotedIntegerType(LHSType);
1212   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1213   if (!LHSBitfieldPromoteTy.isNull())
1214     LHSType = LHSBitfieldPromoteTy;
1215   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1216     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1217 
1218   // If both types are identical, no conversion is needed.
1219   if (LHSType == RHSType)
1220     return LHSType;
1221 
1222   // At this point, we have two different arithmetic types.
1223 
1224   // Handle complex types first (C99 6.3.1.8p1).
1225   if (LHSType->isComplexType() || RHSType->isComplexType())
1226     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1227                                         IsCompAssign);
1228 
1229   // Now handle "real" floating types (i.e. float, double, long double).
1230   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1231     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1232                                  IsCompAssign);
1233 
1234   // Handle GCC complex int extension.
1235   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1236     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1237                                       IsCompAssign);
1238 
1239   // Finally, we have two differing integer types.
1240   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1241            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1242 }
1243 
1244 
1245 //===----------------------------------------------------------------------===//
1246 //  Semantic Analysis for various Expression Types
1247 //===----------------------------------------------------------------------===//
1248 
1249 
1250 ExprResult
1251 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1252                                 SourceLocation DefaultLoc,
1253                                 SourceLocation RParenLoc,
1254                                 Expr *ControllingExpr,
1255                                 ArrayRef<ParsedType> ArgTypes,
1256                                 ArrayRef<Expr *> ArgExprs) {
1257   unsigned NumAssocs = ArgTypes.size();
1258   assert(NumAssocs == ArgExprs.size());
1259 
1260   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1261   for (unsigned i = 0; i < NumAssocs; ++i) {
1262     if (ArgTypes[i])
1263       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1264     else
1265       Types[i] = nullptr;
1266   }
1267 
1268   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1269                                              ControllingExpr,
1270                                              llvm::makeArrayRef(Types, NumAssocs),
1271                                              ArgExprs);
1272   delete [] Types;
1273   return ER;
1274 }
1275 
1276 ExprResult
1277 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1278                                  SourceLocation DefaultLoc,
1279                                  SourceLocation RParenLoc,
1280                                  Expr *ControllingExpr,
1281                                  ArrayRef<TypeSourceInfo *> Types,
1282                                  ArrayRef<Expr *> Exprs) {
1283   unsigned NumAssocs = Types.size();
1284   assert(NumAssocs == Exprs.size());
1285   if (ControllingExpr->getType()->isPlaceholderType()) {
1286     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1287     if (result.isInvalid()) return ExprError();
1288     ControllingExpr = result.get();
1289   }
1290 
1291   bool TypeErrorFound = false,
1292        IsResultDependent = ControllingExpr->isTypeDependent(),
1293        ContainsUnexpandedParameterPack
1294          = ControllingExpr->containsUnexpandedParameterPack();
1295 
1296   for (unsigned i = 0; i < NumAssocs; ++i) {
1297     if (Exprs[i]->containsUnexpandedParameterPack())
1298       ContainsUnexpandedParameterPack = true;
1299 
1300     if (Types[i]) {
1301       if (Types[i]->getType()->containsUnexpandedParameterPack())
1302         ContainsUnexpandedParameterPack = true;
1303 
1304       if (Types[i]->getType()->isDependentType()) {
1305         IsResultDependent = true;
1306       } else {
1307         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1308         // complete object type other than a variably modified type."
1309         unsigned D = 0;
1310         if (Types[i]->getType()->isIncompleteType())
1311           D = diag::err_assoc_type_incomplete;
1312         else if (!Types[i]->getType()->isObjectType())
1313           D = diag::err_assoc_type_nonobject;
1314         else if (Types[i]->getType()->isVariablyModifiedType())
1315           D = diag::err_assoc_type_variably_modified;
1316 
1317         if (D != 0) {
1318           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1319             << Types[i]->getTypeLoc().getSourceRange()
1320             << Types[i]->getType();
1321           TypeErrorFound = true;
1322         }
1323 
1324         // C11 6.5.1.1p2 "No two generic associations in the same generic
1325         // selection shall specify compatible types."
1326         for (unsigned j = i+1; j < NumAssocs; ++j)
1327           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1328               Context.typesAreCompatible(Types[i]->getType(),
1329                                          Types[j]->getType())) {
1330             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1331                  diag::err_assoc_compatible_types)
1332               << Types[j]->getTypeLoc().getSourceRange()
1333               << Types[j]->getType()
1334               << Types[i]->getType();
1335             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1336                  diag::note_compat_assoc)
1337               << Types[i]->getTypeLoc().getSourceRange()
1338               << Types[i]->getType();
1339             TypeErrorFound = true;
1340           }
1341       }
1342     }
1343   }
1344   if (TypeErrorFound)
1345     return ExprError();
1346 
1347   // If we determined that the generic selection is result-dependent, don't
1348   // try to compute the result expression.
1349   if (IsResultDependent)
1350     return new (Context) GenericSelectionExpr(
1351         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1352         ContainsUnexpandedParameterPack);
1353 
1354   SmallVector<unsigned, 1> CompatIndices;
1355   unsigned DefaultIndex = -1U;
1356   for (unsigned i = 0; i < NumAssocs; ++i) {
1357     if (!Types[i])
1358       DefaultIndex = i;
1359     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1360                                         Types[i]->getType()))
1361       CompatIndices.push_back(i);
1362   }
1363 
1364   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1365   // type compatible with at most one of the types named in its generic
1366   // association list."
1367   if (CompatIndices.size() > 1) {
1368     // We strip parens here because the controlling expression is typically
1369     // parenthesized in macro definitions.
1370     ControllingExpr = ControllingExpr->IgnoreParens();
1371     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1372       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1373       << (unsigned) CompatIndices.size();
1374     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1375          E = CompatIndices.end(); I != E; ++I) {
1376       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1377            diag::note_compat_assoc)
1378         << Types[*I]->getTypeLoc().getSourceRange()
1379         << Types[*I]->getType();
1380     }
1381     return ExprError();
1382   }
1383 
1384   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1385   // its controlling expression shall have type compatible with exactly one of
1386   // the types named in its generic association list."
1387   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1388     // We strip parens here because the controlling expression is typically
1389     // parenthesized in macro definitions.
1390     ControllingExpr = ControllingExpr->IgnoreParens();
1391     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1392       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1393     return ExprError();
1394   }
1395 
1396   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1397   // type name that is compatible with the type of the controlling expression,
1398   // then the result expression of the generic selection is the expression
1399   // in that generic association. Otherwise, the result expression of the
1400   // generic selection is the expression in the default generic association."
1401   unsigned ResultIndex =
1402     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1403 
1404   return new (Context) GenericSelectionExpr(
1405       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1406       ContainsUnexpandedParameterPack, ResultIndex);
1407 }
1408 
1409 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1410 /// location of the token and the offset of the ud-suffix within it.
1411 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1412                                      unsigned Offset) {
1413   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1414                                         S.getLangOpts());
1415 }
1416 
1417 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1418 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1419 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1420                                                  IdentifierInfo *UDSuffix,
1421                                                  SourceLocation UDSuffixLoc,
1422                                                  ArrayRef<Expr*> Args,
1423                                                  SourceLocation LitEndLoc) {
1424   assert(Args.size() <= 2 && "too many arguments for literal operator");
1425 
1426   QualType ArgTy[2];
1427   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1428     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1429     if (ArgTy[ArgIdx]->isArrayType())
1430       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1431   }
1432 
1433   DeclarationName OpName =
1434     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1435   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1436   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1437 
1438   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1439   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1440                               /*AllowRaw*/false, /*AllowTemplate*/false,
1441                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1442     return ExprError();
1443 
1444   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1445 }
1446 
1447 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1448 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1449 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1450 /// multiple tokens.  However, the common case is that StringToks points to one
1451 /// string.
1452 ///
1453 ExprResult
1454 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1455   assert(!StringToks.empty() && "Must have at least one string!");
1456 
1457   StringLiteralParser Literal(StringToks, PP);
1458   if (Literal.hadError)
1459     return ExprError();
1460 
1461   SmallVector<SourceLocation, 4> StringTokLocs;
1462   for (unsigned i = 0; i != StringToks.size(); ++i)
1463     StringTokLocs.push_back(StringToks[i].getLocation());
1464 
1465   QualType CharTy = Context.CharTy;
1466   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1467   if (Literal.isWide()) {
1468     CharTy = Context.getWideCharType();
1469     Kind = StringLiteral::Wide;
1470   } else if (Literal.isUTF8()) {
1471     Kind = StringLiteral::UTF8;
1472   } else if (Literal.isUTF16()) {
1473     CharTy = Context.Char16Ty;
1474     Kind = StringLiteral::UTF16;
1475   } else if (Literal.isUTF32()) {
1476     CharTy = Context.Char32Ty;
1477     Kind = StringLiteral::UTF32;
1478   } else if (Literal.isPascal()) {
1479     CharTy = Context.UnsignedCharTy;
1480   }
1481 
1482   QualType CharTyConst = CharTy;
1483   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1484   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1485     CharTyConst.addConst();
1486 
1487   // Get an array type for the string, according to C99 6.4.5.  This includes
1488   // the nul terminator character as well as the string length for pascal
1489   // strings.
1490   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1491                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1492                                  ArrayType::Normal, 0);
1493 
1494   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1495   if (getLangOpts().OpenCL) {
1496     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1497   }
1498 
1499   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1500   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1501                                              Kind, Literal.Pascal, StrTy,
1502                                              &StringTokLocs[0],
1503                                              StringTokLocs.size());
1504   if (Literal.getUDSuffix().empty())
1505     return Lit;
1506 
1507   // We're building a user-defined literal.
1508   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1509   SourceLocation UDSuffixLoc =
1510     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1511                    Literal.getUDSuffixOffset());
1512 
1513   // Make sure we're allowed user-defined literals here.
1514   if (!UDLScope)
1515     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1516 
1517   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1518   //   operator "" X (str, len)
1519   QualType SizeType = Context.getSizeType();
1520 
1521   DeclarationName OpName =
1522     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1523   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1524   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1525 
1526   QualType ArgTy[] = {
1527     Context.getArrayDecayedType(StrTy), SizeType
1528   };
1529 
1530   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1531   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1532                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1533                                 /*AllowStringTemplate*/true)) {
1534 
1535   case LOLR_Cooked: {
1536     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1537     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1538                                                     StringTokLocs[0]);
1539     Expr *Args[] = { Lit, LenArg };
1540 
1541     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1542   }
1543 
1544   case LOLR_StringTemplate: {
1545     TemplateArgumentListInfo ExplicitArgs;
1546 
1547     unsigned CharBits = Context.getIntWidth(CharTy);
1548     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1549     llvm::APSInt Value(CharBits, CharIsUnsigned);
1550 
1551     TemplateArgument TypeArg(CharTy);
1552     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1553     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1554 
1555     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1556       Value = Lit->getCodeUnit(I);
1557       TemplateArgument Arg(Context, Value, CharTy);
1558       TemplateArgumentLocInfo ArgInfo;
1559       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1560     }
1561     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1562                                     &ExplicitArgs);
1563   }
1564   case LOLR_Raw:
1565   case LOLR_Template:
1566     llvm_unreachable("unexpected literal operator lookup result");
1567   case LOLR_Error:
1568     return ExprError();
1569   }
1570   llvm_unreachable("unexpected literal operator lookup result");
1571 }
1572 
1573 ExprResult
1574 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1575                        SourceLocation Loc,
1576                        const CXXScopeSpec *SS) {
1577   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1578   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1579 }
1580 
1581 /// BuildDeclRefExpr - Build an expression that references a
1582 /// declaration that does not require a closure capture.
1583 ExprResult
1584 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1585                        const DeclarationNameInfo &NameInfo,
1586                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1587                        const TemplateArgumentListInfo *TemplateArgs) {
1588   if (getLangOpts().CUDA)
1589     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1590       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1591         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1592                            CalleeTarget = IdentifyCUDATarget(Callee);
1593         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1594           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1595             << CalleeTarget << D->getIdentifier() << CallerTarget;
1596           Diag(D->getLocation(), diag::note_previous_decl)
1597             << D->getIdentifier();
1598           return ExprError();
1599         }
1600       }
1601 
1602   bool refersToEnclosingScope =
1603     (CurContext != D->getDeclContext() &&
1604      D->getDeclContext()->isFunctionOrMethod()) ||
1605     (isa<VarDecl>(D) &&
1606      cast<VarDecl>(D)->isInitCapture());
1607 
1608   DeclRefExpr *E;
1609   if (isa<VarTemplateSpecializationDecl>(D)) {
1610     VarTemplateSpecializationDecl *VarSpec =
1611         cast<VarTemplateSpecializationDecl>(D);
1612 
1613     E = DeclRefExpr::Create(
1614         Context,
1615         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1616         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1617         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1618   } else {
1619     assert(!TemplateArgs && "No template arguments for non-variable"
1620                             " template specialization references");
1621     E = DeclRefExpr::Create(
1622         Context,
1623         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1624         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1625   }
1626 
1627   MarkDeclRefReferenced(E);
1628 
1629   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1630       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1631       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1632       recordUseOfEvaluatedWeak(E);
1633 
1634   // Just in case we're building an illegal pointer-to-member.
1635   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1636   if (FD && FD->isBitField())
1637     E->setObjectKind(OK_BitField);
1638 
1639   return E;
1640 }
1641 
1642 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1643 /// possibly a list of template arguments.
1644 ///
1645 /// If this produces template arguments, it is permitted to call
1646 /// DecomposeTemplateName.
1647 ///
1648 /// This actually loses a lot of source location information for
1649 /// non-standard name kinds; we should consider preserving that in
1650 /// some way.
1651 void
1652 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1653                              TemplateArgumentListInfo &Buffer,
1654                              DeclarationNameInfo &NameInfo,
1655                              const TemplateArgumentListInfo *&TemplateArgs) {
1656   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1657     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1658     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1659 
1660     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1661                                        Id.TemplateId->NumArgs);
1662     translateTemplateArguments(TemplateArgsPtr, Buffer);
1663 
1664     TemplateName TName = Id.TemplateId->Template.get();
1665     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1666     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1667     TemplateArgs = &Buffer;
1668   } else {
1669     NameInfo = GetNameFromUnqualifiedId(Id);
1670     TemplateArgs = nullptr;
1671   }
1672 }
1673 
1674 /// Diagnose an empty lookup.
1675 ///
1676 /// \return false if new lookup candidates were found
1677 bool
1678 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1679                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1680                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1681                           ArrayRef<Expr *> Args) {
1682   DeclarationName Name = R.getLookupName();
1683 
1684   unsigned diagnostic = diag::err_undeclared_var_use;
1685   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1686   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1687       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1688       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1689     diagnostic = diag::err_undeclared_use;
1690     diagnostic_suggest = diag::err_undeclared_use_suggest;
1691   }
1692 
1693   // If the original lookup was an unqualified lookup, fake an
1694   // unqualified lookup.  This is useful when (for example) the
1695   // original lookup would not have found something because it was a
1696   // dependent name.
1697   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1698     ? CurContext : nullptr;
1699   while (DC) {
1700     if (isa<CXXRecordDecl>(DC)) {
1701       LookupQualifiedName(R, DC);
1702 
1703       if (!R.empty()) {
1704         // Don't give errors about ambiguities in this lookup.
1705         R.suppressDiagnostics();
1706 
1707         // During a default argument instantiation the CurContext points
1708         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1709         // function parameter list, hence add an explicit check.
1710         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1711                               ActiveTemplateInstantiations.back().Kind ==
1712             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1713         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1714         bool isInstance = CurMethod &&
1715                           CurMethod->isInstance() &&
1716                           DC == CurMethod->getParent() && !isDefaultArgument;
1717 
1718 
1719         // Give a code modification hint to insert 'this->'.
1720         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1721         // Actually quite difficult!
1722         if (getLangOpts().MSVCCompat)
1723           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1724         if (isInstance) {
1725           Diag(R.getNameLoc(), diagnostic) << Name
1726             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1727           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1728               CallsUndergoingInstantiation.back()->getCallee());
1729 
1730           CXXMethodDecl *DepMethod;
1731           if (CurMethod->isDependentContext())
1732             DepMethod = CurMethod;
1733           else if (CurMethod->getTemplatedKind() ==
1734               FunctionDecl::TK_FunctionTemplateSpecialization)
1735             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1736                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1737           else
1738             DepMethod = cast<CXXMethodDecl>(
1739                 CurMethod->getInstantiatedFromMemberFunction());
1740           assert(DepMethod && "No template pattern found");
1741 
1742           QualType DepThisType = DepMethod->getThisType(Context);
1743           CheckCXXThisCapture(R.getNameLoc());
1744           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1745                                      R.getNameLoc(), DepThisType, false);
1746           TemplateArgumentListInfo TList;
1747           if (ULE->hasExplicitTemplateArgs())
1748             ULE->copyTemplateArgumentsInto(TList);
1749 
1750           CXXScopeSpec SS;
1751           SS.Adopt(ULE->getQualifierLoc());
1752           CXXDependentScopeMemberExpr *DepExpr =
1753               CXXDependentScopeMemberExpr::Create(
1754                   Context, DepThis, DepThisType, true, SourceLocation(),
1755                   SS.getWithLocInContext(Context),
1756                   ULE->getTemplateKeywordLoc(), nullptr,
1757                   R.getLookupNameInfo(),
1758                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1759           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1760         } else {
1761           Diag(R.getNameLoc(), diagnostic) << Name;
1762         }
1763 
1764         // Do we really want to note all of these?
1765         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1766           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1767 
1768         // Return true if we are inside a default argument instantiation
1769         // and the found name refers to an instance member function, otherwise
1770         // the function calling DiagnoseEmptyLookup will try to create an
1771         // implicit member call and this is wrong for default argument.
1772         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1773           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1774           return true;
1775         }
1776 
1777         // Tell the callee to try to recover.
1778         return false;
1779       }
1780 
1781       R.clear();
1782     }
1783 
1784     // In Microsoft mode, if we are performing lookup from within a friend
1785     // function definition declared at class scope then we must set
1786     // DC to the lexical parent to be able to search into the parent
1787     // class.
1788     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1789         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1790         DC->getLexicalParent()->isRecord())
1791       DC = DC->getLexicalParent();
1792     else
1793       DC = DC->getParent();
1794   }
1795 
1796   // We didn't find anything, so try to correct for a typo.
1797   TypoCorrection Corrected;
1798   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1799                                     S, &SS, std::move(CCC), CTK_ErrorRecovery))) {
1800     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1801     bool DroppedSpecifier =
1802         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1803     R.setLookupName(Corrected.getCorrection());
1804 
1805     bool AcceptableWithRecovery = false;
1806     bool AcceptableWithoutRecovery = false;
1807     NamedDecl *ND = Corrected.getCorrectionDecl();
1808     if (ND) {
1809       if (Corrected.isOverloaded()) {
1810         OverloadCandidateSet OCS(R.getNameLoc(),
1811                                  OverloadCandidateSet::CSK_Normal);
1812         OverloadCandidateSet::iterator Best;
1813         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1814                                         CDEnd = Corrected.end();
1815              CD != CDEnd; ++CD) {
1816           if (FunctionTemplateDecl *FTD =
1817                    dyn_cast<FunctionTemplateDecl>(*CD))
1818             AddTemplateOverloadCandidate(
1819                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1820                 Args, OCS);
1821           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1822             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1823               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1824                                    Args, OCS);
1825         }
1826         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1827         case OR_Success:
1828           ND = Best->Function;
1829           Corrected.setCorrectionDecl(ND);
1830           break;
1831         default:
1832           // FIXME: Arbitrarily pick the first declaration for the note.
1833           Corrected.setCorrectionDecl(ND);
1834           break;
1835         }
1836       }
1837       R.addDecl(ND);
1838       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1839         CXXRecordDecl *Record = nullptr;
1840         if (Corrected.getCorrectionSpecifier()) {
1841           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1842           Record = Ty->getAsCXXRecordDecl();
1843         }
1844         if (!Record)
1845           Record = cast<CXXRecordDecl>(
1846               ND->getDeclContext()->getRedeclContext());
1847         R.setNamingClass(Record);
1848       }
1849 
1850       AcceptableWithRecovery =
1851           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1852       // FIXME: If we ended up with a typo for a type name or
1853       // Objective-C class name, we're in trouble because the parser
1854       // is in the wrong place to recover. Suggest the typo
1855       // correction, but don't make it a fix-it since we're not going
1856       // to recover well anyway.
1857       AcceptableWithoutRecovery =
1858           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1859     } else {
1860       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1861       // because we aren't able to recover.
1862       AcceptableWithoutRecovery = true;
1863     }
1864 
1865     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1866       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1867                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1868                             ? diag::note_implicit_param_decl
1869                             : diag::note_previous_decl;
1870       if (SS.isEmpty())
1871         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1872                      PDiag(NoteID), AcceptableWithRecovery);
1873       else
1874         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1875                                   << Name << computeDeclContext(SS, false)
1876                                   << DroppedSpecifier << SS.getRange(),
1877                      PDiag(NoteID), AcceptableWithRecovery);
1878 
1879       // Tell the callee whether to try to recover.
1880       return !AcceptableWithRecovery;
1881     }
1882   }
1883   R.clear();
1884 
1885   // Emit a special diagnostic for failed member lookups.
1886   // FIXME: computing the declaration context might fail here (?)
1887   if (!SS.isEmpty()) {
1888     Diag(R.getNameLoc(), diag::err_no_member)
1889       << Name << computeDeclContext(SS, false)
1890       << SS.getRange();
1891     return true;
1892   }
1893 
1894   // Give up, we can't recover.
1895   Diag(R.getNameLoc(), diagnostic) << Name;
1896   return true;
1897 }
1898 
1899 /// In Microsoft mode, if we are inside a template class whose parent class has
1900 /// dependent base classes, and we can't resolve an unqualified identifier, then
1901 /// assume the identifier is a member of a dependent base class.  We can only
1902 /// recover successfully in static methods, instance methods, and other contexts
1903 /// where 'this' is available.  This doesn't precisely match MSVC's
1904 /// instantiation model, but it's close enough.
1905 static Expr *
1906 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1907                                DeclarationNameInfo &NameInfo,
1908                                SourceLocation TemplateKWLoc,
1909                                const TemplateArgumentListInfo *TemplateArgs) {
1910   // Only try to recover from lookup into dependent bases in static methods or
1911   // contexts where 'this' is available.
1912   QualType ThisType = S.getCurrentThisType();
1913   const CXXRecordDecl *RD = nullptr;
1914   if (!ThisType.isNull())
1915     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1916   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1917     RD = MD->getParent();
1918   if (!RD || !RD->hasAnyDependentBases())
1919     return nullptr;
1920 
1921   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1922   // is available, suggest inserting 'this->' as a fixit.
1923   SourceLocation Loc = NameInfo.getLoc();
1924   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1925   DB << NameInfo.getName() << RD;
1926 
1927   if (!ThisType.isNull()) {
1928     DB << FixItHint::CreateInsertion(Loc, "this->");
1929     return CXXDependentScopeMemberExpr::Create(
1930         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1931         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1932         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1933   }
1934 
1935   // Synthesize a fake NNS that points to the derived class.  This will
1936   // perform name lookup during template instantiation.
1937   CXXScopeSpec SS;
1938   auto *NNS =
1939       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1940   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1941   return DependentScopeDeclRefExpr::Create(
1942       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1943       TemplateArgs);
1944 }
1945 
1946 ExprResult
1947 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
1948                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
1949                         bool HasTrailingLParen, bool IsAddressOfOperand,
1950                         std::unique_ptr<CorrectionCandidateCallback> CCC,
1951                         bool IsInlineAsmIdentifier) {
1952   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1953          "cannot be direct & operand and have a trailing lparen");
1954   if (SS.isInvalid())
1955     return ExprError();
1956 
1957   TemplateArgumentListInfo TemplateArgsBuffer;
1958 
1959   // Decompose the UnqualifiedId into the following data.
1960   DeclarationNameInfo NameInfo;
1961   const TemplateArgumentListInfo *TemplateArgs;
1962   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1963 
1964   DeclarationName Name = NameInfo.getName();
1965   IdentifierInfo *II = Name.getAsIdentifierInfo();
1966   SourceLocation NameLoc = NameInfo.getLoc();
1967 
1968   // C++ [temp.dep.expr]p3:
1969   //   An id-expression is type-dependent if it contains:
1970   //     -- an identifier that was declared with a dependent type,
1971   //        (note: handled after lookup)
1972   //     -- a template-id that is dependent,
1973   //        (note: handled in BuildTemplateIdExpr)
1974   //     -- a conversion-function-id that specifies a dependent type,
1975   //     -- a nested-name-specifier that contains a class-name that
1976   //        names a dependent type.
1977   // Determine whether this is a member of an unknown specialization;
1978   // we need to handle these differently.
1979   bool DependentID = false;
1980   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1981       Name.getCXXNameType()->isDependentType()) {
1982     DependentID = true;
1983   } else if (SS.isSet()) {
1984     if (DeclContext *DC = computeDeclContext(SS, false)) {
1985       if (RequireCompleteDeclContext(SS, DC))
1986         return ExprError();
1987     } else {
1988       DependentID = true;
1989     }
1990   }
1991 
1992   if (DependentID)
1993     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1994                                       IsAddressOfOperand, TemplateArgs);
1995 
1996   // Perform the required lookup.
1997   LookupResult R(*this, NameInfo,
1998                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1999                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2000   if (TemplateArgs) {
2001     // Lookup the template name again to correctly establish the context in
2002     // which it was found. This is really unfortunate as we already did the
2003     // lookup to determine that it was a template name in the first place. If
2004     // this becomes a performance hit, we can work harder to preserve those
2005     // results until we get here but it's likely not worth it.
2006     bool MemberOfUnknownSpecialization;
2007     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2008                        MemberOfUnknownSpecialization);
2009 
2010     if (MemberOfUnknownSpecialization ||
2011         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2012       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2013                                         IsAddressOfOperand, TemplateArgs);
2014   } else {
2015     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2016     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2017 
2018     // If the result might be in a dependent base class, this is a dependent
2019     // id-expression.
2020     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2021       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2022                                         IsAddressOfOperand, TemplateArgs);
2023 
2024     // If this reference is in an Objective-C method, then we need to do
2025     // some special Objective-C lookup, too.
2026     if (IvarLookupFollowUp) {
2027       ExprResult E(LookupInObjCMethod(R, S, II, true));
2028       if (E.isInvalid())
2029         return ExprError();
2030 
2031       if (Expr *Ex = E.getAs<Expr>())
2032         return Ex;
2033     }
2034   }
2035 
2036   if (R.isAmbiguous())
2037     return ExprError();
2038 
2039   // This could be an implicitly declared function reference (legal in C90,
2040   // extension in C99, forbidden in C++).
2041   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2042     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2043     if (D) R.addDecl(D);
2044   }
2045 
2046   // Determine whether this name might be a candidate for
2047   // argument-dependent lookup.
2048   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2049 
2050   if (R.empty() && !ADL) {
2051     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2052       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2053                                                    TemplateKWLoc, TemplateArgs))
2054         return E;
2055     }
2056 
2057     // Don't diagnose an empty lookup for inline assembly.
2058     if (IsInlineAsmIdentifier)
2059       return ExprError();
2060 
2061     // If this name wasn't predeclared and if this is not a function
2062     // call, diagnose the problem.
2063     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>();
2064     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2065     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2066            "Typo correction callback misconfigured");
2067     if (DiagnoseEmptyLookup(S, SS, R,
2068                             CCC ? std::move(CCC) : std::move(DefaultValidator)))
2069       return ExprError();
2070 
2071     assert(!R.empty() &&
2072            "DiagnoseEmptyLookup returned false but added no results");
2073 
2074     // If we found an Objective-C instance variable, let
2075     // LookupInObjCMethod build the appropriate expression to
2076     // reference the ivar.
2077     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2078       R.clear();
2079       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2080       // In a hopelessly buggy code, Objective-C instance variable
2081       // lookup fails and no expression will be built to reference it.
2082       if (!E.isInvalid() && !E.get())
2083         return ExprError();
2084       return E;
2085     }
2086   }
2087 
2088   // This is guaranteed from this point on.
2089   assert(!R.empty() || ADL);
2090 
2091   // Check whether this might be a C++ implicit instance member access.
2092   // C++ [class.mfct.non-static]p3:
2093   //   When an id-expression that is not part of a class member access
2094   //   syntax and not used to form a pointer to member is used in the
2095   //   body of a non-static member function of class X, if name lookup
2096   //   resolves the name in the id-expression to a non-static non-type
2097   //   member of some class C, the id-expression is transformed into a
2098   //   class member access expression using (*this) as the
2099   //   postfix-expression to the left of the . operator.
2100   //
2101   // But we don't actually need to do this for '&' operands if R
2102   // resolved to a function or overloaded function set, because the
2103   // expression is ill-formed if it actually works out to be a
2104   // non-static member function:
2105   //
2106   // C++ [expr.ref]p4:
2107   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2108   //   [t]he expression can be used only as the left-hand operand of a
2109   //   member function call.
2110   //
2111   // There are other safeguards against such uses, but it's important
2112   // to get this right here so that we don't end up making a
2113   // spuriously dependent expression if we're inside a dependent
2114   // instance method.
2115   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2116     bool MightBeImplicitMember;
2117     if (!IsAddressOfOperand)
2118       MightBeImplicitMember = true;
2119     else if (!SS.isEmpty())
2120       MightBeImplicitMember = false;
2121     else if (R.isOverloadedResult())
2122       MightBeImplicitMember = false;
2123     else if (R.isUnresolvableResult())
2124       MightBeImplicitMember = true;
2125     else
2126       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2127                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2128                               isa<MSPropertyDecl>(R.getFoundDecl());
2129 
2130     if (MightBeImplicitMember)
2131       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2132                                              R, TemplateArgs);
2133   }
2134 
2135   if (TemplateArgs || TemplateKWLoc.isValid()) {
2136 
2137     // In C++1y, if this is a variable template id, then check it
2138     // in BuildTemplateIdExpr().
2139     // The single lookup result must be a variable template declaration.
2140     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2141         Id.TemplateId->Kind == TNK_Var_template) {
2142       assert(R.getAsSingle<VarTemplateDecl>() &&
2143              "There should only be one declaration found.");
2144     }
2145 
2146     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2147   }
2148 
2149   return BuildDeclarationNameExpr(SS, R, ADL);
2150 }
2151 
2152 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2153 /// declaration name, generally during template instantiation.
2154 /// There's a large number of things which don't need to be done along
2155 /// this path.
2156 ExprResult
2157 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2158                                         const DeclarationNameInfo &NameInfo,
2159                                         bool IsAddressOfOperand,
2160                                         TypeSourceInfo **RecoveryTSI) {
2161   DeclContext *DC = computeDeclContext(SS, false);
2162   if (!DC)
2163     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2164                                      NameInfo, /*TemplateArgs=*/nullptr);
2165 
2166   if (RequireCompleteDeclContext(SS, DC))
2167     return ExprError();
2168 
2169   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2170   LookupQualifiedName(R, DC);
2171 
2172   if (R.isAmbiguous())
2173     return ExprError();
2174 
2175   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2176     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2177                                      NameInfo, /*TemplateArgs=*/nullptr);
2178 
2179   if (R.empty()) {
2180     Diag(NameInfo.getLoc(), diag::err_no_member)
2181       << NameInfo.getName() << DC << SS.getRange();
2182     return ExprError();
2183   }
2184 
2185   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2186     // Diagnose a missing typename if this resolved unambiguously to a type in
2187     // a dependent context.  If we can recover with a type, downgrade this to
2188     // a warning in Microsoft compatibility mode.
2189     unsigned DiagID = diag::err_typename_missing;
2190     if (RecoveryTSI && getLangOpts().MSVCCompat)
2191       DiagID = diag::ext_typename_missing;
2192     SourceLocation Loc = SS.getBeginLoc();
2193     auto D = Diag(Loc, DiagID);
2194     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2195       << SourceRange(Loc, NameInfo.getEndLoc());
2196 
2197     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2198     // context.
2199     if (!RecoveryTSI)
2200       return ExprError();
2201 
2202     // Only issue the fixit if we're prepared to recover.
2203     D << FixItHint::CreateInsertion(Loc, "typename ");
2204 
2205     // Recover by pretending this was an elaborated type.
2206     QualType Ty = Context.getTypeDeclType(TD);
2207     TypeLocBuilder TLB;
2208     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2209 
2210     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2211     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2212     QTL.setElaboratedKeywordLoc(SourceLocation());
2213     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2214 
2215     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2216 
2217     return ExprEmpty();
2218   }
2219 
2220   // Defend against this resolving to an implicit member access. We usually
2221   // won't get here if this might be a legitimate a class member (we end up in
2222   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2223   // a pointer-to-member or in an unevaluated context in C++11.
2224   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2225     return BuildPossibleImplicitMemberExpr(SS,
2226                                            /*TemplateKWLoc=*/SourceLocation(),
2227                                            R, /*TemplateArgs=*/nullptr);
2228 
2229   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2230 }
2231 
2232 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2233 /// detected that we're currently inside an ObjC method.  Perform some
2234 /// additional lookup.
2235 ///
2236 /// Ideally, most of this would be done by lookup, but there's
2237 /// actually quite a lot of extra work involved.
2238 ///
2239 /// Returns a null sentinel to indicate trivial success.
2240 ExprResult
2241 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2242                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2243   SourceLocation Loc = Lookup.getNameLoc();
2244   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2245 
2246   // Check for error condition which is already reported.
2247   if (!CurMethod)
2248     return ExprError();
2249 
2250   // There are two cases to handle here.  1) scoped lookup could have failed,
2251   // in which case we should look for an ivar.  2) scoped lookup could have
2252   // found a decl, but that decl is outside the current instance method (i.e.
2253   // a global variable).  In these two cases, we do a lookup for an ivar with
2254   // this name, if the lookup sucedes, we replace it our current decl.
2255 
2256   // If we're in a class method, we don't normally want to look for
2257   // ivars.  But if we don't find anything else, and there's an
2258   // ivar, that's an error.
2259   bool IsClassMethod = CurMethod->isClassMethod();
2260 
2261   bool LookForIvars;
2262   if (Lookup.empty())
2263     LookForIvars = true;
2264   else if (IsClassMethod)
2265     LookForIvars = false;
2266   else
2267     LookForIvars = (Lookup.isSingleResult() &&
2268                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2269   ObjCInterfaceDecl *IFace = nullptr;
2270   if (LookForIvars) {
2271     IFace = CurMethod->getClassInterface();
2272     ObjCInterfaceDecl *ClassDeclared;
2273     ObjCIvarDecl *IV = nullptr;
2274     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2275       // Diagnose using an ivar in a class method.
2276       if (IsClassMethod)
2277         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2278                          << IV->getDeclName());
2279 
2280       // If we're referencing an invalid decl, just return this as a silent
2281       // error node.  The error diagnostic was already emitted on the decl.
2282       if (IV->isInvalidDecl())
2283         return ExprError();
2284 
2285       // Check if referencing a field with __attribute__((deprecated)).
2286       if (DiagnoseUseOfDecl(IV, Loc))
2287         return ExprError();
2288 
2289       // Diagnose the use of an ivar outside of the declaring class.
2290       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2291           !declaresSameEntity(ClassDeclared, IFace) &&
2292           !getLangOpts().DebuggerSupport)
2293         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2294 
2295       // FIXME: This should use a new expr for a direct reference, don't
2296       // turn this into Self->ivar, just return a BareIVarExpr or something.
2297       IdentifierInfo &II = Context.Idents.get("self");
2298       UnqualifiedId SelfName;
2299       SelfName.setIdentifier(&II, SourceLocation());
2300       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2301       CXXScopeSpec SelfScopeSpec;
2302       SourceLocation TemplateKWLoc;
2303       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2304                                               SelfName, false, false);
2305       if (SelfExpr.isInvalid())
2306         return ExprError();
2307 
2308       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2309       if (SelfExpr.isInvalid())
2310         return ExprError();
2311 
2312       MarkAnyDeclReferenced(Loc, IV, true);
2313 
2314       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2315       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2316           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2317         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2318 
2319       ObjCIvarRefExpr *Result = new (Context)
2320           ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
2321                           SelfExpr.get(), true, true);
2322 
2323       if (getLangOpts().ObjCAutoRefCount) {
2324         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2325           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2326             recordUseOfEvaluatedWeak(Result);
2327         }
2328         if (CurContext->isClosure())
2329           Diag(Loc, diag::warn_implicitly_retains_self)
2330             << FixItHint::CreateInsertion(Loc, "self->");
2331       }
2332 
2333       return Result;
2334     }
2335   } else if (CurMethod->isInstanceMethod()) {
2336     // We should warn if a local variable hides an ivar.
2337     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2338       ObjCInterfaceDecl *ClassDeclared;
2339       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2340         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2341             declaresSameEntity(IFace, ClassDeclared))
2342           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2343       }
2344     }
2345   } else if (Lookup.isSingleResult() &&
2346              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2347     // If accessing a stand-alone ivar in a class method, this is an error.
2348     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2349       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2350                        << IV->getDeclName());
2351   }
2352 
2353   if (Lookup.empty() && II && AllowBuiltinCreation) {
2354     // FIXME. Consolidate this with similar code in LookupName.
2355     if (unsigned BuiltinID = II->getBuiltinID()) {
2356       if (!(getLangOpts().CPlusPlus &&
2357             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2358         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2359                                            S, Lookup.isForRedeclaration(),
2360                                            Lookup.getNameLoc());
2361         if (D) Lookup.addDecl(D);
2362       }
2363     }
2364   }
2365   // Sentinel value saying that we didn't do anything special.
2366   return ExprResult((Expr *)nullptr);
2367 }
2368 
2369 /// \brief Cast a base object to a member's actual type.
2370 ///
2371 /// Logically this happens in three phases:
2372 ///
2373 /// * First we cast from the base type to the naming class.
2374 ///   The naming class is the class into which we were looking
2375 ///   when we found the member;  it's the qualifier type if a
2376 ///   qualifier was provided, and otherwise it's the base type.
2377 ///
2378 /// * Next we cast from the naming class to the declaring class.
2379 ///   If the member we found was brought into a class's scope by
2380 ///   a using declaration, this is that class;  otherwise it's
2381 ///   the class declaring the member.
2382 ///
2383 /// * Finally we cast from the declaring class to the "true"
2384 ///   declaring class of the member.  This conversion does not
2385 ///   obey access control.
2386 ExprResult
2387 Sema::PerformObjectMemberConversion(Expr *From,
2388                                     NestedNameSpecifier *Qualifier,
2389                                     NamedDecl *FoundDecl,
2390                                     NamedDecl *Member) {
2391   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2392   if (!RD)
2393     return From;
2394 
2395   QualType DestRecordType;
2396   QualType DestType;
2397   QualType FromRecordType;
2398   QualType FromType = From->getType();
2399   bool PointerConversions = false;
2400   if (isa<FieldDecl>(Member)) {
2401     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2402 
2403     if (FromType->getAs<PointerType>()) {
2404       DestType = Context.getPointerType(DestRecordType);
2405       FromRecordType = FromType->getPointeeType();
2406       PointerConversions = true;
2407     } else {
2408       DestType = DestRecordType;
2409       FromRecordType = FromType;
2410     }
2411   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2412     if (Method->isStatic())
2413       return From;
2414 
2415     DestType = Method->getThisType(Context);
2416     DestRecordType = DestType->getPointeeType();
2417 
2418     if (FromType->getAs<PointerType>()) {
2419       FromRecordType = FromType->getPointeeType();
2420       PointerConversions = true;
2421     } else {
2422       FromRecordType = FromType;
2423       DestType = DestRecordType;
2424     }
2425   } else {
2426     // No conversion necessary.
2427     return From;
2428   }
2429 
2430   if (DestType->isDependentType() || FromType->isDependentType())
2431     return From;
2432 
2433   // If the unqualified types are the same, no conversion is necessary.
2434   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2435     return From;
2436 
2437   SourceRange FromRange = From->getSourceRange();
2438   SourceLocation FromLoc = FromRange.getBegin();
2439 
2440   ExprValueKind VK = From->getValueKind();
2441 
2442   // C++ [class.member.lookup]p8:
2443   //   [...] Ambiguities can often be resolved by qualifying a name with its
2444   //   class name.
2445   //
2446   // If the member was a qualified name and the qualified referred to a
2447   // specific base subobject type, we'll cast to that intermediate type
2448   // first and then to the object in which the member is declared. That allows
2449   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2450   //
2451   //   class Base { public: int x; };
2452   //   class Derived1 : public Base { };
2453   //   class Derived2 : public Base { };
2454   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2455   //
2456   //   void VeryDerived::f() {
2457   //     x = 17; // error: ambiguous base subobjects
2458   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2459   //   }
2460   if (Qualifier && Qualifier->getAsType()) {
2461     QualType QType = QualType(Qualifier->getAsType(), 0);
2462     assert(QType->isRecordType() && "lookup done with non-record type");
2463 
2464     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2465 
2466     // In C++98, the qualifier type doesn't actually have to be a base
2467     // type of the object type, in which case we just ignore it.
2468     // Otherwise build the appropriate casts.
2469     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2470       CXXCastPath BasePath;
2471       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2472                                        FromLoc, FromRange, &BasePath))
2473         return ExprError();
2474 
2475       if (PointerConversions)
2476         QType = Context.getPointerType(QType);
2477       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2478                                VK, &BasePath).get();
2479 
2480       FromType = QType;
2481       FromRecordType = QRecordType;
2482 
2483       // If the qualifier type was the same as the destination type,
2484       // we're done.
2485       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2486         return From;
2487     }
2488   }
2489 
2490   bool IgnoreAccess = false;
2491 
2492   // If we actually found the member through a using declaration, cast
2493   // down to the using declaration's type.
2494   //
2495   // Pointer equality is fine here because only one declaration of a
2496   // class ever has member declarations.
2497   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2498     assert(isa<UsingShadowDecl>(FoundDecl));
2499     QualType URecordType = Context.getTypeDeclType(
2500                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2501 
2502     // We only need to do this if the naming-class to declaring-class
2503     // conversion is non-trivial.
2504     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2505       assert(IsDerivedFrom(FromRecordType, URecordType));
2506       CXXCastPath BasePath;
2507       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2508                                        FromLoc, FromRange, &BasePath))
2509         return ExprError();
2510 
2511       QualType UType = URecordType;
2512       if (PointerConversions)
2513         UType = Context.getPointerType(UType);
2514       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2515                                VK, &BasePath).get();
2516       FromType = UType;
2517       FromRecordType = URecordType;
2518     }
2519 
2520     // We don't do access control for the conversion from the
2521     // declaring class to the true declaring class.
2522     IgnoreAccess = true;
2523   }
2524 
2525   CXXCastPath BasePath;
2526   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2527                                    FromLoc, FromRange, &BasePath,
2528                                    IgnoreAccess))
2529     return ExprError();
2530 
2531   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2532                            VK, &BasePath);
2533 }
2534 
2535 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2536                                       const LookupResult &R,
2537                                       bool HasTrailingLParen) {
2538   // Only when used directly as the postfix-expression of a call.
2539   if (!HasTrailingLParen)
2540     return false;
2541 
2542   // Never if a scope specifier was provided.
2543   if (SS.isSet())
2544     return false;
2545 
2546   // Only in C++ or ObjC++.
2547   if (!getLangOpts().CPlusPlus)
2548     return false;
2549 
2550   // Turn off ADL when we find certain kinds of declarations during
2551   // normal lookup:
2552   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2553     NamedDecl *D = *I;
2554 
2555     // C++0x [basic.lookup.argdep]p3:
2556     //     -- a declaration of a class member
2557     // Since using decls preserve this property, we check this on the
2558     // original decl.
2559     if (D->isCXXClassMember())
2560       return false;
2561 
2562     // C++0x [basic.lookup.argdep]p3:
2563     //     -- a block-scope function declaration that is not a
2564     //        using-declaration
2565     // NOTE: we also trigger this for function templates (in fact, we
2566     // don't check the decl type at all, since all other decl types
2567     // turn off ADL anyway).
2568     if (isa<UsingShadowDecl>(D))
2569       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2570     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2571       return false;
2572 
2573     // C++0x [basic.lookup.argdep]p3:
2574     //     -- a declaration that is neither a function or a function
2575     //        template
2576     // And also for builtin functions.
2577     if (isa<FunctionDecl>(D)) {
2578       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2579 
2580       // But also builtin functions.
2581       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2582         return false;
2583     } else if (!isa<FunctionTemplateDecl>(D))
2584       return false;
2585   }
2586 
2587   return true;
2588 }
2589 
2590 
2591 /// Diagnoses obvious problems with the use of the given declaration
2592 /// as an expression.  This is only actually called for lookups that
2593 /// were not overloaded, and it doesn't promise that the declaration
2594 /// will in fact be used.
2595 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2596   if (isa<TypedefNameDecl>(D)) {
2597     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2598     return true;
2599   }
2600 
2601   if (isa<ObjCInterfaceDecl>(D)) {
2602     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2603     return true;
2604   }
2605 
2606   if (isa<NamespaceDecl>(D)) {
2607     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2608     return true;
2609   }
2610 
2611   return false;
2612 }
2613 
2614 ExprResult
2615 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2616                                LookupResult &R,
2617                                bool NeedsADL) {
2618   // If this is a single, fully-resolved result and we don't need ADL,
2619   // just build an ordinary singleton decl ref.
2620   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2621     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2622                                     R.getRepresentativeDecl());
2623 
2624   // We only need to check the declaration if there's exactly one
2625   // result, because in the overloaded case the results can only be
2626   // functions and function templates.
2627   if (R.isSingleResult() &&
2628       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2629     return ExprError();
2630 
2631   // Otherwise, just build an unresolved lookup expression.  Suppress
2632   // any lookup-related diagnostics; we'll hash these out later, when
2633   // we've picked a target.
2634   R.suppressDiagnostics();
2635 
2636   UnresolvedLookupExpr *ULE
2637     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2638                                    SS.getWithLocInContext(Context),
2639                                    R.getLookupNameInfo(),
2640                                    NeedsADL, R.isOverloadedResult(),
2641                                    R.begin(), R.end());
2642 
2643   return ULE;
2644 }
2645 
2646 /// \brief Complete semantic analysis for a reference to the given declaration.
2647 ExprResult Sema::BuildDeclarationNameExpr(
2648     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2649     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2650   assert(D && "Cannot refer to a NULL declaration");
2651   assert(!isa<FunctionTemplateDecl>(D) &&
2652          "Cannot refer unambiguously to a function template");
2653 
2654   SourceLocation Loc = NameInfo.getLoc();
2655   if (CheckDeclInExpr(*this, Loc, D))
2656     return ExprError();
2657 
2658   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2659     // Specifically diagnose references to class templates that are missing
2660     // a template argument list.
2661     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2662                                            << Template << SS.getRange();
2663     Diag(Template->getLocation(), diag::note_template_decl_here);
2664     return ExprError();
2665   }
2666 
2667   // Make sure that we're referring to a value.
2668   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2669   if (!VD) {
2670     Diag(Loc, diag::err_ref_non_value)
2671       << D << SS.getRange();
2672     Diag(D->getLocation(), diag::note_declared_at);
2673     return ExprError();
2674   }
2675 
2676   // Check whether this declaration can be used. Note that we suppress
2677   // this check when we're going to perform argument-dependent lookup
2678   // on this function name, because this might not be the function
2679   // that overload resolution actually selects.
2680   if (DiagnoseUseOfDecl(VD, Loc))
2681     return ExprError();
2682 
2683   // Only create DeclRefExpr's for valid Decl's.
2684   if (VD->isInvalidDecl())
2685     return ExprError();
2686 
2687   // Handle members of anonymous structs and unions.  If we got here,
2688   // and the reference is to a class member indirect field, then this
2689   // must be the subject of a pointer-to-member expression.
2690   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2691     if (!indirectField->isCXXClassMember())
2692       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2693                                                       indirectField);
2694 
2695   {
2696     QualType type = VD->getType();
2697     ExprValueKind valueKind = VK_RValue;
2698 
2699     switch (D->getKind()) {
2700     // Ignore all the non-ValueDecl kinds.
2701 #define ABSTRACT_DECL(kind)
2702 #define VALUE(type, base)
2703 #define DECL(type, base) \
2704     case Decl::type:
2705 #include "clang/AST/DeclNodes.inc"
2706       llvm_unreachable("invalid value decl kind");
2707 
2708     // These shouldn't make it here.
2709     case Decl::ObjCAtDefsField:
2710     case Decl::ObjCIvar:
2711       llvm_unreachable("forming non-member reference to ivar?");
2712 
2713     // Enum constants are always r-values and never references.
2714     // Unresolved using declarations are dependent.
2715     case Decl::EnumConstant:
2716     case Decl::UnresolvedUsingValue:
2717       valueKind = VK_RValue;
2718       break;
2719 
2720     // Fields and indirect fields that got here must be for
2721     // pointer-to-member expressions; we just call them l-values for
2722     // internal consistency, because this subexpression doesn't really
2723     // exist in the high-level semantics.
2724     case Decl::Field:
2725     case Decl::IndirectField:
2726       assert(getLangOpts().CPlusPlus &&
2727              "building reference to field in C?");
2728 
2729       // These can't have reference type in well-formed programs, but
2730       // for internal consistency we do this anyway.
2731       type = type.getNonReferenceType();
2732       valueKind = VK_LValue;
2733       break;
2734 
2735     // Non-type template parameters are either l-values or r-values
2736     // depending on the type.
2737     case Decl::NonTypeTemplateParm: {
2738       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2739         type = reftype->getPointeeType();
2740         valueKind = VK_LValue; // even if the parameter is an r-value reference
2741         break;
2742       }
2743 
2744       // For non-references, we need to strip qualifiers just in case
2745       // the template parameter was declared as 'const int' or whatever.
2746       valueKind = VK_RValue;
2747       type = type.getUnqualifiedType();
2748       break;
2749     }
2750 
2751     case Decl::Var:
2752     case Decl::VarTemplateSpecialization:
2753     case Decl::VarTemplatePartialSpecialization:
2754       // In C, "extern void blah;" is valid and is an r-value.
2755       if (!getLangOpts().CPlusPlus &&
2756           !type.hasQualifiers() &&
2757           type->isVoidType()) {
2758         valueKind = VK_RValue;
2759         break;
2760       }
2761       // fallthrough
2762 
2763     case Decl::ImplicitParam:
2764     case Decl::ParmVar: {
2765       // These are always l-values.
2766       valueKind = VK_LValue;
2767       type = type.getNonReferenceType();
2768 
2769       // FIXME: Does the addition of const really only apply in
2770       // potentially-evaluated contexts? Since the variable isn't actually
2771       // captured in an unevaluated context, it seems that the answer is no.
2772       if (!isUnevaluatedContext()) {
2773         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2774         if (!CapturedType.isNull())
2775           type = CapturedType;
2776       }
2777 
2778       break;
2779     }
2780 
2781     case Decl::Function: {
2782       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2783         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2784           type = Context.BuiltinFnTy;
2785           valueKind = VK_RValue;
2786           break;
2787         }
2788       }
2789 
2790       const FunctionType *fty = type->castAs<FunctionType>();
2791 
2792       // If we're referring to a function with an __unknown_anytype
2793       // result type, make the entire expression __unknown_anytype.
2794       if (fty->getReturnType() == Context.UnknownAnyTy) {
2795         type = Context.UnknownAnyTy;
2796         valueKind = VK_RValue;
2797         break;
2798       }
2799 
2800       // Functions are l-values in C++.
2801       if (getLangOpts().CPlusPlus) {
2802         valueKind = VK_LValue;
2803         break;
2804       }
2805 
2806       // C99 DR 316 says that, if a function type comes from a
2807       // function definition (without a prototype), that type is only
2808       // used for checking compatibility. Therefore, when referencing
2809       // the function, we pretend that we don't have the full function
2810       // type.
2811       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2812           isa<FunctionProtoType>(fty))
2813         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2814                                               fty->getExtInfo());
2815 
2816       // Functions are r-values in C.
2817       valueKind = VK_RValue;
2818       break;
2819     }
2820 
2821     case Decl::MSProperty:
2822       valueKind = VK_LValue;
2823       break;
2824 
2825     case Decl::CXXMethod:
2826       // If we're referring to a method with an __unknown_anytype
2827       // result type, make the entire expression __unknown_anytype.
2828       // This should only be possible with a type written directly.
2829       if (const FunctionProtoType *proto
2830             = dyn_cast<FunctionProtoType>(VD->getType()))
2831         if (proto->getReturnType() == Context.UnknownAnyTy) {
2832           type = Context.UnknownAnyTy;
2833           valueKind = VK_RValue;
2834           break;
2835         }
2836 
2837       // C++ methods are l-values if static, r-values if non-static.
2838       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2839         valueKind = VK_LValue;
2840         break;
2841       }
2842       // fallthrough
2843 
2844     case Decl::CXXConversion:
2845     case Decl::CXXDestructor:
2846     case Decl::CXXConstructor:
2847       valueKind = VK_RValue;
2848       break;
2849     }
2850 
2851     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2852                             TemplateArgs);
2853   }
2854 }
2855 
2856 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2857                                     SmallString<32> &Target) {
2858   Target.resize(CharByteWidth * (Source.size() + 1));
2859   char *ResultPtr = &Target[0];
2860   const UTF8 *ErrorPtr;
2861   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2862   (void)success;
2863   assert(success);
2864   Target.resize(ResultPtr - &Target[0]);
2865 }
2866 
2867 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2868                                      PredefinedExpr::IdentType IT) {
2869   // Pick the current block, lambda, captured statement or function.
2870   Decl *currentDecl = nullptr;
2871   if (const BlockScopeInfo *BSI = getCurBlock())
2872     currentDecl = BSI->TheDecl;
2873   else if (const LambdaScopeInfo *LSI = getCurLambda())
2874     currentDecl = LSI->CallOperator;
2875   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2876     currentDecl = CSI->TheCapturedDecl;
2877   else
2878     currentDecl = getCurFunctionOrMethodDecl();
2879 
2880   if (!currentDecl) {
2881     Diag(Loc, diag::ext_predef_outside_function);
2882     currentDecl = Context.getTranslationUnitDecl();
2883   }
2884 
2885   QualType ResTy;
2886   StringLiteral *SL = nullptr;
2887   if (cast<DeclContext>(currentDecl)->isDependentContext())
2888     ResTy = Context.DependentTy;
2889   else {
2890     // Pre-defined identifiers are of type char[x], where x is the length of
2891     // the string.
2892     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
2893     unsigned Length = Str.length();
2894 
2895     llvm::APInt LengthI(32, Length + 1);
2896     if (IT == PredefinedExpr::LFunction) {
2897       ResTy = Context.WideCharTy.withConst();
2898       SmallString<32> RawChars;
2899       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
2900                               Str, RawChars);
2901       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
2902                                            /*IndexTypeQuals*/ 0);
2903       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
2904                                  /*Pascal*/ false, ResTy, Loc);
2905     } else {
2906       ResTy = Context.CharTy.withConst();
2907       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
2908                                            /*IndexTypeQuals*/ 0);
2909       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
2910                                  /*Pascal*/ false, ResTy, Loc);
2911     }
2912   }
2913 
2914   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
2915 }
2916 
2917 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2918   PredefinedExpr::IdentType IT;
2919 
2920   switch (Kind) {
2921   default: llvm_unreachable("Unknown simple primary expr!");
2922   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2923   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2924   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2925   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2926   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2927   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2928   }
2929 
2930   return BuildPredefinedExpr(Loc, IT);
2931 }
2932 
2933 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2934   SmallString<16> CharBuffer;
2935   bool Invalid = false;
2936   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2937   if (Invalid)
2938     return ExprError();
2939 
2940   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2941                             PP, Tok.getKind());
2942   if (Literal.hadError())
2943     return ExprError();
2944 
2945   QualType Ty;
2946   if (Literal.isWide())
2947     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2948   else if (Literal.isUTF16())
2949     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2950   else if (Literal.isUTF32())
2951     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2952   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2953     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2954   else
2955     Ty = Context.CharTy;  // 'x' -> char in C++
2956 
2957   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2958   if (Literal.isWide())
2959     Kind = CharacterLiteral::Wide;
2960   else if (Literal.isUTF16())
2961     Kind = CharacterLiteral::UTF16;
2962   else if (Literal.isUTF32())
2963     Kind = CharacterLiteral::UTF32;
2964 
2965   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2966                                              Tok.getLocation());
2967 
2968   if (Literal.getUDSuffix().empty())
2969     return Lit;
2970 
2971   // We're building a user-defined literal.
2972   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2973   SourceLocation UDSuffixLoc =
2974     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2975 
2976   // Make sure we're allowed user-defined literals here.
2977   if (!UDLScope)
2978     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2979 
2980   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2981   //   operator "" X (ch)
2982   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2983                                         Lit, Tok.getLocation());
2984 }
2985 
2986 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2987   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2988   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2989                                 Context.IntTy, Loc);
2990 }
2991 
2992 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2993                                   QualType Ty, SourceLocation Loc) {
2994   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2995 
2996   using llvm::APFloat;
2997   APFloat Val(Format);
2998 
2999   APFloat::opStatus result = Literal.GetFloatValue(Val);
3000 
3001   // Overflow is always an error, but underflow is only an error if
3002   // we underflowed to zero (APFloat reports denormals as underflow).
3003   if ((result & APFloat::opOverflow) ||
3004       ((result & APFloat::opUnderflow) && Val.isZero())) {
3005     unsigned diagnostic;
3006     SmallString<20> buffer;
3007     if (result & APFloat::opOverflow) {
3008       diagnostic = diag::warn_float_overflow;
3009       APFloat::getLargest(Format).toString(buffer);
3010     } else {
3011       diagnostic = diag::warn_float_underflow;
3012       APFloat::getSmallest(Format).toString(buffer);
3013     }
3014 
3015     S.Diag(Loc, diagnostic)
3016       << Ty
3017       << StringRef(buffer.data(), buffer.size());
3018   }
3019 
3020   bool isExact = (result == APFloat::opOK);
3021   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3022 }
3023 
3024 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3025   assert(E && "Invalid expression");
3026 
3027   if (E->isValueDependent())
3028     return false;
3029 
3030   QualType QT = E->getType();
3031   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3032     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3033     return true;
3034   }
3035 
3036   llvm::APSInt ValueAPS;
3037   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3038 
3039   if (R.isInvalid())
3040     return true;
3041 
3042   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3043   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3044     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3045         << ValueAPS.toString(10) << ValueIsPositive;
3046     return true;
3047   }
3048 
3049   return false;
3050 }
3051 
3052 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3053   // Fast path for a single digit (which is quite common).  A single digit
3054   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3055   if (Tok.getLength() == 1) {
3056     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3057     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3058   }
3059 
3060   SmallString<128> SpellingBuffer;
3061   // NumericLiteralParser wants to overread by one character.  Add padding to
3062   // the buffer in case the token is copied to the buffer.  If getSpelling()
3063   // returns a StringRef to the memory buffer, it should have a null char at
3064   // the EOF, so it is also safe.
3065   SpellingBuffer.resize(Tok.getLength() + 1);
3066 
3067   // Get the spelling of the token, which eliminates trigraphs, etc.
3068   bool Invalid = false;
3069   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3070   if (Invalid)
3071     return ExprError();
3072 
3073   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3074   if (Literal.hadError)
3075     return ExprError();
3076 
3077   if (Literal.hasUDSuffix()) {
3078     // We're building a user-defined literal.
3079     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3080     SourceLocation UDSuffixLoc =
3081       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3082 
3083     // Make sure we're allowed user-defined literals here.
3084     if (!UDLScope)
3085       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3086 
3087     QualType CookedTy;
3088     if (Literal.isFloatingLiteral()) {
3089       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3090       // long double, the literal is treated as a call of the form
3091       //   operator "" X (f L)
3092       CookedTy = Context.LongDoubleTy;
3093     } else {
3094       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3095       // unsigned long long, the literal is treated as a call of the form
3096       //   operator "" X (n ULL)
3097       CookedTy = Context.UnsignedLongLongTy;
3098     }
3099 
3100     DeclarationName OpName =
3101       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3102     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3103     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3104 
3105     SourceLocation TokLoc = Tok.getLocation();
3106 
3107     // Perform literal operator lookup to determine if we're building a raw
3108     // literal or a cooked one.
3109     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3110     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3111                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3112                                   /*AllowStringTemplate*/false)) {
3113     case LOLR_Error:
3114       return ExprError();
3115 
3116     case LOLR_Cooked: {
3117       Expr *Lit;
3118       if (Literal.isFloatingLiteral()) {
3119         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3120       } else {
3121         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3122         if (Literal.GetIntegerValue(ResultVal))
3123           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3124               << /* Unsigned */ 1;
3125         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3126                                      Tok.getLocation());
3127       }
3128       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3129     }
3130 
3131     case LOLR_Raw: {
3132       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3133       // literal is treated as a call of the form
3134       //   operator "" X ("n")
3135       unsigned Length = Literal.getUDSuffixOffset();
3136       QualType StrTy = Context.getConstantArrayType(
3137           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3138           ArrayType::Normal, 0);
3139       Expr *Lit = StringLiteral::Create(
3140           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3141           /*Pascal*/false, StrTy, &TokLoc, 1);
3142       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3143     }
3144 
3145     case LOLR_Template: {
3146       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3147       // template), L is treated as a call fo the form
3148       //   operator "" X <'c1', 'c2', ... 'ck'>()
3149       // where n is the source character sequence c1 c2 ... ck.
3150       TemplateArgumentListInfo ExplicitArgs;
3151       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3152       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3153       llvm::APSInt Value(CharBits, CharIsUnsigned);
3154       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3155         Value = TokSpelling[I];
3156         TemplateArgument Arg(Context, Value, Context.CharTy);
3157         TemplateArgumentLocInfo ArgInfo;
3158         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3159       }
3160       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3161                                       &ExplicitArgs);
3162     }
3163     case LOLR_StringTemplate:
3164       llvm_unreachable("unexpected literal operator lookup result");
3165     }
3166   }
3167 
3168   Expr *Res;
3169 
3170   if (Literal.isFloatingLiteral()) {
3171     QualType Ty;
3172     if (Literal.isFloat)
3173       Ty = Context.FloatTy;
3174     else if (!Literal.isLong)
3175       Ty = Context.DoubleTy;
3176     else
3177       Ty = Context.LongDoubleTy;
3178 
3179     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3180 
3181     if (Ty == Context.DoubleTy) {
3182       if (getLangOpts().SinglePrecisionConstants) {
3183         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3184       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3185         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3186         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3187       }
3188     }
3189   } else if (!Literal.isIntegerLiteral()) {
3190     return ExprError();
3191   } else {
3192     QualType Ty;
3193 
3194     // 'long long' is a C99 or C++11 feature.
3195     if (!getLangOpts().C99 && Literal.isLongLong) {
3196       if (getLangOpts().CPlusPlus)
3197         Diag(Tok.getLocation(),
3198              getLangOpts().CPlusPlus11 ?
3199              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3200       else
3201         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3202     }
3203 
3204     // Get the value in the widest-possible width.
3205     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3206     // The microsoft literal suffix extensions support 128-bit literals, which
3207     // may be wider than [u]intmax_t.
3208     // FIXME: Actually, they don't. We seem to have accidentally invented the
3209     //        i128 suffix.
3210     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3211         Context.getTargetInfo().hasInt128Type())
3212       MaxWidth = 128;
3213     llvm::APInt ResultVal(MaxWidth, 0);
3214 
3215     if (Literal.GetIntegerValue(ResultVal)) {
3216       // If this value didn't fit into uintmax_t, error and force to ull.
3217       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3218           << /* Unsigned */ 1;
3219       Ty = Context.UnsignedLongLongTy;
3220       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3221              "long long is not intmax_t?");
3222     } else {
3223       // If this value fits into a ULL, try to figure out what else it fits into
3224       // according to the rules of C99 6.4.4.1p5.
3225 
3226       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3227       // be an unsigned int.
3228       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3229 
3230       // Check from smallest to largest, picking the smallest type we can.
3231       unsigned Width = 0;
3232 
3233       // Microsoft specific integer suffixes are explicitly sized.
3234       if (Literal.MicrosoftInteger) {
3235         if (Literal.MicrosoftInteger > MaxWidth) {
3236           // If this target doesn't support __int128, error and force to ull.
3237           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3238           Width = MaxWidth;
3239           Ty = Context.getIntMaxType();
3240         } else {
3241           Width = Literal.MicrosoftInteger;
3242           Ty = Context.getIntTypeForBitwidth(Width,
3243                                              /*Signed=*/!Literal.isUnsigned);
3244         }
3245       }
3246 
3247       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3248         // Are int/unsigned possibilities?
3249         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3250 
3251         // Does it fit in a unsigned int?
3252         if (ResultVal.isIntN(IntSize)) {
3253           // Does it fit in a signed int?
3254           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3255             Ty = Context.IntTy;
3256           else if (AllowUnsigned)
3257             Ty = Context.UnsignedIntTy;
3258           Width = IntSize;
3259         }
3260       }
3261 
3262       // Are long/unsigned long possibilities?
3263       if (Ty.isNull() && !Literal.isLongLong) {
3264         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3265 
3266         // Does it fit in a unsigned long?
3267         if (ResultVal.isIntN(LongSize)) {
3268           // Does it fit in a signed long?
3269           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3270             Ty = Context.LongTy;
3271           else if (AllowUnsigned)
3272             Ty = Context.UnsignedLongTy;
3273           Width = LongSize;
3274         }
3275       }
3276 
3277       // Check long long if needed.
3278       if (Ty.isNull()) {
3279         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3280 
3281         // Does it fit in a unsigned long long?
3282         if (ResultVal.isIntN(LongLongSize)) {
3283           // Does it fit in a signed long long?
3284           // To be compatible with MSVC, hex integer literals ending with the
3285           // LL or i64 suffix are always signed in Microsoft mode.
3286           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3287               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3288             Ty = Context.LongLongTy;
3289           else if (AllowUnsigned)
3290             Ty = Context.UnsignedLongLongTy;
3291           Width = LongLongSize;
3292         }
3293       }
3294 
3295       // If we still couldn't decide a type, we probably have something that
3296       // does not fit in a signed long long, but has no U suffix.
3297       if (Ty.isNull()) {
3298         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3299         Ty = Context.UnsignedLongLongTy;
3300         Width = Context.getTargetInfo().getLongLongWidth();
3301       }
3302 
3303       if (ResultVal.getBitWidth() != Width)
3304         ResultVal = ResultVal.trunc(Width);
3305     }
3306     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3307   }
3308 
3309   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3310   if (Literal.isImaginary)
3311     Res = new (Context) ImaginaryLiteral(Res,
3312                                         Context.getComplexType(Res->getType()));
3313 
3314   return Res;
3315 }
3316 
3317 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3318   assert(E && "ActOnParenExpr() missing expr");
3319   return new (Context) ParenExpr(L, R, E);
3320 }
3321 
3322 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3323                                          SourceLocation Loc,
3324                                          SourceRange ArgRange) {
3325   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3326   // scalar or vector data type argument..."
3327   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3328   // type (C99 6.2.5p18) or void.
3329   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3330     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3331       << T << ArgRange;
3332     return true;
3333   }
3334 
3335   assert((T->isVoidType() || !T->isIncompleteType()) &&
3336          "Scalar types should always be complete");
3337   return false;
3338 }
3339 
3340 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3341                                            SourceLocation Loc,
3342                                            SourceRange ArgRange,
3343                                            UnaryExprOrTypeTrait TraitKind) {
3344   // Invalid types must be hard errors for SFINAE in C++.
3345   if (S.LangOpts.CPlusPlus)
3346     return true;
3347 
3348   // C99 6.5.3.4p1:
3349   if (T->isFunctionType() &&
3350       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3351     // sizeof(function)/alignof(function) is allowed as an extension.
3352     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3353       << TraitKind << ArgRange;
3354     return false;
3355   }
3356 
3357   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3358   // this is an error (OpenCL v1.1 s6.3.k)
3359   if (T->isVoidType()) {
3360     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3361                                         : diag::ext_sizeof_alignof_void_type;
3362     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3363     return false;
3364   }
3365 
3366   return true;
3367 }
3368 
3369 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3370                                              SourceLocation Loc,
3371                                              SourceRange ArgRange,
3372                                              UnaryExprOrTypeTrait TraitKind) {
3373   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3374   // runtime doesn't allow it.
3375   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3376     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3377       << T << (TraitKind == UETT_SizeOf)
3378       << ArgRange;
3379     return true;
3380   }
3381 
3382   return false;
3383 }
3384 
3385 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3386 /// pointer type is equal to T) and emit a warning if it is.
3387 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3388                                      Expr *E) {
3389   // Don't warn if the operation changed the type.
3390   if (T != E->getType())
3391     return;
3392 
3393   // Now look for array decays.
3394   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3395   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3396     return;
3397 
3398   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3399                                              << ICE->getType()
3400                                              << ICE->getSubExpr()->getType();
3401 }
3402 
3403 /// \brief Check the constraints on expression operands to unary type expression
3404 /// and type traits.
3405 ///
3406 /// Completes any types necessary and validates the constraints on the operand
3407 /// expression. The logic mostly mirrors the type-based overload, but may modify
3408 /// the expression as it completes the type for that expression through template
3409 /// instantiation, etc.
3410 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3411                                             UnaryExprOrTypeTrait ExprKind) {
3412   QualType ExprTy = E->getType();
3413   assert(!ExprTy->isReferenceType());
3414 
3415   if (ExprKind == UETT_VecStep)
3416     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3417                                         E->getSourceRange());
3418 
3419   // Whitelist some types as extensions
3420   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3421                                       E->getSourceRange(), ExprKind))
3422     return false;
3423 
3424   // 'alignof' applied to an expression only requires the base element type of
3425   // the expression to be complete. 'sizeof' requires the expression's type to
3426   // be complete (and will attempt to complete it if it's an array of unknown
3427   // bound).
3428   if (ExprKind == UETT_AlignOf) {
3429     if (RequireCompleteType(E->getExprLoc(),
3430                             Context.getBaseElementType(E->getType()),
3431                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3432                             E->getSourceRange()))
3433       return true;
3434   } else {
3435     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3436                                 ExprKind, E->getSourceRange()))
3437       return true;
3438   }
3439 
3440   // Completing the expression's type may have changed it.
3441   ExprTy = E->getType();
3442   assert(!ExprTy->isReferenceType());
3443 
3444   if (ExprTy->isFunctionType()) {
3445     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3446       << ExprKind << E->getSourceRange();
3447     return true;
3448   }
3449 
3450   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3451                                        E->getSourceRange(), ExprKind))
3452     return true;
3453 
3454   if (ExprKind == UETT_SizeOf) {
3455     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3456       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3457         QualType OType = PVD->getOriginalType();
3458         QualType Type = PVD->getType();
3459         if (Type->isPointerType() && OType->isArrayType()) {
3460           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3461             << Type << OType;
3462           Diag(PVD->getLocation(), diag::note_declared_at);
3463         }
3464       }
3465     }
3466 
3467     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3468     // decays into a pointer and returns an unintended result. This is most
3469     // likely a typo for "sizeof(array) op x".
3470     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3471       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3472                                BO->getLHS());
3473       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3474                                BO->getRHS());
3475     }
3476   }
3477 
3478   return false;
3479 }
3480 
3481 /// \brief Check the constraints on operands to unary expression and type
3482 /// traits.
3483 ///
3484 /// This will complete any types necessary, and validate the various constraints
3485 /// on those operands.
3486 ///
3487 /// The UsualUnaryConversions() function is *not* called by this routine.
3488 /// C99 6.3.2.1p[2-4] all state:
3489 ///   Except when it is the operand of the sizeof operator ...
3490 ///
3491 /// C++ [expr.sizeof]p4
3492 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3493 ///   standard conversions are not applied to the operand of sizeof.
3494 ///
3495 /// This policy is followed for all of the unary trait expressions.
3496 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3497                                             SourceLocation OpLoc,
3498                                             SourceRange ExprRange,
3499                                             UnaryExprOrTypeTrait ExprKind) {
3500   if (ExprType->isDependentType())
3501     return false;
3502 
3503   // C++ [expr.sizeof]p2:
3504   //     When applied to a reference or a reference type, the result
3505   //     is the size of the referenced type.
3506   // C++11 [expr.alignof]p3:
3507   //     When alignof is applied to a reference type, the result
3508   //     shall be the alignment of the referenced type.
3509   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3510     ExprType = Ref->getPointeeType();
3511 
3512   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3513   //   When alignof or _Alignof is applied to an array type, the result
3514   //   is the alignment of the element type.
3515   if (ExprKind == UETT_AlignOf)
3516     ExprType = Context.getBaseElementType(ExprType);
3517 
3518   if (ExprKind == UETT_VecStep)
3519     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3520 
3521   // Whitelist some types as extensions
3522   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3523                                       ExprKind))
3524     return false;
3525 
3526   if (RequireCompleteType(OpLoc, ExprType,
3527                           diag::err_sizeof_alignof_incomplete_type,
3528                           ExprKind, ExprRange))
3529     return true;
3530 
3531   if (ExprType->isFunctionType()) {
3532     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3533       << ExprKind << ExprRange;
3534     return true;
3535   }
3536 
3537   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3538                                        ExprKind))
3539     return true;
3540 
3541   return false;
3542 }
3543 
3544 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3545   E = E->IgnoreParens();
3546 
3547   // Cannot know anything else if the expression is dependent.
3548   if (E->isTypeDependent())
3549     return false;
3550 
3551   if (E->getObjectKind() == OK_BitField) {
3552     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3553        << 1 << E->getSourceRange();
3554     return true;
3555   }
3556 
3557   ValueDecl *D = nullptr;
3558   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3559     D = DRE->getDecl();
3560   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3561     D = ME->getMemberDecl();
3562   }
3563 
3564   // If it's a field, require the containing struct to have a
3565   // complete definition so that we can compute the layout.
3566   //
3567   // This can happen in C++11 onwards, either by naming the member
3568   // in a way that is not transformed into a member access expression
3569   // (in an unevaluated operand, for instance), or by naming the member
3570   // in a trailing-return-type.
3571   //
3572   // For the record, since __alignof__ on expressions is a GCC
3573   // extension, GCC seems to permit this but always gives the
3574   // nonsensical answer 0.
3575   //
3576   // We don't really need the layout here --- we could instead just
3577   // directly check for all the appropriate alignment-lowing
3578   // attributes --- but that would require duplicating a lot of
3579   // logic that just isn't worth duplicating for such a marginal
3580   // use-case.
3581   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3582     // Fast path this check, since we at least know the record has a
3583     // definition if we can find a member of it.
3584     if (!FD->getParent()->isCompleteDefinition()) {
3585       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3586         << E->getSourceRange();
3587       return true;
3588     }
3589 
3590     // Otherwise, if it's a field, and the field doesn't have
3591     // reference type, then it must have a complete type (or be a
3592     // flexible array member, which we explicitly want to
3593     // white-list anyway), which makes the following checks trivial.
3594     if (!FD->getType()->isReferenceType())
3595       return false;
3596   }
3597 
3598   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3599 }
3600 
3601 bool Sema::CheckVecStepExpr(Expr *E) {
3602   E = E->IgnoreParens();
3603 
3604   // Cannot know anything else if the expression is dependent.
3605   if (E->isTypeDependent())
3606     return false;
3607 
3608   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3609 }
3610 
3611 /// \brief Build a sizeof or alignof expression given a type operand.
3612 ExprResult
3613 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3614                                      SourceLocation OpLoc,
3615                                      UnaryExprOrTypeTrait ExprKind,
3616                                      SourceRange R) {
3617   if (!TInfo)
3618     return ExprError();
3619 
3620   QualType T = TInfo->getType();
3621 
3622   if (!T->isDependentType() &&
3623       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3624     return ExprError();
3625 
3626   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3627   return new (Context) UnaryExprOrTypeTraitExpr(
3628       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3629 }
3630 
3631 /// \brief Build a sizeof or alignof expression given an expression
3632 /// operand.
3633 ExprResult
3634 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3635                                      UnaryExprOrTypeTrait ExprKind) {
3636   ExprResult PE = CheckPlaceholderExpr(E);
3637   if (PE.isInvalid())
3638     return ExprError();
3639 
3640   E = PE.get();
3641 
3642   // Verify that the operand is valid.
3643   bool isInvalid = false;
3644   if (E->isTypeDependent()) {
3645     // Delay type-checking for type-dependent expressions.
3646   } else if (ExprKind == UETT_AlignOf) {
3647     isInvalid = CheckAlignOfExpr(*this, E);
3648   } else if (ExprKind == UETT_VecStep) {
3649     isInvalid = CheckVecStepExpr(E);
3650   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3651     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3652     isInvalid = true;
3653   } else {
3654     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3655   }
3656 
3657   if (isInvalid)
3658     return ExprError();
3659 
3660   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3661     PE = TransformToPotentiallyEvaluated(E);
3662     if (PE.isInvalid()) return ExprError();
3663     E = PE.get();
3664   }
3665 
3666   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3667   return new (Context) UnaryExprOrTypeTraitExpr(
3668       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3669 }
3670 
3671 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3672 /// expr and the same for @c alignof and @c __alignof
3673 /// Note that the ArgRange is invalid if isType is false.
3674 ExprResult
3675 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3676                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3677                                     void *TyOrEx, const SourceRange &ArgRange) {
3678   // If error parsing type, ignore.
3679   if (!TyOrEx) return ExprError();
3680 
3681   if (IsType) {
3682     TypeSourceInfo *TInfo;
3683     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3684     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3685   }
3686 
3687   Expr *ArgEx = (Expr *)TyOrEx;
3688   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3689   return Result;
3690 }
3691 
3692 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3693                                      bool IsReal) {
3694   if (V.get()->isTypeDependent())
3695     return S.Context.DependentTy;
3696 
3697   // _Real and _Imag are only l-values for normal l-values.
3698   if (V.get()->getObjectKind() != OK_Ordinary) {
3699     V = S.DefaultLvalueConversion(V.get());
3700     if (V.isInvalid())
3701       return QualType();
3702   }
3703 
3704   // These operators return the element type of a complex type.
3705   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3706     return CT->getElementType();
3707 
3708   // Otherwise they pass through real integer and floating point types here.
3709   if (V.get()->getType()->isArithmeticType())
3710     return V.get()->getType();
3711 
3712   // Test for placeholders.
3713   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3714   if (PR.isInvalid()) return QualType();
3715   if (PR.get() != V.get()) {
3716     V = PR;
3717     return CheckRealImagOperand(S, V, Loc, IsReal);
3718   }
3719 
3720   // Reject anything else.
3721   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3722     << (IsReal ? "__real" : "__imag");
3723   return QualType();
3724 }
3725 
3726 
3727 
3728 ExprResult
3729 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3730                           tok::TokenKind Kind, Expr *Input) {
3731   UnaryOperatorKind Opc;
3732   switch (Kind) {
3733   default: llvm_unreachable("Unknown unary op!");
3734   case tok::plusplus:   Opc = UO_PostInc; break;
3735   case tok::minusminus: Opc = UO_PostDec; break;
3736   }
3737 
3738   // Since this might is a postfix expression, get rid of ParenListExprs.
3739   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3740   if (Result.isInvalid()) return ExprError();
3741   Input = Result.get();
3742 
3743   return BuildUnaryOp(S, OpLoc, Opc, Input);
3744 }
3745 
3746 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3747 ///
3748 /// \return true on error
3749 static bool checkArithmeticOnObjCPointer(Sema &S,
3750                                          SourceLocation opLoc,
3751                                          Expr *op) {
3752   assert(op->getType()->isObjCObjectPointerType());
3753   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3754       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3755     return false;
3756 
3757   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3758     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3759     << op->getSourceRange();
3760   return true;
3761 }
3762 
3763 ExprResult
3764 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3765                               Expr *idx, SourceLocation rbLoc) {
3766   // Since this might be a postfix expression, get rid of ParenListExprs.
3767   if (isa<ParenListExpr>(base)) {
3768     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3769     if (result.isInvalid()) return ExprError();
3770     base = result.get();
3771   }
3772 
3773   // Handle any non-overload placeholder types in the base and index
3774   // expressions.  We can't handle overloads here because the other
3775   // operand might be an overloadable type, in which case the overload
3776   // resolution for the operator overload should get the first crack
3777   // at the overload.
3778   if (base->getType()->isNonOverloadPlaceholderType()) {
3779     ExprResult result = CheckPlaceholderExpr(base);
3780     if (result.isInvalid()) return ExprError();
3781     base = result.get();
3782   }
3783   if (idx->getType()->isNonOverloadPlaceholderType()) {
3784     ExprResult result = CheckPlaceholderExpr(idx);
3785     if (result.isInvalid()) return ExprError();
3786     idx = result.get();
3787   }
3788 
3789   // Build an unanalyzed expression if either operand is type-dependent.
3790   if (getLangOpts().CPlusPlus &&
3791       (base->isTypeDependent() || idx->isTypeDependent())) {
3792     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3793                                             VK_LValue, OK_Ordinary, rbLoc);
3794   }
3795 
3796   // Use C++ overloaded-operator rules if either operand has record
3797   // type.  The spec says to do this if either type is *overloadable*,
3798   // but enum types can't declare subscript operators or conversion
3799   // operators, so there's nothing interesting for overload resolution
3800   // to do if there aren't any record types involved.
3801   //
3802   // ObjC pointers have their own subscripting logic that is not tied
3803   // to overload resolution and so should not take this path.
3804   if (getLangOpts().CPlusPlus &&
3805       (base->getType()->isRecordType() ||
3806        (!base->getType()->isObjCObjectPointerType() &&
3807         idx->getType()->isRecordType()))) {
3808     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3809   }
3810 
3811   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3812 }
3813 
3814 ExprResult
3815 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3816                                       Expr *Idx, SourceLocation RLoc) {
3817   Expr *LHSExp = Base;
3818   Expr *RHSExp = Idx;
3819 
3820   // Perform default conversions.
3821   if (!LHSExp->getType()->getAs<VectorType>()) {
3822     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3823     if (Result.isInvalid())
3824       return ExprError();
3825     LHSExp = Result.get();
3826   }
3827   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3828   if (Result.isInvalid())
3829     return ExprError();
3830   RHSExp = Result.get();
3831 
3832   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3833   ExprValueKind VK = VK_LValue;
3834   ExprObjectKind OK = OK_Ordinary;
3835 
3836   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3837   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3838   // in the subscript position. As a result, we need to derive the array base
3839   // and index from the expression types.
3840   Expr *BaseExpr, *IndexExpr;
3841   QualType ResultType;
3842   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3843     BaseExpr = LHSExp;
3844     IndexExpr = RHSExp;
3845     ResultType = Context.DependentTy;
3846   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3847     BaseExpr = LHSExp;
3848     IndexExpr = RHSExp;
3849     ResultType = PTy->getPointeeType();
3850   } else if (const ObjCObjectPointerType *PTy =
3851                LHSTy->getAs<ObjCObjectPointerType>()) {
3852     BaseExpr = LHSExp;
3853     IndexExpr = RHSExp;
3854 
3855     // Use custom logic if this should be the pseudo-object subscript
3856     // expression.
3857     if (!LangOpts.isSubscriptPointerArithmetic())
3858       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3859                                           nullptr);
3860 
3861     ResultType = PTy->getPointeeType();
3862   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3863      // Handle the uncommon case of "123[Ptr]".
3864     BaseExpr = RHSExp;
3865     IndexExpr = LHSExp;
3866     ResultType = PTy->getPointeeType();
3867   } else if (const ObjCObjectPointerType *PTy =
3868                RHSTy->getAs<ObjCObjectPointerType>()) {
3869      // Handle the uncommon case of "123[Ptr]".
3870     BaseExpr = RHSExp;
3871     IndexExpr = LHSExp;
3872     ResultType = PTy->getPointeeType();
3873     if (!LangOpts.isSubscriptPointerArithmetic()) {
3874       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3875         << ResultType << BaseExpr->getSourceRange();
3876       return ExprError();
3877     }
3878   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3879     BaseExpr = LHSExp;    // vectors: V[123]
3880     IndexExpr = RHSExp;
3881     VK = LHSExp->getValueKind();
3882     if (VK != VK_RValue)
3883       OK = OK_VectorComponent;
3884 
3885     // FIXME: need to deal with const...
3886     ResultType = VTy->getElementType();
3887   } else if (LHSTy->isArrayType()) {
3888     // If we see an array that wasn't promoted by
3889     // DefaultFunctionArrayLvalueConversion, it must be an array that
3890     // wasn't promoted because of the C90 rule that doesn't
3891     // allow promoting non-lvalue arrays.  Warn, then
3892     // force the promotion here.
3893     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3894         LHSExp->getSourceRange();
3895     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3896                                CK_ArrayToPointerDecay).get();
3897     LHSTy = LHSExp->getType();
3898 
3899     BaseExpr = LHSExp;
3900     IndexExpr = RHSExp;
3901     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3902   } else if (RHSTy->isArrayType()) {
3903     // Same as previous, except for 123[f().a] case
3904     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3905         RHSExp->getSourceRange();
3906     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3907                                CK_ArrayToPointerDecay).get();
3908     RHSTy = RHSExp->getType();
3909 
3910     BaseExpr = RHSExp;
3911     IndexExpr = LHSExp;
3912     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3913   } else {
3914     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3915        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3916   }
3917   // C99 6.5.2.1p1
3918   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3919     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3920                      << IndexExpr->getSourceRange());
3921 
3922   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3923        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3924          && !IndexExpr->isTypeDependent())
3925     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3926 
3927   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3928   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3929   // type. Note that Functions are not objects, and that (in C99 parlance)
3930   // incomplete types are not object types.
3931   if (ResultType->isFunctionType()) {
3932     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3933       << ResultType << BaseExpr->getSourceRange();
3934     return ExprError();
3935   }
3936 
3937   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3938     // GNU extension: subscripting on pointer to void
3939     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3940       << BaseExpr->getSourceRange();
3941 
3942     // C forbids expressions of unqualified void type from being l-values.
3943     // See IsCForbiddenLValueType.
3944     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3945   } else if (!ResultType->isDependentType() &&
3946       RequireCompleteType(LLoc, ResultType,
3947                           diag::err_subscript_incomplete_type, BaseExpr))
3948     return ExprError();
3949 
3950   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3951          !ResultType.isCForbiddenLValueType());
3952 
3953   return new (Context)
3954       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
3955 }
3956 
3957 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3958                                         FunctionDecl *FD,
3959                                         ParmVarDecl *Param) {
3960   if (Param->hasUnparsedDefaultArg()) {
3961     Diag(CallLoc,
3962          diag::err_use_of_default_argument_to_function_declared_later) <<
3963       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3964     Diag(UnparsedDefaultArgLocs[Param],
3965          diag::note_default_argument_declared_here);
3966     return ExprError();
3967   }
3968 
3969   if (Param->hasUninstantiatedDefaultArg()) {
3970     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3971 
3972     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3973                                                  Param);
3974 
3975     // Instantiate the expression.
3976     MultiLevelTemplateArgumentList MutiLevelArgList
3977       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
3978 
3979     InstantiatingTemplate Inst(*this, CallLoc, Param,
3980                                MutiLevelArgList.getInnermost());
3981     if (Inst.isInvalid())
3982       return ExprError();
3983 
3984     ExprResult Result;
3985     {
3986       // C++ [dcl.fct.default]p5:
3987       //   The names in the [default argument] expression are bound, and
3988       //   the semantic constraints are checked, at the point where the
3989       //   default argument expression appears.
3990       ContextRAII SavedContext(*this, FD);
3991       LocalInstantiationScope Local(*this);
3992       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3993     }
3994     if (Result.isInvalid())
3995       return ExprError();
3996 
3997     // Check the expression as an initializer for the parameter.
3998     InitializedEntity Entity
3999       = InitializedEntity::InitializeParameter(Context, Param);
4000     InitializationKind Kind
4001       = InitializationKind::CreateCopy(Param->getLocation(),
4002              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4003     Expr *ResultE = Result.getAs<Expr>();
4004 
4005     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4006     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4007     if (Result.isInvalid())
4008       return ExprError();
4009 
4010     Expr *Arg = Result.getAs<Expr>();
4011     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4012     // Build the default argument expression.
4013     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4014   }
4015 
4016   // If the default expression creates temporaries, we need to
4017   // push them to the current stack of expression temporaries so they'll
4018   // be properly destroyed.
4019   // FIXME: We should really be rebuilding the default argument with new
4020   // bound temporaries; see the comment in PR5810.
4021   // We don't need to do that with block decls, though, because
4022   // blocks in default argument expression can never capture anything.
4023   if (isa<ExprWithCleanups>(Param->getInit())) {
4024     // Set the "needs cleanups" bit regardless of whether there are
4025     // any explicit objects.
4026     ExprNeedsCleanups = true;
4027 
4028     // Append all the objects to the cleanup list.  Right now, this
4029     // should always be a no-op, because blocks in default argument
4030     // expressions should never be able to capture anything.
4031     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4032            "default argument expression has capturing blocks?");
4033   }
4034 
4035   // We already type-checked the argument, so we know it works.
4036   // Just mark all of the declarations in this potentially-evaluated expression
4037   // as being "referenced".
4038   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4039                                    /*SkipLocalVariables=*/true);
4040   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4041 }
4042 
4043 
4044 Sema::VariadicCallType
4045 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4046                           Expr *Fn) {
4047   if (Proto && Proto->isVariadic()) {
4048     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4049       return VariadicConstructor;
4050     else if (Fn && Fn->getType()->isBlockPointerType())
4051       return VariadicBlock;
4052     else if (FDecl) {
4053       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4054         if (Method->isInstance())
4055           return VariadicMethod;
4056     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4057       return VariadicMethod;
4058     return VariadicFunction;
4059   }
4060   return VariadicDoesNotApply;
4061 }
4062 
4063 namespace {
4064 class FunctionCallCCC : public FunctionCallFilterCCC {
4065 public:
4066   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4067                   unsigned NumArgs, MemberExpr *ME)
4068       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4069         FunctionName(FuncName) {}
4070 
4071   bool ValidateCandidate(const TypoCorrection &candidate) override {
4072     if (!candidate.getCorrectionSpecifier() ||
4073         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4074       return false;
4075     }
4076 
4077     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4078   }
4079 
4080 private:
4081   const IdentifierInfo *const FunctionName;
4082 };
4083 }
4084 
4085 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4086                                                FunctionDecl *FDecl,
4087                                                ArrayRef<Expr *> Args) {
4088   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4089   DeclarationName FuncName = FDecl->getDeclName();
4090   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4091 
4092   if (TypoCorrection Corrected = S.CorrectTypo(
4093           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4094           S.getScopeForContext(S.CurContext), nullptr,
4095           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4096                                              Args.size(), ME),
4097           Sema::CTK_ErrorRecovery)) {
4098     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4099       if (Corrected.isOverloaded()) {
4100         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4101         OverloadCandidateSet::iterator Best;
4102         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4103                                            CDEnd = Corrected.end();
4104              CD != CDEnd; ++CD) {
4105           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4106             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4107                                    OCS);
4108         }
4109         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4110         case OR_Success:
4111           ND = Best->Function;
4112           Corrected.setCorrectionDecl(ND);
4113           break;
4114         default:
4115           break;
4116         }
4117       }
4118       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4119         return Corrected;
4120       }
4121     }
4122   }
4123   return TypoCorrection();
4124 }
4125 
4126 /// ConvertArgumentsForCall - Converts the arguments specified in
4127 /// Args/NumArgs to the parameter types of the function FDecl with
4128 /// function prototype Proto. Call is the call expression itself, and
4129 /// Fn is the function expression. For a C++ member function, this
4130 /// routine does not attempt to convert the object argument. Returns
4131 /// true if the call is ill-formed.
4132 bool
4133 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4134                               FunctionDecl *FDecl,
4135                               const FunctionProtoType *Proto,
4136                               ArrayRef<Expr *> Args,
4137                               SourceLocation RParenLoc,
4138                               bool IsExecConfig) {
4139   // Bail out early if calling a builtin with custom typechecking.
4140   // We don't need to do this in the
4141   if (FDecl)
4142     if (unsigned ID = FDecl->getBuiltinID())
4143       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4144         return false;
4145 
4146   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4147   // assignment, to the types of the corresponding parameter, ...
4148   unsigned NumParams = Proto->getNumParams();
4149   bool Invalid = false;
4150   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4151   unsigned FnKind = Fn->getType()->isBlockPointerType()
4152                        ? 1 /* block */
4153                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4154                                        : 0 /* function */);
4155 
4156   // If too few arguments are available (and we don't have default
4157   // arguments for the remaining parameters), don't make the call.
4158   if (Args.size() < NumParams) {
4159     if (Args.size() < MinArgs) {
4160       TypoCorrection TC;
4161       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4162         unsigned diag_id =
4163             MinArgs == NumParams && !Proto->isVariadic()
4164                 ? diag::err_typecheck_call_too_few_args_suggest
4165                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4166         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4167                                         << static_cast<unsigned>(Args.size())
4168                                         << TC.getCorrectionRange());
4169       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4170         Diag(RParenLoc,
4171              MinArgs == NumParams && !Proto->isVariadic()
4172                  ? diag::err_typecheck_call_too_few_args_one
4173                  : diag::err_typecheck_call_too_few_args_at_least_one)
4174             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4175       else
4176         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4177                             ? diag::err_typecheck_call_too_few_args
4178                             : diag::err_typecheck_call_too_few_args_at_least)
4179             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4180             << Fn->getSourceRange();
4181 
4182       // Emit the location of the prototype.
4183       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4184         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4185           << FDecl;
4186 
4187       return true;
4188     }
4189     Call->setNumArgs(Context, NumParams);
4190   }
4191 
4192   // If too many are passed and not variadic, error on the extras and drop
4193   // them.
4194   if (Args.size() > NumParams) {
4195     if (!Proto->isVariadic()) {
4196       TypoCorrection TC;
4197       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4198         unsigned diag_id =
4199             MinArgs == NumParams && !Proto->isVariadic()
4200                 ? diag::err_typecheck_call_too_many_args_suggest
4201                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4202         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4203                                         << static_cast<unsigned>(Args.size())
4204                                         << TC.getCorrectionRange());
4205       } else if (NumParams == 1 && FDecl &&
4206                  FDecl->getParamDecl(0)->getDeclName())
4207         Diag(Args[NumParams]->getLocStart(),
4208              MinArgs == NumParams
4209                  ? diag::err_typecheck_call_too_many_args_one
4210                  : diag::err_typecheck_call_too_many_args_at_most_one)
4211             << FnKind << FDecl->getParamDecl(0)
4212             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4213             << SourceRange(Args[NumParams]->getLocStart(),
4214                            Args.back()->getLocEnd());
4215       else
4216         Diag(Args[NumParams]->getLocStart(),
4217              MinArgs == NumParams
4218                  ? diag::err_typecheck_call_too_many_args
4219                  : diag::err_typecheck_call_too_many_args_at_most)
4220             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4221             << Fn->getSourceRange()
4222             << SourceRange(Args[NumParams]->getLocStart(),
4223                            Args.back()->getLocEnd());
4224 
4225       // Emit the location of the prototype.
4226       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4227         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4228           << FDecl;
4229 
4230       // This deletes the extra arguments.
4231       Call->setNumArgs(Context, NumParams);
4232       return true;
4233     }
4234   }
4235   SmallVector<Expr *, 8> AllArgs;
4236   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4237 
4238   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4239                                    Proto, 0, Args, AllArgs, CallType);
4240   if (Invalid)
4241     return true;
4242   unsigned TotalNumArgs = AllArgs.size();
4243   for (unsigned i = 0; i < TotalNumArgs; ++i)
4244     Call->setArg(i, AllArgs[i]);
4245 
4246   return false;
4247 }
4248 
4249 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4250                                   const FunctionProtoType *Proto,
4251                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4252                                   SmallVectorImpl<Expr *> &AllArgs,
4253                                   VariadicCallType CallType, bool AllowExplicit,
4254                                   bool IsListInitialization) {
4255   unsigned NumParams = Proto->getNumParams();
4256   bool Invalid = false;
4257   unsigned ArgIx = 0;
4258   // Continue to check argument types (even if we have too few/many args).
4259   for (unsigned i = FirstParam; i < NumParams; i++) {
4260     QualType ProtoArgType = Proto->getParamType(i);
4261 
4262     Expr *Arg;
4263     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4264     if (ArgIx < Args.size()) {
4265       Arg = Args[ArgIx++];
4266 
4267       if (RequireCompleteType(Arg->getLocStart(),
4268                               ProtoArgType,
4269                               diag::err_call_incomplete_argument, Arg))
4270         return true;
4271 
4272       // Strip the unbridged-cast placeholder expression off, if applicable.
4273       bool CFAudited = false;
4274       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4275           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4276           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4277         Arg = stripARCUnbridgedCast(Arg);
4278       else if (getLangOpts().ObjCAutoRefCount &&
4279                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4280                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4281         CFAudited = true;
4282 
4283       InitializedEntity Entity =
4284           Param ? InitializedEntity::InitializeParameter(Context, Param,
4285                                                          ProtoArgType)
4286                 : InitializedEntity::InitializeParameter(
4287                       Context, ProtoArgType, Proto->isParamConsumed(i));
4288 
4289       // Remember that parameter belongs to a CF audited API.
4290       if (CFAudited)
4291         Entity.setParameterCFAudited();
4292 
4293       ExprResult ArgE = PerformCopyInitialization(
4294           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4295       if (ArgE.isInvalid())
4296         return true;
4297 
4298       Arg = ArgE.getAs<Expr>();
4299     } else {
4300       assert(Param && "can't use default arguments without a known callee");
4301 
4302       ExprResult ArgExpr =
4303         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4304       if (ArgExpr.isInvalid())
4305         return true;
4306 
4307       Arg = ArgExpr.getAs<Expr>();
4308     }
4309 
4310     // Check for array bounds violations for each argument to the call. This
4311     // check only triggers warnings when the argument isn't a more complex Expr
4312     // with its own checking, such as a BinaryOperator.
4313     CheckArrayAccess(Arg);
4314 
4315     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4316     CheckStaticArrayArgument(CallLoc, Param, Arg);
4317 
4318     AllArgs.push_back(Arg);
4319   }
4320 
4321   // If this is a variadic call, handle args passed through "...".
4322   if (CallType != VariadicDoesNotApply) {
4323     // Assume that extern "C" functions with variadic arguments that
4324     // return __unknown_anytype aren't *really* variadic.
4325     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4326         FDecl->isExternC()) {
4327       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4328         QualType paramType; // ignored
4329         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4330         Invalid |= arg.isInvalid();
4331         AllArgs.push_back(arg.get());
4332       }
4333 
4334     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4335     } else {
4336       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4337         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4338                                                           FDecl);
4339         Invalid |= Arg.isInvalid();
4340         AllArgs.push_back(Arg.get());
4341       }
4342     }
4343 
4344     // Check for array bounds violations.
4345     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4346       CheckArrayAccess(Args[i]);
4347   }
4348   return Invalid;
4349 }
4350 
4351 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4352   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4353   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4354     TL = DTL.getOriginalLoc();
4355   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4356     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4357       << ATL.getLocalSourceRange();
4358 }
4359 
4360 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4361 /// array parameter, check that it is non-null, and that if it is formed by
4362 /// array-to-pointer decay, the underlying array is sufficiently large.
4363 ///
4364 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4365 /// array type derivation, then for each call to the function, the value of the
4366 /// corresponding actual argument shall provide access to the first element of
4367 /// an array with at least as many elements as specified by the size expression.
4368 void
4369 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4370                                ParmVarDecl *Param,
4371                                const Expr *ArgExpr) {
4372   // Static array parameters are not supported in C++.
4373   if (!Param || getLangOpts().CPlusPlus)
4374     return;
4375 
4376   QualType OrigTy = Param->getOriginalType();
4377 
4378   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4379   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4380     return;
4381 
4382   if (ArgExpr->isNullPointerConstant(Context,
4383                                      Expr::NPC_NeverValueDependent)) {
4384     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4385     DiagnoseCalleeStaticArrayParam(*this, Param);
4386     return;
4387   }
4388 
4389   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4390   if (!CAT)
4391     return;
4392 
4393   const ConstantArrayType *ArgCAT =
4394     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4395   if (!ArgCAT)
4396     return;
4397 
4398   if (ArgCAT->getSize().ult(CAT->getSize())) {
4399     Diag(CallLoc, diag::warn_static_array_too_small)
4400       << ArgExpr->getSourceRange()
4401       << (unsigned) ArgCAT->getSize().getZExtValue()
4402       << (unsigned) CAT->getSize().getZExtValue();
4403     DiagnoseCalleeStaticArrayParam(*this, Param);
4404   }
4405 }
4406 
4407 /// Given a function expression of unknown-any type, try to rebuild it
4408 /// to have a function type.
4409 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4410 
4411 /// Is the given type a placeholder that we need to lower out
4412 /// immediately during argument processing?
4413 static bool isPlaceholderToRemoveAsArg(QualType type) {
4414   // Placeholders are never sugared.
4415   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4416   if (!placeholder) return false;
4417 
4418   switch (placeholder->getKind()) {
4419   // Ignore all the non-placeholder types.
4420 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4421 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4422 #include "clang/AST/BuiltinTypes.def"
4423     return false;
4424 
4425   // We cannot lower out overload sets; they might validly be resolved
4426   // by the call machinery.
4427   case BuiltinType::Overload:
4428     return false;
4429 
4430   // Unbridged casts in ARC can be handled in some call positions and
4431   // should be left in place.
4432   case BuiltinType::ARCUnbridgedCast:
4433     return false;
4434 
4435   // Pseudo-objects should be converted as soon as possible.
4436   case BuiltinType::PseudoObject:
4437     return true;
4438 
4439   // The debugger mode could theoretically but currently does not try
4440   // to resolve unknown-typed arguments based on known parameter types.
4441   case BuiltinType::UnknownAny:
4442     return true;
4443 
4444   // These are always invalid as call arguments and should be reported.
4445   case BuiltinType::BoundMember:
4446   case BuiltinType::BuiltinFn:
4447     return true;
4448   }
4449   llvm_unreachable("bad builtin type kind");
4450 }
4451 
4452 /// Check an argument list for placeholders that we won't try to
4453 /// handle later.
4454 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4455   // Apply this processing to all the arguments at once instead of
4456   // dying at the first failure.
4457   bool hasInvalid = false;
4458   for (size_t i = 0, e = args.size(); i != e; i++) {
4459     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4460       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4461       if (result.isInvalid()) hasInvalid = true;
4462       else args[i] = result.get();
4463     }
4464   }
4465   return hasInvalid;
4466 }
4467 
4468 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4469 /// This provides the location of the left/right parens and a list of comma
4470 /// locations.
4471 ExprResult
4472 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4473                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4474                     Expr *ExecConfig, bool IsExecConfig) {
4475   // Since this might be a postfix expression, get rid of ParenListExprs.
4476   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4477   if (Result.isInvalid()) return ExprError();
4478   Fn = Result.get();
4479 
4480   if (checkArgsForPlaceholders(*this, ArgExprs))
4481     return ExprError();
4482 
4483   if (getLangOpts().CPlusPlus) {
4484     // If this is a pseudo-destructor expression, build the call immediately.
4485     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4486       if (!ArgExprs.empty()) {
4487         // Pseudo-destructor calls should not have any arguments.
4488         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4489           << FixItHint::CreateRemoval(
4490                                     SourceRange(ArgExprs[0]->getLocStart(),
4491                                                 ArgExprs.back()->getLocEnd()));
4492       }
4493 
4494       return new (Context)
4495           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4496     }
4497     if (Fn->getType() == Context.PseudoObjectTy) {
4498       ExprResult result = CheckPlaceholderExpr(Fn);
4499       if (result.isInvalid()) return ExprError();
4500       Fn = result.get();
4501     }
4502 
4503     // Determine whether this is a dependent call inside a C++ template,
4504     // in which case we won't do any semantic analysis now.
4505     // FIXME: Will need to cache the results of name lookup (including ADL) in
4506     // Fn.
4507     bool Dependent = false;
4508     if (Fn->isTypeDependent())
4509       Dependent = true;
4510     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4511       Dependent = true;
4512 
4513     if (Dependent) {
4514       if (ExecConfig) {
4515         return new (Context) CUDAKernelCallExpr(
4516             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4517             Context.DependentTy, VK_RValue, RParenLoc);
4518       } else {
4519         return new (Context) CallExpr(
4520             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4521       }
4522     }
4523 
4524     // Determine whether this is a call to an object (C++ [over.call.object]).
4525     if (Fn->getType()->isRecordType())
4526       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4527                                           RParenLoc);
4528 
4529     if (Fn->getType() == Context.UnknownAnyTy) {
4530       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4531       if (result.isInvalid()) return ExprError();
4532       Fn = result.get();
4533     }
4534 
4535     if (Fn->getType() == Context.BoundMemberTy) {
4536       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4537     }
4538   }
4539 
4540   // Check for overloaded calls.  This can happen even in C due to extensions.
4541   if (Fn->getType() == Context.OverloadTy) {
4542     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4543 
4544     // We aren't supposed to apply this logic for if there's an '&' involved.
4545     if (!find.HasFormOfMemberPointer) {
4546       OverloadExpr *ovl = find.Expression;
4547       if (isa<UnresolvedLookupExpr>(ovl)) {
4548         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4549         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4550                                        RParenLoc, ExecConfig);
4551       } else {
4552         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4553                                          RParenLoc);
4554       }
4555     }
4556   }
4557 
4558   // If we're directly calling a function, get the appropriate declaration.
4559   if (Fn->getType() == Context.UnknownAnyTy) {
4560     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4561     if (result.isInvalid()) return ExprError();
4562     Fn = result.get();
4563   }
4564 
4565   Expr *NakedFn = Fn->IgnoreParens();
4566 
4567   NamedDecl *NDecl = nullptr;
4568   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4569     if (UnOp->getOpcode() == UO_AddrOf)
4570       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4571 
4572   if (isa<DeclRefExpr>(NakedFn))
4573     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4574   else if (isa<MemberExpr>(NakedFn))
4575     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4576 
4577   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4578     if (FD->hasAttr<EnableIfAttr>()) {
4579       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4580         Diag(Fn->getLocStart(),
4581              isa<CXXMethodDecl>(FD) ?
4582                  diag::err_ovl_no_viable_member_function_in_call :
4583                  diag::err_ovl_no_viable_function_in_call)
4584           << FD << FD->getSourceRange();
4585         Diag(FD->getLocation(),
4586              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4587             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4588       }
4589     }
4590   }
4591 
4592   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4593                                ExecConfig, IsExecConfig);
4594 }
4595 
4596 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4597 ///
4598 /// __builtin_astype( value, dst type )
4599 ///
4600 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4601                                  SourceLocation BuiltinLoc,
4602                                  SourceLocation RParenLoc) {
4603   ExprValueKind VK = VK_RValue;
4604   ExprObjectKind OK = OK_Ordinary;
4605   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4606   QualType SrcTy = E->getType();
4607   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4608     return ExprError(Diag(BuiltinLoc,
4609                           diag::err_invalid_astype_of_different_size)
4610                      << DstTy
4611                      << SrcTy
4612                      << E->getSourceRange());
4613   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4614 }
4615 
4616 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4617 /// provided arguments.
4618 ///
4619 /// __builtin_convertvector( value, dst type )
4620 ///
4621 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4622                                         SourceLocation BuiltinLoc,
4623                                         SourceLocation RParenLoc) {
4624   TypeSourceInfo *TInfo;
4625   GetTypeFromParser(ParsedDestTy, &TInfo);
4626   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4627 }
4628 
4629 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4630 /// i.e. an expression not of \p OverloadTy.  The expression should
4631 /// unary-convert to an expression of function-pointer or
4632 /// block-pointer type.
4633 ///
4634 /// \param NDecl the declaration being called, if available
4635 ExprResult
4636 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4637                             SourceLocation LParenLoc,
4638                             ArrayRef<Expr *> Args,
4639                             SourceLocation RParenLoc,
4640                             Expr *Config, bool IsExecConfig) {
4641   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4642   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4643 
4644   // Promote the function operand.
4645   // We special-case function promotion here because we only allow promoting
4646   // builtin functions to function pointers in the callee of a call.
4647   ExprResult Result;
4648   if (BuiltinID &&
4649       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4650     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4651                                CK_BuiltinFnToFnPtr).get();
4652   } else {
4653     Result = CallExprUnaryConversions(Fn);
4654   }
4655   if (Result.isInvalid())
4656     return ExprError();
4657   Fn = Result.get();
4658 
4659   // Make the call expr early, before semantic checks.  This guarantees cleanup
4660   // of arguments and function on error.
4661   CallExpr *TheCall;
4662   if (Config)
4663     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4664                                                cast<CallExpr>(Config), Args,
4665                                                Context.BoolTy, VK_RValue,
4666                                                RParenLoc);
4667   else
4668     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4669                                      VK_RValue, RParenLoc);
4670 
4671   // Bail out early if calling a builtin with custom typechecking.
4672   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4673     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4674 
4675  retry:
4676   const FunctionType *FuncT;
4677   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4678     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4679     // have type pointer to function".
4680     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4681     if (!FuncT)
4682       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4683                          << Fn->getType() << Fn->getSourceRange());
4684   } else if (const BlockPointerType *BPT =
4685                Fn->getType()->getAs<BlockPointerType>()) {
4686     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4687   } else {
4688     // Handle calls to expressions of unknown-any type.
4689     if (Fn->getType() == Context.UnknownAnyTy) {
4690       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4691       if (rewrite.isInvalid()) return ExprError();
4692       Fn = rewrite.get();
4693       TheCall->setCallee(Fn);
4694       goto retry;
4695     }
4696 
4697     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4698       << Fn->getType() << Fn->getSourceRange());
4699   }
4700 
4701   if (getLangOpts().CUDA) {
4702     if (Config) {
4703       // CUDA: Kernel calls must be to global functions
4704       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4705         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4706             << FDecl->getName() << Fn->getSourceRange());
4707 
4708       // CUDA: Kernel function must have 'void' return type
4709       if (!FuncT->getReturnType()->isVoidType())
4710         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4711             << Fn->getType() << Fn->getSourceRange());
4712     } else {
4713       // CUDA: Calls to global functions must be configured
4714       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4715         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4716             << FDecl->getName() << Fn->getSourceRange());
4717     }
4718   }
4719 
4720   // Check for a valid return type
4721   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4722                           FDecl))
4723     return ExprError();
4724 
4725   // We know the result type of the call, set it.
4726   TheCall->setType(FuncT->getCallResultType(Context));
4727   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4728 
4729   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4730   if (Proto) {
4731     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4732                                 IsExecConfig))
4733       return ExprError();
4734   } else {
4735     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4736 
4737     if (FDecl) {
4738       // Check if we have too few/too many template arguments, based
4739       // on our knowledge of the function definition.
4740       const FunctionDecl *Def = nullptr;
4741       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4742         Proto = Def->getType()->getAs<FunctionProtoType>();
4743        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4744           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4745           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4746       }
4747 
4748       // If the function we're calling isn't a function prototype, but we have
4749       // a function prototype from a prior declaratiom, use that prototype.
4750       if (!FDecl->hasPrototype())
4751         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4752     }
4753 
4754     // Promote the arguments (C99 6.5.2.2p6).
4755     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4756       Expr *Arg = Args[i];
4757 
4758       if (Proto && i < Proto->getNumParams()) {
4759         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4760             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4761         ExprResult ArgE =
4762             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4763         if (ArgE.isInvalid())
4764           return true;
4765 
4766         Arg = ArgE.getAs<Expr>();
4767 
4768       } else {
4769         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4770 
4771         if (ArgE.isInvalid())
4772           return true;
4773 
4774         Arg = ArgE.getAs<Expr>();
4775       }
4776 
4777       if (RequireCompleteType(Arg->getLocStart(),
4778                               Arg->getType(),
4779                               diag::err_call_incomplete_argument, Arg))
4780         return ExprError();
4781 
4782       TheCall->setArg(i, Arg);
4783     }
4784   }
4785 
4786   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4787     if (!Method->isStatic())
4788       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4789         << Fn->getSourceRange());
4790 
4791   // Check for sentinels
4792   if (NDecl)
4793     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4794 
4795   // Do special checking on direct calls to functions.
4796   if (FDecl) {
4797     if (CheckFunctionCall(FDecl, TheCall, Proto))
4798       return ExprError();
4799 
4800     if (BuiltinID)
4801       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4802   } else if (NDecl) {
4803     if (CheckPointerCall(NDecl, TheCall, Proto))
4804       return ExprError();
4805   } else {
4806     if (CheckOtherCall(TheCall, Proto))
4807       return ExprError();
4808   }
4809 
4810   return MaybeBindToTemporary(TheCall);
4811 }
4812 
4813 ExprResult
4814 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4815                            SourceLocation RParenLoc, Expr *InitExpr) {
4816   assert(Ty && "ActOnCompoundLiteral(): missing type");
4817   // FIXME: put back this assert when initializers are worked out.
4818   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4819 
4820   TypeSourceInfo *TInfo;
4821   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4822   if (!TInfo)
4823     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4824 
4825   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4826 }
4827 
4828 ExprResult
4829 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4830                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4831   QualType literalType = TInfo->getType();
4832 
4833   if (literalType->isArrayType()) {
4834     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4835           diag::err_illegal_decl_array_incomplete_type,
4836           SourceRange(LParenLoc,
4837                       LiteralExpr->getSourceRange().getEnd())))
4838       return ExprError();
4839     if (literalType->isVariableArrayType())
4840       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4841         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4842   } else if (!literalType->isDependentType() &&
4843              RequireCompleteType(LParenLoc, literalType,
4844                diag::err_typecheck_decl_incomplete_type,
4845                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4846     return ExprError();
4847 
4848   InitializedEntity Entity
4849     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4850   InitializationKind Kind
4851     = InitializationKind::CreateCStyleCast(LParenLoc,
4852                                            SourceRange(LParenLoc, RParenLoc),
4853                                            /*InitList=*/true);
4854   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4855   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4856                                       &literalType);
4857   if (Result.isInvalid())
4858     return ExprError();
4859   LiteralExpr = Result.get();
4860 
4861   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4862   if (isFileScope &&
4863       !LiteralExpr->isTypeDependent() &&
4864       !LiteralExpr->isValueDependent() &&
4865       !literalType->isDependentType()) { // 6.5.2.5p3
4866     if (CheckForConstantInitializer(LiteralExpr, literalType))
4867       return ExprError();
4868   }
4869 
4870   // In C, compound literals are l-values for some reason.
4871   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4872 
4873   return MaybeBindToTemporary(
4874            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4875                                              VK, LiteralExpr, isFileScope));
4876 }
4877 
4878 ExprResult
4879 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4880                     SourceLocation RBraceLoc) {
4881   // Immediately handle non-overload placeholders.  Overloads can be
4882   // resolved contextually, but everything else here can't.
4883   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4884     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4885       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4886 
4887       // Ignore failures; dropping the entire initializer list because
4888       // of one failure would be terrible for indexing/etc.
4889       if (result.isInvalid()) continue;
4890 
4891       InitArgList[I] = result.get();
4892     }
4893   }
4894 
4895   // Semantic analysis for initializers is done by ActOnDeclarator() and
4896   // CheckInitializer() - it requires knowledge of the object being intialized.
4897 
4898   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4899                                                RBraceLoc);
4900   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4901   return E;
4902 }
4903 
4904 /// Do an explicit extend of the given block pointer if we're in ARC.
4905 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4906   assert(E.get()->getType()->isBlockPointerType());
4907   assert(E.get()->isRValue());
4908 
4909   // Only do this in an r-value context.
4910   if (!S.getLangOpts().ObjCAutoRefCount) return;
4911 
4912   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4913                                CK_ARCExtendBlockObject, E.get(),
4914                                /*base path*/ nullptr, VK_RValue);
4915   S.ExprNeedsCleanups = true;
4916 }
4917 
4918 /// Prepare a conversion of the given expression to an ObjC object
4919 /// pointer type.
4920 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4921   QualType type = E.get()->getType();
4922   if (type->isObjCObjectPointerType()) {
4923     return CK_BitCast;
4924   } else if (type->isBlockPointerType()) {
4925     maybeExtendBlockObject(*this, E);
4926     return CK_BlockPointerToObjCPointerCast;
4927   } else {
4928     assert(type->isPointerType());
4929     return CK_CPointerToObjCPointerCast;
4930   }
4931 }
4932 
4933 /// Prepares for a scalar cast, performing all the necessary stages
4934 /// except the final cast and returning the kind required.
4935 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4936   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4937   // Also, callers should have filtered out the invalid cases with
4938   // pointers.  Everything else should be possible.
4939 
4940   QualType SrcTy = Src.get()->getType();
4941   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4942     return CK_NoOp;
4943 
4944   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4945   case Type::STK_MemberPointer:
4946     llvm_unreachable("member pointer type in C");
4947 
4948   case Type::STK_CPointer:
4949   case Type::STK_BlockPointer:
4950   case Type::STK_ObjCObjectPointer:
4951     switch (DestTy->getScalarTypeKind()) {
4952     case Type::STK_CPointer: {
4953       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4954       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4955       if (SrcAS != DestAS)
4956         return CK_AddressSpaceConversion;
4957       return CK_BitCast;
4958     }
4959     case Type::STK_BlockPointer:
4960       return (SrcKind == Type::STK_BlockPointer
4961                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4962     case Type::STK_ObjCObjectPointer:
4963       if (SrcKind == Type::STK_ObjCObjectPointer)
4964         return CK_BitCast;
4965       if (SrcKind == Type::STK_CPointer)
4966         return CK_CPointerToObjCPointerCast;
4967       maybeExtendBlockObject(*this, Src);
4968       return CK_BlockPointerToObjCPointerCast;
4969     case Type::STK_Bool:
4970       return CK_PointerToBoolean;
4971     case Type::STK_Integral:
4972       return CK_PointerToIntegral;
4973     case Type::STK_Floating:
4974     case Type::STK_FloatingComplex:
4975     case Type::STK_IntegralComplex:
4976     case Type::STK_MemberPointer:
4977       llvm_unreachable("illegal cast from pointer");
4978     }
4979     llvm_unreachable("Should have returned before this");
4980 
4981   case Type::STK_Bool: // casting from bool is like casting from an integer
4982   case Type::STK_Integral:
4983     switch (DestTy->getScalarTypeKind()) {
4984     case Type::STK_CPointer:
4985     case Type::STK_ObjCObjectPointer:
4986     case Type::STK_BlockPointer:
4987       if (Src.get()->isNullPointerConstant(Context,
4988                                            Expr::NPC_ValueDependentIsNull))
4989         return CK_NullToPointer;
4990       return CK_IntegralToPointer;
4991     case Type::STK_Bool:
4992       return CK_IntegralToBoolean;
4993     case Type::STK_Integral:
4994       return CK_IntegralCast;
4995     case Type::STK_Floating:
4996       return CK_IntegralToFloating;
4997     case Type::STK_IntegralComplex:
4998       Src = ImpCastExprToType(Src.get(),
4999                               DestTy->castAs<ComplexType>()->getElementType(),
5000                               CK_IntegralCast);
5001       return CK_IntegralRealToComplex;
5002     case Type::STK_FloatingComplex:
5003       Src = ImpCastExprToType(Src.get(),
5004                               DestTy->castAs<ComplexType>()->getElementType(),
5005                               CK_IntegralToFloating);
5006       return CK_FloatingRealToComplex;
5007     case Type::STK_MemberPointer:
5008       llvm_unreachable("member pointer type in C");
5009     }
5010     llvm_unreachable("Should have returned before this");
5011 
5012   case Type::STK_Floating:
5013     switch (DestTy->getScalarTypeKind()) {
5014     case Type::STK_Floating:
5015       return CK_FloatingCast;
5016     case Type::STK_Bool:
5017       return CK_FloatingToBoolean;
5018     case Type::STK_Integral:
5019       return CK_FloatingToIntegral;
5020     case Type::STK_FloatingComplex:
5021       Src = ImpCastExprToType(Src.get(),
5022                               DestTy->castAs<ComplexType>()->getElementType(),
5023                               CK_FloatingCast);
5024       return CK_FloatingRealToComplex;
5025     case Type::STK_IntegralComplex:
5026       Src = ImpCastExprToType(Src.get(),
5027                               DestTy->castAs<ComplexType>()->getElementType(),
5028                               CK_FloatingToIntegral);
5029       return CK_IntegralRealToComplex;
5030     case Type::STK_CPointer:
5031     case Type::STK_ObjCObjectPointer:
5032     case Type::STK_BlockPointer:
5033       llvm_unreachable("valid float->pointer cast?");
5034     case Type::STK_MemberPointer:
5035       llvm_unreachable("member pointer type in C");
5036     }
5037     llvm_unreachable("Should have returned before this");
5038 
5039   case Type::STK_FloatingComplex:
5040     switch (DestTy->getScalarTypeKind()) {
5041     case Type::STK_FloatingComplex:
5042       return CK_FloatingComplexCast;
5043     case Type::STK_IntegralComplex:
5044       return CK_FloatingComplexToIntegralComplex;
5045     case Type::STK_Floating: {
5046       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5047       if (Context.hasSameType(ET, DestTy))
5048         return CK_FloatingComplexToReal;
5049       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5050       return CK_FloatingCast;
5051     }
5052     case Type::STK_Bool:
5053       return CK_FloatingComplexToBoolean;
5054     case Type::STK_Integral:
5055       Src = ImpCastExprToType(Src.get(),
5056                               SrcTy->castAs<ComplexType>()->getElementType(),
5057                               CK_FloatingComplexToReal);
5058       return CK_FloatingToIntegral;
5059     case Type::STK_CPointer:
5060     case Type::STK_ObjCObjectPointer:
5061     case Type::STK_BlockPointer:
5062       llvm_unreachable("valid complex float->pointer cast?");
5063     case Type::STK_MemberPointer:
5064       llvm_unreachable("member pointer type in C");
5065     }
5066     llvm_unreachable("Should have returned before this");
5067 
5068   case Type::STK_IntegralComplex:
5069     switch (DestTy->getScalarTypeKind()) {
5070     case Type::STK_FloatingComplex:
5071       return CK_IntegralComplexToFloatingComplex;
5072     case Type::STK_IntegralComplex:
5073       return CK_IntegralComplexCast;
5074     case Type::STK_Integral: {
5075       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5076       if (Context.hasSameType(ET, DestTy))
5077         return CK_IntegralComplexToReal;
5078       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5079       return CK_IntegralCast;
5080     }
5081     case Type::STK_Bool:
5082       return CK_IntegralComplexToBoolean;
5083     case Type::STK_Floating:
5084       Src = ImpCastExprToType(Src.get(),
5085                               SrcTy->castAs<ComplexType>()->getElementType(),
5086                               CK_IntegralComplexToReal);
5087       return CK_IntegralToFloating;
5088     case Type::STK_CPointer:
5089     case Type::STK_ObjCObjectPointer:
5090     case Type::STK_BlockPointer:
5091       llvm_unreachable("valid complex int->pointer cast?");
5092     case Type::STK_MemberPointer:
5093       llvm_unreachable("member pointer type in C");
5094     }
5095     llvm_unreachable("Should have returned before this");
5096   }
5097 
5098   llvm_unreachable("Unhandled scalar cast");
5099 }
5100 
5101 static bool breakDownVectorType(QualType type, uint64_t &len,
5102                                 QualType &eltType) {
5103   // Vectors are simple.
5104   if (const VectorType *vecType = type->getAs<VectorType>()) {
5105     len = vecType->getNumElements();
5106     eltType = vecType->getElementType();
5107     assert(eltType->isScalarType());
5108     return true;
5109   }
5110 
5111   // We allow lax conversion to and from non-vector types, but only if
5112   // they're real types (i.e. non-complex, non-pointer scalar types).
5113   if (!type->isRealType()) return false;
5114 
5115   len = 1;
5116   eltType = type;
5117   return true;
5118 }
5119 
5120 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5121   uint64_t srcLen, destLen;
5122   QualType srcElt, destElt;
5123   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5124   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5125 
5126   // ASTContext::getTypeSize will return the size rounded up to a
5127   // power of 2, so instead of using that, we need to use the raw
5128   // element size multiplied by the element count.
5129   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5130   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5131 
5132   return (srcLen * srcEltSize == destLen * destEltSize);
5133 }
5134 
5135 /// Is this a legal conversion between two known vector types?
5136 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5137   assert(destTy->isVectorType() || srcTy->isVectorType());
5138 
5139   if (!Context.getLangOpts().LaxVectorConversions)
5140     return false;
5141   return VectorTypesMatch(*this, srcTy, destTy);
5142 }
5143 
5144 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5145                            CastKind &Kind) {
5146   assert(VectorTy->isVectorType() && "Not a vector type!");
5147 
5148   if (Ty->isVectorType() || Ty->isIntegerType()) {
5149     if (!VectorTypesMatch(*this, Ty, VectorTy))
5150       return Diag(R.getBegin(),
5151                   Ty->isVectorType() ?
5152                   diag::err_invalid_conversion_between_vectors :
5153                   diag::err_invalid_conversion_between_vector_and_integer)
5154         << VectorTy << Ty << R;
5155   } else
5156     return Diag(R.getBegin(),
5157                 diag::err_invalid_conversion_between_vector_and_scalar)
5158       << VectorTy << Ty << R;
5159 
5160   Kind = CK_BitCast;
5161   return false;
5162 }
5163 
5164 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5165                                     Expr *CastExpr, CastKind &Kind) {
5166   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5167 
5168   QualType SrcTy = CastExpr->getType();
5169 
5170   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5171   // an ExtVectorType.
5172   // In OpenCL, casts between vectors of different types are not allowed.
5173   // (See OpenCL 6.2).
5174   if (SrcTy->isVectorType()) {
5175     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5176         || (getLangOpts().OpenCL &&
5177             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5178       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5179         << DestTy << SrcTy << R;
5180       return ExprError();
5181     }
5182     Kind = CK_BitCast;
5183     return CastExpr;
5184   }
5185 
5186   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5187   // conversion will take place first from scalar to elt type, and then
5188   // splat from elt type to vector.
5189   if (SrcTy->isPointerType())
5190     return Diag(R.getBegin(),
5191                 diag::err_invalid_conversion_between_vector_and_scalar)
5192       << DestTy << SrcTy << R;
5193 
5194   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5195   ExprResult CastExprRes = CastExpr;
5196   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5197   if (CastExprRes.isInvalid())
5198     return ExprError();
5199   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5200 
5201   Kind = CK_VectorSplat;
5202   return CastExpr;
5203 }
5204 
5205 ExprResult
5206 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5207                     Declarator &D, ParsedType &Ty,
5208                     SourceLocation RParenLoc, Expr *CastExpr) {
5209   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5210          "ActOnCastExpr(): missing type or expr");
5211 
5212   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5213   if (D.isInvalidType())
5214     return ExprError();
5215 
5216   if (getLangOpts().CPlusPlus) {
5217     // Check that there are no default arguments (C++ only).
5218     CheckExtraCXXDefaultArguments(D);
5219   }
5220 
5221   checkUnusedDeclAttributes(D);
5222 
5223   QualType castType = castTInfo->getType();
5224   Ty = CreateParsedType(castType, castTInfo);
5225 
5226   bool isVectorLiteral = false;
5227 
5228   // Check for an altivec or OpenCL literal,
5229   // i.e. all the elements are integer constants.
5230   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5231   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5232   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5233        && castType->isVectorType() && (PE || PLE)) {
5234     if (PLE && PLE->getNumExprs() == 0) {
5235       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5236       return ExprError();
5237     }
5238     if (PE || PLE->getNumExprs() == 1) {
5239       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5240       if (!E->getType()->isVectorType())
5241         isVectorLiteral = true;
5242     }
5243     else
5244       isVectorLiteral = true;
5245   }
5246 
5247   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5248   // then handle it as such.
5249   if (isVectorLiteral)
5250     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5251 
5252   // If the Expr being casted is a ParenListExpr, handle it specially.
5253   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5254   // sequence of BinOp comma operators.
5255   if (isa<ParenListExpr>(CastExpr)) {
5256     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5257     if (Result.isInvalid()) return ExprError();
5258     CastExpr = Result.get();
5259   }
5260 
5261   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5262       !getSourceManager().isInSystemMacro(LParenLoc))
5263     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5264 
5265   CheckTollFreeBridgeCast(castType, CastExpr);
5266 
5267   CheckObjCBridgeRelatedCast(castType, CastExpr);
5268 
5269   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5270 }
5271 
5272 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5273                                     SourceLocation RParenLoc, Expr *E,
5274                                     TypeSourceInfo *TInfo) {
5275   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5276          "Expected paren or paren list expression");
5277 
5278   Expr **exprs;
5279   unsigned numExprs;
5280   Expr *subExpr;
5281   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5282   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5283     LiteralLParenLoc = PE->getLParenLoc();
5284     LiteralRParenLoc = PE->getRParenLoc();
5285     exprs = PE->getExprs();
5286     numExprs = PE->getNumExprs();
5287   } else { // isa<ParenExpr> by assertion at function entrance
5288     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5289     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5290     subExpr = cast<ParenExpr>(E)->getSubExpr();
5291     exprs = &subExpr;
5292     numExprs = 1;
5293   }
5294 
5295   QualType Ty = TInfo->getType();
5296   assert(Ty->isVectorType() && "Expected vector type");
5297 
5298   SmallVector<Expr *, 8> initExprs;
5299   const VectorType *VTy = Ty->getAs<VectorType>();
5300   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5301 
5302   // '(...)' form of vector initialization in AltiVec: the number of
5303   // initializers must be one or must match the size of the vector.
5304   // If a single value is specified in the initializer then it will be
5305   // replicated to all the components of the vector
5306   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5307     // The number of initializers must be one or must match the size of the
5308     // vector. If a single value is specified in the initializer then it will
5309     // be replicated to all the components of the vector
5310     if (numExprs == 1) {
5311       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5312       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5313       if (Literal.isInvalid())
5314         return ExprError();
5315       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5316                                   PrepareScalarCast(Literal, ElemTy));
5317       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5318     }
5319     else if (numExprs < numElems) {
5320       Diag(E->getExprLoc(),
5321            diag::err_incorrect_number_of_vector_initializers);
5322       return ExprError();
5323     }
5324     else
5325       initExprs.append(exprs, exprs + numExprs);
5326   }
5327   else {
5328     // For OpenCL, when the number of initializers is a single value,
5329     // it will be replicated to all components of the vector.
5330     if (getLangOpts().OpenCL &&
5331         VTy->getVectorKind() == VectorType::GenericVector &&
5332         numExprs == 1) {
5333         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5334         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5335         if (Literal.isInvalid())
5336           return ExprError();
5337         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5338                                     PrepareScalarCast(Literal, ElemTy));
5339         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5340     }
5341 
5342     initExprs.append(exprs, exprs + numExprs);
5343   }
5344   // FIXME: This means that pretty-printing the final AST will produce curly
5345   // braces instead of the original commas.
5346   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5347                                                    initExprs, LiteralRParenLoc);
5348   initE->setType(Ty);
5349   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5350 }
5351 
5352 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5353 /// the ParenListExpr into a sequence of comma binary operators.
5354 ExprResult
5355 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5356   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5357   if (!E)
5358     return OrigExpr;
5359 
5360   ExprResult Result(E->getExpr(0));
5361 
5362   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5363     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5364                         E->getExpr(i));
5365 
5366   if (Result.isInvalid()) return ExprError();
5367 
5368   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5369 }
5370 
5371 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5372                                     SourceLocation R,
5373                                     MultiExprArg Val) {
5374   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5375   return expr;
5376 }
5377 
5378 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5379 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5380 /// emitted.
5381 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5382                                       SourceLocation QuestionLoc) {
5383   Expr *NullExpr = LHSExpr;
5384   Expr *NonPointerExpr = RHSExpr;
5385   Expr::NullPointerConstantKind NullKind =
5386       NullExpr->isNullPointerConstant(Context,
5387                                       Expr::NPC_ValueDependentIsNotNull);
5388 
5389   if (NullKind == Expr::NPCK_NotNull) {
5390     NullExpr = RHSExpr;
5391     NonPointerExpr = LHSExpr;
5392     NullKind =
5393         NullExpr->isNullPointerConstant(Context,
5394                                         Expr::NPC_ValueDependentIsNotNull);
5395   }
5396 
5397   if (NullKind == Expr::NPCK_NotNull)
5398     return false;
5399 
5400   if (NullKind == Expr::NPCK_ZeroExpression)
5401     return false;
5402 
5403   if (NullKind == Expr::NPCK_ZeroLiteral) {
5404     // In this case, check to make sure that we got here from a "NULL"
5405     // string in the source code.
5406     NullExpr = NullExpr->IgnoreParenImpCasts();
5407     SourceLocation loc = NullExpr->getExprLoc();
5408     if (!findMacroSpelling(loc, "NULL"))
5409       return false;
5410   }
5411 
5412   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5413   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5414       << NonPointerExpr->getType() << DiagType
5415       << NonPointerExpr->getSourceRange();
5416   return true;
5417 }
5418 
5419 /// \brief Return false if the condition expression is valid, true otherwise.
5420 static bool checkCondition(Sema &S, Expr *Cond) {
5421   QualType CondTy = Cond->getType();
5422 
5423   // C99 6.5.15p2
5424   if (CondTy->isScalarType()) return false;
5425 
5426   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5427   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5428     return false;
5429 
5430   // Emit the proper error message.
5431   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5432                               diag::err_typecheck_cond_expect_scalar :
5433                               diag::err_typecheck_cond_expect_scalar_or_vector)
5434     << CondTy;
5435   return true;
5436 }
5437 
5438 /// \brief Return false if the two expressions can be converted to a vector,
5439 /// true otherwise
5440 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5441                                                     ExprResult &RHS,
5442                                                     QualType CondTy) {
5443   // Both operands should be of scalar type.
5444   if (!LHS.get()->getType()->isScalarType()) {
5445     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5446       << CondTy;
5447     return true;
5448   }
5449   if (!RHS.get()->getType()->isScalarType()) {
5450     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5451       << CondTy;
5452     return true;
5453   }
5454 
5455   // Implicity convert these scalars to the type of the condition.
5456   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5457   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5458   return false;
5459 }
5460 
5461 /// \brief Handle when one or both operands are void type.
5462 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5463                                          ExprResult &RHS) {
5464     Expr *LHSExpr = LHS.get();
5465     Expr *RHSExpr = RHS.get();
5466 
5467     if (!LHSExpr->getType()->isVoidType())
5468       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5469         << RHSExpr->getSourceRange();
5470     if (!RHSExpr->getType()->isVoidType())
5471       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5472         << LHSExpr->getSourceRange();
5473     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5474     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5475     return S.Context.VoidTy;
5476 }
5477 
5478 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5479 /// true otherwise.
5480 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5481                                         QualType PointerTy) {
5482   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5483       !NullExpr.get()->isNullPointerConstant(S.Context,
5484                                             Expr::NPC_ValueDependentIsNull))
5485     return true;
5486 
5487   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5488   return false;
5489 }
5490 
5491 /// \brief Checks compatibility between two pointers and return the resulting
5492 /// type.
5493 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5494                                                      ExprResult &RHS,
5495                                                      SourceLocation Loc) {
5496   QualType LHSTy = LHS.get()->getType();
5497   QualType RHSTy = RHS.get()->getType();
5498 
5499   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5500     // Two identical pointers types are always compatible.
5501     return LHSTy;
5502   }
5503 
5504   QualType lhptee, rhptee;
5505 
5506   // Get the pointee types.
5507   bool IsBlockPointer = false;
5508   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5509     lhptee = LHSBTy->getPointeeType();
5510     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5511     IsBlockPointer = true;
5512   } else {
5513     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5514     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5515   }
5516 
5517   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5518   // differently qualified versions of compatible types, the result type is
5519   // a pointer to an appropriately qualified version of the composite
5520   // type.
5521 
5522   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5523   // clause doesn't make sense for our extensions. E.g. address space 2 should
5524   // be incompatible with address space 3: they may live on different devices or
5525   // anything.
5526   Qualifiers lhQual = lhptee.getQualifiers();
5527   Qualifiers rhQual = rhptee.getQualifiers();
5528 
5529   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5530   lhQual.removeCVRQualifiers();
5531   rhQual.removeCVRQualifiers();
5532 
5533   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5534   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5535 
5536   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5537 
5538   if (CompositeTy.isNull()) {
5539     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5540       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5541       << RHS.get()->getSourceRange();
5542     // In this situation, we assume void* type. No especially good
5543     // reason, but this is what gcc does, and we do have to pick
5544     // to get a consistent AST.
5545     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5546     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5547     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5548     return incompatTy;
5549   }
5550 
5551   // The pointer types are compatible.
5552   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5553   if (IsBlockPointer)
5554     ResultTy = S.Context.getBlockPointerType(ResultTy);
5555   else
5556     ResultTy = S.Context.getPointerType(ResultTy);
5557 
5558   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5559   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5560   return ResultTy;
5561 }
5562 
5563 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5564 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5565 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5566 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5567   if (QT->isObjCIdType())
5568     return true;
5569 
5570   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5571   if (!OPT)
5572     return false;
5573 
5574   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5575     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5576       return false;
5577 
5578   ObjCProtocolDecl* PNSCopying =
5579     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5580   ObjCProtocolDecl* PNSObject =
5581     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5582 
5583   for (auto *Proto : OPT->quals()) {
5584     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5585         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5586       ;
5587     else
5588       return false;
5589   }
5590   return true;
5591 }
5592 
5593 /// \brief Return the resulting type when the operands are both block pointers.
5594 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5595                                                           ExprResult &LHS,
5596                                                           ExprResult &RHS,
5597                                                           SourceLocation Loc) {
5598   QualType LHSTy = LHS.get()->getType();
5599   QualType RHSTy = RHS.get()->getType();
5600 
5601   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5602     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5603       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5604       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5605       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5606       return destType;
5607     }
5608     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5609       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5610       << RHS.get()->getSourceRange();
5611     return QualType();
5612   }
5613 
5614   // We have 2 block pointer types.
5615   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5616 }
5617 
5618 /// \brief Return the resulting type when the operands are both pointers.
5619 static QualType
5620 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5621                                             ExprResult &RHS,
5622                                             SourceLocation Loc) {
5623   // get the pointer types
5624   QualType LHSTy = LHS.get()->getType();
5625   QualType RHSTy = RHS.get()->getType();
5626 
5627   // get the "pointed to" types
5628   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5629   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5630 
5631   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5632   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5633     // Figure out necessary qualifiers (C99 6.5.15p6)
5634     QualType destPointee
5635       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5636     QualType destType = S.Context.getPointerType(destPointee);
5637     // Add qualifiers if necessary.
5638     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5639     // Promote to void*.
5640     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5641     return destType;
5642   }
5643   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5644     QualType destPointee
5645       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5646     QualType destType = S.Context.getPointerType(destPointee);
5647     // Add qualifiers if necessary.
5648     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5649     // Promote to void*.
5650     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5651     return destType;
5652   }
5653 
5654   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5655 }
5656 
5657 /// \brief Return false if the first expression is not an integer and the second
5658 /// expression is not a pointer, true otherwise.
5659 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5660                                         Expr* PointerExpr, SourceLocation Loc,
5661                                         bool IsIntFirstExpr) {
5662   if (!PointerExpr->getType()->isPointerType() ||
5663       !Int.get()->getType()->isIntegerType())
5664     return false;
5665 
5666   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5667   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5668 
5669   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
5670     << Expr1->getType() << Expr2->getType()
5671     << Expr1->getSourceRange() << Expr2->getSourceRange();
5672   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5673                             CK_IntegralToPointer);
5674   return true;
5675 }
5676 
5677 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5678 /// In that case, LHS = cond.
5679 /// C99 6.5.15
5680 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5681                                         ExprResult &RHS, ExprValueKind &VK,
5682                                         ExprObjectKind &OK,
5683                                         SourceLocation QuestionLoc) {
5684 
5685   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5686   if (!LHSResult.isUsable()) return QualType();
5687   LHS = LHSResult;
5688 
5689   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5690   if (!RHSResult.isUsable()) return QualType();
5691   RHS = RHSResult;
5692 
5693   // C++ is sufficiently different to merit its own checker.
5694   if (getLangOpts().CPlusPlus)
5695     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5696 
5697   VK = VK_RValue;
5698   OK = OK_Ordinary;
5699 
5700   // First, check the condition.
5701   Cond = UsualUnaryConversions(Cond.get());
5702   if (Cond.isInvalid())
5703     return QualType();
5704   if (checkCondition(*this, Cond.get()))
5705     return QualType();
5706 
5707   // Now check the two expressions.
5708   if (LHS.get()->getType()->isVectorType() ||
5709       RHS.get()->getType()->isVectorType())
5710     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5711 
5712   UsualArithmeticConversions(LHS, RHS);
5713   if (LHS.isInvalid() || RHS.isInvalid())
5714     return QualType();
5715 
5716   QualType CondTy = Cond.get()->getType();
5717   QualType LHSTy = LHS.get()->getType();
5718   QualType RHSTy = RHS.get()->getType();
5719 
5720   // If the condition is a vector, and both operands are scalar,
5721   // attempt to implicity convert them to the vector type to act like the
5722   // built in select. (OpenCL v1.1 s6.3.i)
5723   if (getLangOpts().OpenCL && CondTy->isVectorType())
5724     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5725       return QualType();
5726 
5727   // If both operands have arithmetic type, do the usual arithmetic conversions
5728   // to find a common type: C99 6.5.15p3,5.
5729   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5730     return LHS.get()->getType();
5731 
5732   // If both operands are the same structure or union type, the result is that
5733   // type.
5734   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5735     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5736       if (LHSRT->getDecl() == RHSRT->getDecl())
5737         // "If both the operands have structure or union type, the result has
5738         // that type."  This implies that CV qualifiers are dropped.
5739         return LHSTy.getUnqualifiedType();
5740     // FIXME: Type of conditional expression must be complete in C mode.
5741   }
5742 
5743   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5744   // The following || allows only one side to be void (a GCC-ism).
5745   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5746     return checkConditionalVoidType(*this, LHS, RHS);
5747   }
5748 
5749   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5750   // the type of the other operand."
5751   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5752   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5753 
5754   // All objective-c pointer type analysis is done here.
5755   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5756                                                         QuestionLoc);
5757   if (LHS.isInvalid() || RHS.isInvalid())
5758     return QualType();
5759   if (!compositeType.isNull())
5760     return compositeType;
5761 
5762 
5763   // Handle block pointer types.
5764   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5765     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5766                                                      QuestionLoc);
5767 
5768   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5769   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5770     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5771                                                        QuestionLoc);
5772 
5773   // GCC compatibility: soften pointer/integer mismatch.  Note that
5774   // null pointers have been filtered out by this point.
5775   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5776       /*isIntFirstExpr=*/true))
5777     return RHSTy;
5778   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5779       /*isIntFirstExpr=*/false))
5780     return LHSTy;
5781 
5782   // Emit a better diagnostic if one of the expressions is a null pointer
5783   // constant and the other is not a pointer type. In this case, the user most
5784   // likely forgot to take the address of the other expression.
5785   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5786     return QualType();
5787 
5788   // Otherwise, the operands are not compatible.
5789   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5790     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5791     << RHS.get()->getSourceRange();
5792   return QualType();
5793 }
5794 
5795 /// FindCompositeObjCPointerType - Helper method to find composite type of
5796 /// two objective-c pointer types of the two input expressions.
5797 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5798                                             SourceLocation QuestionLoc) {
5799   QualType LHSTy = LHS.get()->getType();
5800   QualType RHSTy = RHS.get()->getType();
5801 
5802   // Handle things like Class and struct objc_class*.  Here we case the result
5803   // to the pseudo-builtin, because that will be implicitly cast back to the
5804   // redefinition type if an attempt is made to access its fields.
5805   if (LHSTy->isObjCClassType() &&
5806       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5807     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5808     return LHSTy;
5809   }
5810   if (RHSTy->isObjCClassType() &&
5811       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5812     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5813     return RHSTy;
5814   }
5815   // And the same for struct objc_object* / id
5816   if (LHSTy->isObjCIdType() &&
5817       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5818     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5819     return LHSTy;
5820   }
5821   if (RHSTy->isObjCIdType() &&
5822       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5823     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5824     return RHSTy;
5825   }
5826   // And the same for struct objc_selector* / SEL
5827   if (Context.isObjCSelType(LHSTy) &&
5828       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5829     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5830     return LHSTy;
5831   }
5832   if (Context.isObjCSelType(RHSTy) &&
5833       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5834     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5835     return RHSTy;
5836   }
5837   // Check constraints for Objective-C object pointers types.
5838   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5839 
5840     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5841       // Two identical object pointer types are always compatible.
5842       return LHSTy;
5843     }
5844     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5845     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5846     QualType compositeType = LHSTy;
5847 
5848     // If both operands are interfaces and either operand can be
5849     // assigned to the other, use that type as the composite
5850     // type. This allows
5851     //   xxx ? (A*) a : (B*) b
5852     // where B is a subclass of A.
5853     //
5854     // Additionally, as for assignment, if either type is 'id'
5855     // allow silent coercion. Finally, if the types are
5856     // incompatible then make sure to use 'id' as the composite
5857     // type so the result is acceptable for sending messages to.
5858 
5859     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5860     // It could return the composite type.
5861     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5862       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5863     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5864       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5865     } else if ((LHSTy->isObjCQualifiedIdType() ||
5866                 RHSTy->isObjCQualifiedIdType()) &&
5867                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5868       // Need to handle "id<xx>" explicitly.
5869       // GCC allows qualified id and any Objective-C type to devolve to
5870       // id. Currently localizing to here until clear this should be
5871       // part of ObjCQualifiedIdTypesAreCompatible.
5872       compositeType = Context.getObjCIdType();
5873     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5874       compositeType = Context.getObjCIdType();
5875     } else if (!(compositeType =
5876                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5877       ;
5878     else {
5879       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5880       << LHSTy << RHSTy
5881       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5882       QualType incompatTy = Context.getObjCIdType();
5883       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5884       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5885       return incompatTy;
5886     }
5887     // The object pointer types are compatible.
5888     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5889     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5890     return compositeType;
5891   }
5892   // Check Objective-C object pointer types and 'void *'
5893   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5894     if (getLangOpts().ObjCAutoRefCount) {
5895       // ARC forbids the implicit conversion of object pointers to 'void *',
5896       // so these types are not compatible.
5897       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5898           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5899       LHS = RHS = true;
5900       return QualType();
5901     }
5902     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5903     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5904     QualType destPointee
5905     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5906     QualType destType = Context.getPointerType(destPointee);
5907     // Add qualifiers if necessary.
5908     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5909     // Promote to void*.
5910     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5911     return destType;
5912   }
5913   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5914     if (getLangOpts().ObjCAutoRefCount) {
5915       // ARC forbids the implicit conversion of object pointers to 'void *',
5916       // so these types are not compatible.
5917       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5918           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5919       LHS = RHS = true;
5920       return QualType();
5921     }
5922     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5923     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5924     QualType destPointee
5925     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5926     QualType destType = Context.getPointerType(destPointee);
5927     // Add qualifiers if necessary.
5928     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5929     // Promote to void*.
5930     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5931     return destType;
5932   }
5933   return QualType();
5934 }
5935 
5936 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5937 /// ParenRange in parentheses.
5938 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5939                                const PartialDiagnostic &Note,
5940                                SourceRange ParenRange) {
5941   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5942   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5943       EndLoc.isValid()) {
5944     Self.Diag(Loc, Note)
5945       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5946       << FixItHint::CreateInsertion(EndLoc, ")");
5947   } else {
5948     // We can't display the parentheses, so just show the bare note.
5949     Self.Diag(Loc, Note) << ParenRange;
5950   }
5951 }
5952 
5953 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5954   return Opc >= BO_Mul && Opc <= BO_Shr;
5955 }
5956 
5957 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5958 /// expression, either using a built-in or overloaded operator,
5959 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5960 /// expression.
5961 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5962                                    Expr **RHSExprs) {
5963   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5964   E = E->IgnoreImpCasts();
5965   E = E->IgnoreConversionOperator();
5966   E = E->IgnoreImpCasts();
5967 
5968   // Built-in binary operator.
5969   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5970     if (IsArithmeticOp(OP->getOpcode())) {
5971       *Opcode = OP->getOpcode();
5972       *RHSExprs = OP->getRHS();
5973       return true;
5974     }
5975   }
5976 
5977   // Overloaded operator.
5978   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5979     if (Call->getNumArgs() != 2)
5980       return false;
5981 
5982     // Make sure this is really a binary operator that is safe to pass into
5983     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5984     OverloadedOperatorKind OO = Call->getOperator();
5985     if (OO < OO_Plus || OO > OO_Arrow ||
5986         OO == OO_PlusPlus || OO == OO_MinusMinus)
5987       return false;
5988 
5989     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5990     if (IsArithmeticOp(OpKind)) {
5991       *Opcode = OpKind;
5992       *RHSExprs = Call->getArg(1);
5993       return true;
5994     }
5995   }
5996 
5997   return false;
5998 }
5999 
6000 static bool IsLogicOp(BinaryOperatorKind Opc) {
6001   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6002 }
6003 
6004 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6005 /// or is a logical expression such as (x==y) which has int type, but is
6006 /// commonly interpreted as boolean.
6007 static bool ExprLooksBoolean(Expr *E) {
6008   E = E->IgnoreParenImpCasts();
6009 
6010   if (E->getType()->isBooleanType())
6011     return true;
6012   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6013     return IsLogicOp(OP->getOpcode());
6014   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6015     return OP->getOpcode() == UO_LNot;
6016 
6017   return false;
6018 }
6019 
6020 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6021 /// and binary operator are mixed in a way that suggests the programmer assumed
6022 /// the conditional operator has higher precedence, for example:
6023 /// "int x = a + someBinaryCondition ? 1 : 2".
6024 static void DiagnoseConditionalPrecedence(Sema &Self,
6025                                           SourceLocation OpLoc,
6026                                           Expr *Condition,
6027                                           Expr *LHSExpr,
6028                                           Expr *RHSExpr) {
6029   BinaryOperatorKind CondOpcode;
6030   Expr *CondRHS;
6031 
6032   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6033     return;
6034   if (!ExprLooksBoolean(CondRHS))
6035     return;
6036 
6037   // The condition is an arithmetic binary expression, with a right-
6038   // hand side that looks boolean, so warn.
6039 
6040   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6041       << Condition->getSourceRange()
6042       << BinaryOperator::getOpcodeStr(CondOpcode);
6043 
6044   SuggestParentheses(Self, OpLoc,
6045     Self.PDiag(diag::note_precedence_silence)
6046       << BinaryOperator::getOpcodeStr(CondOpcode),
6047     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6048 
6049   SuggestParentheses(Self, OpLoc,
6050     Self.PDiag(diag::note_precedence_conditional_first),
6051     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6052 }
6053 
6054 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6055 /// in the case of a the GNU conditional expr extension.
6056 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6057                                     SourceLocation ColonLoc,
6058                                     Expr *CondExpr, Expr *LHSExpr,
6059                                     Expr *RHSExpr) {
6060   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6061   // was the condition.
6062   OpaqueValueExpr *opaqueValue = nullptr;
6063   Expr *commonExpr = nullptr;
6064   if (!LHSExpr) {
6065     commonExpr = CondExpr;
6066     // Lower out placeholder types first.  This is important so that we don't
6067     // try to capture a placeholder. This happens in few cases in C++; such
6068     // as Objective-C++'s dictionary subscripting syntax.
6069     if (commonExpr->hasPlaceholderType()) {
6070       ExprResult result = CheckPlaceholderExpr(commonExpr);
6071       if (!result.isUsable()) return ExprError();
6072       commonExpr = result.get();
6073     }
6074     // We usually want to apply unary conversions *before* saving, except
6075     // in the special case of a C++ l-value conditional.
6076     if (!(getLangOpts().CPlusPlus
6077           && !commonExpr->isTypeDependent()
6078           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6079           && commonExpr->isGLValue()
6080           && commonExpr->isOrdinaryOrBitFieldObject()
6081           && RHSExpr->isOrdinaryOrBitFieldObject()
6082           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6083       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6084       if (commonRes.isInvalid())
6085         return ExprError();
6086       commonExpr = commonRes.get();
6087     }
6088 
6089     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6090                                                 commonExpr->getType(),
6091                                                 commonExpr->getValueKind(),
6092                                                 commonExpr->getObjectKind(),
6093                                                 commonExpr);
6094     LHSExpr = CondExpr = opaqueValue;
6095   }
6096 
6097   ExprValueKind VK = VK_RValue;
6098   ExprObjectKind OK = OK_Ordinary;
6099   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6100   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6101                                              VK, OK, QuestionLoc);
6102   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6103       RHS.isInvalid())
6104     return ExprError();
6105 
6106   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6107                                 RHS.get());
6108 
6109   if (!commonExpr)
6110     return new (Context)
6111         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6112                             RHS.get(), result, VK, OK);
6113 
6114   return new (Context) BinaryConditionalOperator(
6115       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6116       ColonLoc, result, VK, OK);
6117 }
6118 
6119 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6120 // being closely modeled after the C99 spec:-). The odd characteristic of this
6121 // routine is it effectively iqnores the qualifiers on the top level pointee.
6122 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6123 // FIXME: add a couple examples in this comment.
6124 static Sema::AssignConvertType
6125 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6126   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6127   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6128 
6129   // get the "pointed to" type (ignoring qualifiers at the top level)
6130   const Type *lhptee, *rhptee;
6131   Qualifiers lhq, rhq;
6132   std::tie(lhptee, lhq) =
6133       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6134   std::tie(rhptee, rhq) =
6135       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6136 
6137   Sema::AssignConvertType ConvTy = Sema::Compatible;
6138 
6139   // C99 6.5.16.1p1: This following citation is common to constraints
6140   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6141   // qualifiers of the type *pointed to* by the right;
6142 
6143   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6144   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6145       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6146     // Ignore lifetime for further calculation.
6147     lhq.removeObjCLifetime();
6148     rhq.removeObjCLifetime();
6149   }
6150 
6151   if (!lhq.compatiblyIncludes(rhq)) {
6152     // Treat address-space mismatches as fatal.  TODO: address subspaces
6153     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6154       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6155 
6156     // It's okay to add or remove GC or lifetime qualifiers when converting to
6157     // and from void*.
6158     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6159                         .compatiblyIncludes(
6160                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6161              && (lhptee->isVoidType() || rhptee->isVoidType()))
6162       ; // keep old
6163 
6164     // Treat lifetime mismatches as fatal.
6165     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6166       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6167 
6168     // For GCC compatibility, other qualifier mismatches are treated
6169     // as still compatible in C.
6170     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6171   }
6172 
6173   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6174   // incomplete type and the other is a pointer to a qualified or unqualified
6175   // version of void...
6176   if (lhptee->isVoidType()) {
6177     if (rhptee->isIncompleteOrObjectType())
6178       return ConvTy;
6179 
6180     // As an extension, we allow cast to/from void* to function pointer.
6181     assert(rhptee->isFunctionType());
6182     return Sema::FunctionVoidPointer;
6183   }
6184 
6185   if (rhptee->isVoidType()) {
6186     if (lhptee->isIncompleteOrObjectType())
6187       return ConvTy;
6188 
6189     // As an extension, we allow cast to/from void* to function pointer.
6190     assert(lhptee->isFunctionType());
6191     return Sema::FunctionVoidPointer;
6192   }
6193 
6194   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6195   // unqualified versions of compatible types, ...
6196   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6197   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6198     // Check if the pointee types are compatible ignoring the sign.
6199     // We explicitly check for char so that we catch "char" vs
6200     // "unsigned char" on systems where "char" is unsigned.
6201     if (lhptee->isCharType())
6202       ltrans = S.Context.UnsignedCharTy;
6203     else if (lhptee->hasSignedIntegerRepresentation())
6204       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6205 
6206     if (rhptee->isCharType())
6207       rtrans = S.Context.UnsignedCharTy;
6208     else if (rhptee->hasSignedIntegerRepresentation())
6209       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6210 
6211     if (ltrans == rtrans) {
6212       // Types are compatible ignoring the sign. Qualifier incompatibility
6213       // takes priority over sign incompatibility because the sign
6214       // warning can be disabled.
6215       if (ConvTy != Sema::Compatible)
6216         return ConvTy;
6217 
6218       return Sema::IncompatiblePointerSign;
6219     }
6220 
6221     // If we are a multi-level pointer, it's possible that our issue is simply
6222     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6223     // the eventual target type is the same and the pointers have the same
6224     // level of indirection, this must be the issue.
6225     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6226       do {
6227         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6228         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6229       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6230 
6231       if (lhptee == rhptee)
6232         return Sema::IncompatibleNestedPointerQualifiers;
6233     }
6234 
6235     // General pointer incompatibility takes priority over qualifiers.
6236     return Sema::IncompatiblePointer;
6237   }
6238   if (!S.getLangOpts().CPlusPlus &&
6239       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6240     return Sema::IncompatiblePointer;
6241   return ConvTy;
6242 }
6243 
6244 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6245 /// block pointer types are compatible or whether a block and normal pointer
6246 /// are compatible. It is more restrict than comparing two function pointer
6247 // types.
6248 static Sema::AssignConvertType
6249 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6250                                     QualType RHSType) {
6251   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6252   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6253 
6254   QualType lhptee, rhptee;
6255 
6256   // get the "pointed to" type (ignoring qualifiers at the top level)
6257   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6258   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6259 
6260   // In C++, the types have to match exactly.
6261   if (S.getLangOpts().CPlusPlus)
6262     return Sema::IncompatibleBlockPointer;
6263 
6264   Sema::AssignConvertType ConvTy = Sema::Compatible;
6265 
6266   // For blocks we enforce that qualifiers are identical.
6267   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6268     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6269 
6270   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6271     return Sema::IncompatibleBlockPointer;
6272 
6273   return ConvTy;
6274 }
6275 
6276 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6277 /// for assignment compatibility.
6278 static Sema::AssignConvertType
6279 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6280                                    QualType RHSType) {
6281   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6282   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6283 
6284   if (LHSType->isObjCBuiltinType()) {
6285     // Class is not compatible with ObjC object pointers.
6286     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6287         !RHSType->isObjCQualifiedClassType())
6288       return Sema::IncompatiblePointer;
6289     return Sema::Compatible;
6290   }
6291   if (RHSType->isObjCBuiltinType()) {
6292     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6293         !LHSType->isObjCQualifiedClassType())
6294       return Sema::IncompatiblePointer;
6295     return Sema::Compatible;
6296   }
6297   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6298   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6299 
6300   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6301       // make an exception for id<P>
6302       !LHSType->isObjCQualifiedIdType())
6303     return Sema::CompatiblePointerDiscardsQualifiers;
6304 
6305   if (S.Context.typesAreCompatible(LHSType, RHSType))
6306     return Sema::Compatible;
6307   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6308     return Sema::IncompatibleObjCQualifiedId;
6309   return Sema::IncompatiblePointer;
6310 }
6311 
6312 Sema::AssignConvertType
6313 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6314                                  QualType LHSType, QualType RHSType) {
6315   // Fake up an opaque expression.  We don't actually care about what
6316   // cast operations are required, so if CheckAssignmentConstraints
6317   // adds casts to this they'll be wasted, but fortunately that doesn't
6318   // usually happen on valid code.
6319   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6320   ExprResult RHSPtr = &RHSExpr;
6321   CastKind K = CK_Invalid;
6322 
6323   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6324 }
6325 
6326 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6327 /// has code to accommodate several GCC extensions when type checking
6328 /// pointers. Here are some objectionable examples that GCC considers warnings:
6329 ///
6330 ///  int a, *pint;
6331 ///  short *pshort;
6332 ///  struct foo *pfoo;
6333 ///
6334 ///  pint = pshort; // warning: assignment from incompatible pointer type
6335 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6336 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6337 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6338 ///
6339 /// As a result, the code for dealing with pointers is more complex than the
6340 /// C99 spec dictates.
6341 ///
6342 /// Sets 'Kind' for any result kind except Incompatible.
6343 Sema::AssignConvertType
6344 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6345                                  CastKind &Kind) {
6346   QualType RHSType = RHS.get()->getType();
6347   QualType OrigLHSType = LHSType;
6348 
6349   // Get canonical types.  We're not formatting these types, just comparing
6350   // them.
6351   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6352   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6353 
6354   // Common case: no conversion required.
6355   if (LHSType == RHSType) {
6356     Kind = CK_NoOp;
6357     return Compatible;
6358   }
6359 
6360   // If we have an atomic type, try a non-atomic assignment, then just add an
6361   // atomic qualification step.
6362   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6363     Sema::AssignConvertType result =
6364       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6365     if (result != Compatible)
6366       return result;
6367     if (Kind != CK_NoOp)
6368       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6369     Kind = CK_NonAtomicToAtomic;
6370     return Compatible;
6371   }
6372 
6373   // If the left-hand side is a reference type, then we are in a
6374   // (rare!) case where we've allowed the use of references in C,
6375   // e.g., as a parameter type in a built-in function. In this case,
6376   // just make sure that the type referenced is compatible with the
6377   // right-hand side type. The caller is responsible for adjusting
6378   // LHSType so that the resulting expression does not have reference
6379   // type.
6380   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6381     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6382       Kind = CK_LValueBitCast;
6383       return Compatible;
6384     }
6385     return Incompatible;
6386   }
6387 
6388   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6389   // to the same ExtVector type.
6390   if (LHSType->isExtVectorType()) {
6391     if (RHSType->isExtVectorType())
6392       return Incompatible;
6393     if (RHSType->isArithmeticType()) {
6394       // CK_VectorSplat does T -> vector T, so first cast to the
6395       // element type.
6396       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6397       if (elType != RHSType) {
6398         Kind = PrepareScalarCast(RHS, elType);
6399         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6400       }
6401       Kind = CK_VectorSplat;
6402       return Compatible;
6403     }
6404   }
6405 
6406   // Conversions to or from vector type.
6407   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6408     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6409       // Allow assignments of an AltiVec vector type to an equivalent GCC
6410       // vector type and vice versa
6411       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6412         Kind = CK_BitCast;
6413         return Compatible;
6414       }
6415 
6416       // If we are allowing lax vector conversions, and LHS and RHS are both
6417       // vectors, the total size only needs to be the same. This is a bitcast;
6418       // no bits are changed but the result type is different.
6419       if (isLaxVectorConversion(RHSType, LHSType)) {
6420         Kind = CK_BitCast;
6421         return IncompatibleVectors;
6422       }
6423     }
6424     return Incompatible;
6425   }
6426 
6427   // Arithmetic conversions.
6428   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6429       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6430     Kind = PrepareScalarCast(RHS, LHSType);
6431     return Compatible;
6432   }
6433 
6434   // Conversions to normal pointers.
6435   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6436     // U* -> T*
6437     if (isa<PointerType>(RHSType)) {
6438       Kind = CK_BitCast;
6439       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6440     }
6441 
6442     // int -> T*
6443     if (RHSType->isIntegerType()) {
6444       Kind = CK_IntegralToPointer; // FIXME: null?
6445       return IntToPointer;
6446     }
6447 
6448     // C pointers are not compatible with ObjC object pointers,
6449     // with two exceptions:
6450     if (isa<ObjCObjectPointerType>(RHSType)) {
6451       //  - conversions to void*
6452       if (LHSPointer->getPointeeType()->isVoidType()) {
6453         Kind = CK_BitCast;
6454         return Compatible;
6455       }
6456 
6457       //  - conversions from 'Class' to the redefinition type
6458       if (RHSType->isObjCClassType() &&
6459           Context.hasSameType(LHSType,
6460                               Context.getObjCClassRedefinitionType())) {
6461         Kind = CK_BitCast;
6462         return Compatible;
6463       }
6464 
6465       Kind = CK_BitCast;
6466       return IncompatiblePointer;
6467     }
6468 
6469     // U^ -> void*
6470     if (RHSType->getAs<BlockPointerType>()) {
6471       if (LHSPointer->getPointeeType()->isVoidType()) {
6472         Kind = CK_BitCast;
6473         return Compatible;
6474       }
6475     }
6476 
6477     return Incompatible;
6478   }
6479 
6480   // Conversions to block pointers.
6481   if (isa<BlockPointerType>(LHSType)) {
6482     // U^ -> T^
6483     if (RHSType->isBlockPointerType()) {
6484       Kind = CK_BitCast;
6485       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6486     }
6487 
6488     // int or null -> T^
6489     if (RHSType->isIntegerType()) {
6490       Kind = CK_IntegralToPointer; // FIXME: null
6491       return IntToBlockPointer;
6492     }
6493 
6494     // id -> T^
6495     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6496       Kind = CK_AnyPointerToBlockPointerCast;
6497       return Compatible;
6498     }
6499 
6500     // void* -> T^
6501     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6502       if (RHSPT->getPointeeType()->isVoidType()) {
6503         Kind = CK_AnyPointerToBlockPointerCast;
6504         return Compatible;
6505       }
6506 
6507     return Incompatible;
6508   }
6509 
6510   // Conversions to Objective-C pointers.
6511   if (isa<ObjCObjectPointerType>(LHSType)) {
6512     // A* -> B*
6513     if (RHSType->isObjCObjectPointerType()) {
6514       Kind = CK_BitCast;
6515       Sema::AssignConvertType result =
6516         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6517       if (getLangOpts().ObjCAutoRefCount &&
6518           result == Compatible &&
6519           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6520         result = IncompatibleObjCWeakRef;
6521       return result;
6522     }
6523 
6524     // int or null -> A*
6525     if (RHSType->isIntegerType()) {
6526       Kind = CK_IntegralToPointer; // FIXME: null
6527       return IntToPointer;
6528     }
6529 
6530     // In general, C pointers are not compatible with ObjC object pointers,
6531     // with two exceptions:
6532     if (isa<PointerType>(RHSType)) {
6533       Kind = CK_CPointerToObjCPointerCast;
6534 
6535       //  - conversions from 'void*'
6536       if (RHSType->isVoidPointerType()) {
6537         return Compatible;
6538       }
6539 
6540       //  - conversions to 'Class' from its redefinition type
6541       if (LHSType->isObjCClassType() &&
6542           Context.hasSameType(RHSType,
6543                               Context.getObjCClassRedefinitionType())) {
6544         return Compatible;
6545       }
6546 
6547       return IncompatiblePointer;
6548     }
6549 
6550     // Only under strict condition T^ is compatible with an Objective-C pointer.
6551     if (RHSType->isBlockPointerType() &&
6552         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6553       maybeExtendBlockObject(*this, RHS);
6554       Kind = CK_BlockPointerToObjCPointerCast;
6555       return Compatible;
6556     }
6557 
6558     return Incompatible;
6559   }
6560 
6561   // Conversions from pointers that are not covered by the above.
6562   if (isa<PointerType>(RHSType)) {
6563     // T* -> _Bool
6564     if (LHSType == Context.BoolTy) {
6565       Kind = CK_PointerToBoolean;
6566       return Compatible;
6567     }
6568 
6569     // T* -> int
6570     if (LHSType->isIntegerType()) {
6571       Kind = CK_PointerToIntegral;
6572       return PointerToInt;
6573     }
6574 
6575     return Incompatible;
6576   }
6577 
6578   // Conversions from Objective-C pointers that are not covered by the above.
6579   if (isa<ObjCObjectPointerType>(RHSType)) {
6580     // T* -> _Bool
6581     if (LHSType == Context.BoolTy) {
6582       Kind = CK_PointerToBoolean;
6583       return Compatible;
6584     }
6585 
6586     // T* -> int
6587     if (LHSType->isIntegerType()) {
6588       Kind = CK_PointerToIntegral;
6589       return PointerToInt;
6590     }
6591 
6592     return Incompatible;
6593   }
6594 
6595   // struct A -> struct B
6596   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6597     if (Context.typesAreCompatible(LHSType, RHSType)) {
6598       Kind = CK_NoOp;
6599       return Compatible;
6600     }
6601   }
6602 
6603   return Incompatible;
6604 }
6605 
6606 /// \brief Constructs a transparent union from an expression that is
6607 /// used to initialize the transparent union.
6608 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6609                                       ExprResult &EResult, QualType UnionType,
6610                                       FieldDecl *Field) {
6611   // Build an initializer list that designates the appropriate member
6612   // of the transparent union.
6613   Expr *E = EResult.get();
6614   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6615                                                    E, SourceLocation());
6616   Initializer->setType(UnionType);
6617   Initializer->setInitializedFieldInUnion(Field);
6618 
6619   // Build a compound literal constructing a value of the transparent
6620   // union type from this initializer list.
6621   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6622   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6623                                         VK_RValue, Initializer, false);
6624 }
6625 
6626 Sema::AssignConvertType
6627 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6628                                                ExprResult &RHS) {
6629   QualType RHSType = RHS.get()->getType();
6630 
6631   // If the ArgType is a Union type, we want to handle a potential
6632   // transparent_union GCC extension.
6633   const RecordType *UT = ArgType->getAsUnionType();
6634   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6635     return Incompatible;
6636 
6637   // The field to initialize within the transparent union.
6638   RecordDecl *UD = UT->getDecl();
6639   FieldDecl *InitField = nullptr;
6640   // It's compatible if the expression matches any of the fields.
6641   for (auto *it : UD->fields()) {
6642     if (it->getType()->isPointerType()) {
6643       // If the transparent union contains a pointer type, we allow:
6644       // 1) void pointer
6645       // 2) null pointer constant
6646       if (RHSType->isPointerType())
6647         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6648           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6649           InitField = it;
6650           break;
6651         }
6652 
6653       if (RHS.get()->isNullPointerConstant(Context,
6654                                            Expr::NPC_ValueDependentIsNull)) {
6655         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6656                                 CK_NullToPointer);
6657         InitField = it;
6658         break;
6659       }
6660     }
6661 
6662     CastKind Kind = CK_Invalid;
6663     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6664           == Compatible) {
6665       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6666       InitField = it;
6667       break;
6668     }
6669   }
6670 
6671   if (!InitField)
6672     return Incompatible;
6673 
6674   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6675   return Compatible;
6676 }
6677 
6678 Sema::AssignConvertType
6679 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6680                                        bool Diagnose,
6681                                        bool DiagnoseCFAudited) {
6682   if (getLangOpts().CPlusPlus) {
6683     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6684       // C++ 5.17p3: If the left operand is not of class type, the
6685       // expression is implicitly converted (C++ 4) to the
6686       // cv-unqualified type of the left operand.
6687       ExprResult Res;
6688       if (Diagnose) {
6689         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6690                                         AA_Assigning);
6691       } else {
6692         ImplicitConversionSequence ICS =
6693             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6694                                   /*SuppressUserConversions=*/false,
6695                                   /*AllowExplicit=*/false,
6696                                   /*InOverloadResolution=*/false,
6697                                   /*CStyle=*/false,
6698                                   /*AllowObjCWritebackConversion=*/false);
6699         if (ICS.isFailure())
6700           return Incompatible;
6701         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6702                                         ICS, AA_Assigning);
6703       }
6704       if (Res.isInvalid())
6705         return Incompatible;
6706       Sema::AssignConvertType result = Compatible;
6707       if (getLangOpts().ObjCAutoRefCount &&
6708           !CheckObjCARCUnavailableWeakConversion(LHSType,
6709                                                  RHS.get()->getType()))
6710         result = IncompatibleObjCWeakRef;
6711       RHS = Res;
6712       return result;
6713     }
6714 
6715     // FIXME: Currently, we fall through and treat C++ classes like C
6716     // structures.
6717     // FIXME: We also fall through for atomics; not sure what should
6718     // happen there, though.
6719   }
6720 
6721   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6722   // a null pointer constant.
6723   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6724        LHSType->isBlockPointerType()) &&
6725       RHS.get()->isNullPointerConstant(Context,
6726                                        Expr::NPC_ValueDependentIsNull)) {
6727     CastKind Kind;
6728     CXXCastPath Path;
6729     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6730     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6731     return Compatible;
6732   }
6733 
6734   // This check seems unnatural, however it is necessary to ensure the proper
6735   // conversion of functions/arrays. If the conversion were done for all
6736   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6737   // expressions that suppress this implicit conversion (&, sizeof).
6738   //
6739   // Suppress this for references: C++ 8.5.3p5.
6740   if (!LHSType->isReferenceType()) {
6741     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6742     if (RHS.isInvalid())
6743       return Incompatible;
6744   }
6745 
6746   Expr *PRE = RHS.get()->IgnoreParenCasts();
6747   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
6748     ObjCProtocolDecl *PDecl = OPE->getProtocol();
6749     if (PDecl && !PDecl->hasDefinition()) {
6750       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
6751       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
6752     }
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->parameters()[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                                                ExprObjectKind &OK,
8756                                                SourceLocation OpLoc,
8757                                                bool IsInc, bool IsPrefix) {
8758   if (Op->isTypeDependent())
8759     return S.Context.DependentTy;
8760 
8761   QualType ResType = Op->getType();
8762   // Atomic types can be used for increment / decrement where the non-atomic
8763   // versions can, so ignore the _Atomic() specifier for the purpose of
8764   // checking.
8765   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8766     ResType = ResAtomicType->getValueType();
8767 
8768   assert(!ResType.isNull() && "no type for increment/decrement expression");
8769 
8770   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8771     // Decrement of bool is not allowed.
8772     if (!IsInc) {
8773       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8774       return QualType();
8775     }
8776     // Increment of bool sets it to true, but is deprecated.
8777     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8778   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8779     // Error on enum increments and decrements in C++ mode
8780     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8781     return QualType();
8782   } else if (ResType->isRealType()) {
8783     // OK!
8784   } else if (ResType->isPointerType()) {
8785     // C99 6.5.2.4p2, 6.5.6p2
8786     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8787       return QualType();
8788   } else if (ResType->isObjCObjectPointerType()) {
8789     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8790     // Otherwise, we just need a complete type.
8791     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8792         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8793       return QualType();
8794   } else if (ResType->isAnyComplexType()) {
8795     // C99 does not support ++/-- on complex types, we allow as an extension.
8796     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8797       << ResType << Op->getSourceRange();
8798   } else if (ResType->isPlaceholderType()) {
8799     ExprResult PR = S.CheckPlaceholderExpr(Op);
8800     if (PR.isInvalid()) return QualType();
8801     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
8802                                           IsInc, IsPrefix);
8803   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8804     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8805   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8806             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8807     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8808   } else {
8809     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8810       << ResType << int(IsInc) << Op->getSourceRange();
8811     return QualType();
8812   }
8813   // At this point, we know we have a real, complex or pointer type.
8814   // Now make sure the operand is a modifiable lvalue.
8815   if (CheckForModifiableLvalue(Op, OpLoc, S))
8816     return QualType();
8817   // In C++, a prefix increment is the same type as the operand. Otherwise
8818   // (in C or with postfix), the increment is the unqualified type of the
8819   // operand.
8820   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8821     VK = VK_LValue;
8822     OK = Op->getObjectKind();
8823     return ResType;
8824   } else {
8825     VK = VK_RValue;
8826     return ResType.getUnqualifiedType();
8827   }
8828 }
8829 
8830 
8831 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8832 /// This routine allows us to typecheck complex/recursive expressions
8833 /// where the declaration is needed for type checking. We only need to
8834 /// handle cases when the expression references a function designator
8835 /// or is an lvalue. Here are some examples:
8836 ///  - &(x) => x
8837 ///  - &*****f => f for f a function designator.
8838 ///  - &s.xx => s
8839 ///  - &s.zz[1].yy -> s, if zz is an array
8840 ///  - *(x + 1) -> x, if x is an array
8841 ///  - &"123"[2] -> 0
8842 ///  - & __real__ x -> x
8843 static ValueDecl *getPrimaryDecl(Expr *E) {
8844   switch (E->getStmtClass()) {
8845   case Stmt::DeclRefExprClass:
8846     return cast<DeclRefExpr>(E)->getDecl();
8847   case Stmt::MemberExprClass:
8848     // If this is an arrow operator, the address is an offset from
8849     // the base's value, so the object the base refers to is
8850     // irrelevant.
8851     if (cast<MemberExpr>(E)->isArrow())
8852       return nullptr;
8853     // Otherwise, the expression refers to a part of the base
8854     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8855   case Stmt::ArraySubscriptExprClass: {
8856     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8857     // promotion of register arrays earlier.
8858     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8859     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8860       if (ICE->getSubExpr()->getType()->isArrayType())
8861         return getPrimaryDecl(ICE->getSubExpr());
8862     }
8863     return nullptr;
8864   }
8865   case Stmt::UnaryOperatorClass: {
8866     UnaryOperator *UO = cast<UnaryOperator>(E);
8867 
8868     switch(UO->getOpcode()) {
8869     case UO_Real:
8870     case UO_Imag:
8871     case UO_Extension:
8872       return getPrimaryDecl(UO->getSubExpr());
8873     default:
8874       return nullptr;
8875     }
8876   }
8877   case Stmt::ParenExprClass:
8878     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8879   case Stmt::ImplicitCastExprClass:
8880     // If the result of an implicit cast is an l-value, we care about
8881     // the sub-expression; otherwise, the result here doesn't matter.
8882     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8883   default:
8884     return nullptr;
8885   }
8886 }
8887 
8888 namespace {
8889   enum {
8890     AO_Bit_Field = 0,
8891     AO_Vector_Element = 1,
8892     AO_Property_Expansion = 2,
8893     AO_Register_Variable = 3,
8894     AO_No_Error = 4
8895   };
8896 }
8897 /// \brief Diagnose invalid operand for address of operations.
8898 ///
8899 /// \param Type The type of operand which cannot have its address taken.
8900 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8901                                          Expr *E, unsigned Type) {
8902   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8903 }
8904 
8905 /// CheckAddressOfOperand - The operand of & must be either a function
8906 /// designator or an lvalue designating an object. If it is an lvalue, the
8907 /// object cannot be declared with storage class register or be a bit field.
8908 /// Note: The usual conversions are *not* applied to the operand of the &
8909 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8910 /// In C++, the operand might be an overloaded function name, in which case
8911 /// we allow the '&' but retain the overloaded-function type.
8912 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8913   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8914     if (PTy->getKind() == BuiltinType::Overload) {
8915       Expr *E = OrigOp.get()->IgnoreParens();
8916       if (!isa<OverloadExpr>(E)) {
8917         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8918         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8919           << OrigOp.get()->getSourceRange();
8920         return QualType();
8921       }
8922 
8923       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8924       if (isa<UnresolvedMemberExpr>(Ovl))
8925         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8926           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8927             << OrigOp.get()->getSourceRange();
8928           return QualType();
8929         }
8930 
8931       return Context.OverloadTy;
8932     }
8933 
8934     if (PTy->getKind() == BuiltinType::UnknownAny)
8935       return Context.UnknownAnyTy;
8936 
8937     if (PTy->getKind() == BuiltinType::BoundMember) {
8938       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8939         << OrigOp.get()->getSourceRange();
8940       return QualType();
8941     }
8942 
8943     OrigOp = CheckPlaceholderExpr(OrigOp.get());
8944     if (OrigOp.isInvalid()) return QualType();
8945   }
8946 
8947   if (OrigOp.get()->isTypeDependent())
8948     return Context.DependentTy;
8949 
8950   assert(!OrigOp.get()->getType()->isPlaceholderType());
8951 
8952   // Make sure to ignore parentheses in subsequent checks
8953   Expr *op = OrigOp.get()->IgnoreParens();
8954 
8955   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8956   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8957     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8958     return QualType();
8959   }
8960 
8961   if (getLangOpts().C99) {
8962     // Implement C99-only parts of addressof rules.
8963     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8964       if (uOp->getOpcode() == UO_Deref)
8965         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8966         // (assuming the deref expression is valid).
8967         return uOp->getSubExpr()->getType();
8968     }
8969     // Technically, there should be a check for array subscript
8970     // expressions here, but the result of one is always an lvalue anyway.
8971   }
8972   ValueDecl *dcl = getPrimaryDecl(op);
8973   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8974   unsigned AddressOfError = AO_No_Error;
8975 
8976   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8977     bool sfinae = (bool)isSFINAEContext();
8978     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8979                                   : diag::ext_typecheck_addrof_temporary)
8980       << op->getType() << op->getSourceRange();
8981     if (sfinae)
8982       return QualType();
8983     // Materialize the temporary as an lvalue so that we can take its address.
8984     OrigOp = op = new (Context)
8985         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
8986   } else if (isa<ObjCSelectorExpr>(op)) {
8987     return Context.getPointerType(op->getType());
8988   } else if (lval == Expr::LV_MemberFunction) {
8989     // If it's an instance method, make a member pointer.
8990     // The expression must have exactly the form &A::foo.
8991 
8992     // If the underlying expression isn't a decl ref, give up.
8993     if (!isa<DeclRefExpr>(op)) {
8994       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8995         << OrigOp.get()->getSourceRange();
8996       return QualType();
8997     }
8998     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8999     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9000 
9001     // The id-expression was parenthesized.
9002     if (OrigOp.get() != DRE) {
9003       Diag(OpLoc, diag::err_parens_pointer_member_function)
9004         << OrigOp.get()->getSourceRange();
9005 
9006     // The method was named without a qualifier.
9007     } else if (!DRE->getQualifier()) {
9008       if (MD->getParent()->getName().empty())
9009         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9010           << op->getSourceRange();
9011       else {
9012         SmallString<32> Str;
9013         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9014         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9015           << op->getSourceRange()
9016           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9017       }
9018     }
9019 
9020     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9021     if (isa<CXXDestructorDecl>(MD))
9022       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9023 
9024     QualType MPTy = Context.getMemberPointerType(
9025         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9026     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9027       RequireCompleteType(OpLoc, MPTy, 0);
9028     return MPTy;
9029   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9030     // C99 6.5.3.2p1
9031     // The operand must be either an l-value or a function designator
9032     if (!op->getType()->isFunctionType()) {
9033       // Use a special diagnostic for loads from property references.
9034       if (isa<PseudoObjectExpr>(op)) {
9035         AddressOfError = AO_Property_Expansion;
9036       } else {
9037         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9038           << op->getType() << op->getSourceRange();
9039         return QualType();
9040       }
9041     }
9042   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9043     // The operand cannot be a bit-field
9044     AddressOfError = AO_Bit_Field;
9045   } else if (op->getObjectKind() == OK_VectorComponent) {
9046     // The operand cannot be an element of a vector
9047     AddressOfError = AO_Vector_Element;
9048   } else if (dcl) { // C99 6.5.3.2p1
9049     // We have an lvalue with a decl. Make sure the decl is not declared
9050     // with the register storage-class specifier.
9051     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9052       // in C++ it is not error to take address of a register
9053       // variable (c++03 7.1.1P3)
9054       if (vd->getStorageClass() == SC_Register &&
9055           !getLangOpts().CPlusPlus) {
9056         AddressOfError = AO_Register_Variable;
9057       }
9058     } else if (isa<FunctionTemplateDecl>(dcl)) {
9059       return Context.OverloadTy;
9060     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9061       // Okay: we can take the address of a field.
9062       // Could be a pointer to member, though, if there is an explicit
9063       // scope qualifier for the class.
9064       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9065         DeclContext *Ctx = dcl->getDeclContext();
9066         if (Ctx && Ctx->isRecord()) {
9067           if (dcl->getType()->isReferenceType()) {
9068             Diag(OpLoc,
9069                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9070               << dcl->getDeclName() << dcl->getType();
9071             return QualType();
9072           }
9073 
9074           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9075             Ctx = Ctx->getParent();
9076 
9077           QualType MPTy = Context.getMemberPointerType(
9078               op->getType(),
9079               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9080           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9081             RequireCompleteType(OpLoc, MPTy, 0);
9082           return MPTy;
9083         }
9084       }
9085     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9086       llvm_unreachable("Unknown/unexpected decl type");
9087   }
9088 
9089   if (AddressOfError != AO_No_Error) {
9090     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9091     return QualType();
9092   }
9093 
9094   if (lval == Expr::LV_IncompleteVoidType) {
9095     // Taking the address of a void variable is technically illegal, but we
9096     // allow it in cases which are otherwise valid.
9097     // Example: "extern void x; void* y = &x;".
9098     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9099   }
9100 
9101   // If the operand has type "type", the result has type "pointer to type".
9102   if (op->getType()->isObjCObjectType())
9103     return Context.getObjCObjectPointerType(op->getType());
9104   return Context.getPointerType(op->getType());
9105 }
9106 
9107 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9108 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9109                                         SourceLocation OpLoc) {
9110   if (Op->isTypeDependent())
9111     return S.Context.DependentTy;
9112 
9113   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9114   if (ConvResult.isInvalid())
9115     return QualType();
9116   Op = ConvResult.get();
9117   QualType OpTy = Op->getType();
9118   QualType Result;
9119 
9120   if (isa<CXXReinterpretCastExpr>(Op)) {
9121     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9122     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9123                                      Op->getSourceRange());
9124   }
9125 
9126   if (const PointerType *PT = OpTy->getAs<PointerType>())
9127     Result = PT->getPointeeType();
9128   else if (const ObjCObjectPointerType *OPT =
9129              OpTy->getAs<ObjCObjectPointerType>())
9130     Result = OPT->getPointeeType();
9131   else {
9132     ExprResult PR = S.CheckPlaceholderExpr(Op);
9133     if (PR.isInvalid()) return QualType();
9134     if (PR.get() != Op)
9135       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9136   }
9137 
9138   if (Result.isNull()) {
9139     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9140       << OpTy << Op->getSourceRange();
9141     return QualType();
9142   }
9143 
9144   // Note that per both C89 and C99, indirection is always legal, even if Result
9145   // is an incomplete type or void.  It would be possible to warn about
9146   // dereferencing a void pointer, but it's completely well-defined, and such a
9147   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9148   // for pointers to 'void' but is fine for any other pointer type:
9149   //
9150   // C++ [expr.unary.op]p1:
9151   //   [...] the expression to which [the unary * operator] is applied shall
9152   //   be a pointer to an object type, or a pointer to a function type
9153   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9154     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9155       << OpTy << Op->getSourceRange();
9156 
9157   // Dereferences are usually l-values...
9158   VK = VK_LValue;
9159 
9160   // ...except that certain expressions are never l-values in C.
9161   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9162     VK = VK_RValue;
9163 
9164   return Result;
9165 }
9166 
9167 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9168   tok::TokenKind Kind) {
9169   BinaryOperatorKind Opc;
9170   switch (Kind) {
9171   default: llvm_unreachable("Unknown binop!");
9172   case tok::periodstar:           Opc = BO_PtrMemD; break;
9173   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9174   case tok::star:                 Opc = BO_Mul; break;
9175   case tok::slash:                Opc = BO_Div; break;
9176   case tok::percent:              Opc = BO_Rem; break;
9177   case tok::plus:                 Opc = BO_Add; break;
9178   case tok::minus:                Opc = BO_Sub; break;
9179   case tok::lessless:             Opc = BO_Shl; break;
9180   case tok::greatergreater:       Opc = BO_Shr; break;
9181   case tok::lessequal:            Opc = BO_LE; break;
9182   case tok::less:                 Opc = BO_LT; break;
9183   case tok::greaterequal:         Opc = BO_GE; break;
9184   case tok::greater:              Opc = BO_GT; break;
9185   case tok::exclaimequal:         Opc = BO_NE; break;
9186   case tok::equalequal:           Opc = BO_EQ; break;
9187   case tok::amp:                  Opc = BO_And; break;
9188   case tok::caret:                Opc = BO_Xor; break;
9189   case tok::pipe:                 Opc = BO_Or; break;
9190   case tok::ampamp:               Opc = BO_LAnd; break;
9191   case tok::pipepipe:             Opc = BO_LOr; break;
9192   case tok::equal:                Opc = BO_Assign; break;
9193   case tok::starequal:            Opc = BO_MulAssign; break;
9194   case tok::slashequal:           Opc = BO_DivAssign; break;
9195   case tok::percentequal:         Opc = BO_RemAssign; break;
9196   case tok::plusequal:            Opc = BO_AddAssign; break;
9197   case tok::minusequal:           Opc = BO_SubAssign; break;
9198   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9199   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9200   case tok::ampequal:             Opc = BO_AndAssign; break;
9201   case tok::caretequal:           Opc = BO_XorAssign; break;
9202   case tok::pipeequal:            Opc = BO_OrAssign; break;
9203   case tok::comma:                Opc = BO_Comma; break;
9204   }
9205   return Opc;
9206 }
9207 
9208 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9209   tok::TokenKind Kind) {
9210   UnaryOperatorKind Opc;
9211   switch (Kind) {
9212   default: llvm_unreachable("Unknown unary op!");
9213   case tok::plusplus:     Opc = UO_PreInc; break;
9214   case tok::minusminus:   Opc = UO_PreDec; break;
9215   case tok::amp:          Opc = UO_AddrOf; break;
9216   case tok::star:         Opc = UO_Deref; break;
9217   case tok::plus:         Opc = UO_Plus; break;
9218   case tok::minus:        Opc = UO_Minus; break;
9219   case tok::tilde:        Opc = UO_Not; break;
9220   case tok::exclaim:      Opc = UO_LNot; break;
9221   case tok::kw___real:    Opc = UO_Real; break;
9222   case tok::kw___imag:    Opc = UO_Imag; break;
9223   case tok::kw___extension__: Opc = UO_Extension; break;
9224   }
9225   return Opc;
9226 }
9227 
9228 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9229 /// This warning is only emitted for builtin assignment operations. It is also
9230 /// suppressed in the event of macro expansions.
9231 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9232                                    SourceLocation OpLoc) {
9233   if (!S.ActiveTemplateInstantiations.empty())
9234     return;
9235   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9236     return;
9237   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9238   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9239   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9240   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9241   if (!LHSDeclRef || !RHSDeclRef ||
9242       LHSDeclRef->getLocation().isMacroID() ||
9243       RHSDeclRef->getLocation().isMacroID())
9244     return;
9245   const ValueDecl *LHSDecl =
9246     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9247   const ValueDecl *RHSDecl =
9248     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9249   if (LHSDecl != RHSDecl)
9250     return;
9251   if (LHSDecl->getType().isVolatileQualified())
9252     return;
9253   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9254     if (RefTy->getPointeeType().isVolatileQualified())
9255       return;
9256 
9257   S.Diag(OpLoc, diag::warn_self_assignment)
9258       << LHSDeclRef->getType()
9259       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9260 }
9261 
9262 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9263 /// is usually indicative of introspection within the Objective-C pointer.
9264 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9265                                           SourceLocation OpLoc) {
9266   if (!S.getLangOpts().ObjC1)
9267     return;
9268 
9269   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9270   const Expr *LHS = L.get();
9271   const Expr *RHS = R.get();
9272 
9273   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9274     ObjCPointerExpr = LHS;
9275     OtherExpr = RHS;
9276   }
9277   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9278     ObjCPointerExpr = RHS;
9279     OtherExpr = LHS;
9280   }
9281 
9282   // This warning is deliberately made very specific to reduce false
9283   // positives with logic that uses '&' for hashing.  This logic mainly
9284   // looks for code trying to introspect into tagged pointers, which
9285   // code should generally never do.
9286   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9287     unsigned Diag = diag::warn_objc_pointer_masking;
9288     // Determine if we are introspecting the result of performSelectorXXX.
9289     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9290     // Special case messages to -performSelector and friends, which
9291     // can return non-pointer values boxed in a pointer value.
9292     // Some clients may wish to silence warnings in this subcase.
9293     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9294       Selector S = ME->getSelector();
9295       StringRef SelArg0 = S.getNameForSlot(0);
9296       if (SelArg0.startswith("performSelector"))
9297         Diag = diag::warn_objc_pointer_masking_performSelector;
9298     }
9299 
9300     S.Diag(OpLoc, Diag)
9301       << ObjCPointerExpr->getSourceRange();
9302   }
9303 }
9304 
9305 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9306 /// operator @p Opc at location @c TokLoc. This routine only supports
9307 /// built-in operations; ActOnBinOp handles overloaded operators.
9308 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9309                                     BinaryOperatorKind Opc,
9310                                     Expr *LHSExpr, Expr *RHSExpr) {
9311   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9312     // The syntax only allows initializer lists on the RHS of assignment,
9313     // so we don't need to worry about accepting invalid code for
9314     // non-assignment operators.
9315     // C++11 5.17p9:
9316     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9317     //   of x = {} is x = T().
9318     InitializationKind Kind =
9319         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9320     InitializedEntity Entity =
9321         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9322     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9323     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9324     if (Init.isInvalid())
9325       return Init;
9326     RHSExpr = Init.get();
9327   }
9328 
9329   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9330   QualType ResultTy;     // Result type of the binary operator.
9331   // The following two variables are used for compound assignment operators
9332   QualType CompLHSTy;    // Type of LHS after promotions for computation
9333   QualType CompResultTy; // Type of computation result
9334   ExprValueKind VK = VK_RValue;
9335   ExprObjectKind OK = OK_Ordinary;
9336 
9337   switch (Opc) {
9338   case BO_Assign:
9339     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9340     if (getLangOpts().CPlusPlus &&
9341         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9342       VK = LHS.get()->getValueKind();
9343       OK = LHS.get()->getObjectKind();
9344     }
9345     if (!ResultTy.isNull())
9346       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9347     break;
9348   case BO_PtrMemD:
9349   case BO_PtrMemI:
9350     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9351                                             Opc == BO_PtrMemI);
9352     break;
9353   case BO_Mul:
9354   case BO_Div:
9355     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9356                                            Opc == BO_Div);
9357     break;
9358   case BO_Rem:
9359     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9360     break;
9361   case BO_Add:
9362     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9363     break;
9364   case BO_Sub:
9365     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9366     break;
9367   case BO_Shl:
9368   case BO_Shr:
9369     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9370     break;
9371   case BO_LE:
9372   case BO_LT:
9373   case BO_GE:
9374   case BO_GT:
9375     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9376     break;
9377   case BO_EQ:
9378   case BO_NE:
9379     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9380     break;
9381   case BO_And:
9382     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9383   case BO_Xor:
9384   case BO_Or:
9385     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9386     break;
9387   case BO_LAnd:
9388   case BO_LOr:
9389     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9390     break;
9391   case BO_MulAssign:
9392   case BO_DivAssign:
9393     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9394                                                Opc == BO_DivAssign);
9395     CompLHSTy = CompResultTy;
9396     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9397       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9398     break;
9399   case BO_RemAssign:
9400     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9401     CompLHSTy = CompResultTy;
9402     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9403       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9404     break;
9405   case BO_AddAssign:
9406     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9407     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9408       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9409     break;
9410   case BO_SubAssign:
9411     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9412     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9413       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9414     break;
9415   case BO_ShlAssign:
9416   case BO_ShrAssign:
9417     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9418     CompLHSTy = CompResultTy;
9419     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9420       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9421     break;
9422   case BO_AndAssign:
9423   case BO_OrAssign: // fallthrough
9424 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9425   case BO_XorAssign:
9426     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9427     CompLHSTy = CompResultTy;
9428     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9429       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9430     break;
9431   case BO_Comma:
9432     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9433     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9434       VK = RHS.get()->getValueKind();
9435       OK = RHS.get()->getObjectKind();
9436     }
9437     break;
9438   }
9439   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9440     return ExprError();
9441 
9442   // Check for array bounds violations for both sides of the BinaryOperator
9443   CheckArrayAccess(LHS.get());
9444   CheckArrayAccess(RHS.get());
9445 
9446   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9447     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9448                                                  &Context.Idents.get("object_setClass"),
9449                                                  SourceLocation(), LookupOrdinaryName);
9450     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9451       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9452       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9453       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9454       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9455       FixItHint::CreateInsertion(RHSLocEnd, ")");
9456     }
9457     else
9458       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9459   }
9460   else if (const ObjCIvarRefExpr *OIRE =
9461            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9462     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9463 
9464   if (CompResultTy.isNull())
9465     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9466                                         OK, OpLoc, FPFeatures.fp_contract);
9467   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9468       OK_ObjCProperty) {
9469     VK = VK_LValue;
9470     OK = LHS.get()->getObjectKind();
9471   }
9472   return new (Context) CompoundAssignOperator(
9473       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9474       OpLoc, FPFeatures.fp_contract);
9475 }
9476 
9477 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9478 /// operators are mixed in a way that suggests that the programmer forgot that
9479 /// comparison operators have higher precedence. The most typical example of
9480 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9481 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9482                                       SourceLocation OpLoc, Expr *LHSExpr,
9483                                       Expr *RHSExpr) {
9484   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9485   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9486 
9487   // Check that one of the sides is a comparison operator.
9488   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9489   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9490   if (!isLeftComp && !isRightComp)
9491     return;
9492 
9493   // Bitwise operations are sometimes used as eager logical ops.
9494   // Don't diagnose this.
9495   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9496   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9497   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9498     return;
9499 
9500   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9501                                                    OpLoc)
9502                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9503   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9504   SourceRange ParensRange = isLeftComp ?
9505       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9506     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
9507 
9508   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9509     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9510   SuggestParentheses(Self, OpLoc,
9511     Self.PDiag(diag::note_precedence_silence) << OpStr,
9512     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9513   SuggestParentheses(Self, OpLoc,
9514     Self.PDiag(diag::note_precedence_bitwise_first)
9515       << BinaryOperator::getOpcodeStr(Opc),
9516     ParensRange);
9517 }
9518 
9519 /// \brief It accepts a '&' expr that is inside a '|' one.
9520 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9521 /// in parentheses.
9522 static void
9523 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9524                                        BinaryOperator *Bop) {
9525   assert(Bop->getOpcode() == BO_And);
9526   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9527       << Bop->getSourceRange() << OpLoc;
9528   SuggestParentheses(Self, Bop->getOperatorLoc(),
9529     Self.PDiag(diag::note_precedence_silence)
9530       << Bop->getOpcodeStr(),
9531     Bop->getSourceRange());
9532 }
9533 
9534 /// \brief It accepts a '&&' expr that is inside a '||' one.
9535 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9536 /// in parentheses.
9537 static void
9538 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9539                                        BinaryOperator *Bop) {
9540   assert(Bop->getOpcode() == BO_LAnd);
9541   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9542       << Bop->getSourceRange() << OpLoc;
9543   SuggestParentheses(Self, Bop->getOperatorLoc(),
9544     Self.PDiag(diag::note_precedence_silence)
9545       << Bop->getOpcodeStr(),
9546     Bop->getSourceRange());
9547 }
9548 
9549 /// \brief Returns true if the given expression can be evaluated as a constant
9550 /// 'true'.
9551 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9552   bool Res;
9553   return !E->isValueDependent() &&
9554          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9555 }
9556 
9557 /// \brief Returns true if the given expression can be evaluated as a constant
9558 /// 'false'.
9559 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9560   bool Res;
9561   return !E->isValueDependent() &&
9562          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9563 }
9564 
9565 /// \brief Look for '&&' in the left hand of a '||' expr.
9566 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9567                                              Expr *LHSExpr, Expr *RHSExpr) {
9568   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9569     if (Bop->getOpcode() == BO_LAnd) {
9570       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9571       if (EvaluatesAsFalse(S, RHSExpr))
9572         return;
9573       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9574       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9575         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9576     } else if (Bop->getOpcode() == BO_LOr) {
9577       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9578         // If it's "a || b && 1 || c" we didn't warn earlier for
9579         // "a || b && 1", but warn now.
9580         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9581           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9582       }
9583     }
9584   }
9585 }
9586 
9587 /// \brief Look for '&&' in the right hand of a '||' expr.
9588 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9589                                              Expr *LHSExpr, Expr *RHSExpr) {
9590   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9591     if (Bop->getOpcode() == BO_LAnd) {
9592       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9593       if (EvaluatesAsFalse(S, LHSExpr))
9594         return;
9595       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9596       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9597         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9598     }
9599   }
9600 }
9601 
9602 /// \brief Look for '&' in the left or right hand of a '|' expr.
9603 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9604                                              Expr *OrArg) {
9605   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9606     if (Bop->getOpcode() == BO_And)
9607       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9608   }
9609 }
9610 
9611 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9612                                     Expr *SubExpr, StringRef Shift) {
9613   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9614     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9615       StringRef Op = Bop->getOpcodeStr();
9616       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9617           << Bop->getSourceRange() << OpLoc << Shift << Op;
9618       SuggestParentheses(S, Bop->getOperatorLoc(),
9619           S.PDiag(diag::note_precedence_silence) << Op,
9620           Bop->getSourceRange());
9621     }
9622   }
9623 }
9624 
9625 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9626                                  Expr *LHSExpr, Expr *RHSExpr) {
9627   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9628   if (!OCE)
9629     return;
9630 
9631   FunctionDecl *FD = OCE->getDirectCallee();
9632   if (!FD || !FD->isOverloadedOperator())
9633     return;
9634 
9635   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9636   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9637     return;
9638 
9639   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9640       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9641       << (Kind == OO_LessLess);
9642   SuggestParentheses(S, OCE->getOperatorLoc(),
9643                      S.PDiag(diag::note_precedence_silence)
9644                          << (Kind == OO_LessLess ? "<<" : ">>"),
9645                      OCE->getSourceRange());
9646   SuggestParentheses(S, OpLoc,
9647                      S.PDiag(diag::note_evaluate_comparison_first),
9648                      SourceRange(OCE->getArg(1)->getLocStart(),
9649                                  RHSExpr->getLocEnd()));
9650 }
9651 
9652 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9653 /// precedence.
9654 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9655                                     SourceLocation OpLoc, Expr *LHSExpr,
9656                                     Expr *RHSExpr){
9657   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9658   if (BinaryOperator::isBitwiseOp(Opc))
9659     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9660 
9661   // Diagnose "arg1 & arg2 | arg3"
9662   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9663     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9664     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9665   }
9666 
9667   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9668   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9669   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9670     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9671     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9672   }
9673 
9674   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9675       || Opc == BO_Shr) {
9676     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9677     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9678     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9679   }
9680 
9681   // Warn on overloaded shift operators and comparisons, such as:
9682   // cout << 5 == 4;
9683   if (BinaryOperator::isComparisonOp(Opc))
9684     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9685 }
9686 
9687 // Binary Operators.  'Tok' is the token for the operator.
9688 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9689                             tok::TokenKind Kind,
9690                             Expr *LHSExpr, Expr *RHSExpr) {
9691   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9692   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9693   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9694 
9695   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9696   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9697 
9698   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9699 }
9700 
9701 /// Build an overloaded binary operator expression in the given scope.
9702 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9703                                        BinaryOperatorKind Opc,
9704                                        Expr *LHS, Expr *RHS) {
9705   // Find all of the overloaded operators visible from this
9706   // point. We perform both an operator-name lookup from the local
9707   // scope and an argument-dependent lookup based on the types of
9708   // the arguments.
9709   UnresolvedSet<16> Functions;
9710   OverloadedOperatorKind OverOp
9711     = BinaryOperator::getOverloadedOperator(Opc);
9712   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
9713     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9714                                    RHS->getType(), Functions);
9715 
9716   // Build the (potentially-overloaded, potentially-dependent)
9717   // binary operation.
9718   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9719 }
9720 
9721 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9722                             BinaryOperatorKind Opc,
9723                             Expr *LHSExpr, Expr *RHSExpr) {
9724   // We want to end up calling one of checkPseudoObjectAssignment
9725   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9726   // both expressions are overloadable or either is type-dependent),
9727   // or CreateBuiltinBinOp (in any other case).  We also want to get
9728   // any placeholder types out of the way.
9729 
9730   // Handle pseudo-objects in the LHS.
9731   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9732     // Assignments with a pseudo-object l-value need special analysis.
9733     if (pty->getKind() == BuiltinType::PseudoObject &&
9734         BinaryOperator::isAssignmentOp(Opc))
9735       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9736 
9737     // Don't resolve overloads if the other type is overloadable.
9738     if (pty->getKind() == BuiltinType::Overload) {
9739       // We can't actually test that if we still have a placeholder,
9740       // though.  Fortunately, none of the exceptions we see in that
9741       // code below are valid when the LHS is an overload set.  Note
9742       // that an overload set can be dependently-typed, but it never
9743       // instantiates to having an overloadable type.
9744       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9745       if (resolvedRHS.isInvalid()) return ExprError();
9746       RHSExpr = resolvedRHS.get();
9747 
9748       if (RHSExpr->isTypeDependent() ||
9749           RHSExpr->getType()->isOverloadableType())
9750         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9751     }
9752 
9753     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9754     if (LHS.isInvalid()) return ExprError();
9755     LHSExpr = LHS.get();
9756   }
9757 
9758   // Handle pseudo-objects in the RHS.
9759   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9760     // An overload in the RHS can potentially be resolved by the type
9761     // being assigned to.
9762     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9763       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9764         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9765 
9766       if (LHSExpr->getType()->isOverloadableType())
9767         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9768 
9769       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9770     }
9771 
9772     // Don't resolve overloads if the other type is overloadable.
9773     if (pty->getKind() == BuiltinType::Overload &&
9774         LHSExpr->getType()->isOverloadableType())
9775       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9776 
9777     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9778     if (!resolvedRHS.isUsable()) return ExprError();
9779     RHSExpr = resolvedRHS.get();
9780   }
9781 
9782   if (getLangOpts().CPlusPlus) {
9783     // If either expression is type-dependent, always build an
9784     // overloaded op.
9785     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9786       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9787 
9788     // Otherwise, build an overloaded op if either expression has an
9789     // overloadable type.
9790     if (LHSExpr->getType()->isOverloadableType() ||
9791         RHSExpr->getType()->isOverloadableType())
9792       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9793   }
9794 
9795   // Build a built-in binary operation.
9796   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9797 }
9798 
9799 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9800                                       UnaryOperatorKind Opc,
9801                                       Expr *InputExpr) {
9802   ExprResult Input = InputExpr;
9803   ExprValueKind VK = VK_RValue;
9804   ExprObjectKind OK = OK_Ordinary;
9805   QualType resultType;
9806   switch (Opc) {
9807   case UO_PreInc:
9808   case UO_PreDec:
9809   case UO_PostInc:
9810   case UO_PostDec:
9811     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
9812                                                 OpLoc,
9813                                                 Opc == UO_PreInc ||
9814                                                 Opc == UO_PostInc,
9815                                                 Opc == UO_PreInc ||
9816                                                 Opc == UO_PreDec);
9817     break;
9818   case UO_AddrOf:
9819     resultType = CheckAddressOfOperand(Input, OpLoc);
9820     break;
9821   case UO_Deref: {
9822     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9823     if (Input.isInvalid()) return ExprError();
9824     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9825     break;
9826   }
9827   case UO_Plus:
9828   case UO_Minus:
9829     Input = UsualUnaryConversions(Input.get());
9830     if (Input.isInvalid()) return ExprError();
9831     resultType = Input.get()->getType();
9832     if (resultType->isDependentType())
9833       break;
9834     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9835         resultType->isVectorType())
9836       break;
9837     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9838              Opc == UO_Plus &&
9839              resultType->isPointerType())
9840       break;
9841 
9842     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9843       << resultType << Input.get()->getSourceRange());
9844 
9845   case UO_Not: // bitwise complement
9846     Input = UsualUnaryConversions(Input.get());
9847     if (Input.isInvalid())
9848       return ExprError();
9849     resultType = Input.get()->getType();
9850     if (resultType->isDependentType())
9851       break;
9852     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9853     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9854       // C99 does not support '~' for complex conjugation.
9855       Diag(OpLoc, diag::ext_integer_complement_complex)
9856           << resultType << Input.get()->getSourceRange();
9857     else if (resultType->hasIntegerRepresentation())
9858       break;
9859     else if (resultType->isExtVectorType()) {
9860       if (Context.getLangOpts().OpenCL) {
9861         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9862         // on vector float types.
9863         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9864         if (!T->isIntegerType())
9865           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9866                            << resultType << Input.get()->getSourceRange());
9867       }
9868       break;
9869     } else {
9870       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9871                        << resultType << Input.get()->getSourceRange());
9872     }
9873     break;
9874 
9875   case UO_LNot: // logical negation
9876     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9877     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9878     if (Input.isInvalid()) return ExprError();
9879     resultType = Input.get()->getType();
9880 
9881     // Though we still have to promote half FP to float...
9882     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9883       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9884       resultType = Context.FloatTy;
9885     }
9886 
9887     if (resultType->isDependentType())
9888       break;
9889     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9890       // C99 6.5.3.3p1: ok, fallthrough;
9891       if (Context.getLangOpts().CPlusPlus) {
9892         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9893         // operand contextually converted to bool.
9894         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
9895                                   ScalarTypeToBooleanCastKind(resultType));
9896       } else if (Context.getLangOpts().OpenCL &&
9897                  Context.getLangOpts().OpenCLVersion < 120) {
9898         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9899         // operate on scalar float types.
9900         if (!resultType->isIntegerType())
9901           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9902                            << resultType << Input.get()->getSourceRange());
9903       }
9904     } else if (resultType->isExtVectorType()) {
9905       if (Context.getLangOpts().OpenCL &&
9906           Context.getLangOpts().OpenCLVersion < 120) {
9907         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9908         // operate on vector float types.
9909         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9910         if (!T->isIntegerType())
9911           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9912                            << resultType << Input.get()->getSourceRange());
9913       }
9914       // Vector logical not returns the signed variant of the operand type.
9915       resultType = GetSignedVectorType(resultType);
9916       break;
9917     } else {
9918       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9919         << resultType << Input.get()->getSourceRange());
9920     }
9921 
9922     // LNot always has type int. C99 6.5.3.3p5.
9923     // In C++, it's bool. C++ 5.3.1p8
9924     resultType = Context.getLogicalOperationType();
9925     break;
9926   case UO_Real:
9927   case UO_Imag:
9928     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9929     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9930     // complex l-values to ordinary l-values and all other values to r-values.
9931     if (Input.isInvalid()) return ExprError();
9932     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9933       if (Input.get()->getValueKind() != VK_RValue &&
9934           Input.get()->getObjectKind() == OK_Ordinary)
9935         VK = Input.get()->getValueKind();
9936     } else if (!getLangOpts().CPlusPlus) {
9937       // In C, a volatile scalar is read by __imag. In C++, it is not.
9938       Input = DefaultLvalueConversion(Input.get());
9939     }
9940     break;
9941   case UO_Extension:
9942     resultType = Input.get()->getType();
9943     VK = Input.get()->getValueKind();
9944     OK = Input.get()->getObjectKind();
9945     break;
9946   }
9947   if (resultType.isNull() || Input.isInvalid())
9948     return ExprError();
9949 
9950   // Check for array bounds violations in the operand of the UnaryOperator,
9951   // except for the '*' and '&' operators that have to be handled specially
9952   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9953   // that are explicitly defined as valid by the standard).
9954   if (Opc != UO_AddrOf && Opc != UO_Deref)
9955     CheckArrayAccess(Input.get());
9956 
9957   return new (Context)
9958       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
9959 }
9960 
9961 /// \brief Determine whether the given expression is a qualified member
9962 /// access expression, of a form that could be turned into a pointer to member
9963 /// with the address-of operator.
9964 static bool isQualifiedMemberAccess(Expr *E) {
9965   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9966     if (!DRE->getQualifier())
9967       return false;
9968 
9969     ValueDecl *VD = DRE->getDecl();
9970     if (!VD->isCXXClassMember())
9971       return false;
9972 
9973     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9974       return true;
9975     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9976       return Method->isInstance();
9977 
9978     return false;
9979   }
9980 
9981   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9982     if (!ULE->getQualifier())
9983       return false;
9984 
9985     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9986                                            DEnd = ULE->decls_end();
9987          D != DEnd; ++D) {
9988       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9989         if (Method->isInstance())
9990           return true;
9991       } else {
9992         // Overload set does not contain methods.
9993         break;
9994       }
9995     }
9996 
9997     return false;
9998   }
9999 
10000   return false;
10001 }
10002 
10003 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10004                               UnaryOperatorKind Opc, Expr *Input) {
10005   // First things first: handle placeholders so that the
10006   // overloaded-operator check considers the right type.
10007   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10008     // Increment and decrement of pseudo-object references.
10009     if (pty->getKind() == BuiltinType::PseudoObject &&
10010         UnaryOperator::isIncrementDecrementOp(Opc))
10011       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10012 
10013     // extension is always a builtin operator.
10014     if (Opc == UO_Extension)
10015       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10016 
10017     // & gets special logic for several kinds of placeholder.
10018     // The builtin code knows what to do.
10019     if (Opc == UO_AddrOf &&
10020         (pty->getKind() == BuiltinType::Overload ||
10021          pty->getKind() == BuiltinType::UnknownAny ||
10022          pty->getKind() == BuiltinType::BoundMember))
10023       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10024 
10025     // Anything else needs to be handled now.
10026     ExprResult Result = CheckPlaceholderExpr(Input);
10027     if (Result.isInvalid()) return ExprError();
10028     Input = Result.get();
10029   }
10030 
10031   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10032       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10033       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10034     // Find all of the overloaded operators visible from this
10035     // point. We perform both an operator-name lookup from the local
10036     // scope and an argument-dependent lookup based on the types of
10037     // the arguments.
10038     UnresolvedSet<16> Functions;
10039     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10040     if (S && OverOp != OO_None)
10041       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10042                                    Functions);
10043 
10044     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10045   }
10046 
10047   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10048 }
10049 
10050 // Unary Operators.  'Tok' is the token for the operator.
10051 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10052                               tok::TokenKind Op, Expr *Input) {
10053   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10054 }
10055 
10056 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10057 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10058                                 LabelDecl *TheDecl) {
10059   TheDecl->markUsed(Context);
10060   // Create the AST node.  The address of a label always has type 'void*'.
10061   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10062                                      Context.getPointerType(Context.VoidTy));
10063 }
10064 
10065 /// Given the last statement in a statement-expression, check whether
10066 /// the result is a producing expression (like a call to an
10067 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10068 /// release out of the full-expression.  Otherwise, return null.
10069 /// Cannot fail.
10070 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10071   // Should always be wrapped with one of these.
10072   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10073   if (!cleanups) return nullptr;
10074 
10075   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10076   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10077     return nullptr;
10078 
10079   // Splice out the cast.  This shouldn't modify any interesting
10080   // features of the statement.
10081   Expr *producer = cast->getSubExpr();
10082   assert(producer->getType() == cast->getType());
10083   assert(producer->getValueKind() == cast->getValueKind());
10084   cleanups->setSubExpr(producer);
10085   return cleanups;
10086 }
10087 
10088 void Sema::ActOnStartStmtExpr() {
10089   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10090 }
10091 
10092 void Sema::ActOnStmtExprError() {
10093   // Note that function is also called by TreeTransform when leaving a
10094   // StmtExpr scope without rebuilding anything.
10095 
10096   DiscardCleanupsInEvaluationContext();
10097   PopExpressionEvaluationContext();
10098 }
10099 
10100 ExprResult
10101 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10102                     SourceLocation RPLoc) { // "({..})"
10103   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10104   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10105 
10106   if (hasAnyUnrecoverableErrorsInThisFunction())
10107     DiscardCleanupsInEvaluationContext();
10108   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10109   PopExpressionEvaluationContext();
10110 
10111   bool isFileScope
10112     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10113   if (isFileScope)
10114     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10115 
10116   // FIXME: there are a variety of strange constraints to enforce here, for
10117   // example, it is not possible to goto into a stmt expression apparently.
10118   // More semantic analysis is needed.
10119 
10120   // If there are sub-stmts in the compound stmt, take the type of the last one
10121   // as the type of the stmtexpr.
10122   QualType Ty = Context.VoidTy;
10123   bool StmtExprMayBindToTemp = false;
10124   if (!Compound->body_empty()) {
10125     Stmt *LastStmt = Compound->body_back();
10126     LabelStmt *LastLabelStmt = nullptr;
10127     // If LastStmt is a label, skip down through into the body.
10128     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10129       LastLabelStmt = Label;
10130       LastStmt = Label->getSubStmt();
10131     }
10132 
10133     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10134       // Do function/array conversion on the last expression, but not
10135       // lvalue-to-rvalue.  However, initialize an unqualified type.
10136       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10137       if (LastExpr.isInvalid())
10138         return ExprError();
10139       Ty = LastExpr.get()->getType().getUnqualifiedType();
10140 
10141       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10142         // In ARC, if the final expression ends in a consume, splice
10143         // the consume out and bind it later.  In the alternate case
10144         // (when dealing with a retainable type), the result
10145         // initialization will create a produce.  In both cases the
10146         // result will be +1, and we'll need to balance that out with
10147         // a bind.
10148         if (Expr *rebuiltLastStmt
10149               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10150           LastExpr = rebuiltLastStmt;
10151         } else {
10152           LastExpr = PerformCopyInitialization(
10153                             InitializedEntity::InitializeResult(LPLoc,
10154                                                                 Ty,
10155                                                                 false),
10156                                                    SourceLocation(),
10157                                                LastExpr);
10158         }
10159 
10160         if (LastExpr.isInvalid())
10161           return ExprError();
10162         if (LastExpr.get() != nullptr) {
10163           if (!LastLabelStmt)
10164             Compound->setLastStmt(LastExpr.get());
10165           else
10166             LastLabelStmt->setSubStmt(LastExpr.get());
10167           StmtExprMayBindToTemp = true;
10168         }
10169       }
10170     }
10171   }
10172 
10173   // FIXME: Check that expression type is complete/non-abstract; statement
10174   // expressions are not lvalues.
10175   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10176   if (StmtExprMayBindToTemp)
10177     return MaybeBindToTemporary(ResStmtExpr);
10178   return ResStmtExpr;
10179 }
10180 
10181 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10182                                       TypeSourceInfo *TInfo,
10183                                       OffsetOfComponent *CompPtr,
10184                                       unsigned NumComponents,
10185                                       SourceLocation RParenLoc) {
10186   QualType ArgTy = TInfo->getType();
10187   bool Dependent = ArgTy->isDependentType();
10188   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10189 
10190   // We must have at least one component that refers to the type, and the first
10191   // one is known to be a field designator.  Verify that the ArgTy represents
10192   // a struct/union/class.
10193   if (!Dependent && !ArgTy->isRecordType())
10194     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10195                        << ArgTy << TypeRange);
10196 
10197   // Type must be complete per C99 7.17p3 because a declaring a variable
10198   // with an incomplete type would be ill-formed.
10199   if (!Dependent
10200       && RequireCompleteType(BuiltinLoc, ArgTy,
10201                              diag::err_offsetof_incomplete_type, TypeRange))
10202     return ExprError();
10203 
10204   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10205   // GCC extension, diagnose them.
10206   // FIXME: This diagnostic isn't actually visible because the location is in
10207   // a system header!
10208   if (NumComponents != 1)
10209     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10210       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10211 
10212   bool DidWarnAboutNonPOD = false;
10213   QualType CurrentType = ArgTy;
10214   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10215   SmallVector<OffsetOfNode, 4> Comps;
10216   SmallVector<Expr*, 4> Exprs;
10217   for (unsigned i = 0; i != NumComponents; ++i) {
10218     const OffsetOfComponent &OC = CompPtr[i];
10219     if (OC.isBrackets) {
10220       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10221       if (!CurrentType->isDependentType()) {
10222         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10223         if(!AT)
10224           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10225                            << CurrentType);
10226         CurrentType = AT->getElementType();
10227       } else
10228         CurrentType = Context.DependentTy;
10229 
10230       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10231       if (IdxRval.isInvalid())
10232         return ExprError();
10233       Expr *Idx = IdxRval.get();
10234 
10235       // The expression must be an integral expression.
10236       // FIXME: An integral constant expression?
10237       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10238           !Idx->getType()->isIntegerType())
10239         return ExprError(Diag(Idx->getLocStart(),
10240                               diag::err_typecheck_subscript_not_integer)
10241                          << Idx->getSourceRange());
10242 
10243       // Record this array index.
10244       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10245       Exprs.push_back(Idx);
10246       continue;
10247     }
10248 
10249     // Offset of a field.
10250     if (CurrentType->isDependentType()) {
10251       // We have the offset of a field, but we can't look into the dependent
10252       // type. Just record the identifier of the field.
10253       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10254       CurrentType = Context.DependentTy;
10255       continue;
10256     }
10257 
10258     // We need to have a complete type to look into.
10259     if (RequireCompleteType(OC.LocStart, CurrentType,
10260                             diag::err_offsetof_incomplete_type))
10261       return ExprError();
10262 
10263     // Look for the designated field.
10264     const RecordType *RC = CurrentType->getAs<RecordType>();
10265     if (!RC)
10266       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10267                        << CurrentType);
10268     RecordDecl *RD = RC->getDecl();
10269 
10270     // C++ [lib.support.types]p5:
10271     //   The macro offsetof accepts a restricted set of type arguments in this
10272     //   International Standard. type shall be a POD structure or a POD union
10273     //   (clause 9).
10274     // C++11 [support.types]p4:
10275     //   If type is not a standard-layout class (Clause 9), the results are
10276     //   undefined.
10277     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10278       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10279       unsigned DiagID =
10280         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10281                             : diag::ext_offsetof_non_pod_type;
10282 
10283       if (!IsSafe && !DidWarnAboutNonPOD &&
10284           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10285                               PDiag(DiagID)
10286                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10287                               << CurrentType))
10288         DidWarnAboutNonPOD = true;
10289     }
10290 
10291     // Look for the field.
10292     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10293     LookupQualifiedName(R, RD);
10294     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10295     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10296     if (!MemberDecl) {
10297       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10298         MemberDecl = IndirectMemberDecl->getAnonField();
10299     }
10300 
10301     if (!MemberDecl)
10302       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10303                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10304                                                               OC.LocEnd));
10305 
10306     // C99 7.17p3:
10307     //   (If the specified member is a bit-field, the behavior is undefined.)
10308     //
10309     // We diagnose this as an error.
10310     if (MemberDecl->isBitField()) {
10311       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10312         << MemberDecl->getDeclName()
10313         << SourceRange(BuiltinLoc, RParenLoc);
10314       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10315       return ExprError();
10316     }
10317 
10318     RecordDecl *Parent = MemberDecl->getParent();
10319     if (IndirectMemberDecl)
10320       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10321 
10322     // If the member was found in a base class, introduce OffsetOfNodes for
10323     // the base class indirections.
10324     CXXBasePaths Paths;
10325     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10326       if (Paths.getDetectedVirtual()) {
10327         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10328           << MemberDecl->getDeclName()
10329           << SourceRange(BuiltinLoc, RParenLoc);
10330         return ExprError();
10331       }
10332 
10333       CXXBasePath &Path = Paths.front();
10334       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10335            B != BEnd; ++B)
10336         Comps.push_back(OffsetOfNode(B->Base));
10337     }
10338 
10339     if (IndirectMemberDecl) {
10340       for (auto *FI : IndirectMemberDecl->chain()) {
10341         assert(isa<FieldDecl>(FI));
10342         Comps.push_back(OffsetOfNode(OC.LocStart,
10343                                      cast<FieldDecl>(FI), OC.LocEnd));
10344       }
10345     } else
10346       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10347 
10348     CurrentType = MemberDecl->getType().getNonReferenceType();
10349   }
10350 
10351   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10352                               Comps, Exprs, RParenLoc);
10353 }
10354 
10355 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10356                                       SourceLocation BuiltinLoc,
10357                                       SourceLocation TypeLoc,
10358                                       ParsedType ParsedArgTy,
10359                                       OffsetOfComponent *CompPtr,
10360                                       unsigned NumComponents,
10361                                       SourceLocation RParenLoc) {
10362 
10363   TypeSourceInfo *ArgTInfo;
10364   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10365   if (ArgTy.isNull())
10366     return ExprError();
10367 
10368   if (!ArgTInfo)
10369     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10370 
10371   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10372                               RParenLoc);
10373 }
10374 
10375 
10376 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10377                                  Expr *CondExpr,
10378                                  Expr *LHSExpr, Expr *RHSExpr,
10379                                  SourceLocation RPLoc) {
10380   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10381 
10382   ExprValueKind VK = VK_RValue;
10383   ExprObjectKind OK = OK_Ordinary;
10384   QualType resType;
10385   bool ValueDependent = false;
10386   bool CondIsTrue = false;
10387   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10388     resType = Context.DependentTy;
10389     ValueDependent = true;
10390   } else {
10391     // The conditional expression is required to be a constant expression.
10392     llvm::APSInt condEval(32);
10393     ExprResult CondICE
10394       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10395           diag::err_typecheck_choose_expr_requires_constant, false);
10396     if (CondICE.isInvalid())
10397       return ExprError();
10398     CondExpr = CondICE.get();
10399     CondIsTrue = condEval.getZExtValue();
10400 
10401     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10402     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10403 
10404     resType = ActiveExpr->getType();
10405     ValueDependent = ActiveExpr->isValueDependent();
10406     VK = ActiveExpr->getValueKind();
10407     OK = ActiveExpr->getObjectKind();
10408   }
10409 
10410   return new (Context)
10411       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10412                  CondIsTrue, resType->isDependentType(), ValueDependent);
10413 }
10414 
10415 //===----------------------------------------------------------------------===//
10416 // Clang Extensions.
10417 //===----------------------------------------------------------------------===//
10418 
10419 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10420 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10421   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10422 
10423   if (LangOpts.CPlusPlus) {
10424     Decl *ManglingContextDecl;
10425     if (MangleNumberingContext *MCtx =
10426             getCurrentMangleNumberContext(Block->getDeclContext(),
10427                                           ManglingContextDecl)) {
10428       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10429       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10430     }
10431   }
10432 
10433   PushBlockScope(CurScope, Block);
10434   CurContext->addDecl(Block);
10435   if (CurScope)
10436     PushDeclContext(CurScope, Block);
10437   else
10438     CurContext = Block;
10439 
10440   getCurBlock()->HasImplicitReturnType = true;
10441 
10442   // Enter a new evaluation context to insulate the block from any
10443   // cleanups from the enclosing full-expression.
10444   PushExpressionEvaluationContext(PotentiallyEvaluated);
10445 }
10446 
10447 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10448                                Scope *CurScope) {
10449   assert(ParamInfo.getIdentifier() == nullptr &&
10450          "block-id should have no identifier!");
10451   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10452   BlockScopeInfo *CurBlock = getCurBlock();
10453 
10454   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10455   QualType T = Sig->getType();
10456 
10457   // FIXME: We should allow unexpanded parameter packs here, but that would,
10458   // in turn, make the block expression contain unexpanded parameter packs.
10459   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10460     // Drop the parameters.
10461     FunctionProtoType::ExtProtoInfo EPI;
10462     EPI.HasTrailingReturn = false;
10463     EPI.TypeQuals |= DeclSpec::TQ_const;
10464     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10465     Sig = Context.getTrivialTypeSourceInfo(T);
10466   }
10467 
10468   // GetTypeForDeclarator always produces a function type for a block
10469   // literal signature.  Furthermore, it is always a FunctionProtoType
10470   // unless the function was written with a typedef.
10471   assert(T->isFunctionType() &&
10472          "GetTypeForDeclarator made a non-function block signature");
10473 
10474   // Look for an explicit signature in that function type.
10475   FunctionProtoTypeLoc ExplicitSignature;
10476 
10477   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10478   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10479 
10480     // Check whether that explicit signature was synthesized by
10481     // GetTypeForDeclarator.  If so, don't save that as part of the
10482     // written signature.
10483     if (ExplicitSignature.getLocalRangeBegin() ==
10484         ExplicitSignature.getLocalRangeEnd()) {
10485       // This would be much cheaper if we stored TypeLocs instead of
10486       // TypeSourceInfos.
10487       TypeLoc Result = ExplicitSignature.getReturnLoc();
10488       unsigned Size = Result.getFullDataSize();
10489       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10490       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10491 
10492       ExplicitSignature = FunctionProtoTypeLoc();
10493     }
10494   }
10495 
10496   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10497   CurBlock->FunctionType = T;
10498 
10499   const FunctionType *Fn = T->getAs<FunctionType>();
10500   QualType RetTy = Fn->getReturnType();
10501   bool isVariadic =
10502     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10503 
10504   CurBlock->TheDecl->setIsVariadic(isVariadic);
10505 
10506   // Context.DependentTy is used as a placeholder for a missing block
10507   // return type.  TODO:  what should we do with declarators like:
10508   //   ^ * { ... }
10509   // If the answer is "apply template argument deduction"....
10510   if (RetTy != Context.DependentTy) {
10511     CurBlock->ReturnType = RetTy;
10512     CurBlock->TheDecl->setBlockMissingReturnType(false);
10513     CurBlock->HasImplicitReturnType = false;
10514   }
10515 
10516   // Push block parameters from the declarator if we had them.
10517   SmallVector<ParmVarDecl*, 8> Params;
10518   if (ExplicitSignature) {
10519     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10520       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10521       if (Param->getIdentifier() == nullptr &&
10522           !Param->isImplicit() &&
10523           !Param->isInvalidDecl() &&
10524           !getLangOpts().CPlusPlus)
10525         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10526       Params.push_back(Param);
10527     }
10528 
10529   // Fake up parameter variables if we have a typedef, like
10530   //   ^ fntype { ... }
10531   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10532     for (const auto &I : Fn->param_types()) {
10533       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10534           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10535       Params.push_back(Param);
10536     }
10537   }
10538 
10539   // Set the parameters on the block decl.
10540   if (!Params.empty()) {
10541     CurBlock->TheDecl->setParams(Params);
10542     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10543                              CurBlock->TheDecl->param_end(),
10544                              /*CheckParameterNames=*/false);
10545   }
10546 
10547   // Finally we can process decl attributes.
10548   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10549 
10550   // Put the parameter variables in scope.
10551   for (auto AI : CurBlock->TheDecl->params()) {
10552     AI->setOwningFunction(CurBlock->TheDecl);
10553 
10554     // If this has an identifier, add it to the scope stack.
10555     if (AI->getIdentifier()) {
10556       CheckShadow(CurBlock->TheScope, AI);
10557 
10558       PushOnScopeChains(AI, CurBlock->TheScope);
10559     }
10560   }
10561 }
10562 
10563 /// ActOnBlockError - If there is an error parsing a block, this callback
10564 /// is invoked to pop the information about the block from the action impl.
10565 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10566   // Leave the expression-evaluation context.
10567   DiscardCleanupsInEvaluationContext();
10568   PopExpressionEvaluationContext();
10569 
10570   // Pop off CurBlock, handle nested blocks.
10571   PopDeclContext();
10572   PopFunctionScopeInfo();
10573 }
10574 
10575 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10576 /// literal was successfully completed.  ^(int x){...}
10577 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10578                                     Stmt *Body, Scope *CurScope) {
10579   // If blocks are disabled, emit an error.
10580   if (!LangOpts.Blocks)
10581     Diag(CaretLoc, diag::err_blocks_disable);
10582 
10583   // Leave the expression-evaluation context.
10584   if (hasAnyUnrecoverableErrorsInThisFunction())
10585     DiscardCleanupsInEvaluationContext();
10586   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10587   PopExpressionEvaluationContext();
10588 
10589   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10590 
10591   if (BSI->HasImplicitReturnType)
10592     deduceClosureReturnType(*BSI);
10593 
10594   PopDeclContext();
10595 
10596   QualType RetTy = Context.VoidTy;
10597   if (!BSI->ReturnType.isNull())
10598     RetTy = BSI->ReturnType;
10599 
10600   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10601   QualType BlockTy;
10602 
10603   // Set the captured variables on the block.
10604   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10605   SmallVector<BlockDecl::Capture, 4> Captures;
10606   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10607     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10608     if (Cap.isThisCapture())
10609       continue;
10610     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10611                               Cap.isNested(), Cap.getInitExpr());
10612     Captures.push_back(NewCap);
10613   }
10614   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10615                             BSI->CXXThisCaptureIndex != 0);
10616 
10617   // If the user wrote a function type in some form, try to use that.
10618   if (!BSI->FunctionType.isNull()) {
10619     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10620 
10621     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10622     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10623 
10624     // Turn protoless block types into nullary block types.
10625     if (isa<FunctionNoProtoType>(FTy)) {
10626       FunctionProtoType::ExtProtoInfo EPI;
10627       EPI.ExtInfo = Ext;
10628       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10629 
10630     // Otherwise, if we don't need to change anything about the function type,
10631     // preserve its sugar structure.
10632     } else if (FTy->getReturnType() == RetTy &&
10633                (!NoReturn || FTy->getNoReturnAttr())) {
10634       BlockTy = BSI->FunctionType;
10635 
10636     // Otherwise, make the minimal modifications to the function type.
10637     } else {
10638       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10639       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10640       EPI.TypeQuals = 0; // FIXME: silently?
10641       EPI.ExtInfo = Ext;
10642       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10643     }
10644 
10645   // If we don't have a function type, just build one from nothing.
10646   } else {
10647     FunctionProtoType::ExtProtoInfo EPI;
10648     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10649     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10650   }
10651 
10652   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10653                            BSI->TheDecl->param_end());
10654   BlockTy = Context.getBlockPointerType(BlockTy);
10655 
10656   // If needed, diagnose invalid gotos and switches in the block.
10657   if (getCurFunction()->NeedsScopeChecking() &&
10658       !PP.isCodeCompletionEnabled())
10659     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10660 
10661   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10662 
10663   // Try to apply the named return value optimization. We have to check again
10664   // if we can do this, though, because blocks keep return statements around
10665   // to deduce an implicit return type.
10666   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10667       !BSI->TheDecl->isDependentContext())
10668     computeNRVO(Body, BSI);
10669 
10670   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10671   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10672   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10673 
10674   // If the block isn't obviously global, i.e. it captures anything at
10675   // all, then we need to do a few things in the surrounding context:
10676   if (Result->getBlockDecl()->hasCaptures()) {
10677     // First, this expression has a new cleanup object.
10678     ExprCleanupObjects.push_back(Result->getBlockDecl());
10679     ExprNeedsCleanups = true;
10680 
10681     // It also gets a branch-protected scope if any of the captured
10682     // variables needs destruction.
10683     for (const auto &CI : Result->getBlockDecl()->captures()) {
10684       const VarDecl *var = CI.getVariable();
10685       if (var->getType().isDestructedType() != QualType::DK_none) {
10686         getCurFunction()->setHasBranchProtectedScope();
10687         break;
10688       }
10689     }
10690   }
10691 
10692   return Result;
10693 }
10694 
10695 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10696                                         Expr *E, ParsedType Ty,
10697                                         SourceLocation RPLoc) {
10698   TypeSourceInfo *TInfo;
10699   GetTypeFromParser(Ty, &TInfo);
10700   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10701 }
10702 
10703 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10704                                 Expr *E, TypeSourceInfo *TInfo,
10705                                 SourceLocation RPLoc) {
10706   Expr *OrigExpr = E;
10707 
10708   // Get the va_list type
10709   QualType VaListType = Context.getBuiltinVaListType();
10710   if (VaListType->isArrayType()) {
10711     // Deal with implicit array decay; for example, on x86-64,
10712     // va_list is an array, but it's supposed to decay to
10713     // a pointer for va_arg.
10714     VaListType = Context.getArrayDecayedType(VaListType);
10715     // Make sure the input expression also decays appropriately.
10716     ExprResult Result = UsualUnaryConversions(E);
10717     if (Result.isInvalid())
10718       return ExprError();
10719     E = Result.get();
10720   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10721     // If va_list is a record type and we are compiling in C++ mode,
10722     // check the argument using reference binding.
10723     InitializedEntity Entity
10724       = InitializedEntity::InitializeParameter(Context,
10725           Context.getLValueReferenceType(VaListType), false);
10726     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10727     if (Init.isInvalid())
10728       return ExprError();
10729     E = Init.getAs<Expr>();
10730   } else {
10731     // Otherwise, the va_list argument must be an l-value because
10732     // it is modified by va_arg.
10733     if (!E->isTypeDependent() &&
10734         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10735       return ExprError();
10736   }
10737 
10738   if (!E->isTypeDependent() &&
10739       !Context.hasSameType(VaListType, E->getType())) {
10740     return ExprError(Diag(E->getLocStart(),
10741                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10742       << OrigExpr->getType() << E->getSourceRange());
10743   }
10744 
10745   if (!TInfo->getType()->isDependentType()) {
10746     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10747                             diag::err_second_parameter_to_va_arg_incomplete,
10748                             TInfo->getTypeLoc()))
10749       return ExprError();
10750 
10751     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10752                                TInfo->getType(),
10753                                diag::err_second_parameter_to_va_arg_abstract,
10754                                TInfo->getTypeLoc()))
10755       return ExprError();
10756 
10757     if (!TInfo->getType().isPODType(Context)) {
10758       Diag(TInfo->getTypeLoc().getBeginLoc(),
10759            TInfo->getType()->isObjCLifetimeType()
10760              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10761              : diag::warn_second_parameter_to_va_arg_not_pod)
10762         << TInfo->getType()
10763         << TInfo->getTypeLoc().getSourceRange();
10764     }
10765 
10766     // Check for va_arg where arguments of the given type will be promoted
10767     // (i.e. this va_arg is guaranteed to have undefined behavior).
10768     QualType PromoteType;
10769     if (TInfo->getType()->isPromotableIntegerType()) {
10770       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10771       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10772         PromoteType = QualType();
10773     }
10774     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10775       PromoteType = Context.DoubleTy;
10776     if (!PromoteType.isNull())
10777       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10778                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10779                           << TInfo->getType()
10780                           << PromoteType
10781                           << TInfo->getTypeLoc().getSourceRange());
10782   }
10783 
10784   QualType T = TInfo->getType().getNonLValueExprType(Context);
10785   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10786 }
10787 
10788 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10789   // The type of __null will be int or long, depending on the size of
10790   // pointers on the target.
10791   QualType Ty;
10792   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10793   if (pw == Context.getTargetInfo().getIntWidth())
10794     Ty = Context.IntTy;
10795   else if (pw == Context.getTargetInfo().getLongWidth())
10796     Ty = Context.LongTy;
10797   else if (pw == Context.getTargetInfo().getLongLongWidth())
10798     Ty = Context.LongLongTy;
10799   else {
10800     llvm_unreachable("I don't know size of pointer!");
10801   }
10802 
10803   return new (Context) GNUNullExpr(Ty, TokenLoc);
10804 }
10805 
10806 bool
10807 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10808   if (!getLangOpts().ObjC1)
10809     return false;
10810 
10811   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10812   if (!PT)
10813     return false;
10814 
10815   if (!PT->isObjCIdType()) {
10816     // Check if the destination is the 'NSString' interface.
10817     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10818     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10819       return false;
10820   }
10821 
10822   // Ignore any parens, implicit casts (should only be
10823   // array-to-pointer decays), and not-so-opaque values.  The last is
10824   // important for making this trigger for property assignments.
10825   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10826   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10827     if (OV->getSourceExpr())
10828       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10829 
10830   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10831   if (!SL || !SL->isAscii())
10832     return false;
10833   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10834     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10835   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10836   return true;
10837 }
10838 
10839 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10840                                     SourceLocation Loc,
10841                                     QualType DstType, QualType SrcType,
10842                                     Expr *SrcExpr, AssignmentAction Action,
10843                                     bool *Complained) {
10844   if (Complained)
10845     *Complained = false;
10846 
10847   // Decode the result (notice that AST's are still created for extensions).
10848   bool CheckInferredResultType = false;
10849   bool isInvalid = false;
10850   unsigned DiagKind = 0;
10851   FixItHint Hint;
10852   ConversionFixItGenerator ConvHints;
10853   bool MayHaveConvFixit = false;
10854   bool MayHaveFunctionDiff = false;
10855   const ObjCInterfaceDecl *IFace = nullptr;
10856   const ObjCProtocolDecl *PDecl = nullptr;
10857 
10858   switch (ConvTy) {
10859   case Compatible:
10860       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10861       return false;
10862 
10863   case PointerToInt:
10864     DiagKind = diag::ext_typecheck_convert_pointer_int;
10865     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10866     MayHaveConvFixit = true;
10867     break;
10868   case IntToPointer:
10869     DiagKind = diag::ext_typecheck_convert_int_pointer;
10870     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10871     MayHaveConvFixit = true;
10872     break;
10873   case IncompatiblePointer:
10874       DiagKind =
10875         (Action == AA_Passing_CFAudited ?
10876           diag::err_arc_typecheck_convert_incompatible_pointer :
10877           diag::ext_typecheck_convert_incompatible_pointer);
10878     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10879       SrcType->isObjCObjectPointerType();
10880     if (Hint.isNull() && !CheckInferredResultType) {
10881       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10882     }
10883     else if (CheckInferredResultType) {
10884       SrcType = SrcType.getUnqualifiedType();
10885       DstType = DstType.getUnqualifiedType();
10886     }
10887     MayHaveConvFixit = true;
10888     break;
10889   case IncompatiblePointerSign:
10890     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10891     break;
10892   case FunctionVoidPointer:
10893     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10894     break;
10895   case IncompatiblePointerDiscardsQualifiers: {
10896     // Perform array-to-pointer decay if necessary.
10897     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10898 
10899     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10900     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10901     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10902       DiagKind = diag::err_typecheck_incompatible_address_space;
10903       break;
10904 
10905 
10906     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10907       DiagKind = diag::err_typecheck_incompatible_ownership;
10908       break;
10909     }
10910 
10911     llvm_unreachable("unknown error case for discarding qualifiers!");
10912     // fallthrough
10913   }
10914   case CompatiblePointerDiscardsQualifiers:
10915     // If the qualifiers lost were because we were applying the
10916     // (deprecated) C++ conversion from a string literal to a char*
10917     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10918     // Ideally, this check would be performed in
10919     // checkPointerTypesForAssignment. However, that would require a
10920     // bit of refactoring (so that the second argument is an
10921     // expression, rather than a type), which should be done as part
10922     // of a larger effort to fix checkPointerTypesForAssignment for
10923     // C++ semantics.
10924     if (getLangOpts().CPlusPlus &&
10925         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10926       return false;
10927     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10928     break;
10929   case IncompatibleNestedPointerQualifiers:
10930     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10931     break;
10932   case IntToBlockPointer:
10933     DiagKind = diag::err_int_to_block_pointer;
10934     break;
10935   case IncompatibleBlockPointer:
10936     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10937     break;
10938   case IncompatibleObjCQualifiedId: {
10939     if (SrcType->isObjCQualifiedIdType()) {
10940       const ObjCObjectPointerType *srcOPT =
10941                 SrcType->getAs<ObjCObjectPointerType>();
10942       for (auto *srcProto : srcOPT->quals()) {
10943         PDecl = srcProto;
10944         break;
10945       }
10946       if (const ObjCInterfaceType *IFaceT =
10947             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10948         IFace = IFaceT->getDecl();
10949     }
10950     else if (DstType->isObjCQualifiedIdType()) {
10951       const ObjCObjectPointerType *dstOPT =
10952         DstType->getAs<ObjCObjectPointerType>();
10953       for (auto *dstProto : dstOPT->quals()) {
10954         PDecl = dstProto;
10955         break;
10956       }
10957       if (const ObjCInterfaceType *IFaceT =
10958             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10959         IFace = IFaceT->getDecl();
10960     }
10961     DiagKind = diag::warn_incompatible_qualified_id;
10962     break;
10963   }
10964   case IncompatibleVectors:
10965     DiagKind = diag::warn_incompatible_vectors;
10966     break;
10967   case IncompatibleObjCWeakRef:
10968     DiagKind = diag::err_arc_weak_unavailable_assign;
10969     break;
10970   case Incompatible:
10971     DiagKind = diag::err_typecheck_convert_incompatible;
10972     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10973     MayHaveConvFixit = true;
10974     isInvalid = true;
10975     MayHaveFunctionDiff = true;
10976     break;
10977   }
10978 
10979   QualType FirstType, SecondType;
10980   switch (Action) {
10981   case AA_Assigning:
10982   case AA_Initializing:
10983     // The destination type comes first.
10984     FirstType = DstType;
10985     SecondType = SrcType;
10986     break;
10987 
10988   case AA_Returning:
10989   case AA_Passing:
10990   case AA_Passing_CFAudited:
10991   case AA_Converting:
10992   case AA_Sending:
10993   case AA_Casting:
10994     // The source type comes first.
10995     FirstType = SrcType;
10996     SecondType = DstType;
10997     break;
10998   }
10999 
11000   PartialDiagnostic FDiag = PDiag(DiagKind);
11001   if (Action == AA_Passing_CFAudited)
11002     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11003   else
11004     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11005 
11006   // If we can fix the conversion, suggest the FixIts.
11007   assert(ConvHints.isNull() || Hint.isNull());
11008   if (!ConvHints.isNull()) {
11009     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11010          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11011       FDiag << *HI;
11012   } else {
11013     FDiag << Hint;
11014   }
11015   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11016 
11017   if (MayHaveFunctionDiff)
11018     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11019 
11020   Diag(Loc, FDiag);
11021   if (DiagKind == diag::warn_incompatible_qualified_id &&
11022       PDecl && IFace && !IFace->hasDefinition())
11023       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11024         << IFace->getName() << PDecl->getName();
11025 
11026   if (SecondType == Context.OverloadTy)
11027     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11028                               FirstType);
11029 
11030   if (CheckInferredResultType)
11031     EmitRelatedResultTypeNote(SrcExpr);
11032 
11033   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11034     EmitRelatedResultTypeNoteForReturn(DstType);
11035 
11036   if (Complained)
11037     *Complained = true;
11038   return isInvalid;
11039 }
11040 
11041 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11042                                                  llvm::APSInt *Result) {
11043   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11044   public:
11045     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11046       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11047     }
11048   } Diagnoser;
11049 
11050   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11051 }
11052 
11053 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11054                                                  llvm::APSInt *Result,
11055                                                  unsigned DiagID,
11056                                                  bool AllowFold) {
11057   class IDDiagnoser : public VerifyICEDiagnoser {
11058     unsigned DiagID;
11059 
11060   public:
11061     IDDiagnoser(unsigned DiagID)
11062       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11063 
11064     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11065       S.Diag(Loc, DiagID) << SR;
11066     }
11067   } Diagnoser(DiagID);
11068 
11069   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11070 }
11071 
11072 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11073                                             SourceRange SR) {
11074   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11075 }
11076 
11077 ExprResult
11078 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11079                                       VerifyICEDiagnoser &Diagnoser,
11080                                       bool AllowFold) {
11081   SourceLocation DiagLoc = E->getLocStart();
11082 
11083   if (getLangOpts().CPlusPlus11) {
11084     // C++11 [expr.const]p5:
11085     //   If an expression of literal class type is used in a context where an
11086     //   integral constant expression is required, then that class type shall
11087     //   have a single non-explicit conversion function to an integral or
11088     //   unscoped enumeration type
11089     ExprResult Converted;
11090     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11091     public:
11092       CXX11ConvertDiagnoser(bool Silent)
11093           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11094                                 Silent, true) {}
11095 
11096       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11097                                            QualType T) override {
11098         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11099       }
11100 
11101       SemaDiagnosticBuilder diagnoseIncomplete(
11102           Sema &S, SourceLocation Loc, QualType T) override {
11103         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11104       }
11105 
11106       SemaDiagnosticBuilder diagnoseExplicitConv(
11107           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11108         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11109       }
11110 
11111       SemaDiagnosticBuilder noteExplicitConv(
11112           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11113         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11114                  << ConvTy->isEnumeralType() << ConvTy;
11115       }
11116 
11117       SemaDiagnosticBuilder diagnoseAmbiguous(
11118           Sema &S, SourceLocation Loc, QualType T) override {
11119         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11120       }
11121 
11122       SemaDiagnosticBuilder noteAmbiguous(
11123           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11124         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11125                  << ConvTy->isEnumeralType() << ConvTy;
11126       }
11127 
11128       SemaDiagnosticBuilder diagnoseConversion(
11129           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11130         llvm_unreachable("conversion functions are permitted");
11131       }
11132     } ConvertDiagnoser(Diagnoser.Suppress);
11133 
11134     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11135                                                     ConvertDiagnoser);
11136     if (Converted.isInvalid())
11137       return Converted;
11138     E = Converted.get();
11139     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11140       return ExprError();
11141   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11142     // An ICE must be of integral or unscoped enumeration type.
11143     if (!Diagnoser.Suppress)
11144       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11145     return ExprError();
11146   }
11147 
11148   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11149   // in the non-ICE case.
11150   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11151     if (Result)
11152       *Result = E->EvaluateKnownConstInt(Context);
11153     return E;
11154   }
11155 
11156   Expr::EvalResult EvalResult;
11157   SmallVector<PartialDiagnosticAt, 8> Notes;
11158   EvalResult.Diag = &Notes;
11159 
11160   // Try to evaluate the expression, and produce diagnostics explaining why it's
11161   // not a constant expression as a side-effect.
11162   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11163                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11164 
11165   // In C++11, we can rely on diagnostics being produced for any expression
11166   // which is not a constant expression. If no diagnostics were produced, then
11167   // this is a constant expression.
11168   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11169     if (Result)
11170       *Result = EvalResult.Val.getInt();
11171     return E;
11172   }
11173 
11174   // If our only note is the usual "invalid subexpression" note, just point
11175   // the caret at its location rather than producing an essentially
11176   // redundant note.
11177   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11178         diag::note_invalid_subexpr_in_const_expr) {
11179     DiagLoc = Notes[0].first;
11180     Notes.clear();
11181   }
11182 
11183   if (!Folded || !AllowFold) {
11184     if (!Diagnoser.Suppress) {
11185       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11186       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11187         Diag(Notes[I].first, Notes[I].second);
11188     }
11189 
11190     return ExprError();
11191   }
11192 
11193   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11194   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11195     Diag(Notes[I].first, Notes[I].second);
11196 
11197   if (Result)
11198     *Result = EvalResult.Val.getInt();
11199   return E;
11200 }
11201 
11202 namespace {
11203   // Handle the case where we conclude a expression which we speculatively
11204   // considered to be unevaluated is actually evaluated.
11205   class TransformToPE : public TreeTransform<TransformToPE> {
11206     typedef TreeTransform<TransformToPE> BaseTransform;
11207 
11208   public:
11209     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11210 
11211     // Make sure we redo semantic analysis
11212     bool AlwaysRebuild() { return true; }
11213 
11214     // Make sure we handle LabelStmts correctly.
11215     // FIXME: This does the right thing, but maybe we need a more general
11216     // fix to TreeTransform?
11217     StmtResult TransformLabelStmt(LabelStmt *S) {
11218       S->getDecl()->setStmt(nullptr);
11219       return BaseTransform::TransformLabelStmt(S);
11220     }
11221 
11222     // We need to special-case DeclRefExprs referring to FieldDecls which
11223     // are not part of a member pointer formation; normal TreeTransforming
11224     // doesn't catch this case because of the way we represent them in the AST.
11225     // FIXME: This is a bit ugly; is it really the best way to handle this
11226     // case?
11227     //
11228     // Error on DeclRefExprs referring to FieldDecls.
11229     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11230       if (isa<FieldDecl>(E->getDecl()) &&
11231           !SemaRef.isUnevaluatedContext())
11232         return SemaRef.Diag(E->getLocation(),
11233                             diag::err_invalid_non_static_member_use)
11234             << E->getDecl() << E->getSourceRange();
11235 
11236       return BaseTransform::TransformDeclRefExpr(E);
11237     }
11238 
11239     // Exception: filter out member pointer formation
11240     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11241       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11242         return E;
11243 
11244       return BaseTransform::TransformUnaryOperator(E);
11245     }
11246 
11247     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11248       // Lambdas never need to be transformed.
11249       return E;
11250     }
11251   };
11252 }
11253 
11254 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11255   assert(isUnevaluatedContext() &&
11256          "Should only transform unevaluated expressions");
11257   ExprEvalContexts.back().Context =
11258       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11259   if (isUnevaluatedContext())
11260     return E;
11261   return TransformToPE(*this).TransformExpr(E);
11262 }
11263 
11264 void
11265 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11266                                       Decl *LambdaContextDecl,
11267                                       bool IsDecltype) {
11268   ExprEvalContexts.push_back(
11269              ExpressionEvaluationContextRecord(NewContext,
11270                                                ExprCleanupObjects.size(),
11271                                                ExprNeedsCleanups,
11272                                                LambdaContextDecl,
11273                                                IsDecltype));
11274   ExprNeedsCleanups = false;
11275   if (!MaybeODRUseExprs.empty())
11276     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11277 }
11278 
11279 void
11280 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11281                                       ReuseLambdaContextDecl_t,
11282                                       bool IsDecltype) {
11283   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11284   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11285 }
11286 
11287 void Sema::PopExpressionEvaluationContext() {
11288   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11289   unsigned NumTypos = Rec.NumTypos;
11290 
11291   if (!Rec.Lambdas.empty()) {
11292     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11293       unsigned D;
11294       if (Rec.isUnevaluated()) {
11295         // C++11 [expr.prim.lambda]p2:
11296         //   A lambda-expression shall not appear in an unevaluated operand
11297         //   (Clause 5).
11298         D = diag::err_lambda_unevaluated_operand;
11299       } else {
11300         // C++1y [expr.const]p2:
11301         //   A conditional-expression e is a core constant expression unless the
11302         //   evaluation of e, following the rules of the abstract machine, would
11303         //   evaluate [...] a lambda-expression.
11304         D = diag::err_lambda_in_constant_expression;
11305       }
11306       for (const auto *L : Rec.Lambdas)
11307         Diag(L->getLocStart(), D);
11308     } else {
11309       // Mark the capture expressions odr-used. This was deferred
11310       // during lambda expression creation.
11311       for (auto *Lambda : Rec.Lambdas) {
11312         for (auto *C : Lambda->capture_inits())
11313           MarkDeclarationsReferencedInExpr(C);
11314       }
11315     }
11316   }
11317 
11318   // When are coming out of an unevaluated context, clear out any
11319   // temporaries that we may have created as part of the evaluation of
11320   // the expression in that context: they aren't relevant because they
11321   // will never be constructed.
11322   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11323     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11324                              ExprCleanupObjects.end());
11325     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11326     CleanupVarDeclMarking();
11327     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11328   // Otherwise, merge the contexts together.
11329   } else {
11330     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11331     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11332                             Rec.SavedMaybeODRUseExprs.end());
11333   }
11334 
11335   // Pop the current expression evaluation context off the stack.
11336   ExprEvalContexts.pop_back();
11337 
11338   if (!ExprEvalContexts.empty())
11339     ExprEvalContexts.back().NumTypos += NumTypos;
11340   else
11341     assert(NumTypos == 0 && "There are outstanding typos after popping the "
11342                             "last ExpressionEvaluationContextRecord");
11343 }
11344 
11345 void Sema::DiscardCleanupsInEvaluationContext() {
11346   ExprCleanupObjects.erase(
11347          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11348          ExprCleanupObjects.end());
11349   ExprNeedsCleanups = false;
11350   MaybeODRUseExprs.clear();
11351 }
11352 
11353 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11354   if (!E->getType()->isVariablyModifiedType())
11355     return E;
11356   return TransformToPotentiallyEvaluated(E);
11357 }
11358 
11359 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11360   // Do not mark anything as "used" within a dependent context; wait for
11361   // an instantiation.
11362   if (SemaRef.CurContext->isDependentContext())
11363     return false;
11364 
11365   switch (SemaRef.ExprEvalContexts.back().Context) {
11366     case Sema::Unevaluated:
11367     case Sema::UnevaluatedAbstract:
11368       // We are in an expression that is not potentially evaluated; do nothing.
11369       // (Depending on how you read the standard, we actually do need to do
11370       // something here for null pointer constants, but the standard's
11371       // definition of a null pointer constant is completely crazy.)
11372       return false;
11373 
11374     case Sema::ConstantEvaluated:
11375     case Sema::PotentiallyEvaluated:
11376       // We are in a potentially evaluated expression (or a constant-expression
11377       // in C++03); we need to do implicit template instantiation, implicitly
11378       // define class members, and mark most declarations as used.
11379       return true;
11380 
11381     case Sema::PotentiallyEvaluatedIfUsed:
11382       // Referenced declarations will only be used if the construct in the
11383       // containing expression is used.
11384       return false;
11385   }
11386   llvm_unreachable("Invalid context");
11387 }
11388 
11389 /// \brief Mark a function referenced, and check whether it is odr-used
11390 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11391 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
11392                                   bool OdrUse) {
11393   assert(Func && "No function?");
11394 
11395   Func->setReferenced();
11396 
11397   // C++11 [basic.def.odr]p3:
11398   //   A function whose name appears as a potentially-evaluated expression is
11399   //   odr-used if it is the unique lookup result or the selected member of a
11400   //   set of overloaded functions [...].
11401   //
11402   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11403   // can just check that here. Skip the rest of this function if we've already
11404   // marked the function as used.
11405   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11406     // C++11 [temp.inst]p3:
11407     //   Unless a function template specialization has been explicitly
11408     //   instantiated or explicitly specialized, the function template
11409     //   specialization is implicitly instantiated when the specialization is
11410     //   referenced in a context that requires a function definition to exist.
11411     //
11412     // We consider constexpr function templates to be referenced in a context
11413     // that requires a definition to exist whenever they are referenced.
11414     //
11415     // FIXME: This instantiates constexpr functions too frequently. If this is
11416     // really an unevaluated context (and we're not just in the definition of a
11417     // function template or overload resolution or other cases which we
11418     // incorrectly consider to be unevaluated contexts), and we're not in a
11419     // subexpression which we actually need to evaluate (for instance, a
11420     // template argument, array bound or an expression in a braced-init-list),
11421     // we are not permitted to instantiate this constexpr function definition.
11422     //
11423     // FIXME: This also implicitly defines special members too frequently. They
11424     // are only supposed to be implicitly defined if they are odr-used, but they
11425     // are not odr-used from constant expressions in unevaluated contexts.
11426     // However, they cannot be referenced if they are deleted, and they are
11427     // deleted whenever the implicit definition of the special member would
11428     // fail.
11429     if (!Func->isConstexpr() || Func->getBody())
11430       return;
11431     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11432     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11433       return;
11434   }
11435 
11436   // Note that this declaration has been used.
11437   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11438     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11439     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11440       if (Constructor->isDefaultConstructor()) {
11441         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11442           return;
11443         DefineImplicitDefaultConstructor(Loc, Constructor);
11444       } else if (Constructor->isCopyConstructor()) {
11445         DefineImplicitCopyConstructor(Loc, Constructor);
11446       } else if (Constructor->isMoveConstructor()) {
11447         DefineImplicitMoveConstructor(Loc, Constructor);
11448       }
11449     } else if (Constructor->getInheritedConstructor()) {
11450       DefineInheritingConstructor(Loc, Constructor);
11451     }
11452   } else if (CXXDestructorDecl *Destructor =
11453                  dyn_cast<CXXDestructorDecl>(Func)) {
11454     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11455     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11456       DefineImplicitDestructor(Loc, Destructor);
11457     if (Destructor->isVirtual())
11458       MarkVTableUsed(Loc, Destructor->getParent());
11459   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11460     if (MethodDecl->isOverloadedOperator() &&
11461         MethodDecl->getOverloadedOperator() == OO_Equal) {
11462       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11463       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11464         if (MethodDecl->isCopyAssignmentOperator())
11465           DefineImplicitCopyAssignment(Loc, MethodDecl);
11466         else
11467           DefineImplicitMoveAssignment(Loc, MethodDecl);
11468       }
11469     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11470                MethodDecl->getParent()->isLambda()) {
11471       CXXConversionDecl *Conversion =
11472           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11473       if (Conversion->isLambdaToBlockPointerConversion())
11474         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11475       else
11476         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11477     } else if (MethodDecl->isVirtual())
11478       MarkVTableUsed(Loc, MethodDecl->getParent());
11479   }
11480 
11481   // Recursive functions should be marked when used from another function.
11482   // FIXME: Is this really right?
11483   if (CurContext == Func) return;
11484 
11485   // Resolve the exception specification for any function which is
11486   // used: CodeGen will need it.
11487   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11488   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11489     ResolveExceptionSpec(Loc, FPT);
11490 
11491   if (!OdrUse) return;
11492 
11493   // Implicit instantiation of function templates and member functions of
11494   // class templates.
11495   if (Func->isImplicitlyInstantiable()) {
11496     bool AlreadyInstantiated = false;
11497     SourceLocation PointOfInstantiation = Loc;
11498     if (FunctionTemplateSpecializationInfo *SpecInfo
11499                               = Func->getTemplateSpecializationInfo()) {
11500       if (SpecInfo->getPointOfInstantiation().isInvalid())
11501         SpecInfo->setPointOfInstantiation(Loc);
11502       else if (SpecInfo->getTemplateSpecializationKind()
11503                  == TSK_ImplicitInstantiation) {
11504         AlreadyInstantiated = true;
11505         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11506       }
11507     } else if (MemberSpecializationInfo *MSInfo
11508                                 = Func->getMemberSpecializationInfo()) {
11509       if (MSInfo->getPointOfInstantiation().isInvalid())
11510         MSInfo->setPointOfInstantiation(Loc);
11511       else if (MSInfo->getTemplateSpecializationKind()
11512                  == TSK_ImplicitInstantiation) {
11513         AlreadyInstantiated = true;
11514         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11515       }
11516     }
11517 
11518     if (!AlreadyInstantiated || Func->isConstexpr()) {
11519       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11520           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11521           ActiveTemplateInstantiations.size())
11522         PendingLocalImplicitInstantiations.push_back(
11523             std::make_pair(Func, PointOfInstantiation));
11524       else if (Func->isConstexpr())
11525         // Do not defer instantiations of constexpr functions, to avoid the
11526         // expression evaluator needing to call back into Sema if it sees a
11527         // call to such a function.
11528         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11529       else {
11530         PendingInstantiations.push_back(std::make_pair(Func,
11531                                                        PointOfInstantiation));
11532         // Notify the consumer that a function was implicitly instantiated.
11533         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11534       }
11535     }
11536   } else {
11537     // Walk redefinitions, as some of them may be instantiable.
11538     for (auto i : Func->redecls()) {
11539       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11540         MarkFunctionReferenced(Loc, i);
11541     }
11542   }
11543 
11544   // Keep track of used but undefined functions.
11545   if (!Func->isDefined()) {
11546     if (mightHaveNonExternalLinkage(Func))
11547       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11548     else if (Func->getMostRecentDecl()->isInlined() &&
11549              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11550              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11551       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11552   }
11553 
11554   // Normally the most current decl is marked used while processing the use and
11555   // any subsequent decls are marked used by decl merging. This fails with
11556   // template instantiation since marking can happen at the end of the file
11557   // and, because of the two phase lookup, this function is called with at
11558   // decl in the middle of a decl chain. We loop to maintain the invariant
11559   // that once a decl is used, all decls after it are also used.
11560   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11561     F->markUsed(Context);
11562     if (F == Func)
11563       break;
11564   }
11565 }
11566 
11567 static void
11568 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11569                                    VarDecl *var, DeclContext *DC) {
11570   DeclContext *VarDC = var->getDeclContext();
11571 
11572   //  If the parameter still belongs to the translation unit, then
11573   //  we're actually just using one parameter in the declaration of
11574   //  the next.
11575   if (isa<ParmVarDecl>(var) &&
11576       isa<TranslationUnitDecl>(VarDC))
11577     return;
11578 
11579   // For C code, don't diagnose about capture if we're not actually in code
11580   // right now; it's impossible to write a non-constant expression outside of
11581   // function context, so we'll get other (more useful) diagnostics later.
11582   //
11583   // For C++, things get a bit more nasty... it would be nice to suppress this
11584   // diagnostic for certain cases like using a local variable in an array bound
11585   // for a member of a local class, but the correct predicate is not obvious.
11586   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11587     return;
11588 
11589   if (isa<CXXMethodDecl>(VarDC) &&
11590       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11591     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11592       << var->getIdentifier();
11593   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11594     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11595       << var->getIdentifier() << fn->getDeclName();
11596   } else if (isa<BlockDecl>(VarDC)) {
11597     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11598       << var->getIdentifier();
11599   } else {
11600     // FIXME: Is there any other context where a local variable can be
11601     // declared?
11602     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11603       << var->getIdentifier();
11604   }
11605 
11606   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11607       << var->getIdentifier();
11608 
11609   // FIXME: Add additional diagnostic info about class etc. which prevents
11610   // capture.
11611 }
11612 
11613 
11614 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11615                                       bool &SubCapturesAreNested,
11616                                       QualType &CaptureType,
11617                                       QualType &DeclRefType) {
11618    // Check whether we've already captured it.
11619   if (CSI->CaptureMap.count(Var)) {
11620     // If we found a capture, any subcaptures are nested.
11621     SubCapturesAreNested = true;
11622 
11623     // Retrieve the capture type for this variable.
11624     CaptureType = CSI->getCapture(Var).getCaptureType();
11625 
11626     // Compute the type of an expression that refers to this variable.
11627     DeclRefType = CaptureType.getNonReferenceType();
11628 
11629     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11630     if (Cap.isCopyCapture() &&
11631         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11632       DeclRefType.addConst();
11633     return true;
11634   }
11635   return false;
11636 }
11637 
11638 // Only block literals, captured statements, and lambda expressions can
11639 // capture; other scopes don't work.
11640 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11641                                  SourceLocation Loc,
11642                                  const bool Diagnose, Sema &S) {
11643   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11644     return getLambdaAwareParentOfDeclContext(DC);
11645   else {
11646     if (Diagnose)
11647        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11648   }
11649   return nullptr;
11650 }
11651 
11652 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11653 // certain types of variables (unnamed, variably modified types etc.)
11654 // so check for eligibility.
11655 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11656                                  SourceLocation Loc,
11657                                  const bool Diagnose, Sema &S) {
11658 
11659   bool IsBlock = isa<BlockScopeInfo>(CSI);
11660   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11661 
11662   // Lambdas are not allowed to capture unnamed variables
11663   // (e.g. anonymous unions).
11664   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11665   // assuming that's the intent.
11666   if (IsLambda && !Var->getDeclName()) {
11667     if (Diagnose) {
11668       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11669       S.Diag(Var->getLocation(), diag::note_declared_at);
11670     }
11671     return false;
11672   }
11673 
11674   // Prohibit variably-modified types in blocks; they're difficult to deal with.
11675   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
11676     if (Diagnose) {
11677       S.Diag(Loc, diag::err_ref_vm_type);
11678       S.Diag(Var->getLocation(), diag::note_previous_decl)
11679         << Var->getDeclName();
11680     }
11681     return false;
11682   }
11683   // Prohibit structs with flexible array members too.
11684   // We cannot capture what is in the tail end of the struct.
11685   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11686     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11687       if (Diagnose) {
11688         if (IsBlock)
11689           S.Diag(Loc, diag::err_ref_flexarray_type);
11690         else
11691           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11692             << Var->getDeclName();
11693         S.Diag(Var->getLocation(), diag::note_previous_decl)
11694           << Var->getDeclName();
11695       }
11696       return false;
11697     }
11698   }
11699   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11700   // Lambdas and captured statements are not allowed to capture __block
11701   // variables; they don't support the expected semantics.
11702   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11703     if (Diagnose) {
11704       S.Diag(Loc, diag::err_capture_block_variable)
11705         << Var->getDeclName() << !IsLambda;
11706       S.Diag(Var->getLocation(), diag::note_previous_decl)
11707         << Var->getDeclName();
11708     }
11709     return false;
11710   }
11711 
11712   return true;
11713 }
11714 
11715 // Returns true if the capture by block was successful.
11716 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11717                                  SourceLocation Loc,
11718                                  const bool BuildAndDiagnose,
11719                                  QualType &CaptureType,
11720                                  QualType &DeclRefType,
11721                                  const bool Nested,
11722                                  Sema &S) {
11723   Expr *CopyExpr = nullptr;
11724   bool ByRef = false;
11725 
11726   // Blocks are not allowed to capture arrays.
11727   if (CaptureType->isArrayType()) {
11728     if (BuildAndDiagnose) {
11729       S.Diag(Loc, diag::err_ref_array_type);
11730       S.Diag(Var->getLocation(), diag::note_previous_decl)
11731       << Var->getDeclName();
11732     }
11733     return false;
11734   }
11735 
11736   // Forbid the block-capture of autoreleasing variables.
11737   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11738     if (BuildAndDiagnose) {
11739       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11740         << /*block*/ 0;
11741       S.Diag(Var->getLocation(), diag::note_previous_decl)
11742         << Var->getDeclName();
11743     }
11744     return false;
11745   }
11746   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11747   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11748     // Block capture by reference does not change the capture or
11749     // declaration reference types.
11750     ByRef = true;
11751   } else {
11752     // Block capture by copy introduces 'const'.
11753     CaptureType = CaptureType.getNonReferenceType().withConst();
11754     DeclRefType = CaptureType;
11755 
11756     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11757       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11758         // The capture logic needs the destructor, so make sure we mark it.
11759         // Usually this is unnecessary because most local variables have
11760         // their destructors marked at declaration time, but parameters are
11761         // an exception because it's technically only the call site that
11762         // actually requires the destructor.
11763         if (isa<ParmVarDecl>(Var))
11764           S.FinalizeVarWithDestructor(Var, Record);
11765 
11766         // Enter a new evaluation context to insulate the copy
11767         // full-expression.
11768         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11769 
11770         // According to the blocks spec, the capture of a variable from
11771         // the stack requires a const copy constructor.  This is not true
11772         // of the copy/move done to move a __block variable to the heap.
11773         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11774                                                   DeclRefType.withConst(),
11775                                                   VK_LValue, Loc);
11776 
11777         ExprResult Result
11778           = S.PerformCopyInitialization(
11779               InitializedEntity::InitializeBlock(Var->getLocation(),
11780                                                   CaptureType, false),
11781               Loc, DeclRef);
11782 
11783         // Build a full-expression copy expression if initialization
11784         // succeeded and used a non-trivial constructor.  Recover from
11785         // errors by pretending that the copy isn't necessary.
11786         if (!Result.isInvalid() &&
11787             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11788                 ->isTrivial()) {
11789           Result = S.MaybeCreateExprWithCleanups(Result);
11790           CopyExpr = Result.get();
11791         }
11792       }
11793     }
11794   }
11795 
11796   // Actually capture the variable.
11797   if (BuildAndDiagnose)
11798     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11799                     SourceLocation(), CaptureType, CopyExpr);
11800 
11801   return true;
11802 
11803 }
11804 
11805 
11806 /// \brief Capture the given variable in the captured region.
11807 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11808                                     VarDecl *Var,
11809                                     SourceLocation Loc,
11810                                     const bool BuildAndDiagnose,
11811                                     QualType &CaptureType,
11812                                     QualType &DeclRefType,
11813                                     const bool RefersToEnclosingLocal,
11814                                     Sema &S) {
11815 
11816   // By default, capture variables by reference.
11817   bool ByRef = true;
11818   // Using an LValue reference type is consistent with Lambdas (see below).
11819   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11820   Expr *CopyExpr = nullptr;
11821   if (BuildAndDiagnose) {
11822     // The current implementation assumes that all variables are captured
11823     // by references. Since there is no capture by copy, no expression
11824     // evaluation will be needed.
11825     RecordDecl *RD = RSI->TheRecordDecl;
11826 
11827     FieldDecl *Field
11828       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11829                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11830                           nullptr, false, ICIS_NoInit);
11831     Field->setImplicit(true);
11832     Field->setAccess(AS_private);
11833     RD->addDecl(Field);
11834 
11835     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11836                                             DeclRefType, VK_LValue, Loc);
11837     Var->setReferenced(true);
11838     Var->markUsed(S.Context);
11839   }
11840 
11841   // Actually capture the variable.
11842   if (BuildAndDiagnose)
11843     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11844                     SourceLocation(), CaptureType, CopyExpr);
11845 
11846 
11847   return true;
11848 }
11849 
11850 /// \brief Create a field within the lambda class for the variable
11851 ///  being captured.  Handle Array captures.
11852 static ExprResult addAsFieldToClosureType(Sema &S,
11853                                  LambdaScopeInfo *LSI,
11854                                   VarDecl *Var, QualType FieldType,
11855                                   QualType DeclRefType,
11856                                   SourceLocation Loc,
11857                                   bool RefersToEnclosingLocal) {
11858   CXXRecordDecl *Lambda = LSI->Lambda;
11859 
11860   // Build the non-static data member.
11861   FieldDecl *Field
11862     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11863                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11864                         nullptr, false, ICIS_NoInit);
11865   Field->setImplicit(true);
11866   Field->setAccess(AS_private);
11867   Lambda->addDecl(Field);
11868 
11869   // C++11 [expr.prim.lambda]p21:
11870   //   When the lambda-expression is evaluated, the entities that
11871   //   are captured by copy are used to direct-initialize each
11872   //   corresponding non-static data member of the resulting closure
11873   //   object. (For array members, the array elements are
11874   //   direct-initialized in increasing subscript order.) These
11875   //   initializations are performed in the (unspecified) order in
11876   //   which the non-static data members are declared.
11877 
11878   // Introduce a new evaluation context for the initialization, so
11879   // that temporaries introduced as part of the capture are retained
11880   // to be re-"exported" from the lambda expression itself.
11881   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11882 
11883   // C++ [expr.prim.labda]p12:
11884   //   An entity captured by a lambda-expression is odr-used (3.2) in
11885   //   the scope containing the lambda-expression.
11886   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11887                                           DeclRefType, VK_LValue, Loc);
11888   Var->setReferenced(true);
11889   Var->markUsed(S.Context);
11890 
11891   // When the field has array type, create index variables for each
11892   // dimension of the array. We use these index variables to subscript
11893   // the source array, and other clients (e.g., CodeGen) will perform
11894   // the necessary iteration with these index variables.
11895   SmallVector<VarDecl *, 4> IndexVariables;
11896   QualType BaseType = FieldType;
11897   QualType SizeType = S.Context.getSizeType();
11898   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11899   while (const ConstantArrayType *Array
11900                         = S.Context.getAsConstantArrayType(BaseType)) {
11901     // Create the iteration variable for this array index.
11902     IdentifierInfo *IterationVarName = nullptr;
11903     {
11904       SmallString<8> Str;
11905       llvm::raw_svector_ostream OS(Str);
11906       OS << "__i" << IndexVariables.size();
11907       IterationVarName = &S.Context.Idents.get(OS.str());
11908     }
11909     VarDecl *IterationVar
11910       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11911                         IterationVarName, SizeType,
11912                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11913                         SC_None);
11914     IndexVariables.push_back(IterationVar);
11915     LSI->ArrayIndexVars.push_back(IterationVar);
11916 
11917     // Create a reference to the iteration variable.
11918     ExprResult IterationVarRef
11919       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11920     assert(!IterationVarRef.isInvalid() &&
11921            "Reference to invented variable cannot fail!");
11922     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11923     assert(!IterationVarRef.isInvalid() &&
11924            "Conversion of invented variable cannot fail!");
11925 
11926     // Subscript the array with this iteration variable.
11927     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11928                              Ref, Loc, IterationVarRef.get(), Loc);
11929     if (Subscript.isInvalid()) {
11930       S.CleanupVarDeclMarking();
11931       S.DiscardCleanupsInEvaluationContext();
11932       return ExprError();
11933     }
11934 
11935     Ref = Subscript.get();
11936     BaseType = Array->getElementType();
11937   }
11938 
11939   // Construct the entity that we will be initializing. For an array, this
11940   // will be first element in the array, which may require several levels
11941   // of array-subscript entities.
11942   SmallVector<InitializedEntity, 4> Entities;
11943   Entities.reserve(1 + IndexVariables.size());
11944   Entities.push_back(
11945     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11946         Field->getType(), Loc));
11947   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11948     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11949                                                             0,
11950                                                             Entities.back()));
11951 
11952   InitializationKind InitKind
11953     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11954   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11955   ExprResult Result(true);
11956   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11957     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11958 
11959   // If this initialization requires any cleanups (e.g., due to a
11960   // default argument to a copy constructor), note that for the
11961   // lambda.
11962   if (S.ExprNeedsCleanups)
11963     LSI->ExprNeedsCleanups = true;
11964 
11965   // Exit the expression evaluation context used for the capture.
11966   S.CleanupVarDeclMarking();
11967   S.DiscardCleanupsInEvaluationContext();
11968   return Result;
11969 }
11970 
11971 
11972 
11973 /// \brief Capture the given variable in the lambda.
11974 static bool captureInLambda(LambdaScopeInfo *LSI,
11975                             VarDecl *Var,
11976                             SourceLocation Loc,
11977                             const bool BuildAndDiagnose,
11978                             QualType &CaptureType,
11979                             QualType &DeclRefType,
11980                             const bool RefersToEnclosingLocal,
11981                             const Sema::TryCaptureKind Kind,
11982                             SourceLocation EllipsisLoc,
11983                             const bool IsTopScope,
11984                             Sema &S) {
11985 
11986   // Determine whether we are capturing by reference or by value.
11987   bool ByRef = false;
11988   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11989     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11990   } else {
11991     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11992   }
11993 
11994   // Compute the type of the field that will capture this variable.
11995   if (ByRef) {
11996     // C++11 [expr.prim.lambda]p15:
11997     //   An entity is captured by reference if it is implicitly or
11998     //   explicitly captured but not captured by copy. It is
11999     //   unspecified whether additional unnamed non-static data
12000     //   members are declared in the closure type for entities
12001     //   captured by reference.
12002     //
12003     // FIXME: It is not clear whether we want to build an lvalue reference
12004     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12005     // to do the former, while EDG does the latter. Core issue 1249 will
12006     // clarify, but for now we follow GCC because it's a more permissive and
12007     // easily defensible position.
12008     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12009   } else {
12010     // C++11 [expr.prim.lambda]p14:
12011     //   For each entity captured by copy, an unnamed non-static
12012     //   data member is declared in the closure type. The
12013     //   declaration order of these members is unspecified. The type
12014     //   of such a data member is the type of the corresponding
12015     //   captured entity if the entity is not a reference to an
12016     //   object, or the referenced type otherwise. [Note: If the
12017     //   captured entity is a reference to a function, the
12018     //   corresponding data member is also a reference to a
12019     //   function. - end note ]
12020     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12021       if (!RefType->getPointeeType()->isFunctionType())
12022         CaptureType = RefType->getPointeeType();
12023     }
12024 
12025     // Forbid the lambda copy-capture of autoreleasing variables.
12026     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12027       if (BuildAndDiagnose) {
12028         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12029         S.Diag(Var->getLocation(), diag::note_previous_decl)
12030           << Var->getDeclName();
12031       }
12032       return false;
12033     }
12034 
12035     // Make sure that by-copy captures are of a complete and non-abstract type.
12036     if (BuildAndDiagnose) {
12037       if (!CaptureType->isDependentType() &&
12038           S.RequireCompleteType(Loc, CaptureType,
12039                                 diag::err_capture_of_incomplete_type,
12040                                 Var->getDeclName()))
12041         return false;
12042 
12043       if (S.RequireNonAbstractType(Loc, CaptureType,
12044                                    diag::err_capture_of_abstract_type))
12045         return false;
12046     }
12047   }
12048 
12049   // Capture this variable in the lambda.
12050   Expr *CopyExpr = nullptr;
12051   if (BuildAndDiagnose) {
12052     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12053                                         CaptureType, DeclRefType, Loc,
12054                                         RefersToEnclosingLocal);
12055     if (!Result.isInvalid())
12056       CopyExpr = Result.get();
12057   }
12058 
12059   // Compute the type of a reference to this captured variable.
12060   if (ByRef)
12061     DeclRefType = CaptureType.getNonReferenceType();
12062   else {
12063     // C++ [expr.prim.lambda]p5:
12064     //   The closure type for a lambda-expression has a public inline
12065     //   function call operator [...]. This function call operator is
12066     //   declared const (9.3.1) if and only if the lambda-expression’s
12067     //   parameter-declaration-clause is not followed by mutable.
12068     DeclRefType = CaptureType.getNonReferenceType();
12069     if (!LSI->Mutable && !CaptureType->isReferenceType())
12070       DeclRefType.addConst();
12071   }
12072 
12073   // Add the capture.
12074   if (BuildAndDiagnose)
12075     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12076                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12077 
12078   return true;
12079 }
12080 
12081 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12082                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12083                               bool BuildAndDiagnose,
12084                               QualType &CaptureType,
12085                               QualType &DeclRefType,
12086 						                const unsigned *const FunctionScopeIndexToStopAt) {
12087   bool Nested = false;
12088 
12089   DeclContext *DC = CurContext;
12090   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12091       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12092   // We need to sync up the Declaration Context with the
12093   // FunctionScopeIndexToStopAt
12094   if (FunctionScopeIndexToStopAt) {
12095     unsigned FSIndex = FunctionScopes.size() - 1;
12096     while (FSIndex != MaxFunctionScopesIndex) {
12097       DC = getLambdaAwareParentOfDeclContext(DC);
12098       --FSIndex;
12099     }
12100   }
12101 
12102 
12103   // If the variable is declared in the current context (and is not an
12104   // init-capture), there is no need to capture it.
12105   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12106   if (!Var->hasLocalStorage()) return true;
12107 
12108   // Walk up the stack to determine whether we can capture the variable,
12109   // performing the "simple" checks that don't depend on type. We stop when
12110   // we've either hit the declared scope of the variable or find an existing
12111   // capture of that variable.  We start from the innermost capturing-entity
12112   // (the DC) and ensure that all intervening capturing-entities
12113   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12114   // declcontext can either capture the variable or have already captured
12115   // the variable.
12116   CaptureType = Var->getType();
12117   DeclRefType = CaptureType.getNonReferenceType();
12118   bool Explicit = (Kind != TryCapture_Implicit);
12119   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12120   do {
12121     // Only block literals, captured statements, and lambda expressions can
12122     // capture; other scopes don't work.
12123     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12124                                                               ExprLoc,
12125                                                               BuildAndDiagnose,
12126                                                               *this);
12127     if (!ParentDC) return true;
12128 
12129     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12130     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12131 
12132 
12133     // Check whether we've already captured it.
12134     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12135                                              DeclRefType))
12136       break;
12137     // If we are instantiating a generic lambda call operator body,
12138     // we do not want to capture new variables.  What was captured
12139     // during either a lambdas transformation or initial parsing
12140     // should be used.
12141     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12142       if (BuildAndDiagnose) {
12143         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12144         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12145           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12146           Diag(Var->getLocation(), diag::note_previous_decl)
12147              << Var->getDeclName();
12148           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12149         } else
12150           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12151       }
12152       return true;
12153     }
12154     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12155     // certain types of variables (unnamed, variably modified types etc.)
12156     // so check for eligibility.
12157     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12158        return true;
12159 
12160     // Try to capture variable-length arrays types.
12161     if (Var->getType()->isVariablyModifiedType()) {
12162       // We're going to walk down into the type and look for VLA
12163       // expressions.
12164       QualType QTy = Var->getType();
12165       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12166         QTy = PVD->getOriginalType();
12167       do {
12168         const Type *Ty = QTy.getTypePtr();
12169         switch (Ty->getTypeClass()) {
12170 #define TYPE(Class, Base)
12171 #define ABSTRACT_TYPE(Class, Base)
12172 #define NON_CANONICAL_TYPE(Class, Base)
12173 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12174 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12175 #include "clang/AST/TypeNodes.def"
12176           QTy = QualType();
12177           break;
12178         // These types are never variably-modified.
12179         case Type::Builtin:
12180         case Type::Complex:
12181         case Type::Vector:
12182         case Type::ExtVector:
12183         case Type::Record:
12184         case Type::Enum:
12185         case Type::Elaborated:
12186         case Type::TemplateSpecialization:
12187         case Type::ObjCObject:
12188         case Type::ObjCInterface:
12189         case Type::ObjCObjectPointer:
12190           llvm_unreachable("type class is never variably-modified!");
12191         case Type::Adjusted:
12192           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12193           break;
12194         case Type::Decayed:
12195           QTy = cast<DecayedType>(Ty)->getPointeeType();
12196           break;
12197         case Type::Pointer:
12198           QTy = cast<PointerType>(Ty)->getPointeeType();
12199           break;
12200         case Type::BlockPointer:
12201           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12202           break;
12203         case Type::LValueReference:
12204         case Type::RValueReference:
12205           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12206           break;
12207         case Type::MemberPointer:
12208           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12209           break;
12210         case Type::ConstantArray:
12211         case Type::IncompleteArray:
12212           // Losing element qualification here is fine.
12213           QTy = cast<ArrayType>(Ty)->getElementType();
12214           break;
12215         case Type::VariableArray: {
12216           // Losing element qualification here is fine.
12217           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
12218 
12219           // Unknown size indication requires no size computation.
12220           // Otherwise, evaluate and record it.
12221           if (auto Size = VAT->getSizeExpr()) {
12222             if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12223               if (!LSI->isVLATypeCaptured(VAT)) {
12224                 auto ExprLoc = Size->getExprLoc();
12225                 auto SizeType = Context.getSizeType();
12226                 auto Lambda = LSI->Lambda;
12227 
12228                 // Build the non-static data member.
12229                 auto Field = FieldDecl::Create(
12230                     Context, Lambda, ExprLoc, ExprLoc,
12231                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12232                     /*BW*/ nullptr, /*Mutable*/ false,
12233                     /*InitStyle*/ ICIS_NoInit);
12234                 Field->setImplicit(true);
12235                 Field->setAccess(AS_private);
12236                 Field->setCapturedVLAType(VAT);
12237                 Lambda->addDecl(Field);
12238 
12239                 LSI->addVLATypeCapture(ExprLoc, SizeType);
12240               }
12241             } else {
12242               // Immediately mark all referenced vars for CapturedStatements,
12243               // they all are captured by reference.
12244               MarkDeclarationsReferencedInExpr(Size);
12245             }
12246           }
12247           QTy = VAT->getElementType();
12248           break;
12249         }
12250         case Type::FunctionProto:
12251         case Type::FunctionNoProto:
12252           QTy = cast<FunctionType>(Ty)->getReturnType();
12253           break;
12254         case Type::Paren:
12255         case Type::TypeOf:
12256         case Type::UnaryTransform:
12257         case Type::Attributed:
12258         case Type::SubstTemplateTypeParm:
12259         case Type::PackExpansion:
12260           // Keep walking after single level desugaring.
12261           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12262           break;
12263         case Type::Typedef:
12264           QTy = cast<TypedefType>(Ty)->desugar();
12265           break;
12266         case Type::Decltype:
12267           QTy = cast<DecltypeType>(Ty)->desugar();
12268           break;
12269         case Type::Auto:
12270           QTy = cast<AutoType>(Ty)->getDeducedType();
12271           break;
12272         case Type::TypeOfExpr:
12273           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12274           break;
12275         case Type::Atomic:
12276           QTy = cast<AtomicType>(Ty)->getValueType();
12277           break;
12278         }
12279       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12280     }
12281 
12282     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12283       // No capture-default, and this is not an explicit capture
12284       // so cannot capture this variable.
12285       if (BuildAndDiagnose) {
12286         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12287         Diag(Var->getLocation(), diag::note_previous_decl)
12288           << Var->getDeclName();
12289         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12290              diag::note_lambda_decl);
12291         // FIXME: If we error out because an outer lambda can not implicitly
12292         // capture a variable that an inner lambda explicitly captures, we
12293         // should have the inner lambda do the explicit capture - because
12294         // it makes for cleaner diagnostics later.  This would purely be done
12295         // so that the diagnostic does not misleadingly claim that a variable
12296         // can not be captured by a lambda implicitly even though it is captured
12297         // explicitly.  Suggestion:
12298         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12299         //    at the function head
12300         //  - cache the StartingDeclContext - this must be a lambda
12301         //  - captureInLambda in the innermost lambda the variable.
12302       }
12303       return true;
12304     }
12305 
12306     FunctionScopesIndex--;
12307     DC = ParentDC;
12308     Explicit = false;
12309   } while (!Var->getDeclContext()->Equals(DC));
12310 
12311   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12312   // computing the type of the capture at each step, checking type-specific
12313   // requirements, and adding captures if requested.
12314   // If the variable had already been captured previously, we start capturing
12315   // at the lambda nested within that one.
12316   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12317        ++I) {
12318     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12319 
12320     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12321       if (!captureInBlock(BSI, Var, ExprLoc,
12322                           BuildAndDiagnose, CaptureType,
12323                           DeclRefType, Nested, *this))
12324         return true;
12325       Nested = true;
12326     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12327       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12328                                    BuildAndDiagnose, CaptureType,
12329                                    DeclRefType, Nested, *this))
12330         return true;
12331       Nested = true;
12332     } else {
12333       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12334       if (!captureInLambda(LSI, Var, ExprLoc,
12335                            BuildAndDiagnose, CaptureType,
12336                            DeclRefType, Nested, Kind, EllipsisLoc,
12337                             /*IsTopScope*/I == N - 1, *this))
12338         return true;
12339       Nested = true;
12340     }
12341   }
12342   return false;
12343 }
12344 
12345 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12346                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12347   QualType CaptureType;
12348   QualType DeclRefType;
12349   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12350                             /*BuildAndDiagnose=*/true, CaptureType,
12351                             DeclRefType, nullptr);
12352 }
12353 
12354 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12355   QualType CaptureType;
12356   QualType DeclRefType;
12357 
12358   // Determine whether we can capture this variable.
12359   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12360                          /*BuildAndDiagnose=*/false, CaptureType,
12361                          DeclRefType, nullptr))
12362     return QualType();
12363 
12364   return DeclRefType;
12365 }
12366 
12367 
12368 
12369 // If either the type of the variable or the initializer is dependent,
12370 // return false. Otherwise, determine whether the variable is a constant
12371 // expression. Use this if you need to know if a variable that might or
12372 // might not be dependent is truly a constant expression.
12373 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12374     ASTContext &Context) {
12375 
12376   if (Var->getType()->isDependentType())
12377     return false;
12378   const VarDecl *DefVD = nullptr;
12379   Var->getAnyInitializer(DefVD);
12380   if (!DefVD)
12381     return false;
12382   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12383   Expr *Init = cast<Expr>(Eval->Value);
12384   if (Init->isValueDependent())
12385     return false;
12386   return IsVariableAConstantExpression(Var, Context);
12387 }
12388 
12389 
12390 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12391   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12392   // an object that satisfies the requirements for appearing in a
12393   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12394   // is immediately applied."  This function handles the lvalue-to-rvalue
12395   // conversion part.
12396   MaybeODRUseExprs.erase(E->IgnoreParens());
12397 
12398   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12399   // to a variable that is a constant expression, and if so, identify it as
12400   // a reference to a variable that does not involve an odr-use of that
12401   // variable.
12402   if (LambdaScopeInfo *LSI = getCurLambda()) {
12403     Expr *SansParensExpr = E->IgnoreParens();
12404     VarDecl *Var = nullptr;
12405     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12406       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12407     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12408       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12409 
12410     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12411       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12412   }
12413 }
12414 
12415 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12416   if (!Res.isUsable())
12417     return Res;
12418 
12419   // If a constant-expression is a reference to a variable where we delay
12420   // deciding whether it is an odr-use, just assume we will apply the
12421   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12422   // (a non-type template argument), we have special handling anyway.
12423   UpdateMarkingForLValueToRValue(Res.get());
12424   return Res;
12425 }
12426 
12427 void Sema::CleanupVarDeclMarking() {
12428   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12429                                         e = MaybeODRUseExprs.end();
12430        i != e; ++i) {
12431     VarDecl *Var;
12432     SourceLocation Loc;
12433     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12434       Var = cast<VarDecl>(DRE->getDecl());
12435       Loc = DRE->getLocation();
12436     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12437       Var = cast<VarDecl>(ME->getMemberDecl());
12438       Loc = ME->getMemberLoc();
12439     } else {
12440       llvm_unreachable("Unexpected expression");
12441     }
12442 
12443     MarkVarDeclODRUsed(Var, Loc, *this,
12444                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12445   }
12446 
12447   MaybeODRUseExprs.clear();
12448 }
12449 
12450 
12451 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12452                                     VarDecl *Var, Expr *E) {
12453   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12454          "Invalid Expr argument to DoMarkVarDeclReferenced");
12455   Var->setReferenced();
12456 
12457   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12458   bool MarkODRUsed = true;
12459 
12460   // If the context is not potentially evaluated, this is not an odr-use and
12461   // does not trigger instantiation.
12462   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12463     if (SemaRef.isUnevaluatedContext())
12464       return;
12465 
12466     // If we don't yet know whether this context is going to end up being an
12467     // evaluated context, and we're referencing a variable from an enclosing
12468     // scope, add a potential capture.
12469     //
12470     // FIXME: Is this necessary? These contexts are only used for default
12471     // arguments, where local variables can't be used.
12472     const bool RefersToEnclosingScope =
12473         (SemaRef.CurContext != Var->getDeclContext() &&
12474          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
12475     if (RefersToEnclosingScope) {
12476       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12477         // If a variable could potentially be odr-used, defer marking it so
12478         // until we finish analyzing the full expression for any
12479         // lvalue-to-rvalue
12480         // or discarded value conversions that would obviate odr-use.
12481         // Add it to the list of potential captures that will be analyzed
12482         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12483         // unless the variable is a reference that was initialized by a constant
12484         // expression (this will never need to be captured or odr-used).
12485         assert(E && "Capture variable should be used in an expression.");
12486         if (!Var->getType()->isReferenceType() ||
12487             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12488           LSI->addPotentialCapture(E->IgnoreParens());
12489       }
12490     }
12491 
12492     if (!isTemplateInstantiation(TSK))
12493     	return;
12494 
12495     // Instantiate, but do not mark as odr-used, variable templates.
12496     MarkODRUsed = false;
12497   }
12498 
12499   VarTemplateSpecializationDecl *VarSpec =
12500       dyn_cast<VarTemplateSpecializationDecl>(Var);
12501   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12502          "Can't instantiate a partial template specialization.");
12503 
12504   // Perform implicit instantiation of static data members, static data member
12505   // templates of class templates, and variable template specializations. Delay
12506   // instantiations of variable templates, except for those that could be used
12507   // in a constant expression.
12508   if (isTemplateInstantiation(TSK)) {
12509     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12510 
12511     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12512       if (Var->getPointOfInstantiation().isInvalid()) {
12513         // This is a modification of an existing AST node. Notify listeners.
12514         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12515           L->StaticDataMemberInstantiated(Var);
12516       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12517         // Don't bother trying to instantiate it again, unless we might need
12518         // its initializer before we get to the end of the TU.
12519         TryInstantiating = false;
12520     }
12521 
12522     if (Var->getPointOfInstantiation().isInvalid())
12523       Var->setTemplateSpecializationKind(TSK, Loc);
12524 
12525     if (TryInstantiating) {
12526       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12527       bool InstantiationDependent = false;
12528       bool IsNonDependent =
12529           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12530                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12531                   : true;
12532 
12533       // Do not instantiate specializations that are still type-dependent.
12534       if (IsNonDependent) {
12535         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12536           // Do not defer instantiations of variables which could be used in a
12537           // constant expression.
12538           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12539         } else {
12540           SemaRef.PendingInstantiations
12541               .push_back(std::make_pair(Var, PointOfInstantiation));
12542         }
12543       }
12544     }
12545   }
12546 
12547   if(!MarkODRUsed) return;
12548 
12549   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12550   // the requirements for appearing in a constant expression (5.19) and, if
12551   // it is an object, the lvalue-to-rvalue conversion (4.1)
12552   // is immediately applied."  We check the first part here, and
12553   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12554   // Note that we use the C++11 definition everywhere because nothing in
12555   // C++03 depends on whether we get the C++03 version correct. The second
12556   // part does not apply to references, since they are not objects.
12557   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12558     // A reference initialized by a constant expression can never be
12559     // odr-used, so simply ignore it.
12560     if (!Var->getType()->isReferenceType())
12561       SemaRef.MaybeODRUseExprs.insert(E);
12562   } else
12563     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12564                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12565 }
12566 
12567 /// \brief Mark a variable referenced, and check whether it is odr-used
12568 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12569 /// used directly for normal expressions referring to VarDecl.
12570 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12571   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12572 }
12573 
12574 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12575                                Decl *D, Expr *E, bool OdrUse) {
12576   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12577     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12578     return;
12579   }
12580 
12581   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12582 
12583   // If this is a call to a method via a cast, also mark the method in the
12584   // derived class used in case codegen can devirtualize the call.
12585   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12586   if (!ME)
12587     return;
12588   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12589   if (!MD)
12590     return;
12591   // Only attempt to devirtualize if this is truly a virtual call.
12592   bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
12593   if (!IsVirtualCall)
12594     return;
12595   const Expr *Base = ME->getBase();
12596   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12597   if (!MostDerivedClassDecl)
12598     return;
12599   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12600   if (!DM || DM->isPure())
12601     return;
12602   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12603 }
12604 
12605 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12606 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12607   // TODO: update this with DR# once a defect report is filed.
12608   // C++11 defect. The address of a pure member should not be an ODR use, even
12609   // if it's a qualified reference.
12610   bool OdrUse = true;
12611   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12612     if (Method->isVirtual())
12613       OdrUse = false;
12614   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12615 }
12616 
12617 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12618 void Sema::MarkMemberReferenced(MemberExpr *E) {
12619   // C++11 [basic.def.odr]p2:
12620   //   A non-overloaded function whose name appears as a potentially-evaluated
12621   //   expression or a member of a set of candidate functions, if selected by
12622   //   overload resolution when referred to from a potentially-evaluated
12623   //   expression, is odr-used, unless it is a pure virtual function and its
12624   //   name is not explicitly qualified.
12625   bool OdrUse = true;
12626   if (!E->hasQualifier()) {
12627     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12628       if (Method->isPure())
12629         OdrUse = false;
12630   }
12631   SourceLocation Loc = E->getMemberLoc().isValid() ?
12632                             E->getMemberLoc() : E->getLocStart();
12633   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12634 }
12635 
12636 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12637 /// marks the declaration referenced, and performs odr-use checking for
12638 /// functions and variables. This method should not be used when building a
12639 /// normal expression which refers to a variable.
12640 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12641   if (OdrUse) {
12642     if (auto *VD = dyn_cast<VarDecl>(D)) {
12643       MarkVariableReferenced(Loc, VD);
12644       return;
12645     }
12646   }
12647   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
12648     MarkFunctionReferenced(Loc, FD, OdrUse);
12649     return;
12650   }
12651   D->setReferenced();
12652 }
12653 
12654 namespace {
12655   // Mark all of the declarations referenced
12656   // FIXME: Not fully implemented yet! We need to have a better understanding
12657   // of when we're entering
12658   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12659     Sema &S;
12660     SourceLocation Loc;
12661 
12662   public:
12663     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12664 
12665     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12666 
12667     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12668     bool TraverseRecordType(RecordType *T);
12669   };
12670 }
12671 
12672 bool MarkReferencedDecls::TraverseTemplateArgument(
12673     const TemplateArgument &Arg) {
12674   if (Arg.getKind() == TemplateArgument::Declaration) {
12675     if (Decl *D = Arg.getAsDecl())
12676       S.MarkAnyDeclReferenced(Loc, D, true);
12677   }
12678 
12679   return Inherited::TraverseTemplateArgument(Arg);
12680 }
12681 
12682 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12683   if (ClassTemplateSpecializationDecl *Spec
12684                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12685     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12686     return TraverseTemplateArguments(Args.data(), Args.size());
12687   }
12688 
12689   return true;
12690 }
12691 
12692 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12693   MarkReferencedDecls Marker(*this, Loc);
12694   Marker.TraverseType(Context.getCanonicalType(T));
12695 }
12696 
12697 namespace {
12698   /// \brief Helper class that marks all of the declarations referenced by
12699   /// potentially-evaluated subexpressions as "referenced".
12700   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12701     Sema &S;
12702     bool SkipLocalVariables;
12703 
12704   public:
12705     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12706 
12707     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12708       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12709 
12710     void VisitDeclRefExpr(DeclRefExpr *E) {
12711       // If we were asked not to visit local variables, don't.
12712       if (SkipLocalVariables) {
12713         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12714           if (VD->hasLocalStorage())
12715             return;
12716       }
12717 
12718       S.MarkDeclRefReferenced(E);
12719     }
12720 
12721     void VisitMemberExpr(MemberExpr *E) {
12722       S.MarkMemberReferenced(E);
12723       Inherited::VisitMemberExpr(E);
12724     }
12725 
12726     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12727       S.MarkFunctionReferenced(E->getLocStart(),
12728             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12729       Visit(E->getSubExpr());
12730     }
12731 
12732     void VisitCXXNewExpr(CXXNewExpr *E) {
12733       if (E->getOperatorNew())
12734         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12735       if (E->getOperatorDelete())
12736         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12737       Inherited::VisitCXXNewExpr(E);
12738     }
12739 
12740     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12741       if (E->getOperatorDelete())
12742         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12743       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12744       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12745         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12746         S.MarkFunctionReferenced(E->getLocStart(),
12747                                     S.LookupDestructor(Record));
12748       }
12749 
12750       Inherited::VisitCXXDeleteExpr(E);
12751     }
12752 
12753     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12754       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12755       Inherited::VisitCXXConstructExpr(E);
12756     }
12757 
12758     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12759       Visit(E->getExpr());
12760     }
12761 
12762     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12763       Inherited::VisitImplicitCastExpr(E);
12764 
12765       if (E->getCastKind() == CK_LValueToRValue)
12766         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12767     }
12768   };
12769 }
12770 
12771 /// \brief Mark any declarations that appear within this expression or any
12772 /// potentially-evaluated subexpressions as "referenced".
12773 ///
12774 /// \param SkipLocalVariables If true, don't mark local variables as
12775 /// 'referenced'.
12776 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12777                                             bool SkipLocalVariables) {
12778   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12779 }
12780 
12781 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12782 /// of the program being compiled.
12783 ///
12784 /// This routine emits the given diagnostic when the code currently being
12785 /// type-checked is "potentially evaluated", meaning that there is a
12786 /// possibility that the code will actually be executable. Code in sizeof()
12787 /// expressions, code used only during overload resolution, etc., are not
12788 /// potentially evaluated. This routine will suppress such diagnostics or,
12789 /// in the absolutely nutty case of potentially potentially evaluated
12790 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12791 /// later.
12792 ///
12793 /// This routine should be used for all diagnostics that describe the run-time
12794 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12795 /// Failure to do so will likely result in spurious diagnostics or failures
12796 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12797 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12798                                const PartialDiagnostic &PD) {
12799   switch (ExprEvalContexts.back().Context) {
12800   case Unevaluated:
12801   case UnevaluatedAbstract:
12802     // The argument will never be evaluated, so don't complain.
12803     break;
12804 
12805   case ConstantEvaluated:
12806     // Relevant diagnostics should be produced by constant evaluation.
12807     break;
12808 
12809   case PotentiallyEvaluated:
12810   case PotentiallyEvaluatedIfUsed:
12811     if (Statement && getCurFunctionOrMethodDecl()) {
12812       FunctionScopes.back()->PossiblyUnreachableDiags.
12813         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12814     }
12815     else
12816       Diag(Loc, PD);
12817 
12818     return true;
12819   }
12820 
12821   return false;
12822 }
12823 
12824 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12825                                CallExpr *CE, FunctionDecl *FD) {
12826   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12827     return false;
12828 
12829   // If we're inside a decltype's expression, don't check for a valid return
12830   // type or construct temporaries until we know whether this is the last call.
12831   if (ExprEvalContexts.back().IsDecltype) {
12832     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12833     return false;
12834   }
12835 
12836   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12837     FunctionDecl *FD;
12838     CallExpr *CE;
12839 
12840   public:
12841     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12842       : FD(FD), CE(CE) { }
12843 
12844     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12845       if (!FD) {
12846         S.Diag(Loc, diag::err_call_incomplete_return)
12847           << T << CE->getSourceRange();
12848         return;
12849       }
12850 
12851       S.Diag(Loc, diag::err_call_function_incomplete_return)
12852         << CE->getSourceRange() << FD->getDeclName() << T;
12853       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12854           << FD->getDeclName();
12855     }
12856   } Diagnoser(FD, CE);
12857 
12858   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12859     return true;
12860 
12861   return false;
12862 }
12863 
12864 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12865 // will prevent this condition from triggering, which is what we want.
12866 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12867   SourceLocation Loc;
12868 
12869   unsigned diagnostic = diag::warn_condition_is_assignment;
12870   bool IsOrAssign = false;
12871 
12872   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12873     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12874       return;
12875 
12876     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12877 
12878     // Greylist some idioms by putting them into a warning subcategory.
12879     if (ObjCMessageExpr *ME
12880           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12881       Selector Sel = ME->getSelector();
12882 
12883       // self = [<foo> init...]
12884       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12885         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12886 
12887       // <foo> = [<bar> nextObject]
12888       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12889         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12890     }
12891 
12892     Loc = Op->getOperatorLoc();
12893   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12894     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12895       return;
12896 
12897     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12898     Loc = Op->getOperatorLoc();
12899   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12900     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12901   else {
12902     // Not an assignment.
12903     return;
12904   }
12905 
12906   Diag(Loc, diagnostic) << E->getSourceRange();
12907 
12908   SourceLocation Open = E->getLocStart();
12909   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12910   Diag(Loc, diag::note_condition_assign_silence)
12911         << FixItHint::CreateInsertion(Open, "(")
12912         << FixItHint::CreateInsertion(Close, ")");
12913 
12914   if (IsOrAssign)
12915     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12916       << FixItHint::CreateReplacement(Loc, "!=");
12917   else
12918     Diag(Loc, diag::note_condition_assign_to_comparison)
12919       << FixItHint::CreateReplacement(Loc, "==");
12920 }
12921 
12922 /// \brief Redundant parentheses over an equality comparison can indicate
12923 /// that the user intended an assignment used as condition.
12924 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12925   // Don't warn if the parens came from a macro.
12926   SourceLocation parenLoc = ParenE->getLocStart();
12927   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12928     return;
12929   // Don't warn for dependent expressions.
12930   if (ParenE->isTypeDependent())
12931     return;
12932 
12933   Expr *E = ParenE->IgnoreParens();
12934 
12935   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12936     if (opE->getOpcode() == BO_EQ &&
12937         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12938                                                            == Expr::MLV_Valid) {
12939       SourceLocation Loc = opE->getOperatorLoc();
12940 
12941       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12942       SourceRange ParenERange = ParenE->getSourceRange();
12943       Diag(Loc, diag::note_equality_comparison_silence)
12944         << FixItHint::CreateRemoval(ParenERange.getBegin())
12945         << FixItHint::CreateRemoval(ParenERange.getEnd());
12946       Diag(Loc, diag::note_equality_comparison_to_assign)
12947         << FixItHint::CreateReplacement(Loc, "=");
12948     }
12949 }
12950 
12951 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12952   DiagnoseAssignmentAsCondition(E);
12953   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12954     DiagnoseEqualityWithExtraParens(parenE);
12955 
12956   ExprResult result = CheckPlaceholderExpr(E);
12957   if (result.isInvalid()) return ExprError();
12958   E = result.get();
12959 
12960   if (!E->isTypeDependent()) {
12961     if (getLangOpts().CPlusPlus)
12962       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12963 
12964     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12965     if (ERes.isInvalid())
12966       return ExprError();
12967     E = ERes.get();
12968 
12969     QualType T = E->getType();
12970     if (!T->isScalarType()) { // C99 6.8.4.1p1
12971       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12972         << T << E->getSourceRange();
12973       return ExprError();
12974     }
12975   }
12976 
12977   return E;
12978 }
12979 
12980 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12981                                        Expr *SubExpr) {
12982   if (!SubExpr)
12983     return ExprError();
12984 
12985   return CheckBooleanCondition(SubExpr, Loc);
12986 }
12987 
12988 namespace {
12989   /// A visitor for rebuilding a call to an __unknown_any expression
12990   /// to have an appropriate type.
12991   struct RebuildUnknownAnyFunction
12992     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12993 
12994     Sema &S;
12995 
12996     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12997 
12998     ExprResult VisitStmt(Stmt *S) {
12999       llvm_unreachable("unexpected statement!");
13000     }
13001 
13002     ExprResult VisitExpr(Expr *E) {
13003       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13004         << E->getSourceRange();
13005       return ExprError();
13006     }
13007 
13008     /// Rebuild an expression which simply semantically wraps another
13009     /// expression which it shares the type and value kind of.
13010     template <class T> ExprResult rebuildSugarExpr(T *E) {
13011       ExprResult SubResult = Visit(E->getSubExpr());
13012       if (SubResult.isInvalid()) return ExprError();
13013 
13014       Expr *SubExpr = SubResult.get();
13015       E->setSubExpr(SubExpr);
13016       E->setType(SubExpr->getType());
13017       E->setValueKind(SubExpr->getValueKind());
13018       assert(E->getObjectKind() == OK_Ordinary);
13019       return E;
13020     }
13021 
13022     ExprResult VisitParenExpr(ParenExpr *E) {
13023       return rebuildSugarExpr(E);
13024     }
13025 
13026     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13027       return rebuildSugarExpr(E);
13028     }
13029 
13030     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13031       ExprResult SubResult = Visit(E->getSubExpr());
13032       if (SubResult.isInvalid()) return ExprError();
13033 
13034       Expr *SubExpr = SubResult.get();
13035       E->setSubExpr(SubExpr);
13036       E->setType(S.Context.getPointerType(SubExpr->getType()));
13037       assert(E->getValueKind() == VK_RValue);
13038       assert(E->getObjectKind() == OK_Ordinary);
13039       return E;
13040     }
13041 
13042     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13043       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13044 
13045       E->setType(VD->getType());
13046 
13047       assert(E->getValueKind() == VK_RValue);
13048       if (S.getLangOpts().CPlusPlus &&
13049           !(isa<CXXMethodDecl>(VD) &&
13050             cast<CXXMethodDecl>(VD)->isInstance()))
13051         E->setValueKind(VK_LValue);
13052 
13053       return E;
13054     }
13055 
13056     ExprResult VisitMemberExpr(MemberExpr *E) {
13057       return resolveDecl(E, E->getMemberDecl());
13058     }
13059 
13060     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13061       return resolveDecl(E, E->getDecl());
13062     }
13063   };
13064 }
13065 
13066 /// Given a function expression of unknown-any type, try to rebuild it
13067 /// to have a function type.
13068 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13069   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13070   if (Result.isInvalid()) return ExprError();
13071   return S.DefaultFunctionArrayConversion(Result.get());
13072 }
13073 
13074 namespace {
13075   /// A visitor for rebuilding an expression of type __unknown_anytype
13076   /// into one which resolves the type directly on the referring
13077   /// expression.  Strict preservation of the original source
13078   /// structure is not a goal.
13079   struct RebuildUnknownAnyExpr
13080     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13081 
13082     Sema &S;
13083 
13084     /// The current destination type.
13085     QualType DestType;
13086 
13087     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13088       : S(S), DestType(CastType) {}
13089 
13090     ExprResult VisitStmt(Stmt *S) {
13091       llvm_unreachable("unexpected statement!");
13092     }
13093 
13094     ExprResult VisitExpr(Expr *E) {
13095       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13096         << E->getSourceRange();
13097       return ExprError();
13098     }
13099 
13100     ExprResult VisitCallExpr(CallExpr *E);
13101     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13102 
13103     /// Rebuild an expression which simply semantically wraps another
13104     /// expression which it shares the type and value kind of.
13105     template <class T> ExprResult rebuildSugarExpr(T *E) {
13106       ExprResult SubResult = Visit(E->getSubExpr());
13107       if (SubResult.isInvalid()) return ExprError();
13108       Expr *SubExpr = SubResult.get();
13109       E->setSubExpr(SubExpr);
13110       E->setType(SubExpr->getType());
13111       E->setValueKind(SubExpr->getValueKind());
13112       assert(E->getObjectKind() == OK_Ordinary);
13113       return E;
13114     }
13115 
13116     ExprResult VisitParenExpr(ParenExpr *E) {
13117       return rebuildSugarExpr(E);
13118     }
13119 
13120     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13121       return rebuildSugarExpr(E);
13122     }
13123 
13124     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13125       const PointerType *Ptr = DestType->getAs<PointerType>();
13126       if (!Ptr) {
13127         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13128           << E->getSourceRange();
13129         return ExprError();
13130       }
13131       assert(E->getValueKind() == VK_RValue);
13132       assert(E->getObjectKind() == OK_Ordinary);
13133       E->setType(DestType);
13134 
13135       // Build the sub-expression as if it were an object of the pointee type.
13136       DestType = Ptr->getPointeeType();
13137       ExprResult SubResult = Visit(E->getSubExpr());
13138       if (SubResult.isInvalid()) return ExprError();
13139       E->setSubExpr(SubResult.get());
13140       return E;
13141     }
13142 
13143     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13144 
13145     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13146 
13147     ExprResult VisitMemberExpr(MemberExpr *E) {
13148       return resolveDecl(E, E->getMemberDecl());
13149     }
13150 
13151     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13152       return resolveDecl(E, E->getDecl());
13153     }
13154   };
13155 }
13156 
13157 /// Rebuilds a call expression which yielded __unknown_anytype.
13158 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13159   Expr *CalleeExpr = E->getCallee();
13160 
13161   enum FnKind {
13162     FK_MemberFunction,
13163     FK_FunctionPointer,
13164     FK_BlockPointer
13165   };
13166 
13167   FnKind Kind;
13168   QualType CalleeType = CalleeExpr->getType();
13169   if (CalleeType == S.Context.BoundMemberTy) {
13170     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13171     Kind = FK_MemberFunction;
13172     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13173   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13174     CalleeType = Ptr->getPointeeType();
13175     Kind = FK_FunctionPointer;
13176   } else {
13177     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13178     Kind = FK_BlockPointer;
13179   }
13180   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13181 
13182   // Verify that this is a legal result type of a function.
13183   if (DestType->isArrayType() || DestType->isFunctionType()) {
13184     unsigned diagID = diag::err_func_returning_array_function;
13185     if (Kind == FK_BlockPointer)
13186       diagID = diag::err_block_returning_array_function;
13187 
13188     S.Diag(E->getExprLoc(), diagID)
13189       << DestType->isFunctionType() << DestType;
13190     return ExprError();
13191   }
13192 
13193   // Otherwise, go ahead and set DestType as the call's result.
13194   E->setType(DestType.getNonLValueExprType(S.Context));
13195   E->setValueKind(Expr::getValueKindForType(DestType));
13196   assert(E->getObjectKind() == OK_Ordinary);
13197 
13198   // Rebuild the function type, replacing the result type with DestType.
13199   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13200   if (Proto) {
13201     // __unknown_anytype(...) is a special case used by the debugger when
13202     // it has no idea what a function's signature is.
13203     //
13204     // We want to build this call essentially under the K&R
13205     // unprototyped rules, but making a FunctionNoProtoType in C++
13206     // would foul up all sorts of assumptions.  However, we cannot
13207     // simply pass all arguments as variadic arguments, nor can we
13208     // portably just call the function under a non-variadic type; see
13209     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13210     // However, it turns out that in practice it is generally safe to
13211     // call a function declared as "A foo(B,C,D);" under the prototype
13212     // "A foo(B,C,D,...);".  The only known exception is with the
13213     // Windows ABI, where any variadic function is implicitly cdecl
13214     // regardless of its normal CC.  Therefore we change the parameter
13215     // types to match the types of the arguments.
13216     //
13217     // This is a hack, but it is far superior to moving the
13218     // corresponding target-specific code from IR-gen to Sema/AST.
13219 
13220     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13221     SmallVector<QualType, 8> ArgTypes;
13222     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13223       ArgTypes.reserve(E->getNumArgs());
13224       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13225         Expr *Arg = E->getArg(i);
13226         QualType ArgType = Arg->getType();
13227         if (E->isLValue()) {
13228           ArgType = S.Context.getLValueReferenceType(ArgType);
13229         } else if (E->isXValue()) {
13230           ArgType = S.Context.getRValueReferenceType(ArgType);
13231         }
13232         ArgTypes.push_back(ArgType);
13233       }
13234       ParamTypes = ArgTypes;
13235     }
13236     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13237                                          Proto->getExtProtoInfo());
13238   } else {
13239     DestType = S.Context.getFunctionNoProtoType(DestType,
13240                                                 FnType->getExtInfo());
13241   }
13242 
13243   // Rebuild the appropriate pointer-to-function type.
13244   switch (Kind) {
13245   case FK_MemberFunction:
13246     // Nothing to do.
13247     break;
13248 
13249   case FK_FunctionPointer:
13250     DestType = S.Context.getPointerType(DestType);
13251     break;
13252 
13253   case FK_BlockPointer:
13254     DestType = S.Context.getBlockPointerType(DestType);
13255     break;
13256   }
13257 
13258   // Finally, we can recurse.
13259   ExprResult CalleeResult = Visit(CalleeExpr);
13260   if (!CalleeResult.isUsable()) return ExprError();
13261   E->setCallee(CalleeResult.get());
13262 
13263   // Bind a temporary if necessary.
13264   return S.MaybeBindToTemporary(E);
13265 }
13266 
13267 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13268   // Verify that this is a legal result type of a call.
13269   if (DestType->isArrayType() || DestType->isFunctionType()) {
13270     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13271       << DestType->isFunctionType() << DestType;
13272     return ExprError();
13273   }
13274 
13275   // Rewrite the method result type if available.
13276   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13277     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13278     Method->setReturnType(DestType);
13279   }
13280 
13281   // Change the type of the message.
13282   E->setType(DestType.getNonReferenceType());
13283   E->setValueKind(Expr::getValueKindForType(DestType));
13284 
13285   return S.MaybeBindToTemporary(E);
13286 }
13287 
13288 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13289   // The only case we should ever see here is a function-to-pointer decay.
13290   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13291     assert(E->getValueKind() == VK_RValue);
13292     assert(E->getObjectKind() == OK_Ordinary);
13293 
13294     E->setType(DestType);
13295 
13296     // Rebuild the sub-expression as the pointee (function) type.
13297     DestType = DestType->castAs<PointerType>()->getPointeeType();
13298 
13299     ExprResult Result = Visit(E->getSubExpr());
13300     if (!Result.isUsable()) return ExprError();
13301 
13302     E->setSubExpr(Result.get());
13303     return E;
13304   } else if (E->getCastKind() == CK_LValueToRValue) {
13305     assert(E->getValueKind() == VK_RValue);
13306     assert(E->getObjectKind() == OK_Ordinary);
13307 
13308     assert(isa<BlockPointerType>(E->getType()));
13309 
13310     E->setType(DestType);
13311 
13312     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13313     DestType = S.Context.getLValueReferenceType(DestType);
13314 
13315     ExprResult Result = Visit(E->getSubExpr());
13316     if (!Result.isUsable()) return ExprError();
13317 
13318     E->setSubExpr(Result.get());
13319     return E;
13320   } else {
13321     llvm_unreachable("Unhandled cast type!");
13322   }
13323 }
13324 
13325 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13326   ExprValueKind ValueKind = VK_LValue;
13327   QualType Type = DestType;
13328 
13329   // We know how to make this work for certain kinds of decls:
13330 
13331   //  - functions
13332   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13333     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13334       DestType = Ptr->getPointeeType();
13335       ExprResult Result = resolveDecl(E, VD);
13336       if (Result.isInvalid()) return ExprError();
13337       return S.ImpCastExprToType(Result.get(), Type,
13338                                  CK_FunctionToPointerDecay, VK_RValue);
13339     }
13340 
13341     if (!Type->isFunctionType()) {
13342       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13343         << VD << E->getSourceRange();
13344       return ExprError();
13345     }
13346 
13347     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13348       if (MD->isInstance()) {
13349         ValueKind = VK_RValue;
13350         Type = S.Context.BoundMemberTy;
13351       }
13352 
13353     // Function references aren't l-values in C.
13354     if (!S.getLangOpts().CPlusPlus)
13355       ValueKind = VK_RValue;
13356 
13357   //  - variables
13358   } else if (isa<VarDecl>(VD)) {
13359     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13360       Type = RefTy->getPointeeType();
13361     } else if (Type->isFunctionType()) {
13362       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13363         << VD << E->getSourceRange();
13364       return ExprError();
13365     }
13366 
13367   //  - nothing else
13368   } else {
13369     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13370       << VD << E->getSourceRange();
13371     return ExprError();
13372   }
13373 
13374   // Modifying the declaration like this is friendly to IR-gen but
13375   // also really dangerous.
13376   VD->setType(DestType);
13377   E->setType(Type);
13378   E->setValueKind(ValueKind);
13379   return E;
13380 }
13381 
13382 /// Check a cast of an unknown-any type.  We intentionally only
13383 /// trigger this for C-style casts.
13384 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13385                                      Expr *CastExpr, CastKind &CastKind,
13386                                      ExprValueKind &VK, CXXCastPath &Path) {
13387   // Rewrite the casted expression from scratch.
13388   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13389   if (!result.isUsable()) return ExprError();
13390 
13391   CastExpr = result.get();
13392   VK = CastExpr->getValueKind();
13393   CastKind = CK_NoOp;
13394 
13395   return CastExpr;
13396 }
13397 
13398 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13399   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13400 }
13401 
13402 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13403                                     Expr *arg, QualType &paramType) {
13404   // If the syntactic form of the argument is not an explicit cast of
13405   // any sort, just do default argument promotion.
13406   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13407   if (!castArg) {
13408     ExprResult result = DefaultArgumentPromotion(arg);
13409     if (result.isInvalid()) return ExprError();
13410     paramType = result.get()->getType();
13411     return result;
13412   }
13413 
13414   // Otherwise, use the type that was written in the explicit cast.
13415   assert(!arg->hasPlaceholderType());
13416   paramType = castArg->getTypeAsWritten();
13417 
13418   // Copy-initialize a parameter of that type.
13419   InitializedEntity entity =
13420     InitializedEntity::InitializeParameter(Context, paramType,
13421                                            /*consumed*/ false);
13422   return PerformCopyInitialization(entity, callLoc, arg);
13423 }
13424 
13425 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13426   Expr *orig = E;
13427   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13428   while (true) {
13429     E = E->IgnoreParenImpCasts();
13430     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13431       E = call->getCallee();
13432       diagID = diag::err_uncasted_call_of_unknown_any;
13433     } else {
13434       break;
13435     }
13436   }
13437 
13438   SourceLocation loc;
13439   NamedDecl *d;
13440   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13441     loc = ref->getLocation();
13442     d = ref->getDecl();
13443   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13444     loc = mem->getMemberLoc();
13445     d = mem->getMemberDecl();
13446   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13447     diagID = diag::err_uncasted_call_of_unknown_any;
13448     loc = msg->getSelectorStartLoc();
13449     d = msg->getMethodDecl();
13450     if (!d) {
13451       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13452         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13453         << orig->getSourceRange();
13454       return ExprError();
13455     }
13456   } else {
13457     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13458       << E->getSourceRange();
13459     return ExprError();
13460   }
13461 
13462   S.Diag(loc, diagID) << d << orig->getSourceRange();
13463 
13464   // Never recoverable.
13465   return ExprError();
13466 }
13467 
13468 /// Check for operands with placeholder types and complain if found.
13469 /// Returns true if there was an error and no recovery was possible.
13470 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13471   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13472   if (!placeholderType) return E;
13473 
13474   switch (placeholderType->getKind()) {
13475 
13476   // Overloaded expressions.
13477   case BuiltinType::Overload: {
13478     // Try to resolve a single function template specialization.
13479     // This is obligatory.
13480     ExprResult result = E;
13481     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13482       return result;
13483 
13484     // If that failed, try to recover with a call.
13485     } else {
13486       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13487                            /*complain*/ true);
13488       return result;
13489     }
13490   }
13491 
13492   // Bound member functions.
13493   case BuiltinType::BoundMember: {
13494     ExprResult result = E;
13495     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13496                          /*complain*/ true);
13497     return result;
13498   }
13499 
13500   // ARC unbridged casts.
13501   case BuiltinType::ARCUnbridgedCast: {
13502     Expr *realCast = stripARCUnbridgedCast(E);
13503     diagnoseARCUnbridgedCast(realCast);
13504     return realCast;
13505   }
13506 
13507   // Expressions of unknown type.
13508   case BuiltinType::UnknownAny:
13509     return diagnoseUnknownAnyExpr(*this, E);
13510 
13511   // Pseudo-objects.
13512   case BuiltinType::PseudoObject:
13513     return checkPseudoObjectRValue(E);
13514 
13515   case BuiltinType::BuiltinFn: {
13516     // Accept __noop without parens by implicitly converting it to a call expr.
13517     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
13518     if (DRE) {
13519       auto *FD = cast<FunctionDecl>(DRE->getDecl());
13520       if (FD->getBuiltinID() == Builtin::BI__noop) {
13521         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
13522                               CK_BuiltinFnToFnPtr).get();
13523         return new (Context) CallExpr(Context, E, None, Context.IntTy,
13524                                       VK_RValue, SourceLocation());
13525       }
13526     }
13527 
13528     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13529     return ExprError();
13530   }
13531 
13532   // Everything else should be impossible.
13533 #define BUILTIN_TYPE(Id, SingletonId) \
13534   case BuiltinType::Id:
13535 #define PLACEHOLDER_TYPE(Id, SingletonId)
13536 #include "clang/AST/BuiltinTypes.def"
13537     break;
13538   }
13539 
13540   llvm_unreachable("invalid placeholder type!");
13541 }
13542 
13543 bool Sema::CheckCaseExpression(Expr *E) {
13544   if (E->isTypeDependent())
13545     return true;
13546   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13547     return E->getType()->isIntegralOrEnumerationType();
13548   return false;
13549 }
13550 
13551 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13552 ExprResult
13553 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13554   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13555          "Unknown Objective-C Boolean value!");
13556   QualType BoolT = Context.ObjCBuiltinBoolTy;
13557   if (!Context.getBOOLDecl()) {
13558     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13559                         Sema::LookupOrdinaryName);
13560     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13561       NamedDecl *ND = Result.getFoundDecl();
13562       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13563         Context.setBOOLDecl(TD);
13564     }
13565   }
13566   if (Context.getBOOLDecl())
13567     BoolT = Context.getBOOLType();
13568   return new (Context)
13569       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13570 }
13571