1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/Support/ConvertUTF.h"
46 using namespace clang;
47 using namespace sema;
48 
49 /// \brief Determine whether the use of this declaration is valid, without
50 /// emitting diagnostics.
51 bool Sema::CanUseDecl(NamedDecl *D) {
52   // See if this is an auto-typed variable whose initializer we are parsing.
53   if (ParsingInitForAutoVars.count(D))
54     return false;
55 
56   // See if this is a deleted function.
57   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
58     if (FD->isDeleted())
59       return false;
60 
61     // If the function has a deduced return type, and we can't deduce it,
62     // then we can't use it either.
63     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
64         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
65       return false;
66   }
67 
68   // See if this function is unavailable.
69   if (D->getAvailability() == AR_Unavailable &&
70       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
71     return false;
72 
73   return true;
74 }
75 
76 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
77   // Warn if this is used but marked unused.
78   if (D->hasAttr<UnusedAttr>()) {
79     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
80     if (!DC->hasAttr<UnusedAttr>())
81       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
82   }
83 }
84 
85 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
86                               NamedDecl *D, SourceLocation Loc,
87                               const ObjCInterfaceDecl *UnknownObjCClass,
88                               bool ObjCPropertyAccess) {
89   // See if this declaration is unavailable or deprecated.
90   std::string Message;
91 
92   // Forward class declarations get their attributes from their definition.
93   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
94     if (IDecl->getDefinition())
95       D = IDecl->getDefinition();
96   }
97   AvailabilityResult Result = D->getAvailability(&Message);
98   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
99     if (Result == AR_Available) {
100       const DeclContext *DC = ECD->getDeclContext();
101       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
102         Result = TheEnumDecl->getAvailability(&Message);
103     }
104 
105   const ObjCPropertyDecl *ObjCPDecl = nullptr;
106   if (Result == AR_Deprecated || Result == AR_Unavailable) {
107     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
108       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
109         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
110         if (PDeclResult == Result)
111           ObjCPDecl = PD;
112       }
113     }
114   }
115 
116   switch (Result) {
117     case AR_Available:
118     case AR_NotYetIntroduced:
119       break;
120 
121     case AR_Deprecated:
122       if (S.getCurContextAvailability() != AR_Deprecated)
123         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
124                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
125                                   ObjCPropertyAccess);
126       break;
127 
128     case AR_Unavailable:
129       if (S.getCurContextAvailability() != AR_Unavailable)
130         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
131                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
132                                   ObjCPropertyAccess);
133       break;
134 
135     }
136     return Result;
137 }
138 
139 /// \brief Emit a note explaining that this function is deleted.
140 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
141   assert(Decl->isDeleted());
142 
143   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
144 
145   if (Method && Method->isDeleted() && Method->isDefaulted()) {
146     // If the method was explicitly defaulted, point at that declaration.
147     if (!Method->isImplicit())
148       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
149 
150     // Try to diagnose why this special member function was implicitly
151     // deleted. This might fail, if that reason no longer applies.
152     CXXSpecialMember CSM = getSpecialMember(Method);
153     if (CSM != CXXInvalid)
154       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
155 
156     return;
157   }
158 
159   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
160     if (CXXConstructorDecl *BaseCD =
161             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
162       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
163       if (BaseCD->isDeleted()) {
164         NoteDeletedFunction(BaseCD);
165       } else {
166         // FIXME: An explanation of why exactly it can't be inherited
167         // would be nice.
168         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
169       }
170       return;
171     }
172   }
173 
174   Diag(Decl->getLocation(), diag::note_availability_specified_here)
175     << Decl << true;
176 }
177 
178 /// \brief Determine whether a FunctionDecl was ever declared with an
179 /// explicit storage class.
180 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
181   for (auto I : D->redecls()) {
182     if (I->getStorageClass() != SC_None)
183       return true;
184   }
185   return false;
186 }
187 
188 /// \brief Check whether we're in an extern inline function and referring to a
189 /// variable or function with internal linkage (C11 6.7.4p3).
190 ///
191 /// This is only a warning because we used to silently accept this code, but
192 /// in many cases it will not behave correctly. This is not enabled in C++ mode
193 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
194 /// and so while there may still be user mistakes, most of the time we can't
195 /// prove that there are errors.
196 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
197                                                       const NamedDecl *D,
198                                                       SourceLocation Loc) {
199   // This is disabled under C++; there are too many ways for this to fire in
200   // contexts where the warning is a false positive, or where it is technically
201   // correct but benign.
202   if (S.getLangOpts().CPlusPlus)
203     return;
204 
205   // Check if this is an inlined function or method.
206   FunctionDecl *Current = S.getCurFunctionDecl();
207   if (!Current)
208     return;
209   if (!Current->isInlined())
210     return;
211   if (!Current->isExternallyVisible())
212     return;
213 
214   // Check if the decl has internal linkage.
215   if (D->getFormalLinkage() != InternalLinkage)
216     return;
217 
218   // Downgrade from ExtWarn to Extension if
219   //  (1) the supposedly external inline function is in the main file,
220   //      and probably won't be included anywhere else.
221   //  (2) the thing we're referencing is a pure function.
222   //  (3) the thing we're referencing is another inline function.
223   // This last can give us false negatives, but it's better than warning on
224   // wrappers for simple C library functions.
225   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
226   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
227   if (!DowngradeWarning && UsedFn)
228     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
229 
230   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
231                                : diag::ext_internal_in_extern_inline)
232     << /*IsVar=*/!UsedFn << D;
233 
234   S.MaybeSuggestAddingStaticToDecl(Current);
235 
236   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
237       << D;
238 }
239 
240 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
241   const FunctionDecl *First = Cur->getFirstDecl();
242 
243   // Suggest "static" on the function, if possible.
244   if (!hasAnyExplicitStorageClass(First)) {
245     SourceLocation DeclBegin = First->getSourceRange().getBegin();
246     Diag(DeclBegin, diag::note_convert_inline_to_static)
247       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
248   }
249 }
250 
251 /// \brief Determine whether the use of this declaration is valid, and
252 /// emit any corresponding diagnostics.
253 ///
254 /// This routine diagnoses various problems with referencing
255 /// declarations that can occur when using a declaration. For example,
256 /// it might warn if a deprecated or unavailable declaration is being
257 /// used, or produce an error (and return true) if a C++0x deleted
258 /// function is being used.
259 ///
260 /// \returns true if there was an error (this declaration cannot be
261 /// referenced), false otherwise.
262 ///
263 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
264                              const ObjCInterfaceDecl *UnknownObjCClass,
265                              bool ObjCPropertyAccess) {
266   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
267     // If there were any diagnostics suppressed by template argument deduction,
268     // emit them now.
269     SuppressedDiagnosticsMap::iterator
270       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
271     if (Pos != SuppressedDiagnostics.end()) {
272       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
273       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
274         Diag(Suppressed[I].first, Suppressed[I].second);
275 
276       // Clear out the list of suppressed diagnostics, so that we don't emit
277       // them again for this specialization. However, we don't obsolete this
278       // entry from the table, because we want to avoid ever emitting these
279       // diagnostics again.
280       Suppressed.clear();
281     }
282 
283     // C++ [basic.start.main]p3:
284     //   The function 'main' shall not be used within a program.
285     if (cast<FunctionDecl>(D)->isMain())
286       Diag(Loc, diag::ext_main_used);
287   }
288 
289   // See if this is an auto-typed variable whose initializer we are parsing.
290   if (ParsingInitForAutoVars.count(D)) {
291     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
292       << D->getDeclName();
293     return true;
294   }
295 
296   // See if this is a deleted function.
297   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
298     if (FD->isDeleted()) {
299       Diag(Loc, diag::err_deleted_function_use);
300       NoteDeletedFunction(FD);
301       return true;
302     }
303 
304     // If the function has a deduced return type, and we can't deduce it,
305     // then we can't use it either.
306     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307         DeduceReturnType(FD, Loc))
308       return true;
309   }
310   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
311 
312   DiagnoseUnusedOfDecl(*this, D, Loc);
313 
314   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
315 
316   return false;
317 }
318 
319 /// \brief Retrieve the message suffix that should be added to a
320 /// diagnostic complaining about the given function being deleted or
321 /// unavailable.
322 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
323   std::string Message;
324   if (FD->getAvailability(&Message))
325     return ": " + Message;
326 
327   return std::string();
328 }
329 
330 /// DiagnoseSentinelCalls - This routine checks whether a call or
331 /// message-send is to a declaration with the sentinel attribute, and
332 /// if so, it checks that the requirements of the sentinel are
333 /// satisfied.
334 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
335                                  ArrayRef<Expr *> Args) {
336   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
337   if (!attr)
338     return;
339 
340   // The number of formal parameters of the declaration.
341   unsigned numFormalParams;
342 
343   // The kind of declaration.  This is also an index into a %select in
344   // the diagnostic.
345   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
346 
347   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
348     numFormalParams = MD->param_size();
349     calleeType = CT_Method;
350   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
351     numFormalParams = FD->param_size();
352     calleeType = CT_Function;
353   } else if (isa<VarDecl>(D)) {
354     QualType type = cast<ValueDecl>(D)->getType();
355     const FunctionType *fn = nullptr;
356     if (const PointerType *ptr = type->getAs<PointerType>()) {
357       fn = ptr->getPointeeType()->getAs<FunctionType>();
358       if (!fn) return;
359       calleeType = CT_Function;
360     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
361       fn = ptr->getPointeeType()->castAs<FunctionType>();
362       calleeType = CT_Block;
363     } else {
364       return;
365     }
366 
367     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
368       numFormalParams = proto->getNumParams();
369     } else {
370       numFormalParams = 0;
371     }
372   } else {
373     return;
374   }
375 
376   // "nullPos" is the number of formal parameters at the end which
377   // effectively count as part of the variadic arguments.  This is
378   // useful if you would prefer to not have *any* formal parameters,
379   // but the language forces you to have at least one.
380   unsigned nullPos = attr->getNullPos();
381   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
382   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
383 
384   // The number of arguments which should follow the sentinel.
385   unsigned numArgsAfterSentinel = attr->getSentinel();
386 
387   // If there aren't enough arguments for all the formal parameters,
388   // the sentinel, and the args after the sentinel, complain.
389   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
390     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
391     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
392     return;
393   }
394 
395   // Otherwise, find the sentinel expression.
396   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
397   if (!sentinelExpr) return;
398   if (sentinelExpr->isValueDependent()) return;
399   if (Context.isSentinelNullExpr(sentinelExpr)) return;
400 
401   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
402   // or 'NULL' if those are actually defined in the context.  Only use
403   // 'nil' for ObjC methods, where it's much more likely that the
404   // variadic arguments form a list of object pointers.
405   SourceLocation MissingNilLoc
406     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
407   std::string NullValue;
408   if (calleeType == CT_Method &&
409       PP.getIdentifierInfo("nil")->hasMacroDefinition())
410     NullValue = "nil";
411   else if (getLangOpts().CPlusPlus11)
412     NullValue = "nullptr";
413   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
414     NullValue = "NULL";
415   else
416     NullValue = "(void*) 0";
417 
418   if (MissingNilLoc.isInvalid())
419     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
420   else
421     Diag(MissingNilLoc, diag::warn_missing_sentinel)
422       << int(calleeType)
423       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
424   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
425 }
426 
427 SourceRange Sema::getExprRange(Expr *E) const {
428   return E ? E->getSourceRange() : SourceRange();
429 }
430 
431 //===----------------------------------------------------------------------===//
432 //  Standard Promotions and Conversions
433 //===----------------------------------------------------------------------===//
434 
435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
437   // Handle any placeholder expressions which made it here.
438   if (E->getType()->isPlaceholderType()) {
439     ExprResult result = CheckPlaceholderExpr(E);
440     if (result.isInvalid()) return ExprError();
441     E = result.get();
442   }
443 
444   QualType Ty = E->getType();
445   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
446 
447   if (Ty->isFunctionType()) {
448     // If we are here, we are not calling a function but taking
449     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
450     if (getLangOpts().OpenCL) {
451       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
452       return ExprError();
453     }
454     E = ImpCastExprToType(E, Context.getPointerType(Ty),
455                           CK_FunctionToPointerDecay).get();
456   } else if (Ty->isArrayType()) {
457     // In C90 mode, arrays only promote to pointers if the array expression is
458     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
459     // type 'array of type' is converted to an expression that has type 'pointer
460     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
461     // that has type 'array of type' ...".  The relevant change is "an lvalue"
462     // (C90) to "an expression" (C99).
463     //
464     // C++ 4.2p1:
465     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
466     // T" can be converted to an rvalue of type "pointer to T".
467     //
468     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
469       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
470                             CK_ArrayToPointerDecay).get();
471   }
472   return E;
473 }
474 
475 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
476   // Check to see if we are dereferencing a null pointer.  If so,
477   // and if not volatile-qualified, this is undefined behavior that the
478   // optimizer will delete, so warn about it.  People sometimes try to use this
479   // to get a deterministic trap and are surprised by clang's behavior.  This
480   // only handles the pattern "*null", which is a very syntactic check.
481   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
482     if (UO->getOpcode() == UO_Deref &&
483         UO->getSubExpr()->IgnoreParenCasts()->
484           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
485         !UO->getType().isVolatileQualified()) {
486     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
487                           S.PDiag(diag::warn_indirection_through_null)
488                             << UO->getSubExpr()->getSourceRange());
489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490                         S.PDiag(diag::note_indirection_through_null));
491   }
492 }
493 
494 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
495                                     SourceLocation AssignLoc,
496                                     const Expr* RHS) {
497   const ObjCIvarDecl *IV = OIRE->getDecl();
498   if (!IV)
499     return;
500 
501   DeclarationName MemberName = IV->getDeclName();
502   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
503   if (!Member || !Member->isStr("isa"))
504     return;
505 
506   const Expr *Base = OIRE->getBase();
507   QualType BaseType = Base->getType();
508   if (OIRE->isArrow())
509     BaseType = BaseType->getPointeeType();
510   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
511     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
512       ObjCInterfaceDecl *ClassDeclared = nullptr;
513       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
514       if (!ClassDeclared->getSuperClass()
515           && (*ClassDeclared->ivar_begin()) == IV) {
516         if (RHS) {
517           NamedDecl *ObjectSetClass =
518             S.LookupSingleName(S.TUScope,
519                                &S.Context.Idents.get("object_setClass"),
520                                SourceLocation(), S.LookupOrdinaryName);
521           if (ObjectSetClass) {
522             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
523             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
524             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
525             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
526                                                      AssignLoc), ",") <<
527             FixItHint::CreateInsertion(RHSLocEnd, ")");
528           }
529           else
530             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
531         } else {
532           NamedDecl *ObjectGetClass =
533             S.LookupSingleName(S.TUScope,
534                                &S.Context.Idents.get("object_getClass"),
535                                SourceLocation(), S.LookupOrdinaryName);
536           if (ObjectGetClass)
537             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
538             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
539             FixItHint::CreateReplacement(
540                                          SourceRange(OIRE->getOpLoc(),
541                                                      OIRE->getLocEnd()), ")");
542           else
543             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
544         }
545         S.Diag(IV->getLocation(), diag::note_ivar_decl);
546       }
547     }
548 }
549 
550 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
551   // Handle any placeholder expressions which made it here.
552   if (E->getType()->isPlaceholderType()) {
553     ExprResult result = CheckPlaceholderExpr(E);
554     if (result.isInvalid()) return ExprError();
555     E = result.get();
556   }
557 
558   // C++ [conv.lval]p1:
559   //   A glvalue of a non-function, non-array type T can be
560   //   converted to a prvalue.
561   if (!E->isGLValue()) return E;
562 
563   QualType T = E->getType();
564   assert(!T.isNull() && "r-value conversion on typeless expression?");
565 
566   // We don't want to throw lvalue-to-rvalue casts on top of
567   // expressions of certain types in C++.
568   if (getLangOpts().CPlusPlus &&
569       (E->getType() == Context.OverloadTy ||
570        T->isDependentType() ||
571        T->isRecordType()))
572     return E;
573 
574   // The C standard is actually really unclear on this point, and
575   // DR106 tells us what the result should be but not why.  It's
576   // generally best to say that void types just doesn't undergo
577   // lvalue-to-rvalue at all.  Note that expressions of unqualified
578   // 'void' type are never l-values, but qualified void can be.
579   if (T->isVoidType())
580     return E;
581 
582   // OpenCL usually rejects direct accesses to values of 'half' type.
583   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
584       T->isHalfType()) {
585     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
586       << 0 << T;
587     return ExprError();
588   }
589 
590   CheckForNullPointerDereference(*this, E);
591   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
592     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
593                                      &Context.Idents.get("object_getClass"),
594                                      SourceLocation(), LookupOrdinaryName);
595     if (ObjectGetClass)
596       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
597         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
598         FixItHint::CreateReplacement(
599                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
600     else
601       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
602   }
603   else if (const ObjCIvarRefExpr *OIRE =
604             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
605     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
606 
607   // C++ [conv.lval]p1:
608   //   [...] If T is a non-class type, the type of the prvalue is the
609   //   cv-unqualified version of T. Otherwise, the type of the
610   //   rvalue is T.
611   //
612   // C99 6.3.2.1p2:
613   //   If the lvalue has qualified type, the value has the unqualified
614   //   version of the type of the lvalue; otherwise, the value has the
615   //   type of the lvalue.
616   if (T.hasQualifiers())
617     T = T.getUnqualifiedType();
618 
619   UpdateMarkingForLValueToRValue(E);
620 
621   // Loading a __weak object implicitly retains the value, so we need a cleanup to
622   // balance that.
623   if (getLangOpts().ObjCAutoRefCount &&
624       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
625     ExprNeedsCleanups = true;
626 
627   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
628                                             nullptr, VK_RValue);
629 
630   // C11 6.3.2.1p2:
631   //   ... if the lvalue has atomic type, the value has the non-atomic version
632   //   of the type of the lvalue ...
633   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
634     T = Atomic->getValueType().getUnqualifiedType();
635     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
636                                    nullptr, VK_RValue);
637   }
638 
639   return Res;
640 }
641 
642 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
643   ExprResult Res = DefaultFunctionArrayConversion(E);
644   if (Res.isInvalid())
645     return ExprError();
646   Res = DefaultLvalueConversion(Res.get());
647   if (Res.isInvalid())
648     return ExprError();
649   return Res;
650 }
651 
652 /// CallExprUnaryConversions - a special case of an unary conversion
653 /// performed on a function designator of a call expression.
654 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
655   QualType Ty = E->getType();
656   ExprResult Res = E;
657   // Only do implicit cast for a function type, but not for a pointer
658   // to function type.
659   if (Ty->isFunctionType()) {
660     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
661                             CK_FunctionToPointerDecay).get();
662     if (Res.isInvalid())
663       return ExprError();
664   }
665   Res = DefaultLvalueConversion(Res.get());
666   if (Res.isInvalid())
667     return ExprError();
668   return Res.get();
669 }
670 
671 /// UsualUnaryConversions - Performs various conversions that are common to most
672 /// operators (C99 6.3). The conversions of array and function types are
673 /// sometimes suppressed. For example, the array->pointer conversion doesn't
674 /// apply if the array is an argument to the sizeof or address (&) operators.
675 /// In these instances, this routine should *not* be called.
676 ExprResult Sema::UsualUnaryConversions(Expr *E) {
677   // First, convert to an r-value.
678   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
679   if (Res.isInvalid())
680     return ExprError();
681   E = Res.get();
682 
683   QualType Ty = E->getType();
684   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
685 
686   // Half FP have to be promoted to float unless it is natively supported
687   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
688     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
689 
690   // Try to perform integral promotions if the object has a theoretically
691   // promotable type.
692   if (Ty->isIntegralOrUnscopedEnumerationType()) {
693     // C99 6.3.1.1p2:
694     //
695     //   The following may be used in an expression wherever an int or
696     //   unsigned int may be used:
697     //     - an object or expression with an integer type whose integer
698     //       conversion rank is less than or equal to the rank of int
699     //       and unsigned int.
700     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
701     //
702     //   If an int can represent all values of the original type, the
703     //   value is converted to an int; otherwise, it is converted to an
704     //   unsigned int. These are called the integer promotions. All
705     //   other types are unchanged by the integer promotions.
706 
707     QualType PTy = Context.isPromotableBitField(E);
708     if (!PTy.isNull()) {
709       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
710       return E;
711     }
712     if (Ty->isPromotableIntegerType()) {
713       QualType PT = Context.getPromotedIntegerType(Ty);
714       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
715       return E;
716     }
717   }
718   return E;
719 }
720 
721 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
722 /// do not have a prototype. Arguments that have type float or __fp16
723 /// are promoted to double. All other argument types are converted by
724 /// UsualUnaryConversions().
725 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
726   QualType Ty = E->getType();
727   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
728 
729   ExprResult Res = UsualUnaryConversions(E);
730   if (Res.isInvalid())
731     return ExprError();
732   E = Res.get();
733 
734   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
735   // double.
736   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
737   if (BTy && (BTy->getKind() == BuiltinType::Half ||
738               BTy->getKind() == BuiltinType::Float))
739     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
740 
741   // C++ performs lvalue-to-rvalue conversion as a default argument
742   // promotion, even on class types, but note:
743   //   C++11 [conv.lval]p2:
744   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
745   //     operand or a subexpression thereof the value contained in the
746   //     referenced object is not accessed. Otherwise, if the glvalue
747   //     has a class type, the conversion copy-initializes a temporary
748   //     of type T from the glvalue and the result of the conversion
749   //     is a prvalue for the temporary.
750   // FIXME: add some way to gate this entire thing for correctness in
751   // potentially potentially evaluated contexts.
752   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
753     ExprResult Temp = PerformCopyInitialization(
754                        InitializedEntity::InitializeTemporary(E->getType()),
755                                                 E->getExprLoc(), E);
756     if (Temp.isInvalid())
757       return ExprError();
758     E = Temp.get();
759   }
760 
761   return E;
762 }
763 
764 /// Determine the degree of POD-ness for an expression.
765 /// Incomplete types are considered POD, since this check can be performed
766 /// when we're in an unevaluated context.
767 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
768   if (Ty->isIncompleteType()) {
769     // C++11 [expr.call]p7:
770     //   After these conversions, if the argument does not have arithmetic,
771     //   enumeration, pointer, pointer to member, or class type, the program
772     //   is ill-formed.
773     //
774     // Since we've already performed array-to-pointer and function-to-pointer
775     // decay, the only such type in C++ is cv void. This also handles
776     // initializer lists as variadic arguments.
777     if (Ty->isVoidType())
778       return VAK_Invalid;
779 
780     if (Ty->isObjCObjectType())
781       return VAK_Invalid;
782     return VAK_Valid;
783   }
784 
785   if (Ty.isCXX98PODType(Context))
786     return VAK_Valid;
787 
788   // C++11 [expr.call]p7:
789   //   Passing a potentially-evaluated argument of class type (Clause 9)
790   //   having a non-trivial copy constructor, a non-trivial move constructor,
791   //   or a non-trivial destructor, with no corresponding parameter,
792   //   is conditionally-supported with implementation-defined semantics.
793   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
794     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
795       if (!Record->hasNonTrivialCopyConstructor() &&
796           !Record->hasNonTrivialMoveConstructor() &&
797           !Record->hasNonTrivialDestructor())
798         return VAK_ValidInCXX11;
799 
800   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
801     return VAK_Valid;
802 
803   if (Ty->isObjCObjectType())
804     return VAK_Invalid;
805 
806   if (getLangOpts().MSVCCompat)
807     return VAK_MSVCUndefined;
808 
809   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
810   // permitted to reject them. We should consider doing so.
811   return VAK_Undefined;
812 }
813 
814 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
815   // Don't allow one to pass an Objective-C interface to a vararg.
816   const QualType &Ty = E->getType();
817   VarArgKind VAK = isValidVarArgType(Ty);
818 
819   // Complain about passing non-POD types through varargs.
820   switch (VAK) {
821   case VAK_ValidInCXX11:
822     DiagRuntimeBehavior(
823         E->getLocStart(), nullptr,
824         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
825           << Ty << CT);
826     // Fall through.
827   case VAK_Valid:
828     if (Ty->isRecordType()) {
829       // This is unlikely to be what the user intended. If the class has a
830       // 'c_str' member function, the user probably meant to call that.
831       DiagRuntimeBehavior(E->getLocStart(), nullptr,
832                           PDiag(diag::warn_pass_class_arg_to_vararg)
833                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
834     }
835     break;
836 
837   case VAK_Undefined:
838   case VAK_MSVCUndefined:
839     DiagRuntimeBehavior(
840         E->getLocStart(), nullptr,
841         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
842           << getLangOpts().CPlusPlus11 << Ty << CT);
843     break;
844 
845   case VAK_Invalid:
846     if (Ty->isObjCObjectType())
847       DiagRuntimeBehavior(
848           E->getLocStart(), nullptr,
849           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
850             << Ty << CT);
851     else
852       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
853         << isa<InitListExpr>(E) << Ty << CT;
854     break;
855   }
856 }
857 
858 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
859 /// will create a trap if the resulting type is not a POD type.
860 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
861                                                   FunctionDecl *FDecl) {
862   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
863     // Strip the unbridged-cast placeholder expression off, if applicable.
864     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
865         (CT == VariadicMethod ||
866          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
867       E = stripARCUnbridgedCast(E);
868 
869     // Otherwise, do normal placeholder checking.
870     } else {
871       ExprResult ExprRes = CheckPlaceholderExpr(E);
872       if (ExprRes.isInvalid())
873         return ExprError();
874       E = ExprRes.get();
875     }
876   }
877 
878   ExprResult ExprRes = DefaultArgumentPromotion(E);
879   if (ExprRes.isInvalid())
880     return ExprError();
881   E = ExprRes.get();
882 
883   // Diagnostics regarding non-POD argument types are
884   // emitted along with format string checking in Sema::CheckFunctionCall().
885   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
886     // Turn this into a trap.
887     CXXScopeSpec SS;
888     SourceLocation TemplateKWLoc;
889     UnqualifiedId Name;
890     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
891                        E->getLocStart());
892     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
893                                           Name, true, false);
894     if (TrapFn.isInvalid())
895       return ExprError();
896 
897     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
898                                     E->getLocStart(), None,
899                                     E->getLocEnd());
900     if (Call.isInvalid())
901       return ExprError();
902 
903     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
904                                   Call.get(), E);
905     if (Comma.isInvalid())
906       return ExprError();
907     return Comma.get();
908   }
909 
910   if (!getLangOpts().CPlusPlus &&
911       RequireCompleteType(E->getExprLoc(), E->getType(),
912                           diag::err_call_incomplete_argument))
913     return ExprError();
914 
915   return E;
916 }
917 
918 /// \brief Converts an integer to complex float type.  Helper function of
919 /// UsualArithmeticConversions()
920 ///
921 /// \return false if the integer expression is an integer type and is
922 /// successfully converted to the complex type.
923 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
924                                                   ExprResult &ComplexExpr,
925                                                   QualType IntTy,
926                                                   QualType ComplexTy,
927                                                   bool SkipCast) {
928   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
929   if (SkipCast) return false;
930   if (IntTy->isIntegerType()) {
931     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
932     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
933     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
934                                   CK_FloatingRealToComplex);
935   } else {
936     assert(IntTy->isComplexIntegerType());
937     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
938                                   CK_IntegralComplexToFloatingComplex);
939   }
940   return false;
941 }
942 
943 /// \brief Handle arithmetic conversion with complex types.  Helper function of
944 /// UsualArithmeticConversions()
945 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
946                                              ExprResult &RHS, QualType LHSType,
947                                              QualType RHSType,
948                                              bool IsCompAssign) {
949   // if we have an integer operand, the result is the complex type.
950   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
951                                              /*skipCast*/false))
952     return LHSType;
953   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
954                                              /*skipCast*/IsCompAssign))
955     return RHSType;
956 
957   // This handles complex/complex, complex/float, or float/complex.
958   // When both operands are complex, the shorter operand is converted to the
959   // type of the longer, and that is the type of the result. This corresponds
960   // to what is done when combining two real floating-point operands.
961   // The fun begins when size promotion occur across type domains.
962   // From H&S 6.3.4: When one operand is complex and the other is a real
963   // floating-point type, the less precise type is converted, within it's
964   // real or complex domain, to the precision of the other type. For example,
965   // when combining a "long double" with a "double _Complex", the
966   // "double _Complex" is promoted to "long double _Complex".
967 
968   // Compute the rank of the two types, regardless of whether they are complex.
969   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
970 
971   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
972   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
973   QualType LHSElementType =
974       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
975   QualType RHSElementType =
976       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
977 
978   QualType ResultType = S.Context.getComplexType(LHSElementType);
979   if (Order < 0) {
980     // Promote the precision of the LHS if not an assignment.
981     ResultType = S.Context.getComplexType(RHSElementType);
982     if (!IsCompAssign) {
983       if (LHSComplexType)
984         LHS =
985             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
986       else
987         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
988     }
989   } else if (Order > 0) {
990     // Promote the precision of the RHS.
991     if (RHSComplexType)
992       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
993     else
994       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
995   }
996   return ResultType;
997 }
998 
999 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1000 /// of UsualArithmeticConversions()
1001 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1002                                            ExprResult &IntExpr,
1003                                            QualType FloatTy, QualType IntTy,
1004                                            bool ConvertFloat, bool ConvertInt) {
1005   if (IntTy->isIntegerType()) {
1006     if (ConvertInt)
1007       // Convert intExpr to the lhs floating point type.
1008       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1009                                     CK_IntegralToFloating);
1010     return FloatTy;
1011   }
1012 
1013   // Convert both sides to the appropriate complex float.
1014   assert(IntTy->isComplexIntegerType());
1015   QualType result = S.Context.getComplexType(FloatTy);
1016 
1017   // _Complex int -> _Complex float
1018   if (ConvertInt)
1019     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1020                                   CK_IntegralComplexToFloatingComplex);
1021 
1022   // float -> _Complex float
1023   if (ConvertFloat)
1024     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1025                                     CK_FloatingRealToComplex);
1026 
1027   return result;
1028 }
1029 
1030 /// \brief Handle arithmethic conversion with floating point types.  Helper
1031 /// function of UsualArithmeticConversions()
1032 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1033                                       ExprResult &RHS, QualType LHSType,
1034                                       QualType RHSType, bool IsCompAssign) {
1035   bool LHSFloat = LHSType->isRealFloatingType();
1036   bool RHSFloat = RHSType->isRealFloatingType();
1037 
1038   // If we have two real floating types, convert the smaller operand
1039   // to the bigger result.
1040   if (LHSFloat && RHSFloat) {
1041     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1042     if (order > 0) {
1043       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1044       return LHSType;
1045     }
1046 
1047     assert(order < 0 && "illegal float comparison");
1048     if (!IsCompAssign)
1049       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1050     return RHSType;
1051   }
1052 
1053   if (LHSFloat)
1054     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1055                                       /*convertFloat=*/!IsCompAssign,
1056                                       /*convertInt=*/ true);
1057   assert(RHSFloat);
1058   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1059                                     /*convertInt=*/ true,
1060                                     /*convertFloat=*/!IsCompAssign);
1061 }
1062 
1063 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1064 
1065 namespace {
1066 /// These helper callbacks are placed in an anonymous namespace to
1067 /// permit their use as function template parameters.
1068 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1069   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1070 }
1071 
1072 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1073   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1074                              CK_IntegralComplexCast);
1075 }
1076 }
1077 
1078 /// \brief Handle integer arithmetic conversions.  Helper function of
1079 /// UsualArithmeticConversions()
1080 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1081 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1082                                         ExprResult &RHS, QualType LHSType,
1083                                         QualType RHSType, bool IsCompAssign) {
1084   // The rules for this case are in C99 6.3.1.8
1085   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1086   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1087   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1088   if (LHSSigned == RHSSigned) {
1089     // Same signedness; use the higher-ranked type
1090     if (order >= 0) {
1091       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1092       return LHSType;
1093     } else if (!IsCompAssign)
1094       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1095     return RHSType;
1096   } else if (order != (LHSSigned ? 1 : -1)) {
1097     // The unsigned type has greater than or equal rank to the
1098     // signed type, so use the unsigned type
1099     if (RHSSigned) {
1100       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1101       return LHSType;
1102     } else if (!IsCompAssign)
1103       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1104     return RHSType;
1105   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1106     // The two types are different widths; if we are here, that
1107     // means the signed type is larger than the unsigned type, so
1108     // use the signed type.
1109     if (LHSSigned) {
1110       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1111       return LHSType;
1112     } else if (!IsCompAssign)
1113       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1114     return RHSType;
1115   } else {
1116     // The signed type is higher-ranked than the unsigned type,
1117     // but isn't actually any bigger (like unsigned int and long
1118     // on most 32-bit systems).  Use the unsigned type corresponding
1119     // to the signed type.
1120     QualType result =
1121       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1122     RHS = (*doRHSCast)(S, RHS.get(), result);
1123     if (!IsCompAssign)
1124       LHS = (*doLHSCast)(S, LHS.get(), result);
1125     return result;
1126   }
1127 }
1128 
1129 /// \brief Handle conversions with GCC complex int extension.  Helper function
1130 /// of UsualArithmeticConversions()
1131 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1132                                            ExprResult &RHS, QualType LHSType,
1133                                            QualType RHSType,
1134                                            bool IsCompAssign) {
1135   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1136   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1137 
1138   if (LHSComplexInt && RHSComplexInt) {
1139     QualType LHSEltType = LHSComplexInt->getElementType();
1140     QualType RHSEltType = RHSComplexInt->getElementType();
1141     QualType ScalarType =
1142       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1143         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1144 
1145     return S.Context.getComplexType(ScalarType);
1146   }
1147 
1148   if (LHSComplexInt) {
1149     QualType LHSEltType = LHSComplexInt->getElementType();
1150     QualType ScalarType =
1151       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1152         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1153     QualType ComplexType = S.Context.getComplexType(ScalarType);
1154     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1155                               CK_IntegralRealToComplex);
1156 
1157     return ComplexType;
1158   }
1159 
1160   assert(RHSComplexInt);
1161 
1162   QualType RHSEltType = RHSComplexInt->getElementType();
1163   QualType ScalarType =
1164     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1165       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1166   QualType ComplexType = S.Context.getComplexType(ScalarType);
1167 
1168   if (!IsCompAssign)
1169     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1170                               CK_IntegralRealToComplex);
1171   return ComplexType;
1172 }
1173 
1174 /// UsualArithmeticConversions - Performs various conversions that are common to
1175 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1176 /// routine returns the first non-arithmetic type found. The client is
1177 /// responsible for emitting appropriate error diagnostics.
1178 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1179                                           bool IsCompAssign) {
1180   if (!IsCompAssign) {
1181     LHS = UsualUnaryConversions(LHS.get());
1182     if (LHS.isInvalid())
1183       return QualType();
1184   }
1185 
1186   RHS = UsualUnaryConversions(RHS.get());
1187   if (RHS.isInvalid())
1188     return QualType();
1189 
1190   // For conversion purposes, we ignore any qualifiers.
1191   // For example, "const float" and "float" are equivalent.
1192   QualType LHSType =
1193     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1194   QualType RHSType =
1195     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1196 
1197   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1198   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1199     LHSType = AtomicLHS->getValueType();
1200 
1201   // If both types are identical, no conversion is needed.
1202   if (LHSType == RHSType)
1203     return LHSType;
1204 
1205   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1206   // The caller can deal with this (e.g. pointer + int).
1207   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1208     return QualType();
1209 
1210   // Apply unary and bitfield promotions to the LHS's type.
1211   QualType LHSUnpromotedType = LHSType;
1212   if (LHSType->isPromotableIntegerType())
1213     LHSType = Context.getPromotedIntegerType(LHSType);
1214   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1215   if (!LHSBitfieldPromoteTy.isNull())
1216     LHSType = LHSBitfieldPromoteTy;
1217   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1218     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1219 
1220   // If both types are identical, no conversion is needed.
1221   if (LHSType == RHSType)
1222     return LHSType;
1223 
1224   // At this point, we have two different arithmetic types.
1225 
1226   // Handle complex types first (C99 6.3.1.8p1).
1227   if (LHSType->isComplexType() || RHSType->isComplexType())
1228     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1229                                         IsCompAssign);
1230 
1231   // Now handle "real" floating types (i.e. float, double, long double).
1232   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1233     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1234                                  IsCompAssign);
1235 
1236   // Handle GCC complex int extension.
1237   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1238     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1239                                       IsCompAssign);
1240 
1241   // Finally, we have two differing integer types.
1242   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1243            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1244 }
1245 
1246 
1247 //===----------------------------------------------------------------------===//
1248 //  Semantic Analysis for various Expression Types
1249 //===----------------------------------------------------------------------===//
1250 
1251 
1252 ExprResult
1253 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1254                                 SourceLocation DefaultLoc,
1255                                 SourceLocation RParenLoc,
1256                                 Expr *ControllingExpr,
1257                                 ArrayRef<ParsedType> ArgTypes,
1258                                 ArrayRef<Expr *> ArgExprs) {
1259   unsigned NumAssocs = ArgTypes.size();
1260   assert(NumAssocs == ArgExprs.size());
1261 
1262   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1263   for (unsigned i = 0; i < NumAssocs; ++i) {
1264     if (ArgTypes[i])
1265       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1266     else
1267       Types[i] = nullptr;
1268   }
1269 
1270   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1271                                              ControllingExpr,
1272                                              llvm::makeArrayRef(Types, NumAssocs),
1273                                              ArgExprs);
1274   delete [] Types;
1275   return ER;
1276 }
1277 
1278 ExprResult
1279 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1280                                  SourceLocation DefaultLoc,
1281                                  SourceLocation RParenLoc,
1282                                  Expr *ControllingExpr,
1283                                  ArrayRef<TypeSourceInfo *> Types,
1284                                  ArrayRef<Expr *> Exprs) {
1285   unsigned NumAssocs = Types.size();
1286   assert(NumAssocs == Exprs.size());
1287   if (ControllingExpr->getType()->isPlaceholderType()) {
1288     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1289     if (result.isInvalid()) return ExprError();
1290     ControllingExpr = result.get();
1291   }
1292 
1293   bool TypeErrorFound = false,
1294        IsResultDependent = ControllingExpr->isTypeDependent(),
1295        ContainsUnexpandedParameterPack
1296          = ControllingExpr->containsUnexpandedParameterPack();
1297 
1298   for (unsigned i = 0; i < NumAssocs; ++i) {
1299     if (Exprs[i]->containsUnexpandedParameterPack())
1300       ContainsUnexpandedParameterPack = true;
1301 
1302     if (Types[i]) {
1303       if (Types[i]->getType()->containsUnexpandedParameterPack())
1304         ContainsUnexpandedParameterPack = true;
1305 
1306       if (Types[i]->getType()->isDependentType()) {
1307         IsResultDependent = true;
1308       } else {
1309         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1310         // complete object type other than a variably modified type."
1311         unsigned D = 0;
1312         if (Types[i]->getType()->isIncompleteType())
1313           D = diag::err_assoc_type_incomplete;
1314         else if (!Types[i]->getType()->isObjectType())
1315           D = diag::err_assoc_type_nonobject;
1316         else if (Types[i]->getType()->isVariablyModifiedType())
1317           D = diag::err_assoc_type_variably_modified;
1318 
1319         if (D != 0) {
1320           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1321             << Types[i]->getTypeLoc().getSourceRange()
1322             << Types[i]->getType();
1323           TypeErrorFound = true;
1324         }
1325 
1326         // C11 6.5.1.1p2 "No two generic associations in the same generic
1327         // selection shall specify compatible types."
1328         for (unsigned j = i+1; j < NumAssocs; ++j)
1329           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1330               Context.typesAreCompatible(Types[i]->getType(),
1331                                          Types[j]->getType())) {
1332             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1333                  diag::err_assoc_compatible_types)
1334               << Types[j]->getTypeLoc().getSourceRange()
1335               << Types[j]->getType()
1336               << Types[i]->getType();
1337             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1338                  diag::note_compat_assoc)
1339               << Types[i]->getTypeLoc().getSourceRange()
1340               << Types[i]->getType();
1341             TypeErrorFound = true;
1342           }
1343       }
1344     }
1345   }
1346   if (TypeErrorFound)
1347     return ExprError();
1348 
1349   // If we determined that the generic selection is result-dependent, don't
1350   // try to compute the result expression.
1351   if (IsResultDependent)
1352     return new (Context) GenericSelectionExpr(
1353         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1354         ContainsUnexpandedParameterPack);
1355 
1356   SmallVector<unsigned, 1> CompatIndices;
1357   unsigned DefaultIndex = -1U;
1358   for (unsigned i = 0; i < NumAssocs; ++i) {
1359     if (!Types[i])
1360       DefaultIndex = i;
1361     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1362                                         Types[i]->getType()))
1363       CompatIndices.push_back(i);
1364   }
1365 
1366   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1367   // type compatible with at most one of the types named in its generic
1368   // association list."
1369   if (CompatIndices.size() > 1) {
1370     // We strip parens here because the controlling expression is typically
1371     // parenthesized in macro definitions.
1372     ControllingExpr = ControllingExpr->IgnoreParens();
1373     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1374       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1375       << (unsigned) CompatIndices.size();
1376     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1377          E = CompatIndices.end(); I != E; ++I) {
1378       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1379            diag::note_compat_assoc)
1380         << Types[*I]->getTypeLoc().getSourceRange()
1381         << Types[*I]->getType();
1382     }
1383     return ExprError();
1384   }
1385 
1386   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1387   // its controlling expression shall have type compatible with exactly one of
1388   // the types named in its generic association list."
1389   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1390     // We strip parens here because the controlling expression is typically
1391     // parenthesized in macro definitions.
1392     ControllingExpr = ControllingExpr->IgnoreParens();
1393     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1394       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1395     return ExprError();
1396   }
1397 
1398   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1399   // type name that is compatible with the type of the controlling expression,
1400   // then the result expression of the generic selection is the expression
1401   // in that generic association. Otherwise, the result expression of the
1402   // generic selection is the expression in the default generic association."
1403   unsigned ResultIndex =
1404     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1405 
1406   return new (Context) GenericSelectionExpr(
1407       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1408       ContainsUnexpandedParameterPack, ResultIndex);
1409 }
1410 
1411 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1412 /// location of the token and the offset of the ud-suffix within it.
1413 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1414                                      unsigned Offset) {
1415   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1416                                         S.getLangOpts());
1417 }
1418 
1419 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1420 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1421 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1422                                                  IdentifierInfo *UDSuffix,
1423                                                  SourceLocation UDSuffixLoc,
1424                                                  ArrayRef<Expr*> Args,
1425                                                  SourceLocation LitEndLoc) {
1426   assert(Args.size() <= 2 && "too many arguments for literal operator");
1427 
1428   QualType ArgTy[2];
1429   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1430     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1431     if (ArgTy[ArgIdx]->isArrayType())
1432       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1433   }
1434 
1435   DeclarationName OpName =
1436     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1437   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1438   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1439 
1440   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1441   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1442                               /*AllowRaw*/false, /*AllowTemplate*/false,
1443                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1444     return ExprError();
1445 
1446   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1447 }
1448 
1449 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1450 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1451 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1452 /// multiple tokens.  However, the common case is that StringToks points to one
1453 /// string.
1454 ///
1455 ExprResult
1456 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1457   assert(!StringToks.empty() && "Must have at least one string!");
1458 
1459   StringLiteralParser Literal(StringToks, PP);
1460   if (Literal.hadError)
1461     return ExprError();
1462 
1463   SmallVector<SourceLocation, 4> StringTokLocs;
1464   for (unsigned i = 0; i != StringToks.size(); ++i)
1465     StringTokLocs.push_back(StringToks[i].getLocation());
1466 
1467   QualType CharTy = Context.CharTy;
1468   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1469   if (Literal.isWide()) {
1470     CharTy = Context.getWideCharType();
1471     Kind = StringLiteral::Wide;
1472   } else if (Literal.isUTF8()) {
1473     Kind = StringLiteral::UTF8;
1474   } else if (Literal.isUTF16()) {
1475     CharTy = Context.Char16Ty;
1476     Kind = StringLiteral::UTF16;
1477   } else if (Literal.isUTF32()) {
1478     CharTy = Context.Char32Ty;
1479     Kind = StringLiteral::UTF32;
1480   } else if (Literal.isPascal()) {
1481     CharTy = Context.UnsignedCharTy;
1482   }
1483 
1484   QualType CharTyConst = CharTy;
1485   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1486   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1487     CharTyConst.addConst();
1488 
1489   // Get an array type for the string, according to C99 6.4.5.  This includes
1490   // the nul terminator character as well as the string length for pascal
1491   // strings.
1492   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1493                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1494                                  ArrayType::Normal, 0);
1495 
1496   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1497   if (getLangOpts().OpenCL) {
1498     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1499   }
1500 
1501   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1502   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1503                                              Kind, Literal.Pascal, StrTy,
1504                                              &StringTokLocs[0],
1505                                              StringTokLocs.size());
1506   if (Literal.getUDSuffix().empty())
1507     return Lit;
1508 
1509   // We're building a user-defined literal.
1510   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1511   SourceLocation UDSuffixLoc =
1512     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1513                    Literal.getUDSuffixOffset());
1514 
1515   // Make sure we're allowed user-defined literals here.
1516   if (!UDLScope)
1517     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1518 
1519   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1520   //   operator "" X (str, len)
1521   QualType SizeType = Context.getSizeType();
1522 
1523   DeclarationName OpName =
1524     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1525   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1526   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1527 
1528   QualType ArgTy[] = {
1529     Context.getArrayDecayedType(StrTy), SizeType
1530   };
1531 
1532   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1533   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1534                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1535                                 /*AllowStringTemplate*/true)) {
1536 
1537   case LOLR_Cooked: {
1538     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1539     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1540                                                     StringTokLocs[0]);
1541     Expr *Args[] = { Lit, LenArg };
1542 
1543     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1544   }
1545 
1546   case LOLR_StringTemplate: {
1547     TemplateArgumentListInfo ExplicitArgs;
1548 
1549     unsigned CharBits = Context.getIntWidth(CharTy);
1550     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1551     llvm::APSInt Value(CharBits, CharIsUnsigned);
1552 
1553     TemplateArgument TypeArg(CharTy);
1554     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1555     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1556 
1557     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1558       Value = Lit->getCodeUnit(I);
1559       TemplateArgument Arg(Context, Value, CharTy);
1560       TemplateArgumentLocInfo ArgInfo;
1561       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1562     }
1563     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1564                                     &ExplicitArgs);
1565   }
1566   case LOLR_Raw:
1567   case LOLR_Template:
1568     llvm_unreachable("unexpected literal operator lookup result");
1569   case LOLR_Error:
1570     return ExprError();
1571   }
1572   llvm_unreachable("unexpected literal operator lookup result");
1573 }
1574 
1575 ExprResult
1576 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1577                        SourceLocation Loc,
1578                        const CXXScopeSpec *SS) {
1579   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1580   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1581 }
1582 
1583 /// BuildDeclRefExpr - Build an expression that references a
1584 /// declaration that does not require a closure capture.
1585 ExprResult
1586 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1587                        const DeclarationNameInfo &NameInfo,
1588                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1589                        const TemplateArgumentListInfo *TemplateArgs) {
1590   if (getLangOpts().CUDA)
1591     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1592       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1593         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1594                            CalleeTarget = IdentifyCUDATarget(Callee);
1595         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1596           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1597             << CalleeTarget << D->getIdentifier() << CallerTarget;
1598           Diag(D->getLocation(), diag::note_previous_decl)
1599             << D->getIdentifier();
1600           return ExprError();
1601         }
1602       }
1603 
1604   bool refersToEnclosingScope =
1605     (CurContext != D->getDeclContext() &&
1606      D->getDeclContext()->isFunctionOrMethod()) ||
1607     (isa<VarDecl>(D) &&
1608      cast<VarDecl>(D)->isInitCapture());
1609 
1610   DeclRefExpr *E;
1611   if (isa<VarTemplateSpecializationDecl>(D)) {
1612     VarTemplateSpecializationDecl *VarSpec =
1613         cast<VarTemplateSpecializationDecl>(D);
1614 
1615     E = DeclRefExpr::Create(
1616         Context,
1617         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1618         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1619         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1620   } else {
1621     assert(!TemplateArgs && "No template arguments for non-variable"
1622                             " template specialization references");
1623     E = DeclRefExpr::Create(
1624         Context,
1625         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1626         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1627   }
1628 
1629   MarkDeclRefReferenced(E);
1630 
1631   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1632       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1633       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1634       recordUseOfEvaluatedWeak(E);
1635 
1636   // Just in case we're building an illegal pointer-to-member.
1637   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1638   if (FD && FD->isBitField())
1639     E->setObjectKind(OK_BitField);
1640 
1641   return E;
1642 }
1643 
1644 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1645 /// possibly a list of template arguments.
1646 ///
1647 /// If this produces template arguments, it is permitted to call
1648 /// DecomposeTemplateName.
1649 ///
1650 /// This actually loses a lot of source location information for
1651 /// non-standard name kinds; we should consider preserving that in
1652 /// some way.
1653 void
1654 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1655                              TemplateArgumentListInfo &Buffer,
1656                              DeclarationNameInfo &NameInfo,
1657                              const TemplateArgumentListInfo *&TemplateArgs) {
1658   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1659     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1660     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1661 
1662     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1663                                        Id.TemplateId->NumArgs);
1664     translateTemplateArguments(TemplateArgsPtr, Buffer);
1665 
1666     TemplateName TName = Id.TemplateId->Template.get();
1667     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1668     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1669     TemplateArgs = &Buffer;
1670   } else {
1671     NameInfo = GetNameFromUnqualifiedId(Id);
1672     TemplateArgs = nullptr;
1673   }
1674 }
1675 
1676 static void emitEmptyLookupTypoDiagnostic(
1677     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1678     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1679     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1680   DeclContext *Ctx =
1681       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1682   if (!TC) {
1683     // Emit a special diagnostic for failed member lookups.
1684     // FIXME: computing the declaration context might fail here (?)
1685     if (Ctx)
1686       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1687                                                  << SS.getRange();
1688     else
1689       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1690     return;
1691   }
1692 
1693   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1694   bool DroppedSpecifier =
1695       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1696   unsigned NoteID =
1697       (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1698           ? diag::note_implicit_param_decl
1699           : diag::note_previous_decl;
1700   if (!Ctx)
1701     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1702                          SemaRef.PDiag(NoteID));
1703   else
1704     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1705                                  << Typo << Ctx << DroppedSpecifier
1706                                  << SS.getRange(),
1707                          SemaRef.PDiag(NoteID));
1708 }
1709 
1710 /// Diagnose an empty lookup.
1711 ///
1712 /// \return false if new lookup candidates were found
1713 bool
1714 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1715                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1716                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1717                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1718   DeclarationName Name = R.getLookupName();
1719 
1720   unsigned diagnostic = diag::err_undeclared_var_use;
1721   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1722   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1723       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1724       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1725     diagnostic = diag::err_undeclared_use;
1726     diagnostic_suggest = diag::err_undeclared_use_suggest;
1727   }
1728 
1729   // If the original lookup was an unqualified lookup, fake an
1730   // unqualified lookup.  This is useful when (for example) the
1731   // original lookup would not have found something because it was a
1732   // dependent name.
1733   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1734     ? CurContext : nullptr;
1735   while (DC) {
1736     if (isa<CXXRecordDecl>(DC)) {
1737       LookupQualifiedName(R, DC);
1738 
1739       if (!R.empty()) {
1740         // Don't give errors about ambiguities in this lookup.
1741         R.suppressDiagnostics();
1742 
1743         // During a default argument instantiation the CurContext points
1744         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1745         // function parameter list, hence add an explicit check.
1746         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1747                               ActiveTemplateInstantiations.back().Kind ==
1748             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1749         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1750         bool isInstance = CurMethod &&
1751                           CurMethod->isInstance() &&
1752                           DC == CurMethod->getParent() && !isDefaultArgument;
1753 
1754 
1755         // Give a code modification hint to insert 'this->'.
1756         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1757         // Actually quite difficult!
1758         if (getLangOpts().MSVCCompat)
1759           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1760         if (isInstance) {
1761           Diag(R.getNameLoc(), diagnostic) << Name
1762             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1763           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1764               CallsUndergoingInstantiation.back()->getCallee());
1765 
1766           CXXMethodDecl *DepMethod;
1767           if (CurMethod->isDependentContext())
1768             DepMethod = CurMethod;
1769           else if (CurMethod->getTemplatedKind() ==
1770               FunctionDecl::TK_FunctionTemplateSpecialization)
1771             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1772                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1773           else
1774             DepMethod = cast<CXXMethodDecl>(
1775                 CurMethod->getInstantiatedFromMemberFunction());
1776           assert(DepMethod && "No template pattern found");
1777 
1778           QualType DepThisType = DepMethod->getThisType(Context);
1779           CheckCXXThisCapture(R.getNameLoc());
1780           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1781                                      R.getNameLoc(), DepThisType, false);
1782           TemplateArgumentListInfo TList;
1783           if (ULE->hasExplicitTemplateArgs())
1784             ULE->copyTemplateArgumentsInto(TList);
1785 
1786           CXXScopeSpec SS;
1787           SS.Adopt(ULE->getQualifierLoc());
1788           CXXDependentScopeMemberExpr *DepExpr =
1789               CXXDependentScopeMemberExpr::Create(
1790                   Context, DepThis, DepThisType, true, SourceLocation(),
1791                   SS.getWithLocInContext(Context),
1792                   ULE->getTemplateKeywordLoc(), nullptr,
1793                   R.getLookupNameInfo(),
1794                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1795           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1796         } else {
1797           Diag(R.getNameLoc(), diagnostic) << Name;
1798         }
1799 
1800         // Do we really want to note all of these?
1801         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1802           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1803 
1804         // Return true if we are inside a default argument instantiation
1805         // and the found name refers to an instance member function, otherwise
1806         // the function calling DiagnoseEmptyLookup will try to create an
1807         // implicit member call and this is wrong for default argument.
1808         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1809           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1810           return true;
1811         }
1812 
1813         // Tell the callee to try to recover.
1814         return false;
1815       }
1816 
1817       R.clear();
1818     }
1819 
1820     // In Microsoft mode, if we are performing lookup from within a friend
1821     // function definition declared at class scope then we must set
1822     // DC to the lexical parent to be able to search into the parent
1823     // class.
1824     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1825         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1826         DC->getLexicalParent()->isRecord())
1827       DC = DC->getLexicalParent();
1828     else
1829       DC = DC->getParent();
1830   }
1831 
1832   // We didn't find anything, so try to correct for a typo.
1833   TypoCorrection Corrected;
1834   if (S && Out) {
1835     SourceLocation TypoLoc = R.getNameLoc();
1836     assert(!ExplicitTemplateArgs &&
1837            "Diagnosing an empty lookup with explicit template args!");
1838     *Out = CorrectTypoDelayed(
1839         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1840         [=](const TypoCorrection &TC) {
1841           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1842                                         diagnostic, diagnostic_suggest);
1843         },
1844         nullptr, CTK_ErrorRecovery);
1845     if (*Out)
1846       return true;
1847   } else if (S && (Corrected =
1848                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1849                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1850     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1851     bool DroppedSpecifier =
1852         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1853     R.setLookupName(Corrected.getCorrection());
1854 
1855     bool AcceptableWithRecovery = false;
1856     bool AcceptableWithoutRecovery = false;
1857     NamedDecl *ND = Corrected.getCorrectionDecl();
1858     if (ND) {
1859       if (Corrected.isOverloaded()) {
1860         OverloadCandidateSet OCS(R.getNameLoc(),
1861                                  OverloadCandidateSet::CSK_Normal);
1862         OverloadCandidateSet::iterator Best;
1863         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1864                                         CDEnd = Corrected.end();
1865              CD != CDEnd; ++CD) {
1866           if (FunctionTemplateDecl *FTD =
1867                    dyn_cast<FunctionTemplateDecl>(*CD))
1868             AddTemplateOverloadCandidate(
1869                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1870                 Args, OCS);
1871           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1872             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1873               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1874                                    Args, OCS);
1875         }
1876         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1877         case OR_Success:
1878           ND = Best->Function;
1879           Corrected.setCorrectionDecl(ND);
1880           break;
1881         default:
1882           // FIXME: Arbitrarily pick the first declaration for the note.
1883           Corrected.setCorrectionDecl(ND);
1884           break;
1885         }
1886       }
1887       R.addDecl(ND);
1888       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1889         CXXRecordDecl *Record = nullptr;
1890         if (Corrected.getCorrectionSpecifier()) {
1891           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1892           Record = Ty->getAsCXXRecordDecl();
1893         }
1894         if (!Record)
1895           Record = cast<CXXRecordDecl>(
1896               ND->getDeclContext()->getRedeclContext());
1897         R.setNamingClass(Record);
1898       }
1899 
1900       AcceptableWithRecovery =
1901           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1902       // FIXME: If we ended up with a typo for a type name or
1903       // Objective-C class name, we're in trouble because the parser
1904       // is in the wrong place to recover. Suggest the typo
1905       // correction, but don't make it a fix-it since we're not going
1906       // to recover well anyway.
1907       AcceptableWithoutRecovery =
1908           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1909     } else {
1910       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1911       // because we aren't able to recover.
1912       AcceptableWithoutRecovery = true;
1913     }
1914 
1915     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1916       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1917                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1918                             ? diag::note_implicit_param_decl
1919                             : diag::note_previous_decl;
1920       if (SS.isEmpty())
1921         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1922                      PDiag(NoteID), AcceptableWithRecovery);
1923       else
1924         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1925                                   << Name << computeDeclContext(SS, false)
1926                                   << DroppedSpecifier << SS.getRange(),
1927                      PDiag(NoteID), AcceptableWithRecovery);
1928 
1929       // Tell the callee whether to try to recover.
1930       return !AcceptableWithRecovery;
1931     }
1932   }
1933   R.clear();
1934 
1935   // Emit a special diagnostic for failed member lookups.
1936   // FIXME: computing the declaration context might fail here (?)
1937   if (!SS.isEmpty()) {
1938     Diag(R.getNameLoc(), diag::err_no_member)
1939       << Name << computeDeclContext(SS, false)
1940       << SS.getRange();
1941     return true;
1942   }
1943 
1944   // Give up, we can't recover.
1945   Diag(R.getNameLoc(), diagnostic) << Name;
1946   return true;
1947 }
1948 
1949 /// In Microsoft mode, if we are inside a template class whose parent class has
1950 /// dependent base classes, and we can't resolve an unqualified identifier, then
1951 /// assume the identifier is a member of a dependent base class.  We can only
1952 /// recover successfully in static methods, instance methods, and other contexts
1953 /// where 'this' is available.  This doesn't precisely match MSVC's
1954 /// instantiation model, but it's close enough.
1955 static Expr *
1956 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1957                                DeclarationNameInfo &NameInfo,
1958                                SourceLocation TemplateKWLoc,
1959                                const TemplateArgumentListInfo *TemplateArgs) {
1960   // Only try to recover from lookup into dependent bases in static methods or
1961   // contexts where 'this' is available.
1962   QualType ThisType = S.getCurrentThisType();
1963   const CXXRecordDecl *RD = nullptr;
1964   if (!ThisType.isNull())
1965     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1966   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1967     RD = MD->getParent();
1968   if (!RD || !RD->hasAnyDependentBases())
1969     return nullptr;
1970 
1971   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1972   // is available, suggest inserting 'this->' as a fixit.
1973   SourceLocation Loc = NameInfo.getLoc();
1974   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1975   DB << NameInfo.getName() << RD;
1976 
1977   if (!ThisType.isNull()) {
1978     DB << FixItHint::CreateInsertion(Loc, "this->");
1979     return CXXDependentScopeMemberExpr::Create(
1980         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1981         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1982         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1983   }
1984 
1985   // Synthesize a fake NNS that points to the derived class.  This will
1986   // perform name lookup during template instantiation.
1987   CXXScopeSpec SS;
1988   auto *NNS =
1989       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1990   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1991   return DependentScopeDeclRefExpr::Create(
1992       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1993       TemplateArgs);
1994 }
1995 
1996 ExprResult
1997 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
1998                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
1999                         bool HasTrailingLParen, bool IsAddressOfOperand,
2000                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2001                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2002   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2003          "cannot be direct & operand and have a trailing lparen");
2004   if (SS.isInvalid())
2005     return ExprError();
2006 
2007   TemplateArgumentListInfo TemplateArgsBuffer;
2008 
2009   // Decompose the UnqualifiedId into the following data.
2010   DeclarationNameInfo NameInfo;
2011   const TemplateArgumentListInfo *TemplateArgs;
2012   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2013 
2014   DeclarationName Name = NameInfo.getName();
2015   IdentifierInfo *II = Name.getAsIdentifierInfo();
2016   SourceLocation NameLoc = NameInfo.getLoc();
2017 
2018   // C++ [temp.dep.expr]p3:
2019   //   An id-expression is type-dependent if it contains:
2020   //     -- an identifier that was declared with a dependent type,
2021   //        (note: handled after lookup)
2022   //     -- a template-id that is dependent,
2023   //        (note: handled in BuildTemplateIdExpr)
2024   //     -- a conversion-function-id that specifies a dependent type,
2025   //     -- a nested-name-specifier that contains a class-name that
2026   //        names a dependent type.
2027   // Determine whether this is a member of an unknown specialization;
2028   // we need to handle these differently.
2029   bool DependentID = false;
2030   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2031       Name.getCXXNameType()->isDependentType()) {
2032     DependentID = true;
2033   } else if (SS.isSet()) {
2034     if (DeclContext *DC = computeDeclContext(SS, false)) {
2035       if (RequireCompleteDeclContext(SS, DC))
2036         return ExprError();
2037     } else {
2038       DependentID = true;
2039     }
2040   }
2041 
2042   if (DependentID)
2043     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2044                                       IsAddressOfOperand, TemplateArgs);
2045 
2046   // Perform the required lookup.
2047   LookupResult R(*this, NameInfo,
2048                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2049                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2050   if (TemplateArgs) {
2051     // Lookup the template name again to correctly establish the context in
2052     // which it was found. This is really unfortunate as we already did the
2053     // lookup to determine that it was a template name in the first place. If
2054     // this becomes a performance hit, we can work harder to preserve those
2055     // results until we get here but it's likely not worth it.
2056     bool MemberOfUnknownSpecialization;
2057     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2058                        MemberOfUnknownSpecialization);
2059 
2060     if (MemberOfUnknownSpecialization ||
2061         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2062       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2063                                         IsAddressOfOperand, TemplateArgs);
2064   } else {
2065     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2066     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2067 
2068     // If the result might be in a dependent base class, this is a dependent
2069     // id-expression.
2070     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2071       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2072                                         IsAddressOfOperand, TemplateArgs);
2073 
2074     // If this reference is in an Objective-C method, then we need to do
2075     // some special Objective-C lookup, too.
2076     if (IvarLookupFollowUp) {
2077       ExprResult E(LookupInObjCMethod(R, S, II, true));
2078       if (E.isInvalid())
2079         return ExprError();
2080 
2081       if (Expr *Ex = E.getAs<Expr>())
2082         return Ex;
2083     }
2084   }
2085 
2086   if (R.isAmbiguous())
2087     return ExprError();
2088 
2089   // This could be an implicitly declared function reference (legal in C90,
2090   // extension in C99, forbidden in C++).
2091   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2092     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2093     if (D) R.addDecl(D);
2094   }
2095 
2096   // Determine whether this name might be a candidate for
2097   // argument-dependent lookup.
2098   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2099 
2100   if (R.empty() && !ADL) {
2101     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2102       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2103                                                    TemplateKWLoc, TemplateArgs))
2104         return E;
2105     }
2106 
2107     // Don't diagnose an empty lookup for inline assembly.
2108     if (IsInlineAsmIdentifier)
2109       return ExprError();
2110 
2111     // If this name wasn't predeclared and if this is not a function
2112     // call, diagnose the problem.
2113     TypoExpr *TE = nullptr;
2114     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2115         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2116     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2117     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2118            "Typo correction callback misconfigured");
2119     if (CCC) {
2120       // Make sure the callback knows what the typo being diagnosed is.
2121       CCC->setTypoName(II);
2122       if (SS.isValid())
2123         CCC->setTypoNNS(SS.getScopeRep());
2124     }
2125     if (DiagnoseEmptyLookup(S, SS, R,
2126                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2127                             nullptr, None, &TE)) {
2128       if (TE && KeywordReplacement) {
2129         auto &State = getTypoExprState(TE);
2130         auto BestTC = State.Consumer->getNextCorrection();
2131         if (BestTC.isKeyword()) {
2132           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2133           if (State.DiagHandler)
2134             State.DiagHandler(BestTC);
2135           KeywordReplacement->startToken();
2136           KeywordReplacement->setKind(II->getTokenID());
2137           KeywordReplacement->setIdentifierInfo(II);
2138           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2139           // Clean up the state associated with the TypoExpr, since it has
2140           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2141           clearDelayedTypo(TE);
2142           // Signal that a correction to a keyword was performed by returning a
2143           // valid-but-null ExprResult.
2144           return (Expr*)nullptr;
2145         }
2146         State.Consumer->resetCorrectionStream();
2147       }
2148       return TE ? TE : ExprError();
2149     }
2150 
2151     assert(!R.empty() &&
2152            "DiagnoseEmptyLookup returned false but added no results");
2153 
2154     // If we found an Objective-C instance variable, let
2155     // LookupInObjCMethod build the appropriate expression to
2156     // reference the ivar.
2157     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2158       R.clear();
2159       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2160       // In a hopelessly buggy code, Objective-C instance variable
2161       // lookup fails and no expression will be built to reference it.
2162       if (!E.isInvalid() && !E.get())
2163         return ExprError();
2164       return E;
2165     }
2166   }
2167 
2168   // This is guaranteed from this point on.
2169   assert(!R.empty() || ADL);
2170 
2171   // Check whether this might be a C++ implicit instance member access.
2172   // C++ [class.mfct.non-static]p3:
2173   //   When an id-expression that is not part of a class member access
2174   //   syntax and not used to form a pointer to member is used in the
2175   //   body of a non-static member function of class X, if name lookup
2176   //   resolves the name in the id-expression to a non-static non-type
2177   //   member of some class C, the id-expression is transformed into a
2178   //   class member access expression using (*this) as the
2179   //   postfix-expression to the left of the . operator.
2180   //
2181   // But we don't actually need to do this for '&' operands if R
2182   // resolved to a function or overloaded function set, because the
2183   // expression is ill-formed if it actually works out to be a
2184   // non-static member function:
2185   //
2186   // C++ [expr.ref]p4:
2187   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2188   //   [t]he expression can be used only as the left-hand operand of a
2189   //   member function call.
2190   //
2191   // There are other safeguards against such uses, but it's important
2192   // to get this right here so that we don't end up making a
2193   // spuriously dependent expression if we're inside a dependent
2194   // instance method.
2195   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2196     bool MightBeImplicitMember;
2197     if (!IsAddressOfOperand)
2198       MightBeImplicitMember = true;
2199     else if (!SS.isEmpty())
2200       MightBeImplicitMember = false;
2201     else if (R.isOverloadedResult())
2202       MightBeImplicitMember = false;
2203     else if (R.isUnresolvableResult())
2204       MightBeImplicitMember = true;
2205     else
2206       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2207                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2208                               isa<MSPropertyDecl>(R.getFoundDecl());
2209 
2210     if (MightBeImplicitMember)
2211       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2212                                              R, TemplateArgs);
2213   }
2214 
2215   if (TemplateArgs || TemplateKWLoc.isValid()) {
2216 
2217     // In C++1y, if this is a variable template id, then check it
2218     // in BuildTemplateIdExpr().
2219     // The single lookup result must be a variable template declaration.
2220     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2221         Id.TemplateId->Kind == TNK_Var_template) {
2222       assert(R.getAsSingle<VarTemplateDecl>() &&
2223              "There should only be one declaration found.");
2224     }
2225 
2226     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2227   }
2228 
2229   return BuildDeclarationNameExpr(SS, R, ADL);
2230 }
2231 
2232 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2233 /// declaration name, generally during template instantiation.
2234 /// There's a large number of things which don't need to be done along
2235 /// this path.
2236 ExprResult
2237 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2238                                         const DeclarationNameInfo &NameInfo,
2239                                         bool IsAddressOfOperand,
2240                                         TypeSourceInfo **RecoveryTSI) {
2241   DeclContext *DC = computeDeclContext(SS, false);
2242   if (!DC)
2243     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2244                                      NameInfo, /*TemplateArgs=*/nullptr);
2245 
2246   if (RequireCompleteDeclContext(SS, DC))
2247     return ExprError();
2248 
2249   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2250   LookupQualifiedName(R, DC);
2251 
2252   if (R.isAmbiguous())
2253     return ExprError();
2254 
2255   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2256     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2257                                      NameInfo, /*TemplateArgs=*/nullptr);
2258 
2259   if (R.empty()) {
2260     Diag(NameInfo.getLoc(), diag::err_no_member)
2261       << NameInfo.getName() << DC << SS.getRange();
2262     return ExprError();
2263   }
2264 
2265   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2266     // Diagnose a missing typename if this resolved unambiguously to a type in
2267     // a dependent context.  If we can recover with a type, downgrade this to
2268     // a warning in Microsoft compatibility mode.
2269     unsigned DiagID = diag::err_typename_missing;
2270     if (RecoveryTSI && getLangOpts().MSVCCompat)
2271       DiagID = diag::ext_typename_missing;
2272     SourceLocation Loc = SS.getBeginLoc();
2273     auto D = Diag(Loc, DiagID);
2274     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2275       << SourceRange(Loc, NameInfo.getEndLoc());
2276 
2277     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2278     // context.
2279     if (!RecoveryTSI)
2280       return ExprError();
2281 
2282     // Only issue the fixit if we're prepared to recover.
2283     D << FixItHint::CreateInsertion(Loc, "typename ");
2284 
2285     // Recover by pretending this was an elaborated type.
2286     QualType Ty = Context.getTypeDeclType(TD);
2287     TypeLocBuilder TLB;
2288     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2289 
2290     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2291     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2292     QTL.setElaboratedKeywordLoc(SourceLocation());
2293     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2294 
2295     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2296 
2297     return ExprEmpty();
2298   }
2299 
2300   // Defend against this resolving to an implicit member access. We usually
2301   // won't get here if this might be a legitimate a class member (we end up in
2302   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2303   // a pointer-to-member or in an unevaluated context in C++11.
2304   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2305     return BuildPossibleImplicitMemberExpr(SS,
2306                                            /*TemplateKWLoc=*/SourceLocation(),
2307                                            R, /*TemplateArgs=*/nullptr);
2308 
2309   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2310 }
2311 
2312 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2313 /// detected that we're currently inside an ObjC method.  Perform some
2314 /// additional lookup.
2315 ///
2316 /// Ideally, most of this would be done by lookup, but there's
2317 /// actually quite a lot of extra work involved.
2318 ///
2319 /// Returns a null sentinel to indicate trivial success.
2320 ExprResult
2321 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2322                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2323   SourceLocation Loc = Lookup.getNameLoc();
2324   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2325 
2326   // Check for error condition which is already reported.
2327   if (!CurMethod)
2328     return ExprError();
2329 
2330   // There are two cases to handle here.  1) scoped lookup could have failed,
2331   // in which case we should look for an ivar.  2) scoped lookup could have
2332   // found a decl, but that decl is outside the current instance method (i.e.
2333   // a global variable).  In these two cases, we do a lookup for an ivar with
2334   // this name, if the lookup sucedes, we replace it our current decl.
2335 
2336   // If we're in a class method, we don't normally want to look for
2337   // ivars.  But if we don't find anything else, and there's an
2338   // ivar, that's an error.
2339   bool IsClassMethod = CurMethod->isClassMethod();
2340 
2341   bool LookForIvars;
2342   if (Lookup.empty())
2343     LookForIvars = true;
2344   else if (IsClassMethod)
2345     LookForIvars = false;
2346   else
2347     LookForIvars = (Lookup.isSingleResult() &&
2348                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2349   ObjCInterfaceDecl *IFace = nullptr;
2350   if (LookForIvars) {
2351     IFace = CurMethod->getClassInterface();
2352     ObjCInterfaceDecl *ClassDeclared;
2353     ObjCIvarDecl *IV = nullptr;
2354     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2355       // Diagnose using an ivar in a class method.
2356       if (IsClassMethod)
2357         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2358                          << IV->getDeclName());
2359 
2360       // If we're referencing an invalid decl, just return this as a silent
2361       // error node.  The error diagnostic was already emitted on the decl.
2362       if (IV->isInvalidDecl())
2363         return ExprError();
2364 
2365       // Check if referencing a field with __attribute__((deprecated)).
2366       if (DiagnoseUseOfDecl(IV, Loc))
2367         return ExprError();
2368 
2369       // Diagnose the use of an ivar outside of the declaring class.
2370       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2371           !declaresSameEntity(ClassDeclared, IFace) &&
2372           !getLangOpts().DebuggerSupport)
2373         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2374 
2375       // FIXME: This should use a new expr for a direct reference, don't
2376       // turn this into Self->ivar, just return a BareIVarExpr or something.
2377       IdentifierInfo &II = Context.Idents.get("self");
2378       UnqualifiedId SelfName;
2379       SelfName.setIdentifier(&II, SourceLocation());
2380       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2381       CXXScopeSpec SelfScopeSpec;
2382       SourceLocation TemplateKWLoc;
2383       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2384                                               SelfName, false, false);
2385       if (SelfExpr.isInvalid())
2386         return ExprError();
2387 
2388       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2389       if (SelfExpr.isInvalid())
2390         return ExprError();
2391 
2392       MarkAnyDeclReferenced(Loc, IV, true);
2393 
2394       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2395       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2396           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2397         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2398 
2399       ObjCIvarRefExpr *Result = new (Context)
2400           ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
2401                           SelfExpr.get(), true, true);
2402 
2403       if (getLangOpts().ObjCAutoRefCount) {
2404         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2405           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2406             recordUseOfEvaluatedWeak(Result);
2407         }
2408         if (CurContext->isClosure())
2409           Diag(Loc, diag::warn_implicitly_retains_self)
2410             << FixItHint::CreateInsertion(Loc, "self->");
2411       }
2412 
2413       return Result;
2414     }
2415   } else if (CurMethod->isInstanceMethod()) {
2416     // We should warn if a local variable hides an ivar.
2417     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2418       ObjCInterfaceDecl *ClassDeclared;
2419       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2420         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2421             declaresSameEntity(IFace, ClassDeclared))
2422           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2423       }
2424     }
2425   } else if (Lookup.isSingleResult() &&
2426              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2427     // If accessing a stand-alone ivar in a class method, this is an error.
2428     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2429       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2430                        << IV->getDeclName());
2431   }
2432 
2433   if (Lookup.empty() && II && AllowBuiltinCreation) {
2434     // FIXME. Consolidate this with similar code in LookupName.
2435     if (unsigned BuiltinID = II->getBuiltinID()) {
2436       if (!(getLangOpts().CPlusPlus &&
2437             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2438         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2439                                            S, Lookup.isForRedeclaration(),
2440                                            Lookup.getNameLoc());
2441         if (D) Lookup.addDecl(D);
2442       }
2443     }
2444   }
2445   // Sentinel value saying that we didn't do anything special.
2446   return ExprResult((Expr *)nullptr);
2447 }
2448 
2449 /// \brief Cast a base object to a member's actual type.
2450 ///
2451 /// Logically this happens in three phases:
2452 ///
2453 /// * First we cast from the base type to the naming class.
2454 ///   The naming class is the class into which we were looking
2455 ///   when we found the member;  it's the qualifier type if a
2456 ///   qualifier was provided, and otherwise it's the base type.
2457 ///
2458 /// * Next we cast from the naming class to the declaring class.
2459 ///   If the member we found was brought into a class's scope by
2460 ///   a using declaration, this is that class;  otherwise it's
2461 ///   the class declaring the member.
2462 ///
2463 /// * Finally we cast from the declaring class to the "true"
2464 ///   declaring class of the member.  This conversion does not
2465 ///   obey access control.
2466 ExprResult
2467 Sema::PerformObjectMemberConversion(Expr *From,
2468                                     NestedNameSpecifier *Qualifier,
2469                                     NamedDecl *FoundDecl,
2470                                     NamedDecl *Member) {
2471   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2472   if (!RD)
2473     return From;
2474 
2475   QualType DestRecordType;
2476   QualType DestType;
2477   QualType FromRecordType;
2478   QualType FromType = From->getType();
2479   bool PointerConversions = false;
2480   if (isa<FieldDecl>(Member)) {
2481     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2482 
2483     if (FromType->getAs<PointerType>()) {
2484       DestType = Context.getPointerType(DestRecordType);
2485       FromRecordType = FromType->getPointeeType();
2486       PointerConversions = true;
2487     } else {
2488       DestType = DestRecordType;
2489       FromRecordType = FromType;
2490     }
2491   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2492     if (Method->isStatic())
2493       return From;
2494 
2495     DestType = Method->getThisType(Context);
2496     DestRecordType = DestType->getPointeeType();
2497 
2498     if (FromType->getAs<PointerType>()) {
2499       FromRecordType = FromType->getPointeeType();
2500       PointerConversions = true;
2501     } else {
2502       FromRecordType = FromType;
2503       DestType = DestRecordType;
2504     }
2505   } else {
2506     // No conversion necessary.
2507     return From;
2508   }
2509 
2510   if (DestType->isDependentType() || FromType->isDependentType())
2511     return From;
2512 
2513   // If the unqualified types are the same, no conversion is necessary.
2514   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2515     return From;
2516 
2517   SourceRange FromRange = From->getSourceRange();
2518   SourceLocation FromLoc = FromRange.getBegin();
2519 
2520   ExprValueKind VK = From->getValueKind();
2521 
2522   // C++ [class.member.lookup]p8:
2523   //   [...] Ambiguities can often be resolved by qualifying a name with its
2524   //   class name.
2525   //
2526   // If the member was a qualified name and the qualified referred to a
2527   // specific base subobject type, we'll cast to that intermediate type
2528   // first and then to the object in which the member is declared. That allows
2529   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2530   //
2531   //   class Base { public: int x; };
2532   //   class Derived1 : public Base { };
2533   //   class Derived2 : public Base { };
2534   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2535   //
2536   //   void VeryDerived::f() {
2537   //     x = 17; // error: ambiguous base subobjects
2538   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2539   //   }
2540   if (Qualifier && Qualifier->getAsType()) {
2541     QualType QType = QualType(Qualifier->getAsType(), 0);
2542     assert(QType->isRecordType() && "lookup done with non-record type");
2543 
2544     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2545 
2546     // In C++98, the qualifier type doesn't actually have to be a base
2547     // type of the object type, in which case we just ignore it.
2548     // Otherwise build the appropriate casts.
2549     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2550       CXXCastPath BasePath;
2551       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2552                                        FromLoc, FromRange, &BasePath))
2553         return ExprError();
2554 
2555       if (PointerConversions)
2556         QType = Context.getPointerType(QType);
2557       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2558                                VK, &BasePath).get();
2559 
2560       FromType = QType;
2561       FromRecordType = QRecordType;
2562 
2563       // If the qualifier type was the same as the destination type,
2564       // we're done.
2565       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2566         return From;
2567     }
2568   }
2569 
2570   bool IgnoreAccess = false;
2571 
2572   // If we actually found the member through a using declaration, cast
2573   // down to the using declaration's type.
2574   //
2575   // Pointer equality is fine here because only one declaration of a
2576   // class ever has member declarations.
2577   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2578     assert(isa<UsingShadowDecl>(FoundDecl));
2579     QualType URecordType = Context.getTypeDeclType(
2580                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2581 
2582     // We only need to do this if the naming-class to declaring-class
2583     // conversion is non-trivial.
2584     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2585       assert(IsDerivedFrom(FromRecordType, URecordType));
2586       CXXCastPath BasePath;
2587       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2588                                        FromLoc, FromRange, &BasePath))
2589         return ExprError();
2590 
2591       QualType UType = URecordType;
2592       if (PointerConversions)
2593         UType = Context.getPointerType(UType);
2594       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2595                                VK, &BasePath).get();
2596       FromType = UType;
2597       FromRecordType = URecordType;
2598     }
2599 
2600     // We don't do access control for the conversion from the
2601     // declaring class to the true declaring class.
2602     IgnoreAccess = true;
2603   }
2604 
2605   CXXCastPath BasePath;
2606   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2607                                    FromLoc, FromRange, &BasePath,
2608                                    IgnoreAccess))
2609     return ExprError();
2610 
2611   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2612                            VK, &BasePath);
2613 }
2614 
2615 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2616                                       const LookupResult &R,
2617                                       bool HasTrailingLParen) {
2618   // Only when used directly as the postfix-expression of a call.
2619   if (!HasTrailingLParen)
2620     return false;
2621 
2622   // Never if a scope specifier was provided.
2623   if (SS.isSet())
2624     return false;
2625 
2626   // Only in C++ or ObjC++.
2627   if (!getLangOpts().CPlusPlus)
2628     return false;
2629 
2630   // Turn off ADL when we find certain kinds of declarations during
2631   // normal lookup:
2632   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2633     NamedDecl *D = *I;
2634 
2635     // C++0x [basic.lookup.argdep]p3:
2636     //     -- a declaration of a class member
2637     // Since using decls preserve this property, we check this on the
2638     // original decl.
2639     if (D->isCXXClassMember())
2640       return false;
2641 
2642     // C++0x [basic.lookup.argdep]p3:
2643     //     -- a block-scope function declaration that is not a
2644     //        using-declaration
2645     // NOTE: we also trigger this for function templates (in fact, we
2646     // don't check the decl type at all, since all other decl types
2647     // turn off ADL anyway).
2648     if (isa<UsingShadowDecl>(D))
2649       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2650     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2651       return false;
2652 
2653     // C++0x [basic.lookup.argdep]p3:
2654     //     -- a declaration that is neither a function or a function
2655     //        template
2656     // And also for builtin functions.
2657     if (isa<FunctionDecl>(D)) {
2658       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2659 
2660       // But also builtin functions.
2661       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2662         return false;
2663     } else if (!isa<FunctionTemplateDecl>(D))
2664       return false;
2665   }
2666 
2667   return true;
2668 }
2669 
2670 
2671 /// Diagnoses obvious problems with the use of the given declaration
2672 /// as an expression.  This is only actually called for lookups that
2673 /// were not overloaded, and it doesn't promise that the declaration
2674 /// will in fact be used.
2675 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2676   if (isa<TypedefNameDecl>(D)) {
2677     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2678     return true;
2679   }
2680 
2681   if (isa<ObjCInterfaceDecl>(D)) {
2682     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2683     return true;
2684   }
2685 
2686   if (isa<NamespaceDecl>(D)) {
2687     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2688     return true;
2689   }
2690 
2691   return false;
2692 }
2693 
2694 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2695                                           LookupResult &R, bool NeedsADL,
2696                                           bool AcceptInvalidDecl) {
2697   // If this is a single, fully-resolved result and we don't need ADL,
2698   // just build an ordinary singleton decl ref.
2699   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2700     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2701                                     R.getRepresentativeDecl(), nullptr,
2702                                     AcceptInvalidDecl);
2703 
2704   // We only need to check the declaration if there's exactly one
2705   // result, because in the overloaded case the results can only be
2706   // functions and function templates.
2707   if (R.isSingleResult() &&
2708       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2709     return ExprError();
2710 
2711   // Otherwise, just build an unresolved lookup expression.  Suppress
2712   // any lookup-related diagnostics; we'll hash these out later, when
2713   // we've picked a target.
2714   R.suppressDiagnostics();
2715 
2716   UnresolvedLookupExpr *ULE
2717     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2718                                    SS.getWithLocInContext(Context),
2719                                    R.getLookupNameInfo(),
2720                                    NeedsADL, R.isOverloadedResult(),
2721                                    R.begin(), R.end());
2722 
2723   return ULE;
2724 }
2725 
2726 /// \brief Complete semantic analysis for a reference to the given declaration.
2727 ExprResult Sema::BuildDeclarationNameExpr(
2728     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2729     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2730     bool AcceptInvalidDecl) {
2731   assert(D && "Cannot refer to a NULL declaration");
2732   assert(!isa<FunctionTemplateDecl>(D) &&
2733          "Cannot refer unambiguously to a function template");
2734 
2735   SourceLocation Loc = NameInfo.getLoc();
2736   if (CheckDeclInExpr(*this, Loc, D))
2737     return ExprError();
2738 
2739   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2740     // Specifically diagnose references to class templates that are missing
2741     // a template argument list.
2742     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2743                                            << Template << SS.getRange();
2744     Diag(Template->getLocation(), diag::note_template_decl_here);
2745     return ExprError();
2746   }
2747 
2748   // Make sure that we're referring to a value.
2749   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2750   if (!VD) {
2751     Diag(Loc, diag::err_ref_non_value)
2752       << D << SS.getRange();
2753     Diag(D->getLocation(), diag::note_declared_at);
2754     return ExprError();
2755   }
2756 
2757   // Check whether this declaration can be used. Note that we suppress
2758   // this check when we're going to perform argument-dependent lookup
2759   // on this function name, because this might not be the function
2760   // that overload resolution actually selects.
2761   if (DiagnoseUseOfDecl(VD, Loc))
2762     return ExprError();
2763 
2764   // Only create DeclRefExpr's for valid Decl's.
2765   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2766     return ExprError();
2767 
2768   // Handle members of anonymous structs and unions.  If we got here,
2769   // and the reference is to a class member indirect field, then this
2770   // must be the subject of a pointer-to-member expression.
2771   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2772     if (!indirectField->isCXXClassMember())
2773       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2774                                                       indirectField);
2775 
2776   {
2777     QualType type = VD->getType();
2778     ExprValueKind valueKind = VK_RValue;
2779 
2780     switch (D->getKind()) {
2781     // Ignore all the non-ValueDecl kinds.
2782 #define ABSTRACT_DECL(kind)
2783 #define VALUE(type, base)
2784 #define DECL(type, base) \
2785     case Decl::type:
2786 #include "clang/AST/DeclNodes.inc"
2787       llvm_unreachable("invalid value decl kind");
2788 
2789     // These shouldn't make it here.
2790     case Decl::ObjCAtDefsField:
2791     case Decl::ObjCIvar:
2792       llvm_unreachable("forming non-member reference to ivar?");
2793 
2794     // Enum constants are always r-values and never references.
2795     // Unresolved using declarations are dependent.
2796     case Decl::EnumConstant:
2797     case Decl::UnresolvedUsingValue:
2798       valueKind = VK_RValue;
2799       break;
2800 
2801     // Fields and indirect fields that got here must be for
2802     // pointer-to-member expressions; we just call them l-values for
2803     // internal consistency, because this subexpression doesn't really
2804     // exist in the high-level semantics.
2805     case Decl::Field:
2806     case Decl::IndirectField:
2807       assert(getLangOpts().CPlusPlus &&
2808              "building reference to field in C?");
2809 
2810       // These can't have reference type in well-formed programs, but
2811       // for internal consistency we do this anyway.
2812       type = type.getNonReferenceType();
2813       valueKind = VK_LValue;
2814       break;
2815 
2816     // Non-type template parameters are either l-values or r-values
2817     // depending on the type.
2818     case Decl::NonTypeTemplateParm: {
2819       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2820         type = reftype->getPointeeType();
2821         valueKind = VK_LValue; // even if the parameter is an r-value reference
2822         break;
2823       }
2824 
2825       // For non-references, we need to strip qualifiers just in case
2826       // the template parameter was declared as 'const int' or whatever.
2827       valueKind = VK_RValue;
2828       type = type.getUnqualifiedType();
2829       break;
2830     }
2831 
2832     case Decl::Var:
2833     case Decl::VarTemplateSpecialization:
2834     case Decl::VarTemplatePartialSpecialization:
2835       // In C, "extern void blah;" is valid and is an r-value.
2836       if (!getLangOpts().CPlusPlus &&
2837           !type.hasQualifiers() &&
2838           type->isVoidType()) {
2839         valueKind = VK_RValue;
2840         break;
2841       }
2842       // fallthrough
2843 
2844     case Decl::ImplicitParam:
2845     case Decl::ParmVar: {
2846       // These are always l-values.
2847       valueKind = VK_LValue;
2848       type = type.getNonReferenceType();
2849 
2850       // FIXME: Does the addition of const really only apply in
2851       // potentially-evaluated contexts? Since the variable isn't actually
2852       // captured in an unevaluated context, it seems that the answer is no.
2853       if (!isUnevaluatedContext()) {
2854         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2855         if (!CapturedType.isNull())
2856           type = CapturedType;
2857       }
2858 
2859       break;
2860     }
2861 
2862     case Decl::Function: {
2863       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2864         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2865           type = Context.BuiltinFnTy;
2866           valueKind = VK_RValue;
2867           break;
2868         }
2869       }
2870 
2871       const FunctionType *fty = type->castAs<FunctionType>();
2872 
2873       // If we're referring to a function with an __unknown_anytype
2874       // result type, make the entire expression __unknown_anytype.
2875       if (fty->getReturnType() == Context.UnknownAnyTy) {
2876         type = Context.UnknownAnyTy;
2877         valueKind = VK_RValue;
2878         break;
2879       }
2880 
2881       // Functions are l-values in C++.
2882       if (getLangOpts().CPlusPlus) {
2883         valueKind = VK_LValue;
2884         break;
2885       }
2886 
2887       // C99 DR 316 says that, if a function type comes from a
2888       // function definition (without a prototype), that type is only
2889       // used for checking compatibility. Therefore, when referencing
2890       // the function, we pretend that we don't have the full function
2891       // type.
2892       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2893           isa<FunctionProtoType>(fty))
2894         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2895                                               fty->getExtInfo());
2896 
2897       // Functions are r-values in C.
2898       valueKind = VK_RValue;
2899       break;
2900     }
2901 
2902     case Decl::MSProperty:
2903       valueKind = VK_LValue;
2904       break;
2905 
2906     case Decl::CXXMethod:
2907       // If we're referring to a method with an __unknown_anytype
2908       // result type, make the entire expression __unknown_anytype.
2909       // This should only be possible with a type written directly.
2910       if (const FunctionProtoType *proto
2911             = dyn_cast<FunctionProtoType>(VD->getType()))
2912         if (proto->getReturnType() == Context.UnknownAnyTy) {
2913           type = Context.UnknownAnyTy;
2914           valueKind = VK_RValue;
2915           break;
2916         }
2917 
2918       // C++ methods are l-values if static, r-values if non-static.
2919       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2920         valueKind = VK_LValue;
2921         break;
2922       }
2923       // fallthrough
2924 
2925     case Decl::CXXConversion:
2926     case Decl::CXXDestructor:
2927     case Decl::CXXConstructor:
2928       valueKind = VK_RValue;
2929       break;
2930     }
2931 
2932     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2933                             TemplateArgs);
2934   }
2935 }
2936 
2937 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2938                                     SmallString<32> &Target) {
2939   Target.resize(CharByteWidth * (Source.size() + 1));
2940   char *ResultPtr = &Target[0];
2941   const UTF8 *ErrorPtr;
2942   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2943   (void)success;
2944   assert(success);
2945   Target.resize(ResultPtr - &Target[0]);
2946 }
2947 
2948 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2949                                      PredefinedExpr::IdentType IT) {
2950   // Pick the current block, lambda, captured statement or function.
2951   Decl *currentDecl = nullptr;
2952   if (const BlockScopeInfo *BSI = getCurBlock())
2953     currentDecl = BSI->TheDecl;
2954   else if (const LambdaScopeInfo *LSI = getCurLambda())
2955     currentDecl = LSI->CallOperator;
2956   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2957     currentDecl = CSI->TheCapturedDecl;
2958   else
2959     currentDecl = getCurFunctionOrMethodDecl();
2960 
2961   if (!currentDecl) {
2962     Diag(Loc, diag::ext_predef_outside_function);
2963     currentDecl = Context.getTranslationUnitDecl();
2964   }
2965 
2966   QualType ResTy;
2967   StringLiteral *SL = nullptr;
2968   if (cast<DeclContext>(currentDecl)->isDependentContext())
2969     ResTy = Context.DependentTy;
2970   else {
2971     // Pre-defined identifiers are of type char[x], where x is the length of
2972     // the string.
2973     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
2974     unsigned Length = Str.length();
2975 
2976     llvm::APInt LengthI(32, Length + 1);
2977     if (IT == PredefinedExpr::LFunction) {
2978       ResTy = Context.WideCharTy.withConst();
2979       SmallString<32> RawChars;
2980       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
2981                               Str, RawChars);
2982       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
2983                                            /*IndexTypeQuals*/ 0);
2984       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
2985                                  /*Pascal*/ false, ResTy, Loc);
2986     } else {
2987       ResTy = Context.CharTy.withConst();
2988       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
2989                                            /*IndexTypeQuals*/ 0);
2990       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
2991                                  /*Pascal*/ false, ResTy, Loc);
2992     }
2993   }
2994 
2995   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
2996 }
2997 
2998 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2999   PredefinedExpr::IdentType IT;
3000 
3001   switch (Kind) {
3002   default: llvm_unreachable("Unknown simple primary expr!");
3003   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3004   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3005   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3006   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3007   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3008   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3009   }
3010 
3011   return BuildPredefinedExpr(Loc, IT);
3012 }
3013 
3014 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3015   SmallString<16> CharBuffer;
3016   bool Invalid = false;
3017   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3018   if (Invalid)
3019     return ExprError();
3020 
3021   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3022                             PP, Tok.getKind());
3023   if (Literal.hadError())
3024     return ExprError();
3025 
3026   QualType Ty;
3027   if (Literal.isWide())
3028     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3029   else if (Literal.isUTF16())
3030     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3031   else if (Literal.isUTF32())
3032     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3033   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3034     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3035   else
3036     Ty = Context.CharTy;  // 'x' -> char in C++
3037 
3038   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3039   if (Literal.isWide())
3040     Kind = CharacterLiteral::Wide;
3041   else if (Literal.isUTF16())
3042     Kind = CharacterLiteral::UTF16;
3043   else if (Literal.isUTF32())
3044     Kind = CharacterLiteral::UTF32;
3045 
3046   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3047                                              Tok.getLocation());
3048 
3049   if (Literal.getUDSuffix().empty())
3050     return Lit;
3051 
3052   // We're building a user-defined literal.
3053   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3054   SourceLocation UDSuffixLoc =
3055     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3056 
3057   // Make sure we're allowed user-defined literals here.
3058   if (!UDLScope)
3059     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3060 
3061   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3062   //   operator "" X (ch)
3063   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3064                                         Lit, Tok.getLocation());
3065 }
3066 
3067 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3068   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3069   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3070                                 Context.IntTy, Loc);
3071 }
3072 
3073 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3074                                   QualType Ty, SourceLocation Loc) {
3075   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3076 
3077   using llvm::APFloat;
3078   APFloat Val(Format);
3079 
3080   APFloat::opStatus result = Literal.GetFloatValue(Val);
3081 
3082   // Overflow is always an error, but underflow is only an error if
3083   // we underflowed to zero (APFloat reports denormals as underflow).
3084   if ((result & APFloat::opOverflow) ||
3085       ((result & APFloat::opUnderflow) && Val.isZero())) {
3086     unsigned diagnostic;
3087     SmallString<20> buffer;
3088     if (result & APFloat::opOverflow) {
3089       diagnostic = diag::warn_float_overflow;
3090       APFloat::getLargest(Format).toString(buffer);
3091     } else {
3092       diagnostic = diag::warn_float_underflow;
3093       APFloat::getSmallest(Format).toString(buffer);
3094     }
3095 
3096     S.Diag(Loc, diagnostic)
3097       << Ty
3098       << StringRef(buffer.data(), buffer.size());
3099   }
3100 
3101   bool isExact = (result == APFloat::opOK);
3102   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3103 }
3104 
3105 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3106   assert(E && "Invalid expression");
3107 
3108   if (E->isValueDependent())
3109     return false;
3110 
3111   QualType QT = E->getType();
3112   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3113     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3114     return true;
3115   }
3116 
3117   llvm::APSInt ValueAPS;
3118   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3119 
3120   if (R.isInvalid())
3121     return true;
3122 
3123   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3124   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3125     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3126         << ValueAPS.toString(10) << ValueIsPositive;
3127     return true;
3128   }
3129 
3130   return false;
3131 }
3132 
3133 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3134   // Fast path for a single digit (which is quite common).  A single digit
3135   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3136   if (Tok.getLength() == 1) {
3137     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3138     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3139   }
3140 
3141   SmallString<128> SpellingBuffer;
3142   // NumericLiteralParser wants to overread by one character.  Add padding to
3143   // the buffer in case the token is copied to the buffer.  If getSpelling()
3144   // returns a StringRef to the memory buffer, it should have a null char at
3145   // the EOF, so it is also safe.
3146   SpellingBuffer.resize(Tok.getLength() + 1);
3147 
3148   // Get the spelling of the token, which eliminates trigraphs, etc.
3149   bool Invalid = false;
3150   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3151   if (Invalid)
3152     return ExprError();
3153 
3154   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3155   if (Literal.hadError)
3156     return ExprError();
3157 
3158   if (Literal.hasUDSuffix()) {
3159     // We're building a user-defined literal.
3160     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3161     SourceLocation UDSuffixLoc =
3162       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3163 
3164     // Make sure we're allowed user-defined literals here.
3165     if (!UDLScope)
3166       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3167 
3168     QualType CookedTy;
3169     if (Literal.isFloatingLiteral()) {
3170       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3171       // long double, the literal is treated as a call of the form
3172       //   operator "" X (f L)
3173       CookedTy = Context.LongDoubleTy;
3174     } else {
3175       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3176       // unsigned long long, the literal is treated as a call of the form
3177       //   operator "" X (n ULL)
3178       CookedTy = Context.UnsignedLongLongTy;
3179     }
3180 
3181     DeclarationName OpName =
3182       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3183     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3184     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3185 
3186     SourceLocation TokLoc = Tok.getLocation();
3187 
3188     // Perform literal operator lookup to determine if we're building a raw
3189     // literal or a cooked one.
3190     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3191     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3192                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3193                                   /*AllowStringTemplate*/false)) {
3194     case LOLR_Error:
3195       return ExprError();
3196 
3197     case LOLR_Cooked: {
3198       Expr *Lit;
3199       if (Literal.isFloatingLiteral()) {
3200         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3201       } else {
3202         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3203         if (Literal.GetIntegerValue(ResultVal))
3204           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3205               << /* Unsigned */ 1;
3206         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3207                                      Tok.getLocation());
3208       }
3209       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3210     }
3211 
3212     case LOLR_Raw: {
3213       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3214       // literal is treated as a call of the form
3215       //   operator "" X ("n")
3216       unsigned Length = Literal.getUDSuffixOffset();
3217       QualType StrTy = Context.getConstantArrayType(
3218           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3219           ArrayType::Normal, 0);
3220       Expr *Lit = StringLiteral::Create(
3221           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3222           /*Pascal*/false, StrTy, &TokLoc, 1);
3223       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3224     }
3225 
3226     case LOLR_Template: {
3227       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3228       // template), L is treated as a call fo the form
3229       //   operator "" X <'c1', 'c2', ... 'ck'>()
3230       // where n is the source character sequence c1 c2 ... ck.
3231       TemplateArgumentListInfo ExplicitArgs;
3232       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3233       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3234       llvm::APSInt Value(CharBits, CharIsUnsigned);
3235       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3236         Value = TokSpelling[I];
3237         TemplateArgument Arg(Context, Value, Context.CharTy);
3238         TemplateArgumentLocInfo ArgInfo;
3239         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3240       }
3241       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3242                                       &ExplicitArgs);
3243     }
3244     case LOLR_StringTemplate:
3245       llvm_unreachable("unexpected literal operator lookup result");
3246     }
3247   }
3248 
3249   Expr *Res;
3250 
3251   if (Literal.isFloatingLiteral()) {
3252     QualType Ty;
3253     if (Literal.isFloat)
3254       Ty = Context.FloatTy;
3255     else if (!Literal.isLong)
3256       Ty = Context.DoubleTy;
3257     else
3258       Ty = Context.LongDoubleTy;
3259 
3260     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3261 
3262     if (Ty == Context.DoubleTy) {
3263       if (getLangOpts().SinglePrecisionConstants) {
3264         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3265       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3266         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3267         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3268       }
3269     }
3270   } else if (!Literal.isIntegerLiteral()) {
3271     return ExprError();
3272   } else {
3273     QualType Ty;
3274 
3275     // 'long long' is a C99 or C++11 feature.
3276     if (!getLangOpts().C99 && Literal.isLongLong) {
3277       if (getLangOpts().CPlusPlus)
3278         Diag(Tok.getLocation(),
3279              getLangOpts().CPlusPlus11 ?
3280              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3281       else
3282         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3283     }
3284 
3285     // Get the value in the widest-possible width.
3286     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3287     // The microsoft literal suffix extensions support 128-bit literals, which
3288     // may be wider than [u]intmax_t.
3289     // FIXME: Actually, they don't. We seem to have accidentally invented the
3290     //        i128 suffix.
3291     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3292         Context.getTargetInfo().hasInt128Type())
3293       MaxWidth = 128;
3294     llvm::APInt ResultVal(MaxWidth, 0);
3295 
3296     if (Literal.GetIntegerValue(ResultVal)) {
3297       // If this value didn't fit into uintmax_t, error and force to ull.
3298       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3299           << /* Unsigned */ 1;
3300       Ty = Context.UnsignedLongLongTy;
3301       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3302              "long long is not intmax_t?");
3303     } else {
3304       // If this value fits into a ULL, try to figure out what else it fits into
3305       // according to the rules of C99 6.4.4.1p5.
3306 
3307       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3308       // be an unsigned int.
3309       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3310 
3311       // Check from smallest to largest, picking the smallest type we can.
3312       unsigned Width = 0;
3313 
3314       // Microsoft specific integer suffixes are explicitly sized.
3315       if (Literal.MicrosoftInteger) {
3316         if (Literal.MicrosoftInteger > MaxWidth) {
3317           // If this target doesn't support __int128, error and force to ull.
3318           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3319           Width = MaxWidth;
3320           Ty = Context.getIntMaxType();
3321         } else {
3322           Width = Literal.MicrosoftInteger;
3323           Ty = Context.getIntTypeForBitwidth(Width,
3324                                              /*Signed=*/!Literal.isUnsigned);
3325         }
3326       }
3327 
3328       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3329         // Are int/unsigned possibilities?
3330         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3331 
3332         // Does it fit in a unsigned int?
3333         if (ResultVal.isIntN(IntSize)) {
3334           // Does it fit in a signed int?
3335           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3336             Ty = Context.IntTy;
3337           else if (AllowUnsigned)
3338             Ty = Context.UnsignedIntTy;
3339           Width = IntSize;
3340         }
3341       }
3342 
3343       // Are long/unsigned long possibilities?
3344       if (Ty.isNull() && !Literal.isLongLong) {
3345         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3346 
3347         // Does it fit in a unsigned long?
3348         if (ResultVal.isIntN(LongSize)) {
3349           // Does it fit in a signed long?
3350           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3351             Ty = Context.LongTy;
3352           else if (AllowUnsigned)
3353             Ty = Context.UnsignedLongTy;
3354           Width = LongSize;
3355         }
3356       }
3357 
3358       // Check long long if needed.
3359       if (Ty.isNull()) {
3360         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3361 
3362         // Does it fit in a unsigned long long?
3363         if (ResultVal.isIntN(LongLongSize)) {
3364           // Does it fit in a signed long long?
3365           // To be compatible with MSVC, hex integer literals ending with the
3366           // LL or i64 suffix are always signed in Microsoft mode.
3367           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3368               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3369             Ty = Context.LongLongTy;
3370           else if (AllowUnsigned)
3371             Ty = Context.UnsignedLongLongTy;
3372           Width = LongLongSize;
3373         }
3374       }
3375 
3376       // If we still couldn't decide a type, we probably have something that
3377       // does not fit in a signed long long, but has no U suffix.
3378       if (Ty.isNull()) {
3379         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3380         Ty = Context.UnsignedLongLongTy;
3381         Width = Context.getTargetInfo().getLongLongWidth();
3382       }
3383 
3384       if (ResultVal.getBitWidth() != Width)
3385         ResultVal = ResultVal.trunc(Width);
3386     }
3387     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3388   }
3389 
3390   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3391   if (Literal.isImaginary)
3392     Res = new (Context) ImaginaryLiteral(Res,
3393                                         Context.getComplexType(Res->getType()));
3394 
3395   return Res;
3396 }
3397 
3398 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3399   assert(E && "ActOnParenExpr() missing expr");
3400   return new (Context) ParenExpr(L, R, E);
3401 }
3402 
3403 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3404                                          SourceLocation Loc,
3405                                          SourceRange ArgRange) {
3406   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3407   // scalar or vector data type argument..."
3408   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3409   // type (C99 6.2.5p18) or void.
3410   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3411     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3412       << T << ArgRange;
3413     return true;
3414   }
3415 
3416   assert((T->isVoidType() || !T->isIncompleteType()) &&
3417          "Scalar types should always be complete");
3418   return false;
3419 }
3420 
3421 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3422                                            SourceLocation Loc,
3423                                            SourceRange ArgRange,
3424                                            UnaryExprOrTypeTrait TraitKind) {
3425   // Invalid types must be hard errors for SFINAE in C++.
3426   if (S.LangOpts.CPlusPlus)
3427     return true;
3428 
3429   // C99 6.5.3.4p1:
3430   if (T->isFunctionType() &&
3431       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3432     // sizeof(function)/alignof(function) is allowed as an extension.
3433     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3434       << TraitKind << ArgRange;
3435     return false;
3436   }
3437 
3438   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3439   // this is an error (OpenCL v1.1 s6.3.k)
3440   if (T->isVoidType()) {
3441     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3442                                         : diag::ext_sizeof_alignof_void_type;
3443     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3444     return false;
3445   }
3446 
3447   return true;
3448 }
3449 
3450 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3451                                              SourceLocation Loc,
3452                                              SourceRange ArgRange,
3453                                              UnaryExprOrTypeTrait TraitKind) {
3454   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3455   // runtime doesn't allow it.
3456   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3457     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3458       << T << (TraitKind == UETT_SizeOf)
3459       << ArgRange;
3460     return true;
3461   }
3462 
3463   return false;
3464 }
3465 
3466 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3467 /// pointer type is equal to T) and emit a warning if it is.
3468 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3469                                      Expr *E) {
3470   // Don't warn if the operation changed the type.
3471   if (T != E->getType())
3472     return;
3473 
3474   // Now look for array decays.
3475   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3476   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3477     return;
3478 
3479   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3480                                              << ICE->getType()
3481                                              << ICE->getSubExpr()->getType();
3482 }
3483 
3484 /// \brief Check the constraints on expression operands to unary type expression
3485 /// and type traits.
3486 ///
3487 /// Completes any types necessary and validates the constraints on the operand
3488 /// expression. The logic mostly mirrors the type-based overload, but may modify
3489 /// the expression as it completes the type for that expression through template
3490 /// instantiation, etc.
3491 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3492                                             UnaryExprOrTypeTrait ExprKind) {
3493   QualType ExprTy = E->getType();
3494   assert(!ExprTy->isReferenceType());
3495 
3496   if (ExprKind == UETT_VecStep)
3497     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3498                                         E->getSourceRange());
3499 
3500   // Whitelist some types as extensions
3501   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3502                                       E->getSourceRange(), ExprKind))
3503     return false;
3504 
3505   // 'alignof' applied to an expression only requires the base element type of
3506   // the expression to be complete. 'sizeof' requires the expression's type to
3507   // be complete (and will attempt to complete it if it's an array of unknown
3508   // bound).
3509   if (ExprKind == UETT_AlignOf) {
3510     if (RequireCompleteType(E->getExprLoc(),
3511                             Context.getBaseElementType(E->getType()),
3512                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3513                             E->getSourceRange()))
3514       return true;
3515   } else {
3516     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3517                                 ExprKind, E->getSourceRange()))
3518       return true;
3519   }
3520 
3521   // Completing the expression's type may have changed it.
3522   ExprTy = E->getType();
3523   assert(!ExprTy->isReferenceType());
3524 
3525   if (ExprTy->isFunctionType()) {
3526     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3527       << ExprKind << E->getSourceRange();
3528     return true;
3529   }
3530 
3531   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3532                                        E->getSourceRange(), ExprKind))
3533     return true;
3534 
3535   if (ExprKind == UETT_SizeOf) {
3536     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3537       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3538         QualType OType = PVD->getOriginalType();
3539         QualType Type = PVD->getType();
3540         if (Type->isPointerType() && OType->isArrayType()) {
3541           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3542             << Type << OType;
3543           Diag(PVD->getLocation(), diag::note_declared_at);
3544         }
3545       }
3546     }
3547 
3548     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3549     // decays into a pointer and returns an unintended result. This is most
3550     // likely a typo for "sizeof(array) op x".
3551     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3552       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3553                                BO->getLHS());
3554       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3555                                BO->getRHS());
3556     }
3557   }
3558 
3559   return false;
3560 }
3561 
3562 /// \brief Check the constraints on operands to unary expression and type
3563 /// traits.
3564 ///
3565 /// This will complete any types necessary, and validate the various constraints
3566 /// on those operands.
3567 ///
3568 /// The UsualUnaryConversions() function is *not* called by this routine.
3569 /// C99 6.3.2.1p[2-4] all state:
3570 ///   Except when it is the operand of the sizeof operator ...
3571 ///
3572 /// C++ [expr.sizeof]p4
3573 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3574 ///   standard conversions are not applied to the operand of sizeof.
3575 ///
3576 /// This policy is followed for all of the unary trait expressions.
3577 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3578                                             SourceLocation OpLoc,
3579                                             SourceRange ExprRange,
3580                                             UnaryExprOrTypeTrait ExprKind) {
3581   if (ExprType->isDependentType())
3582     return false;
3583 
3584   // C++ [expr.sizeof]p2:
3585   //     When applied to a reference or a reference type, the result
3586   //     is the size of the referenced type.
3587   // C++11 [expr.alignof]p3:
3588   //     When alignof is applied to a reference type, the result
3589   //     shall be the alignment of the referenced type.
3590   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3591     ExprType = Ref->getPointeeType();
3592 
3593   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3594   //   When alignof or _Alignof is applied to an array type, the result
3595   //   is the alignment of the element type.
3596   if (ExprKind == UETT_AlignOf)
3597     ExprType = Context.getBaseElementType(ExprType);
3598 
3599   if (ExprKind == UETT_VecStep)
3600     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3601 
3602   // Whitelist some types as extensions
3603   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3604                                       ExprKind))
3605     return false;
3606 
3607   if (RequireCompleteType(OpLoc, ExprType,
3608                           diag::err_sizeof_alignof_incomplete_type,
3609                           ExprKind, ExprRange))
3610     return true;
3611 
3612   if (ExprType->isFunctionType()) {
3613     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3614       << ExprKind << ExprRange;
3615     return true;
3616   }
3617 
3618   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3619                                        ExprKind))
3620     return true;
3621 
3622   return false;
3623 }
3624 
3625 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3626   E = E->IgnoreParens();
3627 
3628   // Cannot know anything else if the expression is dependent.
3629   if (E->isTypeDependent())
3630     return false;
3631 
3632   if (E->getObjectKind() == OK_BitField) {
3633     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3634        << 1 << E->getSourceRange();
3635     return true;
3636   }
3637 
3638   ValueDecl *D = nullptr;
3639   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3640     D = DRE->getDecl();
3641   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3642     D = ME->getMemberDecl();
3643   }
3644 
3645   // If it's a field, require the containing struct to have a
3646   // complete definition so that we can compute the layout.
3647   //
3648   // This can happen in C++11 onwards, either by naming the member
3649   // in a way that is not transformed into a member access expression
3650   // (in an unevaluated operand, for instance), or by naming the member
3651   // in a trailing-return-type.
3652   //
3653   // For the record, since __alignof__ on expressions is a GCC
3654   // extension, GCC seems to permit this but always gives the
3655   // nonsensical answer 0.
3656   //
3657   // We don't really need the layout here --- we could instead just
3658   // directly check for all the appropriate alignment-lowing
3659   // attributes --- but that would require duplicating a lot of
3660   // logic that just isn't worth duplicating for such a marginal
3661   // use-case.
3662   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3663     // Fast path this check, since we at least know the record has a
3664     // definition if we can find a member of it.
3665     if (!FD->getParent()->isCompleteDefinition()) {
3666       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3667         << E->getSourceRange();
3668       return true;
3669     }
3670 
3671     // Otherwise, if it's a field, and the field doesn't have
3672     // reference type, then it must have a complete type (or be a
3673     // flexible array member, which we explicitly want to
3674     // white-list anyway), which makes the following checks trivial.
3675     if (!FD->getType()->isReferenceType())
3676       return false;
3677   }
3678 
3679   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3680 }
3681 
3682 bool Sema::CheckVecStepExpr(Expr *E) {
3683   E = E->IgnoreParens();
3684 
3685   // Cannot know anything else if the expression is dependent.
3686   if (E->isTypeDependent())
3687     return false;
3688 
3689   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3690 }
3691 
3692 /// \brief Build a sizeof or alignof expression given a type operand.
3693 ExprResult
3694 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3695                                      SourceLocation OpLoc,
3696                                      UnaryExprOrTypeTrait ExprKind,
3697                                      SourceRange R) {
3698   if (!TInfo)
3699     return ExprError();
3700 
3701   QualType T = TInfo->getType();
3702 
3703   if (!T->isDependentType() &&
3704       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3705     return ExprError();
3706 
3707   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3708   return new (Context) UnaryExprOrTypeTraitExpr(
3709       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3710 }
3711 
3712 /// \brief Build a sizeof or alignof expression given an expression
3713 /// operand.
3714 ExprResult
3715 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3716                                      UnaryExprOrTypeTrait ExprKind) {
3717   ExprResult PE = CheckPlaceholderExpr(E);
3718   if (PE.isInvalid())
3719     return ExprError();
3720 
3721   E = PE.get();
3722 
3723   // Verify that the operand is valid.
3724   bool isInvalid = false;
3725   if (E->isTypeDependent()) {
3726     // Delay type-checking for type-dependent expressions.
3727   } else if (ExprKind == UETT_AlignOf) {
3728     isInvalid = CheckAlignOfExpr(*this, E);
3729   } else if (ExprKind == UETT_VecStep) {
3730     isInvalid = CheckVecStepExpr(E);
3731   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3732     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3733     isInvalid = true;
3734   } else {
3735     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3736   }
3737 
3738   if (isInvalid)
3739     return ExprError();
3740 
3741   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3742     PE = TransformToPotentiallyEvaluated(E);
3743     if (PE.isInvalid()) return ExprError();
3744     E = PE.get();
3745   }
3746 
3747   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3748   return new (Context) UnaryExprOrTypeTraitExpr(
3749       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3750 }
3751 
3752 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3753 /// expr and the same for @c alignof and @c __alignof
3754 /// Note that the ArgRange is invalid if isType is false.
3755 ExprResult
3756 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3757                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3758                                     void *TyOrEx, const SourceRange &ArgRange) {
3759   // If error parsing type, ignore.
3760   if (!TyOrEx) return ExprError();
3761 
3762   if (IsType) {
3763     TypeSourceInfo *TInfo;
3764     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3765     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3766   }
3767 
3768   Expr *ArgEx = (Expr *)TyOrEx;
3769   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3770   return Result;
3771 }
3772 
3773 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3774                                      bool IsReal) {
3775   if (V.get()->isTypeDependent())
3776     return S.Context.DependentTy;
3777 
3778   // _Real and _Imag are only l-values for normal l-values.
3779   if (V.get()->getObjectKind() != OK_Ordinary) {
3780     V = S.DefaultLvalueConversion(V.get());
3781     if (V.isInvalid())
3782       return QualType();
3783   }
3784 
3785   // These operators return the element type of a complex type.
3786   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3787     return CT->getElementType();
3788 
3789   // Otherwise they pass through real integer and floating point types here.
3790   if (V.get()->getType()->isArithmeticType())
3791     return V.get()->getType();
3792 
3793   // Test for placeholders.
3794   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3795   if (PR.isInvalid()) return QualType();
3796   if (PR.get() != V.get()) {
3797     V = PR;
3798     return CheckRealImagOperand(S, V, Loc, IsReal);
3799   }
3800 
3801   // Reject anything else.
3802   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3803     << (IsReal ? "__real" : "__imag");
3804   return QualType();
3805 }
3806 
3807 
3808 
3809 ExprResult
3810 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3811                           tok::TokenKind Kind, Expr *Input) {
3812   UnaryOperatorKind Opc;
3813   switch (Kind) {
3814   default: llvm_unreachable("Unknown unary op!");
3815   case tok::plusplus:   Opc = UO_PostInc; break;
3816   case tok::minusminus: Opc = UO_PostDec; break;
3817   }
3818 
3819   // Since this might is a postfix expression, get rid of ParenListExprs.
3820   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3821   if (Result.isInvalid()) return ExprError();
3822   Input = Result.get();
3823 
3824   return BuildUnaryOp(S, OpLoc, Opc, Input);
3825 }
3826 
3827 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3828 ///
3829 /// \return true on error
3830 static bool checkArithmeticOnObjCPointer(Sema &S,
3831                                          SourceLocation opLoc,
3832                                          Expr *op) {
3833   assert(op->getType()->isObjCObjectPointerType());
3834   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3835       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3836     return false;
3837 
3838   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3839     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3840     << op->getSourceRange();
3841   return true;
3842 }
3843 
3844 ExprResult
3845 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3846                               Expr *idx, SourceLocation rbLoc) {
3847   // Since this might be a postfix expression, get rid of ParenListExprs.
3848   if (isa<ParenListExpr>(base)) {
3849     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3850     if (result.isInvalid()) return ExprError();
3851     base = result.get();
3852   }
3853 
3854   // Handle any non-overload placeholder types in the base and index
3855   // expressions.  We can't handle overloads here because the other
3856   // operand might be an overloadable type, in which case the overload
3857   // resolution for the operator overload should get the first crack
3858   // at the overload.
3859   if (base->getType()->isNonOverloadPlaceholderType()) {
3860     ExprResult result = CheckPlaceholderExpr(base);
3861     if (result.isInvalid()) return ExprError();
3862     base = result.get();
3863   }
3864   if (idx->getType()->isNonOverloadPlaceholderType()) {
3865     ExprResult result = CheckPlaceholderExpr(idx);
3866     if (result.isInvalid()) return ExprError();
3867     idx = result.get();
3868   }
3869 
3870   // Build an unanalyzed expression if either operand is type-dependent.
3871   if (getLangOpts().CPlusPlus &&
3872       (base->isTypeDependent() || idx->isTypeDependent())) {
3873     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3874                                             VK_LValue, OK_Ordinary, rbLoc);
3875   }
3876 
3877   // Use C++ overloaded-operator rules if either operand has record
3878   // type.  The spec says to do this if either type is *overloadable*,
3879   // but enum types can't declare subscript operators or conversion
3880   // operators, so there's nothing interesting for overload resolution
3881   // to do if there aren't any record types involved.
3882   //
3883   // ObjC pointers have their own subscripting logic that is not tied
3884   // to overload resolution and so should not take this path.
3885   if (getLangOpts().CPlusPlus &&
3886       (base->getType()->isRecordType() ||
3887        (!base->getType()->isObjCObjectPointerType() &&
3888         idx->getType()->isRecordType()))) {
3889     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3890   }
3891 
3892   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3893 }
3894 
3895 ExprResult
3896 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3897                                       Expr *Idx, SourceLocation RLoc) {
3898   Expr *LHSExp = Base;
3899   Expr *RHSExp = Idx;
3900 
3901   // Perform default conversions.
3902   if (!LHSExp->getType()->getAs<VectorType>()) {
3903     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3904     if (Result.isInvalid())
3905       return ExprError();
3906     LHSExp = Result.get();
3907   }
3908   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3909   if (Result.isInvalid())
3910     return ExprError();
3911   RHSExp = Result.get();
3912 
3913   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3914   ExprValueKind VK = VK_LValue;
3915   ExprObjectKind OK = OK_Ordinary;
3916 
3917   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3918   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3919   // in the subscript position. As a result, we need to derive the array base
3920   // and index from the expression types.
3921   Expr *BaseExpr, *IndexExpr;
3922   QualType ResultType;
3923   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3924     BaseExpr = LHSExp;
3925     IndexExpr = RHSExp;
3926     ResultType = Context.DependentTy;
3927   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3928     BaseExpr = LHSExp;
3929     IndexExpr = RHSExp;
3930     ResultType = PTy->getPointeeType();
3931   } else if (const ObjCObjectPointerType *PTy =
3932                LHSTy->getAs<ObjCObjectPointerType>()) {
3933     BaseExpr = LHSExp;
3934     IndexExpr = RHSExp;
3935 
3936     // Use custom logic if this should be the pseudo-object subscript
3937     // expression.
3938     if (!LangOpts.isSubscriptPointerArithmetic())
3939       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3940                                           nullptr);
3941 
3942     ResultType = PTy->getPointeeType();
3943   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3944      // Handle the uncommon case of "123[Ptr]".
3945     BaseExpr = RHSExp;
3946     IndexExpr = LHSExp;
3947     ResultType = PTy->getPointeeType();
3948   } else if (const ObjCObjectPointerType *PTy =
3949                RHSTy->getAs<ObjCObjectPointerType>()) {
3950      // Handle the uncommon case of "123[Ptr]".
3951     BaseExpr = RHSExp;
3952     IndexExpr = LHSExp;
3953     ResultType = PTy->getPointeeType();
3954     if (!LangOpts.isSubscriptPointerArithmetic()) {
3955       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3956         << ResultType << BaseExpr->getSourceRange();
3957       return ExprError();
3958     }
3959   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3960     BaseExpr = LHSExp;    // vectors: V[123]
3961     IndexExpr = RHSExp;
3962     VK = LHSExp->getValueKind();
3963     if (VK != VK_RValue)
3964       OK = OK_VectorComponent;
3965 
3966     // FIXME: need to deal with const...
3967     ResultType = VTy->getElementType();
3968   } else if (LHSTy->isArrayType()) {
3969     // If we see an array that wasn't promoted by
3970     // DefaultFunctionArrayLvalueConversion, it must be an array that
3971     // wasn't promoted because of the C90 rule that doesn't
3972     // allow promoting non-lvalue arrays.  Warn, then
3973     // force the promotion here.
3974     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3975         LHSExp->getSourceRange();
3976     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3977                                CK_ArrayToPointerDecay).get();
3978     LHSTy = LHSExp->getType();
3979 
3980     BaseExpr = LHSExp;
3981     IndexExpr = RHSExp;
3982     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3983   } else if (RHSTy->isArrayType()) {
3984     // Same as previous, except for 123[f().a] case
3985     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3986         RHSExp->getSourceRange();
3987     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3988                                CK_ArrayToPointerDecay).get();
3989     RHSTy = RHSExp->getType();
3990 
3991     BaseExpr = RHSExp;
3992     IndexExpr = LHSExp;
3993     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3994   } else {
3995     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3996        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3997   }
3998   // C99 6.5.2.1p1
3999   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4000     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4001                      << IndexExpr->getSourceRange());
4002 
4003   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4004        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4005          && !IndexExpr->isTypeDependent())
4006     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4007 
4008   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4009   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4010   // type. Note that Functions are not objects, and that (in C99 parlance)
4011   // incomplete types are not object types.
4012   if (ResultType->isFunctionType()) {
4013     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4014       << ResultType << BaseExpr->getSourceRange();
4015     return ExprError();
4016   }
4017 
4018   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4019     // GNU extension: subscripting on pointer to void
4020     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4021       << BaseExpr->getSourceRange();
4022 
4023     // C forbids expressions of unqualified void type from being l-values.
4024     // See IsCForbiddenLValueType.
4025     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4026   } else if (!ResultType->isDependentType() &&
4027       RequireCompleteType(LLoc, ResultType,
4028                           diag::err_subscript_incomplete_type, BaseExpr))
4029     return ExprError();
4030 
4031   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4032          !ResultType.isCForbiddenLValueType());
4033 
4034   return new (Context)
4035       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4036 }
4037 
4038 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4039                                         FunctionDecl *FD,
4040                                         ParmVarDecl *Param) {
4041   if (Param->hasUnparsedDefaultArg()) {
4042     Diag(CallLoc,
4043          diag::err_use_of_default_argument_to_function_declared_later) <<
4044       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4045     Diag(UnparsedDefaultArgLocs[Param],
4046          diag::note_default_argument_declared_here);
4047     return ExprError();
4048   }
4049 
4050   if (Param->hasUninstantiatedDefaultArg()) {
4051     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4052 
4053     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4054                                                  Param);
4055 
4056     // Instantiate the expression.
4057     MultiLevelTemplateArgumentList MutiLevelArgList
4058       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4059 
4060     InstantiatingTemplate Inst(*this, CallLoc, Param,
4061                                MutiLevelArgList.getInnermost());
4062     if (Inst.isInvalid())
4063       return ExprError();
4064 
4065     ExprResult Result;
4066     {
4067       // C++ [dcl.fct.default]p5:
4068       //   The names in the [default argument] expression are bound, and
4069       //   the semantic constraints are checked, at the point where the
4070       //   default argument expression appears.
4071       ContextRAII SavedContext(*this, FD);
4072       LocalInstantiationScope Local(*this);
4073       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4074     }
4075     if (Result.isInvalid())
4076       return ExprError();
4077 
4078     // Check the expression as an initializer for the parameter.
4079     InitializedEntity Entity
4080       = InitializedEntity::InitializeParameter(Context, Param);
4081     InitializationKind Kind
4082       = InitializationKind::CreateCopy(Param->getLocation(),
4083              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4084     Expr *ResultE = Result.getAs<Expr>();
4085 
4086     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4087     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4088     if (Result.isInvalid())
4089       return ExprError();
4090 
4091     Expr *Arg = Result.getAs<Expr>();
4092     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4093     // Build the default argument expression.
4094     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4095   }
4096 
4097   // If the default expression creates temporaries, we need to
4098   // push them to the current stack of expression temporaries so they'll
4099   // be properly destroyed.
4100   // FIXME: We should really be rebuilding the default argument with new
4101   // bound temporaries; see the comment in PR5810.
4102   // We don't need to do that with block decls, though, because
4103   // blocks in default argument expression can never capture anything.
4104   if (isa<ExprWithCleanups>(Param->getInit())) {
4105     // Set the "needs cleanups" bit regardless of whether there are
4106     // any explicit objects.
4107     ExprNeedsCleanups = true;
4108 
4109     // Append all the objects to the cleanup list.  Right now, this
4110     // should always be a no-op, because blocks in default argument
4111     // expressions should never be able to capture anything.
4112     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4113            "default argument expression has capturing blocks?");
4114   }
4115 
4116   // We already type-checked the argument, so we know it works.
4117   // Just mark all of the declarations in this potentially-evaluated expression
4118   // as being "referenced".
4119   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4120                                    /*SkipLocalVariables=*/true);
4121   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4122 }
4123 
4124 
4125 Sema::VariadicCallType
4126 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4127                           Expr *Fn) {
4128   if (Proto && Proto->isVariadic()) {
4129     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4130       return VariadicConstructor;
4131     else if (Fn && Fn->getType()->isBlockPointerType())
4132       return VariadicBlock;
4133     else if (FDecl) {
4134       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4135         if (Method->isInstance())
4136           return VariadicMethod;
4137     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4138       return VariadicMethod;
4139     return VariadicFunction;
4140   }
4141   return VariadicDoesNotApply;
4142 }
4143 
4144 namespace {
4145 class FunctionCallCCC : public FunctionCallFilterCCC {
4146 public:
4147   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4148                   unsigned NumArgs, MemberExpr *ME)
4149       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4150         FunctionName(FuncName) {}
4151 
4152   bool ValidateCandidate(const TypoCorrection &candidate) override {
4153     if (!candidate.getCorrectionSpecifier() ||
4154         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4155       return false;
4156     }
4157 
4158     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4159   }
4160 
4161 private:
4162   const IdentifierInfo *const FunctionName;
4163 };
4164 }
4165 
4166 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4167                                                FunctionDecl *FDecl,
4168                                                ArrayRef<Expr *> Args) {
4169   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4170   DeclarationName FuncName = FDecl->getDeclName();
4171   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4172 
4173   if (TypoCorrection Corrected = S.CorrectTypo(
4174           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4175           S.getScopeForContext(S.CurContext), nullptr,
4176           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4177                                              Args.size(), ME),
4178           Sema::CTK_ErrorRecovery)) {
4179     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4180       if (Corrected.isOverloaded()) {
4181         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4182         OverloadCandidateSet::iterator Best;
4183         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4184                                            CDEnd = Corrected.end();
4185              CD != CDEnd; ++CD) {
4186           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4187             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4188                                    OCS);
4189         }
4190         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4191         case OR_Success:
4192           ND = Best->Function;
4193           Corrected.setCorrectionDecl(ND);
4194           break;
4195         default:
4196           break;
4197         }
4198       }
4199       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4200         return Corrected;
4201       }
4202     }
4203   }
4204   return TypoCorrection();
4205 }
4206 
4207 /// ConvertArgumentsForCall - Converts the arguments specified in
4208 /// Args/NumArgs to the parameter types of the function FDecl with
4209 /// function prototype Proto. Call is the call expression itself, and
4210 /// Fn is the function expression. For a C++ member function, this
4211 /// routine does not attempt to convert the object argument. Returns
4212 /// true if the call is ill-formed.
4213 bool
4214 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4215                               FunctionDecl *FDecl,
4216                               const FunctionProtoType *Proto,
4217                               ArrayRef<Expr *> Args,
4218                               SourceLocation RParenLoc,
4219                               bool IsExecConfig) {
4220   // Bail out early if calling a builtin with custom typechecking.
4221   // We don't need to do this in the
4222   if (FDecl)
4223     if (unsigned ID = FDecl->getBuiltinID())
4224       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4225         return false;
4226 
4227   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4228   // assignment, to the types of the corresponding parameter, ...
4229   unsigned NumParams = Proto->getNumParams();
4230   bool Invalid = false;
4231   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4232   unsigned FnKind = Fn->getType()->isBlockPointerType()
4233                        ? 1 /* block */
4234                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4235                                        : 0 /* function */);
4236 
4237   // If too few arguments are available (and we don't have default
4238   // arguments for the remaining parameters), don't make the call.
4239   if (Args.size() < NumParams) {
4240     if (Args.size() < MinArgs) {
4241       TypoCorrection TC;
4242       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4243         unsigned diag_id =
4244             MinArgs == NumParams && !Proto->isVariadic()
4245                 ? diag::err_typecheck_call_too_few_args_suggest
4246                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4247         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4248                                         << static_cast<unsigned>(Args.size())
4249                                         << TC.getCorrectionRange());
4250       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4251         Diag(RParenLoc,
4252              MinArgs == NumParams && !Proto->isVariadic()
4253                  ? diag::err_typecheck_call_too_few_args_one
4254                  : diag::err_typecheck_call_too_few_args_at_least_one)
4255             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4256       else
4257         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4258                             ? diag::err_typecheck_call_too_few_args
4259                             : diag::err_typecheck_call_too_few_args_at_least)
4260             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4261             << Fn->getSourceRange();
4262 
4263       // Emit the location of the prototype.
4264       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4265         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4266           << FDecl;
4267 
4268       return true;
4269     }
4270     Call->setNumArgs(Context, NumParams);
4271   }
4272 
4273   // If too many are passed and not variadic, error on the extras and drop
4274   // them.
4275   if (Args.size() > NumParams) {
4276     if (!Proto->isVariadic()) {
4277       TypoCorrection TC;
4278       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4279         unsigned diag_id =
4280             MinArgs == NumParams && !Proto->isVariadic()
4281                 ? diag::err_typecheck_call_too_many_args_suggest
4282                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4283         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4284                                         << static_cast<unsigned>(Args.size())
4285                                         << TC.getCorrectionRange());
4286       } else if (NumParams == 1 && FDecl &&
4287                  FDecl->getParamDecl(0)->getDeclName())
4288         Diag(Args[NumParams]->getLocStart(),
4289              MinArgs == NumParams
4290                  ? diag::err_typecheck_call_too_many_args_one
4291                  : diag::err_typecheck_call_too_many_args_at_most_one)
4292             << FnKind << FDecl->getParamDecl(0)
4293             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4294             << SourceRange(Args[NumParams]->getLocStart(),
4295                            Args.back()->getLocEnd());
4296       else
4297         Diag(Args[NumParams]->getLocStart(),
4298              MinArgs == NumParams
4299                  ? diag::err_typecheck_call_too_many_args
4300                  : diag::err_typecheck_call_too_many_args_at_most)
4301             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4302             << Fn->getSourceRange()
4303             << SourceRange(Args[NumParams]->getLocStart(),
4304                            Args.back()->getLocEnd());
4305 
4306       // Emit the location of the prototype.
4307       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4308         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4309           << FDecl;
4310 
4311       // This deletes the extra arguments.
4312       Call->setNumArgs(Context, NumParams);
4313       return true;
4314     }
4315   }
4316   SmallVector<Expr *, 8> AllArgs;
4317   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4318 
4319   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4320                                    Proto, 0, Args, AllArgs, CallType);
4321   if (Invalid)
4322     return true;
4323   unsigned TotalNumArgs = AllArgs.size();
4324   for (unsigned i = 0; i < TotalNumArgs; ++i)
4325     Call->setArg(i, AllArgs[i]);
4326 
4327   return false;
4328 }
4329 
4330 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4331                                   const FunctionProtoType *Proto,
4332                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4333                                   SmallVectorImpl<Expr *> &AllArgs,
4334                                   VariadicCallType CallType, bool AllowExplicit,
4335                                   bool IsListInitialization) {
4336   unsigned NumParams = Proto->getNumParams();
4337   bool Invalid = false;
4338   unsigned ArgIx = 0;
4339   // Continue to check argument types (even if we have too few/many args).
4340   for (unsigned i = FirstParam; i < NumParams; i++) {
4341     QualType ProtoArgType = Proto->getParamType(i);
4342 
4343     Expr *Arg;
4344     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4345     if (ArgIx < Args.size()) {
4346       Arg = Args[ArgIx++];
4347 
4348       if (RequireCompleteType(Arg->getLocStart(),
4349                               ProtoArgType,
4350                               diag::err_call_incomplete_argument, Arg))
4351         return true;
4352 
4353       // Strip the unbridged-cast placeholder expression off, if applicable.
4354       bool CFAudited = false;
4355       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4356           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4357           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4358         Arg = stripARCUnbridgedCast(Arg);
4359       else if (getLangOpts().ObjCAutoRefCount &&
4360                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4361                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4362         CFAudited = true;
4363 
4364       InitializedEntity Entity =
4365           Param ? InitializedEntity::InitializeParameter(Context, Param,
4366                                                          ProtoArgType)
4367                 : InitializedEntity::InitializeParameter(
4368                       Context, ProtoArgType, Proto->isParamConsumed(i));
4369 
4370       // Remember that parameter belongs to a CF audited API.
4371       if (CFAudited)
4372         Entity.setParameterCFAudited();
4373 
4374       ExprResult ArgE = PerformCopyInitialization(
4375           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4376       if (ArgE.isInvalid())
4377         return true;
4378 
4379       Arg = ArgE.getAs<Expr>();
4380     } else {
4381       assert(Param && "can't use default arguments without a known callee");
4382 
4383       ExprResult ArgExpr =
4384         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4385       if (ArgExpr.isInvalid())
4386         return true;
4387 
4388       Arg = ArgExpr.getAs<Expr>();
4389     }
4390 
4391     // Check for array bounds violations for each argument to the call. This
4392     // check only triggers warnings when the argument isn't a more complex Expr
4393     // with its own checking, such as a BinaryOperator.
4394     CheckArrayAccess(Arg);
4395 
4396     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4397     CheckStaticArrayArgument(CallLoc, Param, Arg);
4398 
4399     AllArgs.push_back(Arg);
4400   }
4401 
4402   // If this is a variadic call, handle args passed through "...".
4403   if (CallType != VariadicDoesNotApply) {
4404     // Assume that extern "C" functions with variadic arguments that
4405     // return __unknown_anytype aren't *really* variadic.
4406     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4407         FDecl->isExternC()) {
4408       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4409         QualType paramType; // ignored
4410         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4411         Invalid |= arg.isInvalid();
4412         AllArgs.push_back(arg.get());
4413       }
4414 
4415     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4416     } else {
4417       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4418         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4419                                                           FDecl);
4420         Invalid |= Arg.isInvalid();
4421         AllArgs.push_back(Arg.get());
4422       }
4423     }
4424 
4425     // Check for array bounds violations.
4426     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4427       CheckArrayAccess(Args[i]);
4428   }
4429   return Invalid;
4430 }
4431 
4432 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4433   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4434   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4435     TL = DTL.getOriginalLoc();
4436   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4437     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4438       << ATL.getLocalSourceRange();
4439 }
4440 
4441 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4442 /// array parameter, check that it is non-null, and that if it is formed by
4443 /// array-to-pointer decay, the underlying array is sufficiently large.
4444 ///
4445 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4446 /// array type derivation, then for each call to the function, the value of the
4447 /// corresponding actual argument shall provide access to the first element of
4448 /// an array with at least as many elements as specified by the size expression.
4449 void
4450 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4451                                ParmVarDecl *Param,
4452                                const Expr *ArgExpr) {
4453   // Static array parameters are not supported in C++.
4454   if (!Param || getLangOpts().CPlusPlus)
4455     return;
4456 
4457   QualType OrigTy = Param->getOriginalType();
4458 
4459   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4460   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4461     return;
4462 
4463   if (ArgExpr->isNullPointerConstant(Context,
4464                                      Expr::NPC_NeverValueDependent)) {
4465     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4466     DiagnoseCalleeStaticArrayParam(*this, Param);
4467     return;
4468   }
4469 
4470   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4471   if (!CAT)
4472     return;
4473 
4474   const ConstantArrayType *ArgCAT =
4475     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4476   if (!ArgCAT)
4477     return;
4478 
4479   if (ArgCAT->getSize().ult(CAT->getSize())) {
4480     Diag(CallLoc, diag::warn_static_array_too_small)
4481       << ArgExpr->getSourceRange()
4482       << (unsigned) ArgCAT->getSize().getZExtValue()
4483       << (unsigned) CAT->getSize().getZExtValue();
4484     DiagnoseCalleeStaticArrayParam(*this, Param);
4485   }
4486 }
4487 
4488 /// Given a function expression of unknown-any type, try to rebuild it
4489 /// to have a function type.
4490 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4491 
4492 /// Is the given type a placeholder that we need to lower out
4493 /// immediately during argument processing?
4494 static bool isPlaceholderToRemoveAsArg(QualType type) {
4495   // Placeholders are never sugared.
4496   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4497   if (!placeholder) return false;
4498 
4499   switch (placeholder->getKind()) {
4500   // Ignore all the non-placeholder types.
4501 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4502 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4503 #include "clang/AST/BuiltinTypes.def"
4504     return false;
4505 
4506   // We cannot lower out overload sets; they might validly be resolved
4507   // by the call machinery.
4508   case BuiltinType::Overload:
4509     return false;
4510 
4511   // Unbridged casts in ARC can be handled in some call positions and
4512   // should be left in place.
4513   case BuiltinType::ARCUnbridgedCast:
4514     return false;
4515 
4516   // Pseudo-objects should be converted as soon as possible.
4517   case BuiltinType::PseudoObject:
4518     return true;
4519 
4520   // The debugger mode could theoretically but currently does not try
4521   // to resolve unknown-typed arguments based on known parameter types.
4522   case BuiltinType::UnknownAny:
4523     return true;
4524 
4525   // These are always invalid as call arguments and should be reported.
4526   case BuiltinType::BoundMember:
4527   case BuiltinType::BuiltinFn:
4528     return true;
4529   }
4530   llvm_unreachable("bad builtin type kind");
4531 }
4532 
4533 /// Check an argument list for placeholders that we won't try to
4534 /// handle later.
4535 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4536   // Apply this processing to all the arguments at once instead of
4537   // dying at the first failure.
4538   bool hasInvalid = false;
4539   for (size_t i = 0, e = args.size(); i != e; i++) {
4540     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4541       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4542       if (result.isInvalid()) hasInvalid = true;
4543       else args[i] = result.get();
4544     } else if (hasInvalid) {
4545       (void)S.CorrectDelayedTyposInExpr(args[i]);
4546     }
4547   }
4548   return hasInvalid;
4549 }
4550 
4551 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4552 /// This provides the location of the left/right parens and a list of comma
4553 /// locations.
4554 ExprResult
4555 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4556                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4557                     Expr *ExecConfig, bool IsExecConfig) {
4558   // Since this might be a postfix expression, get rid of ParenListExprs.
4559   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4560   if (Result.isInvalid()) return ExprError();
4561   Fn = Result.get();
4562 
4563   if (checkArgsForPlaceholders(*this, ArgExprs))
4564     return ExprError();
4565 
4566   if (getLangOpts().CPlusPlus) {
4567     // If this is a pseudo-destructor expression, build the call immediately.
4568     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4569       if (!ArgExprs.empty()) {
4570         // Pseudo-destructor calls should not have any arguments.
4571         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4572           << FixItHint::CreateRemoval(
4573                                     SourceRange(ArgExprs[0]->getLocStart(),
4574                                                 ArgExprs.back()->getLocEnd()));
4575       }
4576 
4577       return new (Context)
4578           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4579     }
4580     if (Fn->getType() == Context.PseudoObjectTy) {
4581       ExprResult result = CheckPlaceholderExpr(Fn);
4582       if (result.isInvalid()) return ExprError();
4583       Fn = result.get();
4584     }
4585 
4586     // Determine whether this is a dependent call inside a C++ template,
4587     // in which case we won't do any semantic analysis now.
4588     // FIXME: Will need to cache the results of name lookup (including ADL) in
4589     // Fn.
4590     bool Dependent = false;
4591     if (Fn->isTypeDependent())
4592       Dependent = true;
4593     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4594       Dependent = true;
4595 
4596     if (Dependent) {
4597       if (ExecConfig) {
4598         return new (Context) CUDAKernelCallExpr(
4599             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4600             Context.DependentTy, VK_RValue, RParenLoc);
4601       } else {
4602         return new (Context) CallExpr(
4603             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4604       }
4605     }
4606 
4607     // Determine whether this is a call to an object (C++ [over.call.object]).
4608     if (Fn->getType()->isRecordType())
4609       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4610                                           RParenLoc);
4611 
4612     if (Fn->getType() == Context.UnknownAnyTy) {
4613       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4614       if (result.isInvalid()) return ExprError();
4615       Fn = result.get();
4616     }
4617 
4618     if (Fn->getType() == Context.BoundMemberTy) {
4619       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4620     }
4621   }
4622 
4623   // Check for overloaded calls.  This can happen even in C due to extensions.
4624   if (Fn->getType() == Context.OverloadTy) {
4625     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4626 
4627     // We aren't supposed to apply this logic for if there's an '&' involved.
4628     if (!find.HasFormOfMemberPointer) {
4629       OverloadExpr *ovl = find.Expression;
4630       if (isa<UnresolvedLookupExpr>(ovl)) {
4631         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4632         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4633                                        RParenLoc, ExecConfig);
4634       } else {
4635         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4636                                          RParenLoc);
4637       }
4638     }
4639   }
4640 
4641   // If we're directly calling a function, get the appropriate declaration.
4642   if (Fn->getType() == Context.UnknownAnyTy) {
4643     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4644     if (result.isInvalid()) return ExprError();
4645     Fn = result.get();
4646   }
4647 
4648   Expr *NakedFn = Fn->IgnoreParens();
4649 
4650   NamedDecl *NDecl = nullptr;
4651   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4652     if (UnOp->getOpcode() == UO_AddrOf)
4653       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4654 
4655   if (isa<DeclRefExpr>(NakedFn))
4656     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4657   else if (isa<MemberExpr>(NakedFn))
4658     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4659 
4660   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4661     if (FD->hasAttr<EnableIfAttr>()) {
4662       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4663         Diag(Fn->getLocStart(),
4664              isa<CXXMethodDecl>(FD) ?
4665                  diag::err_ovl_no_viable_member_function_in_call :
4666                  diag::err_ovl_no_viable_function_in_call)
4667           << FD << FD->getSourceRange();
4668         Diag(FD->getLocation(),
4669              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4670             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4671       }
4672     }
4673   }
4674 
4675   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4676                                ExecConfig, IsExecConfig);
4677 }
4678 
4679 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4680 ///
4681 /// __builtin_astype( value, dst type )
4682 ///
4683 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4684                                  SourceLocation BuiltinLoc,
4685                                  SourceLocation RParenLoc) {
4686   ExprValueKind VK = VK_RValue;
4687   ExprObjectKind OK = OK_Ordinary;
4688   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4689   QualType SrcTy = E->getType();
4690   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4691     return ExprError(Diag(BuiltinLoc,
4692                           diag::err_invalid_astype_of_different_size)
4693                      << DstTy
4694                      << SrcTy
4695                      << E->getSourceRange());
4696   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4697 }
4698 
4699 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4700 /// provided arguments.
4701 ///
4702 /// __builtin_convertvector( value, dst type )
4703 ///
4704 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4705                                         SourceLocation BuiltinLoc,
4706                                         SourceLocation RParenLoc) {
4707   TypeSourceInfo *TInfo;
4708   GetTypeFromParser(ParsedDestTy, &TInfo);
4709   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4710 }
4711 
4712 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4713 /// i.e. an expression not of \p OverloadTy.  The expression should
4714 /// unary-convert to an expression of function-pointer or
4715 /// block-pointer type.
4716 ///
4717 /// \param NDecl the declaration being called, if available
4718 ExprResult
4719 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4720                             SourceLocation LParenLoc,
4721                             ArrayRef<Expr *> Args,
4722                             SourceLocation RParenLoc,
4723                             Expr *Config, bool IsExecConfig) {
4724   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4725   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4726 
4727   // Promote the function operand.
4728   // We special-case function promotion here because we only allow promoting
4729   // builtin functions to function pointers in the callee of a call.
4730   ExprResult Result;
4731   if (BuiltinID &&
4732       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4733     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4734                                CK_BuiltinFnToFnPtr).get();
4735   } else {
4736     Result = CallExprUnaryConversions(Fn);
4737   }
4738   if (Result.isInvalid())
4739     return ExprError();
4740   Fn = Result.get();
4741 
4742   // Make the call expr early, before semantic checks.  This guarantees cleanup
4743   // of arguments and function on error.
4744   CallExpr *TheCall;
4745   if (Config)
4746     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4747                                                cast<CallExpr>(Config), Args,
4748                                                Context.BoolTy, VK_RValue,
4749                                                RParenLoc);
4750   else
4751     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4752                                      VK_RValue, RParenLoc);
4753 
4754   // Bail out early if calling a builtin with custom typechecking.
4755   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
4756     ExprResult Res = CorrectDelayedTyposInExpr(TheCall);
4757     if (!Res.isUsable() || !isa<CallExpr>(Res.get()))
4758       return Res;
4759     return CheckBuiltinFunctionCall(FDecl, BuiltinID, cast<CallExpr>(Res.get()));
4760   }
4761 
4762  retry:
4763   const FunctionType *FuncT;
4764   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4765     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4766     // have type pointer to function".
4767     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4768     if (!FuncT)
4769       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4770                          << Fn->getType() << Fn->getSourceRange());
4771   } else if (const BlockPointerType *BPT =
4772                Fn->getType()->getAs<BlockPointerType>()) {
4773     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4774   } else {
4775     // Handle calls to expressions of unknown-any type.
4776     if (Fn->getType() == Context.UnknownAnyTy) {
4777       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4778       if (rewrite.isInvalid()) return ExprError();
4779       Fn = rewrite.get();
4780       TheCall->setCallee(Fn);
4781       goto retry;
4782     }
4783 
4784     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4785       << Fn->getType() << Fn->getSourceRange());
4786   }
4787 
4788   if (getLangOpts().CUDA) {
4789     if (Config) {
4790       // CUDA: Kernel calls must be to global functions
4791       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4792         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4793             << FDecl->getName() << Fn->getSourceRange());
4794 
4795       // CUDA: Kernel function must have 'void' return type
4796       if (!FuncT->getReturnType()->isVoidType())
4797         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4798             << Fn->getType() << Fn->getSourceRange());
4799     } else {
4800       // CUDA: Calls to global functions must be configured
4801       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4802         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4803             << FDecl->getName() << Fn->getSourceRange());
4804     }
4805   }
4806 
4807   // Check for a valid return type
4808   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4809                           FDecl))
4810     return ExprError();
4811 
4812   // We know the result type of the call, set it.
4813   TheCall->setType(FuncT->getCallResultType(Context));
4814   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4815 
4816   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4817   if (Proto) {
4818     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4819                                 IsExecConfig))
4820       return ExprError();
4821   } else {
4822     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4823 
4824     if (FDecl) {
4825       // Check if we have too few/too many template arguments, based
4826       // on our knowledge of the function definition.
4827       const FunctionDecl *Def = nullptr;
4828       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4829         Proto = Def->getType()->getAs<FunctionProtoType>();
4830        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4831           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4832           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4833       }
4834 
4835       // If the function we're calling isn't a function prototype, but we have
4836       // a function prototype from a prior declaratiom, use that prototype.
4837       if (!FDecl->hasPrototype())
4838         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4839     }
4840 
4841     // Promote the arguments (C99 6.5.2.2p6).
4842     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4843       Expr *Arg = Args[i];
4844 
4845       if (Proto && i < Proto->getNumParams()) {
4846         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4847             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4848         ExprResult ArgE =
4849             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4850         if (ArgE.isInvalid())
4851           return true;
4852 
4853         Arg = ArgE.getAs<Expr>();
4854 
4855       } else {
4856         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4857 
4858         if (ArgE.isInvalid())
4859           return true;
4860 
4861         Arg = ArgE.getAs<Expr>();
4862       }
4863 
4864       if (RequireCompleteType(Arg->getLocStart(),
4865                               Arg->getType(),
4866                               diag::err_call_incomplete_argument, Arg))
4867         return ExprError();
4868 
4869       TheCall->setArg(i, Arg);
4870     }
4871   }
4872 
4873   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4874     if (!Method->isStatic())
4875       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4876         << Fn->getSourceRange());
4877 
4878   // Check for sentinels
4879   if (NDecl)
4880     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4881 
4882   // Do special checking on direct calls to functions.
4883   if (FDecl) {
4884     if (CheckFunctionCall(FDecl, TheCall, Proto))
4885       return ExprError();
4886 
4887     if (BuiltinID)
4888       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4889   } else if (NDecl) {
4890     if (CheckPointerCall(NDecl, TheCall, Proto))
4891       return ExprError();
4892   } else {
4893     if (CheckOtherCall(TheCall, Proto))
4894       return ExprError();
4895   }
4896 
4897   return MaybeBindToTemporary(TheCall);
4898 }
4899 
4900 ExprResult
4901 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4902                            SourceLocation RParenLoc, Expr *InitExpr) {
4903   assert(Ty && "ActOnCompoundLiteral(): missing type");
4904   // FIXME: put back this assert when initializers are worked out.
4905   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4906 
4907   TypeSourceInfo *TInfo;
4908   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4909   if (!TInfo)
4910     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4911 
4912   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4913 }
4914 
4915 ExprResult
4916 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4917                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4918   QualType literalType = TInfo->getType();
4919 
4920   if (literalType->isArrayType()) {
4921     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4922           diag::err_illegal_decl_array_incomplete_type,
4923           SourceRange(LParenLoc,
4924                       LiteralExpr->getSourceRange().getEnd())))
4925       return ExprError();
4926     if (literalType->isVariableArrayType())
4927       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4928         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4929   } else if (!literalType->isDependentType() &&
4930              RequireCompleteType(LParenLoc, literalType,
4931                diag::err_typecheck_decl_incomplete_type,
4932                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4933     return ExprError();
4934 
4935   InitializedEntity Entity
4936     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4937   InitializationKind Kind
4938     = InitializationKind::CreateCStyleCast(LParenLoc,
4939                                            SourceRange(LParenLoc, RParenLoc),
4940                                            /*InitList=*/true);
4941   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4942   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4943                                       &literalType);
4944   if (Result.isInvalid())
4945     return ExprError();
4946   LiteralExpr = Result.get();
4947 
4948   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4949   if (isFileScope &&
4950       !LiteralExpr->isTypeDependent() &&
4951       !LiteralExpr->isValueDependent() &&
4952       !literalType->isDependentType()) { // 6.5.2.5p3
4953     if (CheckForConstantInitializer(LiteralExpr, literalType))
4954       return ExprError();
4955   }
4956 
4957   // In C, compound literals are l-values for some reason.
4958   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4959 
4960   return MaybeBindToTemporary(
4961            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4962                                              VK, LiteralExpr, isFileScope));
4963 }
4964 
4965 ExprResult
4966 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4967                     SourceLocation RBraceLoc) {
4968   // Immediately handle non-overload placeholders.  Overloads can be
4969   // resolved contextually, but everything else here can't.
4970   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4971     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4972       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4973 
4974       // Ignore failures; dropping the entire initializer list because
4975       // of one failure would be terrible for indexing/etc.
4976       if (result.isInvalid()) continue;
4977 
4978       InitArgList[I] = result.get();
4979     }
4980   }
4981 
4982   // Semantic analysis for initializers is done by ActOnDeclarator() and
4983   // CheckInitializer() - it requires knowledge of the object being intialized.
4984 
4985   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4986                                                RBraceLoc);
4987   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4988   return E;
4989 }
4990 
4991 /// Do an explicit extend of the given block pointer if we're in ARC.
4992 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4993   assert(E.get()->getType()->isBlockPointerType());
4994   assert(E.get()->isRValue());
4995 
4996   // Only do this in an r-value context.
4997   if (!S.getLangOpts().ObjCAutoRefCount) return;
4998 
4999   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
5000                                CK_ARCExtendBlockObject, E.get(),
5001                                /*base path*/ nullptr, VK_RValue);
5002   S.ExprNeedsCleanups = true;
5003 }
5004 
5005 /// Prepare a conversion of the given expression to an ObjC object
5006 /// pointer type.
5007 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5008   QualType type = E.get()->getType();
5009   if (type->isObjCObjectPointerType()) {
5010     return CK_BitCast;
5011   } else if (type->isBlockPointerType()) {
5012     maybeExtendBlockObject(*this, E);
5013     return CK_BlockPointerToObjCPointerCast;
5014   } else {
5015     assert(type->isPointerType());
5016     return CK_CPointerToObjCPointerCast;
5017   }
5018 }
5019 
5020 /// Prepares for a scalar cast, performing all the necessary stages
5021 /// except the final cast and returning the kind required.
5022 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5023   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5024   // Also, callers should have filtered out the invalid cases with
5025   // pointers.  Everything else should be possible.
5026 
5027   QualType SrcTy = Src.get()->getType();
5028   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5029     return CK_NoOp;
5030 
5031   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5032   case Type::STK_MemberPointer:
5033     llvm_unreachable("member pointer type in C");
5034 
5035   case Type::STK_CPointer:
5036   case Type::STK_BlockPointer:
5037   case Type::STK_ObjCObjectPointer:
5038     switch (DestTy->getScalarTypeKind()) {
5039     case Type::STK_CPointer: {
5040       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5041       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5042       if (SrcAS != DestAS)
5043         return CK_AddressSpaceConversion;
5044       return CK_BitCast;
5045     }
5046     case Type::STK_BlockPointer:
5047       return (SrcKind == Type::STK_BlockPointer
5048                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5049     case Type::STK_ObjCObjectPointer:
5050       if (SrcKind == Type::STK_ObjCObjectPointer)
5051         return CK_BitCast;
5052       if (SrcKind == Type::STK_CPointer)
5053         return CK_CPointerToObjCPointerCast;
5054       maybeExtendBlockObject(*this, Src);
5055       return CK_BlockPointerToObjCPointerCast;
5056     case Type::STK_Bool:
5057       return CK_PointerToBoolean;
5058     case Type::STK_Integral:
5059       return CK_PointerToIntegral;
5060     case Type::STK_Floating:
5061     case Type::STK_FloatingComplex:
5062     case Type::STK_IntegralComplex:
5063     case Type::STK_MemberPointer:
5064       llvm_unreachable("illegal cast from pointer");
5065     }
5066     llvm_unreachable("Should have returned before this");
5067 
5068   case Type::STK_Bool: // casting from bool is like casting from an integer
5069   case Type::STK_Integral:
5070     switch (DestTy->getScalarTypeKind()) {
5071     case Type::STK_CPointer:
5072     case Type::STK_ObjCObjectPointer:
5073     case Type::STK_BlockPointer:
5074       if (Src.get()->isNullPointerConstant(Context,
5075                                            Expr::NPC_ValueDependentIsNull))
5076         return CK_NullToPointer;
5077       return CK_IntegralToPointer;
5078     case Type::STK_Bool:
5079       return CK_IntegralToBoolean;
5080     case Type::STK_Integral:
5081       return CK_IntegralCast;
5082     case Type::STK_Floating:
5083       return CK_IntegralToFloating;
5084     case Type::STK_IntegralComplex:
5085       Src = ImpCastExprToType(Src.get(),
5086                               DestTy->castAs<ComplexType>()->getElementType(),
5087                               CK_IntegralCast);
5088       return CK_IntegralRealToComplex;
5089     case Type::STK_FloatingComplex:
5090       Src = ImpCastExprToType(Src.get(),
5091                               DestTy->castAs<ComplexType>()->getElementType(),
5092                               CK_IntegralToFloating);
5093       return CK_FloatingRealToComplex;
5094     case Type::STK_MemberPointer:
5095       llvm_unreachable("member pointer type in C");
5096     }
5097     llvm_unreachable("Should have returned before this");
5098 
5099   case Type::STK_Floating:
5100     switch (DestTy->getScalarTypeKind()) {
5101     case Type::STK_Floating:
5102       return CK_FloatingCast;
5103     case Type::STK_Bool:
5104       return CK_FloatingToBoolean;
5105     case Type::STK_Integral:
5106       return CK_FloatingToIntegral;
5107     case Type::STK_FloatingComplex:
5108       Src = ImpCastExprToType(Src.get(),
5109                               DestTy->castAs<ComplexType>()->getElementType(),
5110                               CK_FloatingCast);
5111       return CK_FloatingRealToComplex;
5112     case Type::STK_IntegralComplex:
5113       Src = ImpCastExprToType(Src.get(),
5114                               DestTy->castAs<ComplexType>()->getElementType(),
5115                               CK_FloatingToIntegral);
5116       return CK_IntegralRealToComplex;
5117     case Type::STK_CPointer:
5118     case Type::STK_ObjCObjectPointer:
5119     case Type::STK_BlockPointer:
5120       llvm_unreachable("valid float->pointer cast?");
5121     case Type::STK_MemberPointer:
5122       llvm_unreachable("member pointer type in C");
5123     }
5124     llvm_unreachable("Should have returned before this");
5125 
5126   case Type::STK_FloatingComplex:
5127     switch (DestTy->getScalarTypeKind()) {
5128     case Type::STK_FloatingComplex:
5129       return CK_FloatingComplexCast;
5130     case Type::STK_IntegralComplex:
5131       return CK_FloatingComplexToIntegralComplex;
5132     case Type::STK_Floating: {
5133       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5134       if (Context.hasSameType(ET, DestTy))
5135         return CK_FloatingComplexToReal;
5136       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5137       return CK_FloatingCast;
5138     }
5139     case Type::STK_Bool:
5140       return CK_FloatingComplexToBoolean;
5141     case Type::STK_Integral:
5142       Src = ImpCastExprToType(Src.get(),
5143                               SrcTy->castAs<ComplexType>()->getElementType(),
5144                               CK_FloatingComplexToReal);
5145       return CK_FloatingToIntegral;
5146     case Type::STK_CPointer:
5147     case Type::STK_ObjCObjectPointer:
5148     case Type::STK_BlockPointer:
5149       llvm_unreachable("valid complex float->pointer cast?");
5150     case Type::STK_MemberPointer:
5151       llvm_unreachable("member pointer type in C");
5152     }
5153     llvm_unreachable("Should have returned before this");
5154 
5155   case Type::STK_IntegralComplex:
5156     switch (DestTy->getScalarTypeKind()) {
5157     case Type::STK_FloatingComplex:
5158       return CK_IntegralComplexToFloatingComplex;
5159     case Type::STK_IntegralComplex:
5160       return CK_IntegralComplexCast;
5161     case Type::STK_Integral: {
5162       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5163       if (Context.hasSameType(ET, DestTy))
5164         return CK_IntegralComplexToReal;
5165       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5166       return CK_IntegralCast;
5167     }
5168     case Type::STK_Bool:
5169       return CK_IntegralComplexToBoolean;
5170     case Type::STK_Floating:
5171       Src = ImpCastExprToType(Src.get(),
5172                               SrcTy->castAs<ComplexType>()->getElementType(),
5173                               CK_IntegralComplexToReal);
5174       return CK_IntegralToFloating;
5175     case Type::STK_CPointer:
5176     case Type::STK_ObjCObjectPointer:
5177     case Type::STK_BlockPointer:
5178       llvm_unreachable("valid complex int->pointer cast?");
5179     case Type::STK_MemberPointer:
5180       llvm_unreachable("member pointer type in C");
5181     }
5182     llvm_unreachable("Should have returned before this");
5183   }
5184 
5185   llvm_unreachable("Unhandled scalar cast");
5186 }
5187 
5188 static bool breakDownVectorType(QualType type, uint64_t &len,
5189                                 QualType &eltType) {
5190   // Vectors are simple.
5191   if (const VectorType *vecType = type->getAs<VectorType>()) {
5192     len = vecType->getNumElements();
5193     eltType = vecType->getElementType();
5194     assert(eltType->isScalarType());
5195     return true;
5196   }
5197 
5198   // We allow lax conversion to and from non-vector types, but only if
5199   // they're real types (i.e. non-complex, non-pointer scalar types).
5200   if (!type->isRealType()) return false;
5201 
5202   len = 1;
5203   eltType = type;
5204   return true;
5205 }
5206 
5207 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5208   uint64_t srcLen, destLen;
5209   QualType srcElt, destElt;
5210   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5211   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5212 
5213   // ASTContext::getTypeSize will return the size rounded up to a
5214   // power of 2, so instead of using that, we need to use the raw
5215   // element size multiplied by the element count.
5216   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5217   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5218 
5219   return (srcLen * srcEltSize == destLen * destEltSize);
5220 }
5221 
5222 /// Is this a legal conversion between two known vector types?
5223 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5224   assert(destTy->isVectorType() || srcTy->isVectorType());
5225 
5226   if (!Context.getLangOpts().LaxVectorConversions)
5227     return false;
5228   return VectorTypesMatch(*this, srcTy, destTy);
5229 }
5230 
5231 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5232                            CastKind &Kind) {
5233   assert(VectorTy->isVectorType() && "Not a vector type!");
5234 
5235   if (Ty->isVectorType() || Ty->isIntegerType()) {
5236     if (!VectorTypesMatch(*this, Ty, VectorTy))
5237       return Diag(R.getBegin(),
5238                   Ty->isVectorType() ?
5239                   diag::err_invalid_conversion_between_vectors :
5240                   diag::err_invalid_conversion_between_vector_and_integer)
5241         << VectorTy << Ty << R;
5242   } else
5243     return Diag(R.getBegin(),
5244                 diag::err_invalid_conversion_between_vector_and_scalar)
5245       << VectorTy << Ty << R;
5246 
5247   Kind = CK_BitCast;
5248   return false;
5249 }
5250 
5251 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5252                                     Expr *CastExpr, CastKind &Kind) {
5253   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5254 
5255   QualType SrcTy = CastExpr->getType();
5256 
5257   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5258   // an ExtVectorType.
5259   // In OpenCL, casts between vectors of different types are not allowed.
5260   // (See OpenCL 6.2).
5261   if (SrcTy->isVectorType()) {
5262     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5263         || (getLangOpts().OpenCL &&
5264             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5265       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5266         << DestTy << SrcTy << R;
5267       return ExprError();
5268     }
5269     Kind = CK_BitCast;
5270     return CastExpr;
5271   }
5272 
5273   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5274   // conversion will take place first from scalar to elt type, and then
5275   // splat from elt type to vector.
5276   if (SrcTy->isPointerType())
5277     return Diag(R.getBegin(),
5278                 diag::err_invalid_conversion_between_vector_and_scalar)
5279       << DestTy << SrcTy << R;
5280 
5281   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5282   ExprResult CastExprRes = CastExpr;
5283   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5284   if (CastExprRes.isInvalid())
5285     return ExprError();
5286   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5287 
5288   Kind = CK_VectorSplat;
5289   return CastExpr;
5290 }
5291 
5292 ExprResult
5293 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5294                     Declarator &D, ParsedType &Ty,
5295                     SourceLocation RParenLoc, Expr *CastExpr) {
5296   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5297          "ActOnCastExpr(): missing type or expr");
5298 
5299   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5300   if (D.isInvalidType())
5301     return ExprError();
5302 
5303   if (getLangOpts().CPlusPlus) {
5304     // Check that there are no default arguments (C++ only).
5305     CheckExtraCXXDefaultArguments(D);
5306   } else {
5307     // Make sure any TypoExprs have been dealt with.
5308     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5309     if (!Res.isUsable())
5310       return ExprError();
5311     CastExpr = Res.get();
5312   }
5313 
5314   checkUnusedDeclAttributes(D);
5315 
5316   QualType castType = castTInfo->getType();
5317   Ty = CreateParsedType(castType, castTInfo);
5318 
5319   bool isVectorLiteral = false;
5320 
5321   // Check for an altivec or OpenCL literal,
5322   // i.e. all the elements are integer constants.
5323   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5324   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5325   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5326        && castType->isVectorType() && (PE || PLE)) {
5327     if (PLE && PLE->getNumExprs() == 0) {
5328       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5329       return ExprError();
5330     }
5331     if (PE || PLE->getNumExprs() == 1) {
5332       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5333       if (!E->getType()->isVectorType())
5334         isVectorLiteral = true;
5335     }
5336     else
5337       isVectorLiteral = true;
5338   }
5339 
5340   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5341   // then handle it as such.
5342   if (isVectorLiteral)
5343     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5344 
5345   // If the Expr being casted is a ParenListExpr, handle it specially.
5346   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5347   // sequence of BinOp comma operators.
5348   if (isa<ParenListExpr>(CastExpr)) {
5349     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5350     if (Result.isInvalid()) return ExprError();
5351     CastExpr = Result.get();
5352   }
5353 
5354   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5355       !getSourceManager().isInSystemMacro(LParenLoc))
5356     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5357 
5358   CheckTollFreeBridgeCast(castType, CastExpr);
5359 
5360   CheckObjCBridgeRelatedCast(castType, CastExpr);
5361 
5362   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5363 }
5364 
5365 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5366                                     SourceLocation RParenLoc, Expr *E,
5367                                     TypeSourceInfo *TInfo) {
5368   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5369          "Expected paren or paren list expression");
5370 
5371   Expr **exprs;
5372   unsigned numExprs;
5373   Expr *subExpr;
5374   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5375   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5376     LiteralLParenLoc = PE->getLParenLoc();
5377     LiteralRParenLoc = PE->getRParenLoc();
5378     exprs = PE->getExprs();
5379     numExprs = PE->getNumExprs();
5380   } else { // isa<ParenExpr> by assertion at function entrance
5381     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5382     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5383     subExpr = cast<ParenExpr>(E)->getSubExpr();
5384     exprs = &subExpr;
5385     numExprs = 1;
5386   }
5387 
5388   QualType Ty = TInfo->getType();
5389   assert(Ty->isVectorType() && "Expected vector type");
5390 
5391   SmallVector<Expr *, 8> initExprs;
5392   const VectorType *VTy = Ty->getAs<VectorType>();
5393   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5394 
5395   // '(...)' form of vector initialization in AltiVec: the number of
5396   // initializers must be one or must match the size of the vector.
5397   // If a single value is specified in the initializer then it will be
5398   // replicated to all the components of the vector
5399   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5400     // The number of initializers must be one or must match the size of the
5401     // vector. If a single value is specified in the initializer then it will
5402     // be replicated to all the components of the vector
5403     if (numExprs == 1) {
5404       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5405       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5406       if (Literal.isInvalid())
5407         return ExprError();
5408       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5409                                   PrepareScalarCast(Literal, ElemTy));
5410       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5411     }
5412     else if (numExprs < numElems) {
5413       Diag(E->getExprLoc(),
5414            diag::err_incorrect_number_of_vector_initializers);
5415       return ExprError();
5416     }
5417     else
5418       initExprs.append(exprs, exprs + numExprs);
5419   }
5420   else {
5421     // For OpenCL, when the number of initializers is a single value,
5422     // it will be replicated to all components of the vector.
5423     if (getLangOpts().OpenCL &&
5424         VTy->getVectorKind() == VectorType::GenericVector &&
5425         numExprs == 1) {
5426         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5427         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5428         if (Literal.isInvalid())
5429           return ExprError();
5430         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5431                                     PrepareScalarCast(Literal, ElemTy));
5432         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5433     }
5434 
5435     initExprs.append(exprs, exprs + numExprs);
5436   }
5437   // FIXME: This means that pretty-printing the final AST will produce curly
5438   // braces instead of the original commas.
5439   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5440                                                    initExprs, LiteralRParenLoc);
5441   initE->setType(Ty);
5442   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5443 }
5444 
5445 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5446 /// the ParenListExpr into a sequence of comma binary operators.
5447 ExprResult
5448 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5449   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5450   if (!E)
5451     return OrigExpr;
5452 
5453   ExprResult Result(E->getExpr(0));
5454 
5455   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5456     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5457                         E->getExpr(i));
5458 
5459   if (Result.isInvalid()) return ExprError();
5460 
5461   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5462 }
5463 
5464 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5465                                     SourceLocation R,
5466                                     MultiExprArg Val) {
5467   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5468   return expr;
5469 }
5470 
5471 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5472 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5473 /// emitted.
5474 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5475                                       SourceLocation QuestionLoc) {
5476   Expr *NullExpr = LHSExpr;
5477   Expr *NonPointerExpr = RHSExpr;
5478   Expr::NullPointerConstantKind NullKind =
5479       NullExpr->isNullPointerConstant(Context,
5480                                       Expr::NPC_ValueDependentIsNotNull);
5481 
5482   if (NullKind == Expr::NPCK_NotNull) {
5483     NullExpr = RHSExpr;
5484     NonPointerExpr = LHSExpr;
5485     NullKind =
5486         NullExpr->isNullPointerConstant(Context,
5487                                         Expr::NPC_ValueDependentIsNotNull);
5488   }
5489 
5490   if (NullKind == Expr::NPCK_NotNull)
5491     return false;
5492 
5493   if (NullKind == Expr::NPCK_ZeroExpression)
5494     return false;
5495 
5496   if (NullKind == Expr::NPCK_ZeroLiteral) {
5497     // In this case, check to make sure that we got here from a "NULL"
5498     // string in the source code.
5499     NullExpr = NullExpr->IgnoreParenImpCasts();
5500     SourceLocation loc = NullExpr->getExprLoc();
5501     if (!findMacroSpelling(loc, "NULL"))
5502       return false;
5503   }
5504 
5505   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5506   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5507       << NonPointerExpr->getType() << DiagType
5508       << NonPointerExpr->getSourceRange();
5509   return true;
5510 }
5511 
5512 /// \brief Return false if the condition expression is valid, true otherwise.
5513 static bool checkCondition(Sema &S, Expr *Cond) {
5514   QualType CondTy = Cond->getType();
5515 
5516   // C99 6.5.15p2
5517   if (CondTy->isScalarType()) return false;
5518 
5519   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5520   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5521     return false;
5522 
5523   // Emit the proper error message.
5524   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5525                               diag::err_typecheck_cond_expect_scalar :
5526                               diag::err_typecheck_cond_expect_scalar_or_vector)
5527     << CondTy;
5528   return true;
5529 }
5530 
5531 /// \brief Return false if the two expressions can be converted to a vector,
5532 /// true otherwise
5533 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5534                                                     ExprResult &RHS,
5535                                                     QualType CondTy) {
5536   // Both operands should be of scalar type.
5537   if (!LHS.get()->getType()->isScalarType()) {
5538     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5539       << CondTy;
5540     return true;
5541   }
5542   if (!RHS.get()->getType()->isScalarType()) {
5543     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5544       << CondTy;
5545     return true;
5546   }
5547 
5548   // Implicity convert these scalars to the type of the condition.
5549   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5550   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5551   return false;
5552 }
5553 
5554 /// \brief Handle when one or both operands are void type.
5555 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5556                                          ExprResult &RHS) {
5557     Expr *LHSExpr = LHS.get();
5558     Expr *RHSExpr = RHS.get();
5559 
5560     if (!LHSExpr->getType()->isVoidType())
5561       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5562         << RHSExpr->getSourceRange();
5563     if (!RHSExpr->getType()->isVoidType())
5564       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5565         << LHSExpr->getSourceRange();
5566     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5567     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5568     return S.Context.VoidTy;
5569 }
5570 
5571 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5572 /// true otherwise.
5573 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5574                                         QualType PointerTy) {
5575   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5576       !NullExpr.get()->isNullPointerConstant(S.Context,
5577                                             Expr::NPC_ValueDependentIsNull))
5578     return true;
5579 
5580   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5581   return false;
5582 }
5583 
5584 /// \brief Checks compatibility between two pointers and return the resulting
5585 /// type.
5586 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5587                                                      ExprResult &RHS,
5588                                                      SourceLocation Loc) {
5589   QualType LHSTy = LHS.get()->getType();
5590   QualType RHSTy = RHS.get()->getType();
5591 
5592   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5593     // Two identical pointers types are always compatible.
5594     return LHSTy;
5595   }
5596 
5597   QualType lhptee, rhptee;
5598 
5599   // Get the pointee types.
5600   bool IsBlockPointer = false;
5601   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5602     lhptee = LHSBTy->getPointeeType();
5603     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5604     IsBlockPointer = true;
5605   } else {
5606     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5607     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5608   }
5609 
5610   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5611   // differently qualified versions of compatible types, the result type is
5612   // a pointer to an appropriately qualified version of the composite
5613   // type.
5614 
5615   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5616   // clause doesn't make sense for our extensions. E.g. address space 2 should
5617   // be incompatible with address space 3: they may live on different devices or
5618   // anything.
5619   Qualifiers lhQual = lhptee.getQualifiers();
5620   Qualifiers rhQual = rhptee.getQualifiers();
5621 
5622   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5623   lhQual.removeCVRQualifiers();
5624   rhQual.removeCVRQualifiers();
5625 
5626   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5627   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5628 
5629   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5630 
5631   if (CompositeTy.isNull()) {
5632     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5633       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5634       << RHS.get()->getSourceRange();
5635     // In this situation, we assume void* type. No especially good
5636     // reason, but this is what gcc does, and we do have to pick
5637     // to get a consistent AST.
5638     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5639     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5640     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5641     return incompatTy;
5642   }
5643 
5644   // The pointer types are compatible.
5645   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5646   if (IsBlockPointer)
5647     ResultTy = S.Context.getBlockPointerType(ResultTy);
5648   else
5649     ResultTy = S.Context.getPointerType(ResultTy);
5650 
5651   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5652   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5653   return ResultTy;
5654 }
5655 
5656 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5657 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5658 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5659 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5660   if (QT->isObjCIdType())
5661     return true;
5662 
5663   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5664   if (!OPT)
5665     return false;
5666 
5667   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5668     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5669       return false;
5670 
5671   ObjCProtocolDecl* PNSCopying =
5672     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5673   ObjCProtocolDecl* PNSObject =
5674     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5675 
5676   for (auto *Proto : OPT->quals()) {
5677     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5678         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5679       ;
5680     else
5681       return false;
5682   }
5683   return true;
5684 }
5685 
5686 /// \brief Return the resulting type when the operands are both block pointers.
5687 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5688                                                           ExprResult &LHS,
5689                                                           ExprResult &RHS,
5690                                                           SourceLocation Loc) {
5691   QualType LHSTy = LHS.get()->getType();
5692   QualType RHSTy = RHS.get()->getType();
5693 
5694   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5695     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5696       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5697       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5698       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5699       return destType;
5700     }
5701     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5702       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5703       << RHS.get()->getSourceRange();
5704     return QualType();
5705   }
5706 
5707   // We have 2 block pointer types.
5708   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5709 }
5710 
5711 /// \brief Return the resulting type when the operands are both pointers.
5712 static QualType
5713 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5714                                             ExprResult &RHS,
5715                                             SourceLocation Loc) {
5716   // get the pointer types
5717   QualType LHSTy = LHS.get()->getType();
5718   QualType RHSTy = RHS.get()->getType();
5719 
5720   // get the "pointed to" types
5721   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5722   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5723 
5724   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5725   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5726     // Figure out necessary qualifiers (C99 6.5.15p6)
5727     QualType destPointee
5728       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5729     QualType destType = S.Context.getPointerType(destPointee);
5730     // Add qualifiers if necessary.
5731     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5732     // Promote to void*.
5733     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5734     return destType;
5735   }
5736   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5737     QualType destPointee
5738       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5739     QualType destType = S.Context.getPointerType(destPointee);
5740     // Add qualifiers if necessary.
5741     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5742     // Promote to void*.
5743     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5744     return destType;
5745   }
5746 
5747   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5748 }
5749 
5750 /// \brief Return false if the first expression is not an integer and the second
5751 /// expression is not a pointer, true otherwise.
5752 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5753                                         Expr* PointerExpr, SourceLocation Loc,
5754                                         bool IsIntFirstExpr) {
5755   if (!PointerExpr->getType()->isPointerType() ||
5756       !Int.get()->getType()->isIntegerType())
5757     return false;
5758 
5759   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5760   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5761 
5762   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
5763     << Expr1->getType() << Expr2->getType()
5764     << Expr1->getSourceRange() << Expr2->getSourceRange();
5765   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5766                             CK_IntegralToPointer);
5767   return true;
5768 }
5769 
5770 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5771 /// In that case, LHS = cond.
5772 /// C99 6.5.15
5773 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5774                                         ExprResult &RHS, ExprValueKind &VK,
5775                                         ExprObjectKind &OK,
5776                                         SourceLocation QuestionLoc) {
5777 
5778   if (!getLangOpts().CPlusPlus) {
5779     // C cannot handle TypoExpr nodes on either side of a binop because it
5780     // doesn't handle dependent types properly, so make sure any TypoExprs have
5781     // been dealt with before checking the operands.
5782     ExprResult CondResult = CorrectDelayedTyposInExpr(Cond);
5783     if (!CondResult.isUsable()) return QualType();
5784     Cond = CondResult;
5785   }
5786 
5787   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5788   if (!LHSResult.isUsable()) return QualType();
5789   LHS = LHSResult;
5790 
5791   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5792   if (!RHSResult.isUsable()) return QualType();
5793   RHS = RHSResult;
5794 
5795   // C++ is sufficiently different to merit its own checker.
5796   if (getLangOpts().CPlusPlus)
5797     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5798 
5799   VK = VK_RValue;
5800   OK = OK_Ordinary;
5801 
5802   // First, check the condition.
5803   Cond = UsualUnaryConversions(Cond.get());
5804   if (Cond.isInvalid())
5805     return QualType();
5806   if (checkCondition(*this, Cond.get()))
5807     return QualType();
5808 
5809   // Now check the two expressions.
5810   if (LHS.get()->getType()->isVectorType() ||
5811       RHS.get()->getType()->isVectorType())
5812     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5813 
5814   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5815   if (LHS.isInvalid() || RHS.isInvalid())
5816     return QualType();
5817 
5818   QualType CondTy = Cond.get()->getType();
5819   QualType LHSTy = LHS.get()->getType();
5820   QualType RHSTy = RHS.get()->getType();
5821 
5822   // If the condition is a vector, and both operands are scalar,
5823   // attempt to implicity convert them to the vector type to act like the
5824   // built in select. (OpenCL v1.1 s6.3.i)
5825   if (getLangOpts().OpenCL && CondTy->isVectorType())
5826     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5827       return QualType();
5828 
5829   // If both operands have arithmetic type, do the usual arithmetic conversions
5830   // to find a common type: C99 6.5.15p3,5.
5831   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5832     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5833     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5834 
5835     return ResTy;
5836   }
5837 
5838   // If both operands are the same structure or union type, the result is that
5839   // type.
5840   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5841     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5842       if (LHSRT->getDecl() == RHSRT->getDecl())
5843         // "If both the operands have structure or union type, the result has
5844         // that type."  This implies that CV qualifiers are dropped.
5845         return LHSTy.getUnqualifiedType();
5846     // FIXME: Type of conditional expression must be complete in C mode.
5847   }
5848 
5849   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5850   // The following || allows only one side to be void (a GCC-ism).
5851   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5852     return checkConditionalVoidType(*this, LHS, RHS);
5853   }
5854 
5855   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5856   // the type of the other operand."
5857   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5858   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5859 
5860   // All objective-c pointer type analysis is done here.
5861   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5862                                                         QuestionLoc);
5863   if (LHS.isInvalid() || RHS.isInvalid())
5864     return QualType();
5865   if (!compositeType.isNull())
5866     return compositeType;
5867 
5868 
5869   // Handle block pointer types.
5870   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5871     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5872                                                      QuestionLoc);
5873 
5874   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5875   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5876     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5877                                                        QuestionLoc);
5878 
5879   // GCC compatibility: soften pointer/integer mismatch.  Note that
5880   // null pointers have been filtered out by this point.
5881   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5882       /*isIntFirstExpr=*/true))
5883     return RHSTy;
5884   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5885       /*isIntFirstExpr=*/false))
5886     return LHSTy;
5887 
5888   // Emit a better diagnostic if one of the expressions is a null pointer
5889   // constant and the other is not a pointer type. In this case, the user most
5890   // likely forgot to take the address of the other expression.
5891   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5892     return QualType();
5893 
5894   // Otherwise, the operands are not compatible.
5895   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5896     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5897     << RHS.get()->getSourceRange();
5898   return QualType();
5899 }
5900 
5901 /// FindCompositeObjCPointerType - Helper method to find composite type of
5902 /// two objective-c pointer types of the two input expressions.
5903 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5904                                             SourceLocation QuestionLoc) {
5905   QualType LHSTy = LHS.get()->getType();
5906   QualType RHSTy = RHS.get()->getType();
5907 
5908   // Handle things like Class and struct objc_class*.  Here we case the result
5909   // to the pseudo-builtin, because that will be implicitly cast back to the
5910   // redefinition type if an attempt is made to access its fields.
5911   if (LHSTy->isObjCClassType() &&
5912       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5913     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5914     return LHSTy;
5915   }
5916   if (RHSTy->isObjCClassType() &&
5917       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5918     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5919     return RHSTy;
5920   }
5921   // And the same for struct objc_object* / id
5922   if (LHSTy->isObjCIdType() &&
5923       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5924     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5925     return LHSTy;
5926   }
5927   if (RHSTy->isObjCIdType() &&
5928       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5929     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5930     return RHSTy;
5931   }
5932   // And the same for struct objc_selector* / SEL
5933   if (Context.isObjCSelType(LHSTy) &&
5934       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5935     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5936     return LHSTy;
5937   }
5938   if (Context.isObjCSelType(RHSTy) &&
5939       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5940     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5941     return RHSTy;
5942   }
5943   // Check constraints for Objective-C object pointers types.
5944   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5945 
5946     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5947       // Two identical object pointer types are always compatible.
5948       return LHSTy;
5949     }
5950     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5951     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5952     QualType compositeType = LHSTy;
5953 
5954     // If both operands are interfaces and either operand can be
5955     // assigned to the other, use that type as the composite
5956     // type. This allows
5957     //   xxx ? (A*) a : (B*) b
5958     // where B is a subclass of A.
5959     //
5960     // Additionally, as for assignment, if either type is 'id'
5961     // allow silent coercion. Finally, if the types are
5962     // incompatible then make sure to use 'id' as the composite
5963     // type so the result is acceptable for sending messages to.
5964 
5965     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5966     // It could return the composite type.
5967     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5968       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5969     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5970       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5971     } else if ((LHSTy->isObjCQualifiedIdType() ||
5972                 RHSTy->isObjCQualifiedIdType()) &&
5973                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5974       // Need to handle "id<xx>" explicitly.
5975       // GCC allows qualified id and any Objective-C type to devolve to
5976       // id. Currently localizing to here until clear this should be
5977       // part of ObjCQualifiedIdTypesAreCompatible.
5978       compositeType = Context.getObjCIdType();
5979     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5980       compositeType = Context.getObjCIdType();
5981     } else if (!(compositeType =
5982                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5983       ;
5984     else {
5985       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5986       << LHSTy << RHSTy
5987       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5988       QualType incompatTy = Context.getObjCIdType();
5989       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5990       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5991       return incompatTy;
5992     }
5993     // The object pointer types are compatible.
5994     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5995     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5996     return compositeType;
5997   }
5998   // Check Objective-C object pointer types and 'void *'
5999   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6000     if (getLangOpts().ObjCAutoRefCount) {
6001       // ARC forbids the implicit conversion of object pointers to 'void *',
6002       // so these types are not compatible.
6003       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6004           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6005       LHS = RHS = true;
6006       return QualType();
6007     }
6008     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6009     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6010     QualType destPointee
6011     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6012     QualType destType = Context.getPointerType(destPointee);
6013     // Add qualifiers if necessary.
6014     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6015     // Promote to void*.
6016     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6017     return destType;
6018   }
6019   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6020     if (getLangOpts().ObjCAutoRefCount) {
6021       // ARC forbids the implicit conversion of object pointers to 'void *',
6022       // so these types are not compatible.
6023       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6024           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6025       LHS = RHS = true;
6026       return QualType();
6027     }
6028     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6029     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6030     QualType destPointee
6031     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6032     QualType destType = Context.getPointerType(destPointee);
6033     // Add qualifiers if necessary.
6034     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6035     // Promote to void*.
6036     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6037     return destType;
6038   }
6039   return QualType();
6040 }
6041 
6042 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6043 /// ParenRange in parentheses.
6044 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6045                                const PartialDiagnostic &Note,
6046                                SourceRange ParenRange) {
6047   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6048   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6049       EndLoc.isValid()) {
6050     Self.Diag(Loc, Note)
6051       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6052       << FixItHint::CreateInsertion(EndLoc, ")");
6053   } else {
6054     // We can't display the parentheses, so just show the bare note.
6055     Self.Diag(Loc, Note) << ParenRange;
6056   }
6057 }
6058 
6059 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6060   return Opc >= BO_Mul && Opc <= BO_Shr;
6061 }
6062 
6063 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6064 /// expression, either using a built-in or overloaded operator,
6065 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6066 /// expression.
6067 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6068                                    Expr **RHSExprs) {
6069   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6070   E = E->IgnoreImpCasts();
6071   E = E->IgnoreConversionOperator();
6072   E = E->IgnoreImpCasts();
6073 
6074   // Built-in binary operator.
6075   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6076     if (IsArithmeticOp(OP->getOpcode())) {
6077       *Opcode = OP->getOpcode();
6078       *RHSExprs = OP->getRHS();
6079       return true;
6080     }
6081   }
6082 
6083   // Overloaded operator.
6084   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6085     if (Call->getNumArgs() != 2)
6086       return false;
6087 
6088     // Make sure this is really a binary operator that is safe to pass into
6089     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6090     OverloadedOperatorKind OO = Call->getOperator();
6091     if (OO < OO_Plus || OO > OO_Arrow ||
6092         OO == OO_PlusPlus || OO == OO_MinusMinus)
6093       return false;
6094 
6095     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6096     if (IsArithmeticOp(OpKind)) {
6097       *Opcode = OpKind;
6098       *RHSExprs = Call->getArg(1);
6099       return true;
6100     }
6101   }
6102 
6103   return false;
6104 }
6105 
6106 static bool IsLogicOp(BinaryOperatorKind Opc) {
6107   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6108 }
6109 
6110 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6111 /// or is a logical expression such as (x==y) which has int type, but is
6112 /// commonly interpreted as boolean.
6113 static bool ExprLooksBoolean(Expr *E) {
6114   E = E->IgnoreParenImpCasts();
6115 
6116   if (E->getType()->isBooleanType())
6117     return true;
6118   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6119     return IsLogicOp(OP->getOpcode());
6120   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6121     return OP->getOpcode() == UO_LNot;
6122 
6123   return false;
6124 }
6125 
6126 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6127 /// and binary operator are mixed in a way that suggests the programmer assumed
6128 /// the conditional operator has higher precedence, for example:
6129 /// "int x = a + someBinaryCondition ? 1 : 2".
6130 static void DiagnoseConditionalPrecedence(Sema &Self,
6131                                           SourceLocation OpLoc,
6132                                           Expr *Condition,
6133                                           Expr *LHSExpr,
6134                                           Expr *RHSExpr) {
6135   BinaryOperatorKind CondOpcode;
6136   Expr *CondRHS;
6137 
6138   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6139     return;
6140   if (!ExprLooksBoolean(CondRHS))
6141     return;
6142 
6143   // The condition is an arithmetic binary expression, with a right-
6144   // hand side that looks boolean, so warn.
6145 
6146   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6147       << Condition->getSourceRange()
6148       << BinaryOperator::getOpcodeStr(CondOpcode);
6149 
6150   SuggestParentheses(Self, OpLoc,
6151     Self.PDiag(diag::note_precedence_silence)
6152       << BinaryOperator::getOpcodeStr(CondOpcode),
6153     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6154 
6155   SuggestParentheses(Self, OpLoc,
6156     Self.PDiag(diag::note_precedence_conditional_first),
6157     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6158 }
6159 
6160 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6161 /// in the case of a the GNU conditional expr extension.
6162 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6163                                     SourceLocation ColonLoc,
6164                                     Expr *CondExpr, Expr *LHSExpr,
6165                                     Expr *RHSExpr) {
6166   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6167   // was the condition.
6168   OpaqueValueExpr *opaqueValue = nullptr;
6169   Expr *commonExpr = nullptr;
6170   if (!LHSExpr) {
6171     commonExpr = CondExpr;
6172     // Lower out placeholder types first.  This is important so that we don't
6173     // try to capture a placeholder. This happens in few cases in C++; such
6174     // as Objective-C++'s dictionary subscripting syntax.
6175     if (commonExpr->hasPlaceholderType()) {
6176       ExprResult result = CheckPlaceholderExpr(commonExpr);
6177       if (!result.isUsable()) return ExprError();
6178       commonExpr = result.get();
6179     }
6180     // We usually want to apply unary conversions *before* saving, except
6181     // in the special case of a C++ l-value conditional.
6182     if (!(getLangOpts().CPlusPlus
6183           && !commonExpr->isTypeDependent()
6184           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6185           && commonExpr->isGLValue()
6186           && commonExpr->isOrdinaryOrBitFieldObject()
6187           && RHSExpr->isOrdinaryOrBitFieldObject()
6188           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6189       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6190       if (commonRes.isInvalid())
6191         return ExprError();
6192       commonExpr = commonRes.get();
6193     }
6194 
6195     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6196                                                 commonExpr->getType(),
6197                                                 commonExpr->getValueKind(),
6198                                                 commonExpr->getObjectKind(),
6199                                                 commonExpr);
6200     LHSExpr = CondExpr = opaqueValue;
6201   }
6202 
6203   ExprValueKind VK = VK_RValue;
6204   ExprObjectKind OK = OK_Ordinary;
6205   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6206   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6207                                              VK, OK, QuestionLoc);
6208   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6209       RHS.isInvalid())
6210     return ExprError();
6211 
6212   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6213                                 RHS.get());
6214 
6215   if (!commonExpr)
6216     return new (Context)
6217         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6218                             RHS.get(), result, VK, OK);
6219 
6220   return new (Context) BinaryConditionalOperator(
6221       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6222       ColonLoc, result, VK, OK);
6223 }
6224 
6225 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6226 // being closely modeled after the C99 spec:-). The odd characteristic of this
6227 // routine is it effectively iqnores the qualifiers on the top level pointee.
6228 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6229 // FIXME: add a couple examples in this comment.
6230 static Sema::AssignConvertType
6231 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6232   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6233   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6234 
6235   // get the "pointed to" type (ignoring qualifiers at the top level)
6236   const Type *lhptee, *rhptee;
6237   Qualifiers lhq, rhq;
6238   std::tie(lhptee, lhq) =
6239       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6240   std::tie(rhptee, rhq) =
6241       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6242 
6243   Sema::AssignConvertType ConvTy = Sema::Compatible;
6244 
6245   // C99 6.5.16.1p1: This following citation is common to constraints
6246   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6247   // qualifiers of the type *pointed to* by the right;
6248 
6249   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6250   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6251       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6252     // Ignore lifetime for further calculation.
6253     lhq.removeObjCLifetime();
6254     rhq.removeObjCLifetime();
6255   }
6256 
6257   if (!lhq.compatiblyIncludes(rhq)) {
6258     // Treat address-space mismatches as fatal.  TODO: address subspaces
6259     if (!lhq.isAddressSpaceSupersetOf(rhq))
6260       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6261 
6262     // It's okay to add or remove GC or lifetime qualifiers when converting to
6263     // and from void*.
6264     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6265                         .compatiblyIncludes(
6266                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6267              && (lhptee->isVoidType() || rhptee->isVoidType()))
6268       ; // keep old
6269 
6270     // Treat lifetime mismatches as fatal.
6271     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6272       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6273 
6274     // For GCC compatibility, other qualifier mismatches are treated
6275     // as still compatible in C.
6276     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6277   }
6278 
6279   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6280   // incomplete type and the other is a pointer to a qualified or unqualified
6281   // version of void...
6282   if (lhptee->isVoidType()) {
6283     if (rhptee->isIncompleteOrObjectType())
6284       return ConvTy;
6285 
6286     // As an extension, we allow cast to/from void* to function pointer.
6287     assert(rhptee->isFunctionType());
6288     return Sema::FunctionVoidPointer;
6289   }
6290 
6291   if (rhptee->isVoidType()) {
6292     if (lhptee->isIncompleteOrObjectType())
6293       return ConvTy;
6294 
6295     // As an extension, we allow cast to/from void* to function pointer.
6296     assert(lhptee->isFunctionType());
6297     return Sema::FunctionVoidPointer;
6298   }
6299 
6300   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6301   // unqualified versions of compatible types, ...
6302   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6303   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6304     // Check if the pointee types are compatible ignoring the sign.
6305     // We explicitly check for char so that we catch "char" vs
6306     // "unsigned char" on systems where "char" is unsigned.
6307     if (lhptee->isCharType())
6308       ltrans = S.Context.UnsignedCharTy;
6309     else if (lhptee->hasSignedIntegerRepresentation())
6310       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6311 
6312     if (rhptee->isCharType())
6313       rtrans = S.Context.UnsignedCharTy;
6314     else if (rhptee->hasSignedIntegerRepresentation())
6315       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6316 
6317     if (ltrans == rtrans) {
6318       // Types are compatible ignoring the sign. Qualifier incompatibility
6319       // takes priority over sign incompatibility because the sign
6320       // warning can be disabled.
6321       if (ConvTy != Sema::Compatible)
6322         return ConvTy;
6323 
6324       return Sema::IncompatiblePointerSign;
6325     }
6326 
6327     // If we are a multi-level pointer, it's possible that our issue is simply
6328     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6329     // the eventual target type is the same and the pointers have the same
6330     // level of indirection, this must be the issue.
6331     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6332       do {
6333         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6334         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6335       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6336 
6337       if (lhptee == rhptee)
6338         return Sema::IncompatibleNestedPointerQualifiers;
6339     }
6340 
6341     // General pointer incompatibility takes priority over qualifiers.
6342     return Sema::IncompatiblePointer;
6343   }
6344   if (!S.getLangOpts().CPlusPlus &&
6345       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6346     return Sema::IncompatiblePointer;
6347   return ConvTy;
6348 }
6349 
6350 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6351 /// block pointer types are compatible or whether a block and normal pointer
6352 /// are compatible. It is more restrict than comparing two function pointer
6353 // types.
6354 static Sema::AssignConvertType
6355 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6356                                     QualType RHSType) {
6357   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6358   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6359 
6360   QualType lhptee, rhptee;
6361 
6362   // get the "pointed to" type (ignoring qualifiers at the top level)
6363   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6364   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6365 
6366   // In C++, the types have to match exactly.
6367   if (S.getLangOpts().CPlusPlus)
6368     return Sema::IncompatibleBlockPointer;
6369 
6370   Sema::AssignConvertType ConvTy = Sema::Compatible;
6371 
6372   // For blocks we enforce that qualifiers are identical.
6373   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6374     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6375 
6376   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6377     return Sema::IncompatibleBlockPointer;
6378 
6379   return ConvTy;
6380 }
6381 
6382 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6383 /// for assignment compatibility.
6384 static Sema::AssignConvertType
6385 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6386                                    QualType RHSType) {
6387   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6388   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6389 
6390   if (LHSType->isObjCBuiltinType()) {
6391     // Class is not compatible with ObjC object pointers.
6392     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6393         !RHSType->isObjCQualifiedClassType())
6394       return Sema::IncompatiblePointer;
6395     return Sema::Compatible;
6396   }
6397   if (RHSType->isObjCBuiltinType()) {
6398     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6399         !LHSType->isObjCQualifiedClassType())
6400       return Sema::IncompatiblePointer;
6401     return Sema::Compatible;
6402   }
6403   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6404   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6405 
6406   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6407       // make an exception for id<P>
6408       !LHSType->isObjCQualifiedIdType())
6409     return Sema::CompatiblePointerDiscardsQualifiers;
6410 
6411   if (S.Context.typesAreCompatible(LHSType, RHSType))
6412     return Sema::Compatible;
6413   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6414     return Sema::IncompatibleObjCQualifiedId;
6415   return Sema::IncompatiblePointer;
6416 }
6417 
6418 Sema::AssignConvertType
6419 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6420                                  QualType LHSType, QualType RHSType) {
6421   // Fake up an opaque expression.  We don't actually care about what
6422   // cast operations are required, so if CheckAssignmentConstraints
6423   // adds casts to this they'll be wasted, but fortunately that doesn't
6424   // usually happen on valid code.
6425   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6426   ExprResult RHSPtr = &RHSExpr;
6427   CastKind K = CK_Invalid;
6428 
6429   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6430 }
6431 
6432 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6433 /// has code to accommodate several GCC extensions when type checking
6434 /// pointers. Here are some objectionable examples that GCC considers warnings:
6435 ///
6436 ///  int a, *pint;
6437 ///  short *pshort;
6438 ///  struct foo *pfoo;
6439 ///
6440 ///  pint = pshort; // warning: assignment from incompatible pointer type
6441 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6442 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6443 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6444 ///
6445 /// As a result, the code for dealing with pointers is more complex than the
6446 /// C99 spec dictates.
6447 ///
6448 /// Sets 'Kind' for any result kind except Incompatible.
6449 Sema::AssignConvertType
6450 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6451                                  CastKind &Kind) {
6452   QualType RHSType = RHS.get()->getType();
6453   QualType OrigLHSType = LHSType;
6454 
6455   // Get canonical types.  We're not formatting these types, just comparing
6456   // them.
6457   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6458   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6459 
6460   // Common case: no conversion required.
6461   if (LHSType == RHSType) {
6462     Kind = CK_NoOp;
6463     return Compatible;
6464   }
6465 
6466   // If we have an atomic type, try a non-atomic assignment, then just add an
6467   // atomic qualification step.
6468   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6469     Sema::AssignConvertType result =
6470       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6471     if (result != Compatible)
6472       return result;
6473     if (Kind != CK_NoOp)
6474       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6475     Kind = CK_NonAtomicToAtomic;
6476     return Compatible;
6477   }
6478 
6479   // If the left-hand side is a reference type, then we are in a
6480   // (rare!) case where we've allowed the use of references in C,
6481   // e.g., as a parameter type in a built-in function. In this case,
6482   // just make sure that the type referenced is compatible with the
6483   // right-hand side type. The caller is responsible for adjusting
6484   // LHSType so that the resulting expression does not have reference
6485   // type.
6486   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6487     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6488       Kind = CK_LValueBitCast;
6489       return Compatible;
6490     }
6491     return Incompatible;
6492   }
6493 
6494   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6495   // to the same ExtVector type.
6496   if (LHSType->isExtVectorType()) {
6497     if (RHSType->isExtVectorType())
6498       return Incompatible;
6499     if (RHSType->isArithmeticType()) {
6500       // CK_VectorSplat does T -> vector T, so first cast to the
6501       // element type.
6502       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6503       if (elType != RHSType) {
6504         Kind = PrepareScalarCast(RHS, elType);
6505         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6506       }
6507       Kind = CK_VectorSplat;
6508       return Compatible;
6509     }
6510   }
6511 
6512   // Conversions to or from vector type.
6513   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6514     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6515       // Allow assignments of an AltiVec vector type to an equivalent GCC
6516       // vector type and vice versa
6517       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6518         Kind = CK_BitCast;
6519         return Compatible;
6520       }
6521 
6522       // If we are allowing lax vector conversions, and LHS and RHS are both
6523       // vectors, the total size only needs to be the same. This is a bitcast;
6524       // no bits are changed but the result type is different.
6525       if (isLaxVectorConversion(RHSType, LHSType)) {
6526         Kind = CK_BitCast;
6527         return IncompatibleVectors;
6528       }
6529     }
6530     return Incompatible;
6531   }
6532 
6533   // Arithmetic conversions.
6534   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6535       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6536     Kind = PrepareScalarCast(RHS, LHSType);
6537     return Compatible;
6538   }
6539 
6540   // Conversions to normal pointers.
6541   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6542     // U* -> T*
6543     if (isa<PointerType>(RHSType)) {
6544       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
6545       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
6546       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
6547       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6548     }
6549 
6550     // int -> T*
6551     if (RHSType->isIntegerType()) {
6552       Kind = CK_IntegralToPointer; // FIXME: null?
6553       return IntToPointer;
6554     }
6555 
6556     // C pointers are not compatible with ObjC object pointers,
6557     // with two exceptions:
6558     if (isa<ObjCObjectPointerType>(RHSType)) {
6559       //  - conversions to void*
6560       if (LHSPointer->getPointeeType()->isVoidType()) {
6561         Kind = CK_BitCast;
6562         return Compatible;
6563       }
6564 
6565       //  - conversions from 'Class' to the redefinition type
6566       if (RHSType->isObjCClassType() &&
6567           Context.hasSameType(LHSType,
6568                               Context.getObjCClassRedefinitionType())) {
6569         Kind = CK_BitCast;
6570         return Compatible;
6571       }
6572 
6573       Kind = CK_BitCast;
6574       return IncompatiblePointer;
6575     }
6576 
6577     // U^ -> void*
6578     if (RHSType->getAs<BlockPointerType>()) {
6579       if (LHSPointer->getPointeeType()->isVoidType()) {
6580         Kind = CK_BitCast;
6581         return Compatible;
6582       }
6583     }
6584 
6585     return Incompatible;
6586   }
6587 
6588   // Conversions to block pointers.
6589   if (isa<BlockPointerType>(LHSType)) {
6590     // U^ -> T^
6591     if (RHSType->isBlockPointerType()) {
6592       Kind = CK_BitCast;
6593       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6594     }
6595 
6596     // int or null -> T^
6597     if (RHSType->isIntegerType()) {
6598       Kind = CK_IntegralToPointer; // FIXME: null
6599       return IntToBlockPointer;
6600     }
6601 
6602     // id -> T^
6603     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6604       Kind = CK_AnyPointerToBlockPointerCast;
6605       return Compatible;
6606     }
6607 
6608     // void* -> T^
6609     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6610       if (RHSPT->getPointeeType()->isVoidType()) {
6611         Kind = CK_AnyPointerToBlockPointerCast;
6612         return Compatible;
6613       }
6614 
6615     return Incompatible;
6616   }
6617 
6618   // Conversions to Objective-C pointers.
6619   if (isa<ObjCObjectPointerType>(LHSType)) {
6620     // A* -> B*
6621     if (RHSType->isObjCObjectPointerType()) {
6622       Kind = CK_BitCast;
6623       Sema::AssignConvertType result =
6624         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6625       if (getLangOpts().ObjCAutoRefCount &&
6626           result == Compatible &&
6627           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6628         result = IncompatibleObjCWeakRef;
6629       return result;
6630     }
6631 
6632     // int or null -> A*
6633     if (RHSType->isIntegerType()) {
6634       Kind = CK_IntegralToPointer; // FIXME: null
6635       return IntToPointer;
6636     }
6637 
6638     // In general, C pointers are not compatible with ObjC object pointers,
6639     // with two exceptions:
6640     if (isa<PointerType>(RHSType)) {
6641       Kind = CK_CPointerToObjCPointerCast;
6642 
6643       //  - conversions from 'void*'
6644       if (RHSType->isVoidPointerType()) {
6645         return Compatible;
6646       }
6647 
6648       //  - conversions to 'Class' from its redefinition type
6649       if (LHSType->isObjCClassType() &&
6650           Context.hasSameType(RHSType,
6651                               Context.getObjCClassRedefinitionType())) {
6652         return Compatible;
6653       }
6654 
6655       return IncompatiblePointer;
6656     }
6657 
6658     // Only under strict condition T^ is compatible with an Objective-C pointer.
6659     if (RHSType->isBlockPointerType() &&
6660         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6661       maybeExtendBlockObject(*this, RHS);
6662       Kind = CK_BlockPointerToObjCPointerCast;
6663       return Compatible;
6664     }
6665 
6666     return Incompatible;
6667   }
6668 
6669   // Conversions from pointers that are not covered by the above.
6670   if (isa<PointerType>(RHSType)) {
6671     // T* -> _Bool
6672     if (LHSType == Context.BoolTy) {
6673       Kind = CK_PointerToBoolean;
6674       return Compatible;
6675     }
6676 
6677     // T* -> int
6678     if (LHSType->isIntegerType()) {
6679       Kind = CK_PointerToIntegral;
6680       return PointerToInt;
6681     }
6682 
6683     return Incompatible;
6684   }
6685 
6686   // Conversions from Objective-C pointers that are not covered by the above.
6687   if (isa<ObjCObjectPointerType>(RHSType)) {
6688     // T* -> _Bool
6689     if (LHSType == Context.BoolTy) {
6690       Kind = CK_PointerToBoolean;
6691       return Compatible;
6692     }
6693 
6694     // T* -> int
6695     if (LHSType->isIntegerType()) {
6696       Kind = CK_PointerToIntegral;
6697       return PointerToInt;
6698     }
6699 
6700     return Incompatible;
6701   }
6702 
6703   // struct A -> struct B
6704   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6705     if (Context.typesAreCompatible(LHSType, RHSType)) {
6706       Kind = CK_NoOp;
6707       return Compatible;
6708     }
6709   }
6710 
6711   return Incompatible;
6712 }
6713 
6714 /// \brief Constructs a transparent union from an expression that is
6715 /// used to initialize the transparent union.
6716 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6717                                       ExprResult &EResult, QualType UnionType,
6718                                       FieldDecl *Field) {
6719   // Build an initializer list that designates the appropriate member
6720   // of the transparent union.
6721   Expr *E = EResult.get();
6722   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6723                                                    E, SourceLocation());
6724   Initializer->setType(UnionType);
6725   Initializer->setInitializedFieldInUnion(Field);
6726 
6727   // Build a compound literal constructing a value of the transparent
6728   // union type from this initializer list.
6729   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6730   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6731                                         VK_RValue, Initializer, false);
6732 }
6733 
6734 Sema::AssignConvertType
6735 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6736                                                ExprResult &RHS) {
6737   QualType RHSType = RHS.get()->getType();
6738 
6739   // If the ArgType is a Union type, we want to handle a potential
6740   // transparent_union GCC extension.
6741   const RecordType *UT = ArgType->getAsUnionType();
6742   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6743     return Incompatible;
6744 
6745   // The field to initialize within the transparent union.
6746   RecordDecl *UD = UT->getDecl();
6747   FieldDecl *InitField = nullptr;
6748   // It's compatible if the expression matches any of the fields.
6749   for (auto *it : UD->fields()) {
6750     if (it->getType()->isPointerType()) {
6751       // If the transparent union contains a pointer type, we allow:
6752       // 1) void pointer
6753       // 2) null pointer constant
6754       if (RHSType->isPointerType())
6755         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6756           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6757           InitField = it;
6758           break;
6759         }
6760 
6761       if (RHS.get()->isNullPointerConstant(Context,
6762                                            Expr::NPC_ValueDependentIsNull)) {
6763         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6764                                 CK_NullToPointer);
6765         InitField = it;
6766         break;
6767       }
6768     }
6769 
6770     CastKind Kind = CK_Invalid;
6771     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6772           == Compatible) {
6773       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6774       InitField = it;
6775       break;
6776     }
6777   }
6778 
6779   if (!InitField)
6780     return Incompatible;
6781 
6782   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6783   return Compatible;
6784 }
6785 
6786 Sema::AssignConvertType
6787 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6788                                        bool Diagnose,
6789                                        bool DiagnoseCFAudited) {
6790   if (getLangOpts().CPlusPlus) {
6791     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6792       // C++ 5.17p3: If the left operand is not of class type, the
6793       // expression is implicitly converted (C++ 4) to the
6794       // cv-unqualified type of the left operand.
6795       ExprResult Res;
6796       if (Diagnose) {
6797         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6798                                         AA_Assigning);
6799       } else {
6800         ImplicitConversionSequence ICS =
6801             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6802                                   /*SuppressUserConversions=*/false,
6803                                   /*AllowExplicit=*/false,
6804                                   /*InOverloadResolution=*/false,
6805                                   /*CStyle=*/false,
6806                                   /*AllowObjCWritebackConversion=*/false);
6807         if (ICS.isFailure())
6808           return Incompatible;
6809         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6810                                         ICS, AA_Assigning);
6811       }
6812       if (Res.isInvalid())
6813         return Incompatible;
6814       Sema::AssignConvertType result = Compatible;
6815       if (getLangOpts().ObjCAutoRefCount &&
6816           !CheckObjCARCUnavailableWeakConversion(LHSType,
6817                                                  RHS.get()->getType()))
6818         result = IncompatibleObjCWeakRef;
6819       RHS = Res;
6820       return result;
6821     }
6822 
6823     // FIXME: Currently, we fall through and treat C++ classes like C
6824     // structures.
6825     // FIXME: We also fall through for atomics; not sure what should
6826     // happen there, though.
6827   }
6828 
6829   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6830   // a null pointer constant.
6831   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6832        LHSType->isBlockPointerType()) &&
6833       RHS.get()->isNullPointerConstant(Context,
6834                                        Expr::NPC_ValueDependentIsNull)) {
6835     CastKind Kind;
6836     CXXCastPath Path;
6837     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6838     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6839     return Compatible;
6840   }
6841 
6842   // This check seems unnatural, however it is necessary to ensure the proper
6843   // conversion of functions/arrays. If the conversion were done for all
6844   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6845   // expressions that suppress this implicit conversion (&, sizeof).
6846   //
6847   // Suppress this for references: C++ 8.5.3p5.
6848   if (!LHSType->isReferenceType()) {
6849     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6850     if (RHS.isInvalid())
6851       return Incompatible;
6852   }
6853 
6854   Expr *PRE = RHS.get()->IgnoreParenCasts();
6855   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
6856     ObjCProtocolDecl *PDecl = OPE->getProtocol();
6857     if (PDecl && !PDecl->hasDefinition()) {
6858       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
6859       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
6860     }
6861   }
6862 
6863   CastKind Kind = CK_Invalid;
6864   Sema::AssignConvertType result =
6865     CheckAssignmentConstraints(LHSType, RHS, Kind);
6866 
6867   // C99 6.5.16.1p2: The value of the right operand is converted to the
6868   // type of the assignment expression.
6869   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6870   // so that we can use references in built-in functions even in C.
6871   // The getNonReferenceType() call makes sure that the resulting expression
6872   // does not have reference type.
6873   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6874     QualType Ty = LHSType.getNonLValueExprType(Context);
6875     Expr *E = RHS.get();
6876     if (getLangOpts().ObjCAutoRefCount)
6877       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6878                              DiagnoseCFAudited);
6879     if (getLangOpts().ObjC1 &&
6880         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6881                                           LHSType, E->getType(), E) ||
6882          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6883       RHS = E;
6884       return Compatible;
6885     }
6886 
6887     RHS = ImpCastExprToType(E, Ty, Kind);
6888   }
6889   return result;
6890 }
6891 
6892 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6893                                ExprResult &RHS) {
6894   Diag(Loc, diag::err_typecheck_invalid_operands)
6895     << LHS.get()->getType() << RHS.get()->getType()
6896     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6897   return QualType();
6898 }
6899 
6900 /// Try to convert a value of non-vector type to a vector type by converting
6901 /// the type to the element type of the vector and then performing a splat.
6902 /// If the language is OpenCL, we only use conversions that promote scalar
6903 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6904 /// for float->int.
6905 ///
6906 /// \param scalar - if non-null, actually perform the conversions
6907 /// \return true if the operation fails (but without diagnosing the failure)
6908 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6909                                      QualType scalarTy,
6910                                      QualType vectorEltTy,
6911                                      QualType vectorTy) {
6912   // The conversion to apply to the scalar before splatting it,
6913   // if necessary.
6914   CastKind scalarCast = CK_Invalid;
6915 
6916   if (vectorEltTy->isIntegralType(S.Context)) {
6917     if (!scalarTy->isIntegralType(S.Context))
6918       return true;
6919     if (S.getLangOpts().OpenCL &&
6920         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6921       return true;
6922     scalarCast = CK_IntegralCast;
6923   } else if (vectorEltTy->isRealFloatingType()) {
6924     if (scalarTy->isRealFloatingType()) {
6925       if (S.getLangOpts().OpenCL &&
6926           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6927         return true;
6928       scalarCast = CK_FloatingCast;
6929     }
6930     else if (scalarTy->isIntegralType(S.Context))
6931       scalarCast = CK_IntegralToFloating;
6932     else
6933       return true;
6934   } else {
6935     return true;
6936   }
6937 
6938   // Adjust scalar if desired.
6939   if (scalar) {
6940     if (scalarCast != CK_Invalid)
6941       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6942     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6943   }
6944   return false;
6945 }
6946 
6947 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6948                                    SourceLocation Loc, bool IsCompAssign) {
6949   if (!IsCompAssign) {
6950     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6951     if (LHS.isInvalid())
6952       return QualType();
6953   }
6954   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6955   if (RHS.isInvalid())
6956     return QualType();
6957 
6958   // For conversion purposes, we ignore any qualifiers.
6959   // For example, "const float" and "float" are equivalent.
6960   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6961   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6962 
6963   // If the vector types are identical, return.
6964   if (Context.hasSameType(LHSType, RHSType))
6965     return LHSType;
6966 
6967   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6968   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6969   assert(LHSVecType || RHSVecType);
6970 
6971   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6972   if (LHSVecType && RHSVecType &&
6973       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6974     if (isa<ExtVectorType>(LHSVecType)) {
6975       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6976       return LHSType;
6977     }
6978 
6979     if (!IsCompAssign)
6980       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6981     return RHSType;
6982   }
6983 
6984   // If there's an ext-vector type and a scalar, try to convert the scalar to
6985   // the vector element type and splat.
6986   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6987     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6988                                   LHSVecType->getElementType(), LHSType))
6989       return LHSType;
6990   }
6991   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6992     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6993                                   LHSType, RHSVecType->getElementType(),
6994                                   RHSType))
6995       return RHSType;
6996   }
6997 
6998   // If we're allowing lax vector conversions, only the total (data) size
6999   // needs to be the same.
7000   // FIXME: Should we really be allowing this?
7001   // FIXME: We really just pick the LHS type arbitrarily?
7002   if (isLaxVectorConversion(RHSType, LHSType)) {
7003     QualType resultType = LHSType;
7004     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7005     return resultType;
7006   }
7007 
7008   // Okay, the expression is invalid.
7009 
7010   // If there's a non-vector, non-real operand, diagnose that.
7011   if ((!RHSVecType && !RHSType->isRealType()) ||
7012       (!LHSVecType && !LHSType->isRealType())) {
7013     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7014       << LHSType << RHSType
7015       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7016     return QualType();
7017   }
7018 
7019   // Otherwise, use the generic diagnostic.
7020   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7021     << LHSType << RHSType
7022     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7023   return QualType();
7024 }
7025 
7026 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7027 // expression.  These are mainly cases where the null pointer is used as an
7028 // integer instead of a pointer.
7029 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7030                                 SourceLocation Loc, bool IsCompare) {
7031   // The canonical way to check for a GNU null is with isNullPointerConstant,
7032   // but we use a bit of a hack here for speed; this is a relatively
7033   // hot path, and isNullPointerConstant is slow.
7034   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7035   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7036 
7037   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7038 
7039   // Avoid analyzing cases where the result will either be invalid (and
7040   // diagnosed as such) or entirely valid and not something to warn about.
7041   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7042       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7043     return;
7044 
7045   // Comparison operations would not make sense with a null pointer no matter
7046   // what the other expression is.
7047   if (!IsCompare) {
7048     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7049         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7050         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7051     return;
7052   }
7053 
7054   // The rest of the operations only make sense with a null pointer
7055   // if the other expression is a pointer.
7056   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7057       NonNullType->canDecayToPointerType())
7058     return;
7059 
7060   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7061       << LHSNull /* LHS is NULL */ << NonNullType
7062       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7063 }
7064 
7065 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7066                                            SourceLocation Loc,
7067                                            bool IsCompAssign, bool IsDiv) {
7068   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7069 
7070   if (LHS.get()->getType()->isVectorType() ||
7071       RHS.get()->getType()->isVectorType())
7072     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7073 
7074   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7075   if (LHS.isInvalid() || RHS.isInvalid())
7076     return QualType();
7077 
7078 
7079   if (compType.isNull() || !compType->isArithmeticType())
7080     return InvalidOperands(Loc, LHS, RHS);
7081 
7082   // Check for division by zero.
7083   llvm::APSInt RHSValue;
7084   if (IsDiv && !RHS.get()->isValueDependent() &&
7085       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7086     DiagRuntimeBehavior(Loc, RHS.get(),
7087                         PDiag(diag::warn_division_by_zero)
7088                           << RHS.get()->getSourceRange());
7089 
7090   return compType;
7091 }
7092 
7093 QualType Sema::CheckRemainderOperands(
7094   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7095   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7096 
7097   if (LHS.get()->getType()->isVectorType() ||
7098       RHS.get()->getType()->isVectorType()) {
7099     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7100         RHS.get()->getType()->hasIntegerRepresentation())
7101       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7102     return InvalidOperands(Loc, LHS, RHS);
7103   }
7104 
7105   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7106   if (LHS.isInvalid() || RHS.isInvalid())
7107     return QualType();
7108 
7109   if (compType.isNull() || !compType->isIntegerType())
7110     return InvalidOperands(Loc, LHS, RHS);
7111 
7112   // Check for remainder by zero.
7113   llvm::APSInt RHSValue;
7114   if (!RHS.get()->isValueDependent() &&
7115       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7116     DiagRuntimeBehavior(Loc, RHS.get(),
7117                         PDiag(diag::warn_remainder_by_zero)
7118                           << RHS.get()->getSourceRange());
7119 
7120   return compType;
7121 }
7122 
7123 /// \brief Diagnose invalid arithmetic on two void pointers.
7124 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7125                                                 Expr *LHSExpr, Expr *RHSExpr) {
7126   S.Diag(Loc, S.getLangOpts().CPlusPlus
7127                 ? diag::err_typecheck_pointer_arith_void_type
7128                 : diag::ext_gnu_void_ptr)
7129     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7130                             << RHSExpr->getSourceRange();
7131 }
7132 
7133 /// \brief Diagnose invalid arithmetic on a void pointer.
7134 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7135                                             Expr *Pointer) {
7136   S.Diag(Loc, S.getLangOpts().CPlusPlus
7137                 ? diag::err_typecheck_pointer_arith_void_type
7138                 : diag::ext_gnu_void_ptr)
7139     << 0 /* one pointer */ << Pointer->getSourceRange();
7140 }
7141 
7142 /// \brief Diagnose invalid arithmetic on two function pointers.
7143 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7144                                                     Expr *LHS, Expr *RHS) {
7145   assert(LHS->getType()->isAnyPointerType());
7146   assert(RHS->getType()->isAnyPointerType());
7147   S.Diag(Loc, S.getLangOpts().CPlusPlus
7148                 ? diag::err_typecheck_pointer_arith_function_type
7149                 : diag::ext_gnu_ptr_func_arith)
7150     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7151     // We only show the second type if it differs from the first.
7152     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7153                                                    RHS->getType())
7154     << RHS->getType()->getPointeeType()
7155     << LHS->getSourceRange() << RHS->getSourceRange();
7156 }
7157 
7158 /// \brief Diagnose invalid arithmetic on a function pointer.
7159 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7160                                                 Expr *Pointer) {
7161   assert(Pointer->getType()->isAnyPointerType());
7162   S.Diag(Loc, S.getLangOpts().CPlusPlus
7163                 ? diag::err_typecheck_pointer_arith_function_type
7164                 : diag::ext_gnu_ptr_func_arith)
7165     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7166     << 0 /* one pointer, so only one type */
7167     << Pointer->getSourceRange();
7168 }
7169 
7170 /// \brief Emit error if Operand is incomplete pointer type
7171 ///
7172 /// \returns True if pointer has incomplete type
7173 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7174                                                  Expr *Operand) {
7175   assert(Operand->getType()->isAnyPointerType() &&
7176          !Operand->getType()->isDependentType());
7177   QualType PointeeTy = Operand->getType()->getPointeeType();
7178   return S.RequireCompleteType(Loc, PointeeTy,
7179                                diag::err_typecheck_arithmetic_incomplete_type,
7180                                PointeeTy, Operand->getSourceRange());
7181 }
7182 
7183 /// \brief Check the validity of an arithmetic pointer operand.
7184 ///
7185 /// If the operand has pointer type, this code will check for pointer types
7186 /// which are invalid in arithmetic operations. These will be diagnosed
7187 /// appropriately, including whether or not the use is supported as an
7188 /// extension.
7189 ///
7190 /// \returns True when the operand is valid to use (even if as an extension).
7191 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7192                                             Expr *Operand) {
7193   if (!Operand->getType()->isAnyPointerType()) return true;
7194 
7195   QualType PointeeTy = Operand->getType()->getPointeeType();
7196   if (PointeeTy->isVoidType()) {
7197     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7198     return !S.getLangOpts().CPlusPlus;
7199   }
7200   if (PointeeTy->isFunctionType()) {
7201     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7202     return !S.getLangOpts().CPlusPlus;
7203   }
7204 
7205   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7206 
7207   return true;
7208 }
7209 
7210 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7211 /// operands.
7212 ///
7213 /// This routine will diagnose any invalid arithmetic on pointer operands much
7214 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7215 /// for emitting a single diagnostic even for operations where both LHS and RHS
7216 /// are (potentially problematic) pointers.
7217 ///
7218 /// \returns True when the operand is valid to use (even if as an extension).
7219 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7220                                                 Expr *LHSExpr, Expr *RHSExpr) {
7221   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7222   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7223   if (!isLHSPointer && !isRHSPointer) return true;
7224 
7225   QualType LHSPointeeTy, RHSPointeeTy;
7226   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7227   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7228 
7229   // if both are pointers check if operation is valid wrt address spaces
7230   if (isLHSPointer && isRHSPointer) {
7231     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7232     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7233     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7234       S.Diag(Loc,
7235              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7236           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7237           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7238       return false;
7239     }
7240   }
7241 
7242   // Check for arithmetic on pointers to incomplete types.
7243   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7244   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7245   if (isLHSVoidPtr || isRHSVoidPtr) {
7246     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7247     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7248     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7249 
7250     return !S.getLangOpts().CPlusPlus;
7251   }
7252 
7253   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7254   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7255   if (isLHSFuncPtr || isRHSFuncPtr) {
7256     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7257     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7258                                                                 RHSExpr);
7259     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7260 
7261     return !S.getLangOpts().CPlusPlus;
7262   }
7263 
7264   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7265     return false;
7266   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7267     return false;
7268 
7269   return true;
7270 }
7271 
7272 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7273 /// literal.
7274 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7275                                   Expr *LHSExpr, Expr *RHSExpr) {
7276   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7277   Expr* IndexExpr = RHSExpr;
7278   if (!StrExpr) {
7279     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7280     IndexExpr = LHSExpr;
7281   }
7282 
7283   bool IsStringPlusInt = StrExpr &&
7284       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7285   if (!IsStringPlusInt)
7286     return;
7287 
7288   llvm::APSInt index;
7289   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7290     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7291     if (index.isNonNegative() &&
7292         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7293                               index.isUnsigned()))
7294       return;
7295   }
7296 
7297   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7298   Self.Diag(OpLoc, diag::warn_string_plus_int)
7299       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7300 
7301   // Only print a fixit for "str" + int, not for int + "str".
7302   if (IndexExpr == RHSExpr) {
7303     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7304     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7305         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7306         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7307         << FixItHint::CreateInsertion(EndLoc, "]");
7308   } else
7309     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7310 }
7311 
7312 /// \brief Emit a warning when adding a char literal to a string.
7313 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7314                                    Expr *LHSExpr, Expr *RHSExpr) {
7315   const DeclRefExpr *StringRefExpr =
7316       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7317   const CharacterLiteral *CharExpr =
7318       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7319   if (!StringRefExpr) {
7320     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7321     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7322   }
7323 
7324   if (!CharExpr || !StringRefExpr)
7325     return;
7326 
7327   const QualType StringType = StringRefExpr->getType();
7328 
7329   // Return if not a PointerType.
7330   if (!StringType->isAnyPointerType())
7331     return;
7332 
7333   // Return if not a CharacterType.
7334   if (!StringType->getPointeeType()->isAnyCharacterType())
7335     return;
7336 
7337   ASTContext &Ctx = Self.getASTContext();
7338   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7339 
7340   const QualType CharType = CharExpr->getType();
7341   if (!CharType->isAnyCharacterType() &&
7342       CharType->isIntegerType() &&
7343       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7344     Self.Diag(OpLoc, diag::warn_string_plus_char)
7345         << DiagRange << Ctx.CharTy;
7346   } else {
7347     Self.Diag(OpLoc, diag::warn_string_plus_char)
7348         << DiagRange << CharExpr->getType();
7349   }
7350 
7351   // Only print a fixit for str + char, not for char + str.
7352   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7353     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7354     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7355         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7356         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7357         << FixItHint::CreateInsertion(EndLoc, "]");
7358   } else {
7359     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7360   }
7361 }
7362 
7363 /// \brief Emit error when two pointers are incompatible.
7364 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7365                                            Expr *LHSExpr, Expr *RHSExpr) {
7366   assert(LHSExpr->getType()->isAnyPointerType());
7367   assert(RHSExpr->getType()->isAnyPointerType());
7368   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7369     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7370     << RHSExpr->getSourceRange();
7371 }
7372 
7373 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7374     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7375     QualType* CompLHSTy) {
7376   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7377 
7378   if (LHS.get()->getType()->isVectorType() ||
7379       RHS.get()->getType()->isVectorType()) {
7380     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7381     if (CompLHSTy) *CompLHSTy = compType;
7382     return compType;
7383   }
7384 
7385   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7386   if (LHS.isInvalid() || RHS.isInvalid())
7387     return QualType();
7388 
7389   // Diagnose "string literal" '+' int and string '+' "char literal".
7390   if (Opc == BO_Add) {
7391     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7392     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7393   }
7394 
7395   // handle the common case first (both operands are arithmetic).
7396   if (!compType.isNull() && compType->isArithmeticType()) {
7397     if (CompLHSTy) *CompLHSTy = compType;
7398     return compType;
7399   }
7400 
7401   // Type-checking.  Ultimately the pointer's going to be in PExp;
7402   // note that we bias towards the LHS being the pointer.
7403   Expr *PExp = LHS.get(), *IExp = RHS.get();
7404 
7405   bool isObjCPointer;
7406   if (PExp->getType()->isPointerType()) {
7407     isObjCPointer = false;
7408   } else if (PExp->getType()->isObjCObjectPointerType()) {
7409     isObjCPointer = true;
7410   } else {
7411     std::swap(PExp, IExp);
7412     if (PExp->getType()->isPointerType()) {
7413       isObjCPointer = false;
7414     } else if (PExp->getType()->isObjCObjectPointerType()) {
7415       isObjCPointer = true;
7416     } else {
7417       return InvalidOperands(Loc, LHS, RHS);
7418     }
7419   }
7420   assert(PExp->getType()->isAnyPointerType());
7421 
7422   if (!IExp->getType()->isIntegerType())
7423     return InvalidOperands(Loc, LHS, RHS);
7424 
7425   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7426     return QualType();
7427 
7428   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7429     return QualType();
7430 
7431   // Check array bounds for pointer arithemtic
7432   CheckArrayAccess(PExp, IExp);
7433 
7434   if (CompLHSTy) {
7435     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7436     if (LHSTy.isNull()) {
7437       LHSTy = LHS.get()->getType();
7438       if (LHSTy->isPromotableIntegerType())
7439         LHSTy = Context.getPromotedIntegerType(LHSTy);
7440     }
7441     *CompLHSTy = LHSTy;
7442   }
7443 
7444   return PExp->getType();
7445 }
7446 
7447 // C99 6.5.6
7448 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7449                                         SourceLocation Loc,
7450                                         QualType* CompLHSTy) {
7451   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7452 
7453   if (LHS.get()->getType()->isVectorType() ||
7454       RHS.get()->getType()->isVectorType()) {
7455     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7456     if (CompLHSTy) *CompLHSTy = compType;
7457     return compType;
7458   }
7459 
7460   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7461   if (LHS.isInvalid() || RHS.isInvalid())
7462     return QualType();
7463 
7464   // Enforce type constraints: C99 6.5.6p3.
7465 
7466   // Handle the common case first (both operands are arithmetic).
7467   if (!compType.isNull() && compType->isArithmeticType()) {
7468     if (CompLHSTy) *CompLHSTy = compType;
7469     return compType;
7470   }
7471 
7472   // Either ptr - int   or   ptr - ptr.
7473   if (LHS.get()->getType()->isAnyPointerType()) {
7474     QualType lpointee = LHS.get()->getType()->getPointeeType();
7475 
7476     // Diagnose bad cases where we step over interface counts.
7477     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7478         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7479       return QualType();
7480 
7481     // The result type of a pointer-int computation is the pointer type.
7482     if (RHS.get()->getType()->isIntegerType()) {
7483       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7484         return QualType();
7485 
7486       // Check array bounds for pointer arithemtic
7487       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7488                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7489 
7490       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7491       return LHS.get()->getType();
7492     }
7493 
7494     // Handle pointer-pointer subtractions.
7495     if (const PointerType *RHSPTy
7496           = RHS.get()->getType()->getAs<PointerType>()) {
7497       QualType rpointee = RHSPTy->getPointeeType();
7498 
7499       if (getLangOpts().CPlusPlus) {
7500         // Pointee types must be the same: C++ [expr.add]
7501         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7502           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7503         }
7504       } else {
7505         // Pointee types must be compatible C99 6.5.6p3
7506         if (!Context.typesAreCompatible(
7507                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7508                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7509           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7510           return QualType();
7511         }
7512       }
7513 
7514       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7515                                                LHS.get(), RHS.get()))
7516         return QualType();
7517 
7518       // The pointee type may have zero size.  As an extension, a structure or
7519       // union may have zero size or an array may have zero length.  In this
7520       // case subtraction does not make sense.
7521       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7522         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7523         if (ElementSize.isZero()) {
7524           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7525             << rpointee.getUnqualifiedType()
7526             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7527         }
7528       }
7529 
7530       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7531       return Context.getPointerDiffType();
7532     }
7533   }
7534 
7535   return InvalidOperands(Loc, LHS, RHS);
7536 }
7537 
7538 static bool isScopedEnumerationType(QualType T) {
7539   if (const EnumType *ET = dyn_cast<EnumType>(T))
7540     return ET->getDecl()->isScoped();
7541   return false;
7542 }
7543 
7544 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7545                                    SourceLocation Loc, unsigned Opc,
7546                                    QualType LHSType) {
7547   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7548   // so skip remaining warnings as we don't want to modify values within Sema.
7549   if (S.getLangOpts().OpenCL)
7550     return;
7551 
7552   llvm::APSInt Right;
7553   // Check right/shifter operand
7554   if (RHS.get()->isValueDependent() ||
7555       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7556     return;
7557 
7558   if (Right.isNegative()) {
7559     S.DiagRuntimeBehavior(Loc, RHS.get(),
7560                           S.PDiag(diag::warn_shift_negative)
7561                             << RHS.get()->getSourceRange());
7562     return;
7563   }
7564   llvm::APInt LeftBits(Right.getBitWidth(),
7565                        S.Context.getTypeSize(LHS.get()->getType()));
7566   if (Right.uge(LeftBits)) {
7567     S.DiagRuntimeBehavior(Loc, RHS.get(),
7568                           S.PDiag(diag::warn_shift_gt_typewidth)
7569                             << RHS.get()->getSourceRange());
7570     return;
7571   }
7572   if (Opc != BO_Shl)
7573     return;
7574 
7575   // When left shifting an ICE which is signed, we can check for overflow which
7576   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7577   // integers have defined behavior modulo one more than the maximum value
7578   // representable in the result type, so never warn for those.
7579   llvm::APSInt Left;
7580   if (LHS.get()->isValueDependent() ||
7581       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7582       LHSType->hasUnsignedIntegerRepresentation())
7583     return;
7584   llvm::APInt ResultBits =
7585       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7586   if (LeftBits.uge(ResultBits))
7587     return;
7588   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7589   Result = Result.shl(Right);
7590 
7591   // Print the bit representation of the signed integer as an unsigned
7592   // hexadecimal number.
7593   SmallString<40> HexResult;
7594   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7595 
7596   // If we are only missing a sign bit, this is less likely to result in actual
7597   // bugs -- if the result is cast back to an unsigned type, it will have the
7598   // expected value. Thus we place this behind a different warning that can be
7599   // turned off separately if needed.
7600   if (LeftBits == ResultBits - 1) {
7601     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7602         << HexResult.str() << LHSType
7603         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7604     return;
7605   }
7606 
7607   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7608     << HexResult.str() << Result.getMinSignedBits() << LHSType
7609     << Left.getBitWidth() << LHS.get()->getSourceRange()
7610     << RHS.get()->getSourceRange();
7611 }
7612 
7613 // C99 6.5.7
7614 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7615                                   SourceLocation Loc, unsigned Opc,
7616                                   bool IsCompAssign) {
7617   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7618 
7619   // Vector shifts promote their scalar inputs to vector type.
7620   if (LHS.get()->getType()->isVectorType() ||
7621       RHS.get()->getType()->isVectorType())
7622     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7623 
7624   // Shifts don't perform usual arithmetic conversions, they just do integer
7625   // promotions on each operand. C99 6.5.7p3
7626 
7627   // For the LHS, do usual unary conversions, but then reset them away
7628   // if this is a compound assignment.
7629   ExprResult OldLHS = LHS;
7630   LHS = UsualUnaryConversions(LHS.get());
7631   if (LHS.isInvalid())
7632     return QualType();
7633   QualType LHSType = LHS.get()->getType();
7634   if (IsCompAssign) LHS = OldLHS;
7635 
7636   // The RHS is simpler.
7637   RHS = UsualUnaryConversions(RHS.get());
7638   if (RHS.isInvalid())
7639     return QualType();
7640   QualType RHSType = RHS.get()->getType();
7641 
7642   // C99 6.5.7p2: Each of the operands shall have integer type.
7643   if (!LHSType->hasIntegerRepresentation() ||
7644       !RHSType->hasIntegerRepresentation())
7645     return InvalidOperands(Loc, LHS, RHS);
7646 
7647   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7648   // hasIntegerRepresentation() above instead of this.
7649   if (isScopedEnumerationType(LHSType) ||
7650       isScopedEnumerationType(RHSType)) {
7651     return InvalidOperands(Loc, LHS, RHS);
7652   }
7653   // Sanity-check shift operands
7654   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7655 
7656   // "The type of the result is that of the promoted left operand."
7657   return LHSType;
7658 }
7659 
7660 static bool IsWithinTemplateSpecialization(Decl *D) {
7661   if (DeclContext *DC = D->getDeclContext()) {
7662     if (isa<ClassTemplateSpecializationDecl>(DC))
7663       return true;
7664     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7665       return FD->isFunctionTemplateSpecialization();
7666   }
7667   return false;
7668 }
7669 
7670 /// If two different enums are compared, raise a warning.
7671 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7672                                 Expr *RHS) {
7673   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7674   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7675 
7676   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7677   if (!LHSEnumType)
7678     return;
7679   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7680   if (!RHSEnumType)
7681     return;
7682 
7683   // Ignore anonymous enums.
7684   if (!LHSEnumType->getDecl()->getIdentifier())
7685     return;
7686   if (!RHSEnumType->getDecl()->getIdentifier())
7687     return;
7688 
7689   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7690     return;
7691 
7692   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7693       << LHSStrippedType << RHSStrippedType
7694       << LHS->getSourceRange() << RHS->getSourceRange();
7695 }
7696 
7697 /// \brief Diagnose bad pointer comparisons.
7698 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7699                                               ExprResult &LHS, ExprResult &RHS,
7700                                               bool IsError) {
7701   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7702                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7703     << LHS.get()->getType() << RHS.get()->getType()
7704     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7705 }
7706 
7707 /// \brief Returns false if the pointers are converted to a composite type,
7708 /// true otherwise.
7709 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7710                                            ExprResult &LHS, ExprResult &RHS) {
7711   // C++ [expr.rel]p2:
7712   //   [...] Pointer conversions (4.10) and qualification
7713   //   conversions (4.4) are performed on pointer operands (or on
7714   //   a pointer operand and a null pointer constant) to bring
7715   //   them to their composite pointer type. [...]
7716   //
7717   // C++ [expr.eq]p1 uses the same notion for (in)equality
7718   // comparisons of pointers.
7719 
7720   // C++ [expr.eq]p2:
7721   //   In addition, pointers to members can be compared, or a pointer to
7722   //   member and a null pointer constant. Pointer to member conversions
7723   //   (4.11) and qualification conversions (4.4) are performed to bring
7724   //   them to a common type. If one operand is a null pointer constant,
7725   //   the common type is the type of the other operand. Otherwise, the
7726   //   common type is a pointer to member type similar (4.4) to the type
7727   //   of one of the operands, with a cv-qualification signature (4.4)
7728   //   that is the union of the cv-qualification signatures of the operand
7729   //   types.
7730 
7731   QualType LHSType = LHS.get()->getType();
7732   QualType RHSType = RHS.get()->getType();
7733   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7734          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7735 
7736   bool NonStandardCompositeType = false;
7737   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7738   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7739   if (T.isNull()) {
7740     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7741     return true;
7742   }
7743 
7744   if (NonStandardCompositeType)
7745     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7746       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7747       << RHS.get()->getSourceRange();
7748 
7749   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7750   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7751   return false;
7752 }
7753 
7754 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7755                                                     ExprResult &LHS,
7756                                                     ExprResult &RHS,
7757                                                     bool IsError) {
7758   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7759                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7760     << LHS.get()->getType() << RHS.get()->getType()
7761     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7762 }
7763 
7764 static bool isObjCObjectLiteral(ExprResult &E) {
7765   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7766   case Stmt::ObjCArrayLiteralClass:
7767   case Stmt::ObjCDictionaryLiteralClass:
7768   case Stmt::ObjCStringLiteralClass:
7769   case Stmt::ObjCBoxedExprClass:
7770     return true;
7771   default:
7772     // Note that ObjCBoolLiteral is NOT an object literal!
7773     return false;
7774   }
7775 }
7776 
7777 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7778   const ObjCObjectPointerType *Type =
7779     LHS->getType()->getAs<ObjCObjectPointerType>();
7780 
7781   // If this is not actually an Objective-C object, bail out.
7782   if (!Type)
7783     return false;
7784 
7785   // Get the LHS object's interface type.
7786   QualType InterfaceType = Type->getPointeeType();
7787   if (const ObjCObjectType *iQFaceTy =
7788       InterfaceType->getAsObjCQualifiedInterfaceType())
7789     InterfaceType = iQFaceTy->getBaseType();
7790 
7791   // If the RHS isn't an Objective-C object, bail out.
7792   if (!RHS->getType()->isObjCObjectPointerType())
7793     return false;
7794 
7795   // Try to find the -isEqual: method.
7796   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7797   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7798                                                       InterfaceType,
7799                                                       /*instance=*/true);
7800   if (!Method) {
7801     if (Type->isObjCIdType()) {
7802       // For 'id', just check the global pool.
7803       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7804                                                   /*receiverId=*/true,
7805                                                   /*warn=*/false);
7806     } else {
7807       // Check protocols.
7808       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7809                                              /*instance=*/true);
7810     }
7811   }
7812 
7813   if (!Method)
7814     return false;
7815 
7816   QualType T = Method->parameters()[0]->getType();
7817   if (!T->isObjCObjectPointerType())
7818     return false;
7819 
7820   QualType R = Method->getReturnType();
7821   if (!R->isScalarType())
7822     return false;
7823 
7824   return true;
7825 }
7826 
7827 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7828   FromE = FromE->IgnoreParenImpCasts();
7829   switch (FromE->getStmtClass()) {
7830     default:
7831       break;
7832     case Stmt::ObjCStringLiteralClass:
7833       // "string literal"
7834       return LK_String;
7835     case Stmt::ObjCArrayLiteralClass:
7836       // "array literal"
7837       return LK_Array;
7838     case Stmt::ObjCDictionaryLiteralClass:
7839       // "dictionary literal"
7840       return LK_Dictionary;
7841     case Stmt::BlockExprClass:
7842       return LK_Block;
7843     case Stmt::ObjCBoxedExprClass: {
7844       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7845       switch (Inner->getStmtClass()) {
7846         case Stmt::IntegerLiteralClass:
7847         case Stmt::FloatingLiteralClass:
7848         case Stmt::CharacterLiteralClass:
7849         case Stmt::ObjCBoolLiteralExprClass:
7850         case Stmt::CXXBoolLiteralExprClass:
7851           // "numeric literal"
7852           return LK_Numeric;
7853         case Stmt::ImplicitCastExprClass: {
7854           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7855           // Boolean literals can be represented by implicit casts.
7856           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7857             return LK_Numeric;
7858           break;
7859         }
7860         default:
7861           break;
7862       }
7863       return LK_Boxed;
7864     }
7865   }
7866   return LK_None;
7867 }
7868 
7869 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7870                                           ExprResult &LHS, ExprResult &RHS,
7871                                           BinaryOperator::Opcode Opc){
7872   Expr *Literal;
7873   Expr *Other;
7874   if (isObjCObjectLiteral(LHS)) {
7875     Literal = LHS.get();
7876     Other = RHS.get();
7877   } else {
7878     Literal = RHS.get();
7879     Other = LHS.get();
7880   }
7881 
7882   // Don't warn on comparisons against nil.
7883   Other = Other->IgnoreParenCasts();
7884   if (Other->isNullPointerConstant(S.getASTContext(),
7885                                    Expr::NPC_ValueDependentIsNotNull))
7886     return;
7887 
7888   // This should be kept in sync with warn_objc_literal_comparison.
7889   // LK_String should always be after the other literals, since it has its own
7890   // warning flag.
7891   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7892   assert(LiteralKind != Sema::LK_Block);
7893   if (LiteralKind == Sema::LK_None) {
7894     llvm_unreachable("Unknown Objective-C object literal kind");
7895   }
7896 
7897   if (LiteralKind == Sema::LK_String)
7898     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7899       << Literal->getSourceRange();
7900   else
7901     S.Diag(Loc, diag::warn_objc_literal_comparison)
7902       << LiteralKind << Literal->getSourceRange();
7903 
7904   if (BinaryOperator::isEqualityOp(Opc) &&
7905       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7906     SourceLocation Start = LHS.get()->getLocStart();
7907     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7908     CharSourceRange OpRange =
7909       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7910 
7911     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7912       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7913       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7914       << FixItHint::CreateInsertion(End, "]");
7915   }
7916 }
7917 
7918 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7919                                                 ExprResult &RHS,
7920                                                 SourceLocation Loc,
7921                                                 unsigned OpaqueOpc) {
7922   // This checking requires bools.
7923   if (!S.getLangOpts().Bool) return;
7924 
7925   // Check that left hand side is !something.
7926   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7927   if (!UO || UO->getOpcode() != UO_LNot) return;
7928 
7929   // Only check if the right hand side is non-bool arithmetic type.
7930   if (RHS.get()->getType()->isBooleanType()) return;
7931 
7932   // Make sure that the something in !something is not bool.
7933   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7934   if (SubExpr->getType()->isBooleanType()) return;
7935 
7936   // Emit warning.
7937   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7938       << Loc;
7939 
7940   // First note suggest !(x < y)
7941   SourceLocation FirstOpen = SubExpr->getLocStart();
7942   SourceLocation FirstClose = RHS.get()->getLocEnd();
7943   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7944   if (FirstClose.isInvalid())
7945     FirstOpen = SourceLocation();
7946   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7947       << FixItHint::CreateInsertion(FirstOpen, "(")
7948       << FixItHint::CreateInsertion(FirstClose, ")");
7949 
7950   // Second note suggests (!x) < y
7951   SourceLocation SecondOpen = LHS.get()->getLocStart();
7952   SourceLocation SecondClose = LHS.get()->getLocEnd();
7953   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7954   if (SecondClose.isInvalid())
7955     SecondOpen = SourceLocation();
7956   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7957       << FixItHint::CreateInsertion(SecondOpen, "(")
7958       << FixItHint::CreateInsertion(SecondClose, ")");
7959 }
7960 
7961 // Get the decl for a simple expression: a reference to a variable,
7962 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7963 static ValueDecl *getCompareDecl(Expr *E) {
7964   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7965     return DR->getDecl();
7966   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7967     if (Ivar->isFreeIvar())
7968       return Ivar->getDecl();
7969   }
7970   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7971     if (Mem->isImplicitAccess())
7972       return Mem->getMemberDecl();
7973   }
7974   return nullptr;
7975 }
7976 
7977 // C99 6.5.8, C++ [expr.rel]
7978 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7979                                     SourceLocation Loc, unsigned OpaqueOpc,
7980                                     bool IsRelational) {
7981   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7982 
7983   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7984 
7985   // Handle vector comparisons separately.
7986   if (LHS.get()->getType()->isVectorType() ||
7987       RHS.get()->getType()->isVectorType())
7988     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7989 
7990   QualType LHSType = LHS.get()->getType();
7991   QualType RHSType = RHS.get()->getType();
7992 
7993   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7994   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7995 
7996   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7997   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7998 
7999   if (!LHSType->hasFloatingRepresentation() &&
8000       !(LHSType->isBlockPointerType() && IsRelational) &&
8001       !LHS.get()->getLocStart().isMacroID() &&
8002       !RHS.get()->getLocStart().isMacroID() &&
8003       ActiveTemplateInstantiations.empty()) {
8004     // For non-floating point types, check for self-comparisons of the form
8005     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8006     // often indicate logic errors in the program.
8007     //
8008     // NOTE: Don't warn about comparison expressions resulting from macro
8009     // expansion. Also don't warn about comparisons which are only self
8010     // comparisons within a template specialization. The warnings should catch
8011     // obvious cases in the definition of the template anyways. The idea is to
8012     // warn when the typed comparison operator will always evaluate to the same
8013     // result.
8014     ValueDecl *DL = getCompareDecl(LHSStripped);
8015     ValueDecl *DR = getCompareDecl(RHSStripped);
8016     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8017       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8018                           << 0 // self-
8019                           << (Opc == BO_EQ
8020                               || Opc == BO_LE
8021                               || Opc == BO_GE));
8022     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8023                !DL->getType()->isReferenceType() &&
8024                !DR->getType()->isReferenceType()) {
8025         // what is it always going to eval to?
8026         char always_evals_to;
8027         switch(Opc) {
8028         case BO_EQ: // e.g. array1 == array2
8029           always_evals_to = 0; // false
8030           break;
8031         case BO_NE: // e.g. array1 != array2
8032           always_evals_to = 1; // true
8033           break;
8034         default:
8035           // best we can say is 'a constant'
8036           always_evals_to = 2; // e.g. array1 <= array2
8037           break;
8038         }
8039         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8040                             << 1 // array
8041                             << always_evals_to);
8042     }
8043 
8044     if (isa<CastExpr>(LHSStripped))
8045       LHSStripped = LHSStripped->IgnoreParenCasts();
8046     if (isa<CastExpr>(RHSStripped))
8047       RHSStripped = RHSStripped->IgnoreParenCasts();
8048 
8049     // Warn about comparisons against a string constant (unless the other
8050     // operand is null), the user probably wants strcmp.
8051     Expr *literalString = nullptr;
8052     Expr *literalStringStripped = nullptr;
8053     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8054         !RHSStripped->isNullPointerConstant(Context,
8055                                             Expr::NPC_ValueDependentIsNull)) {
8056       literalString = LHS.get();
8057       literalStringStripped = LHSStripped;
8058     } else if ((isa<StringLiteral>(RHSStripped) ||
8059                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8060                !LHSStripped->isNullPointerConstant(Context,
8061                                             Expr::NPC_ValueDependentIsNull)) {
8062       literalString = RHS.get();
8063       literalStringStripped = RHSStripped;
8064     }
8065 
8066     if (literalString) {
8067       DiagRuntimeBehavior(Loc, nullptr,
8068         PDiag(diag::warn_stringcompare)
8069           << isa<ObjCEncodeExpr>(literalStringStripped)
8070           << literalString->getSourceRange());
8071     }
8072   }
8073 
8074   // C99 6.5.8p3 / C99 6.5.9p4
8075   UsualArithmeticConversions(LHS, RHS);
8076   if (LHS.isInvalid() || RHS.isInvalid())
8077     return QualType();
8078 
8079   LHSType = LHS.get()->getType();
8080   RHSType = RHS.get()->getType();
8081 
8082   // The result of comparisons is 'bool' in C++, 'int' in C.
8083   QualType ResultTy = Context.getLogicalOperationType();
8084 
8085   if (IsRelational) {
8086     if (LHSType->isRealType() && RHSType->isRealType())
8087       return ResultTy;
8088   } else {
8089     // Check for comparisons of floating point operands using != and ==.
8090     if (LHSType->hasFloatingRepresentation())
8091       CheckFloatComparison(Loc, LHS.get(), RHS.get());
8092 
8093     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8094       return ResultTy;
8095   }
8096 
8097   const Expr::NullPointerConstantKind LHSNullKind =
8098       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8099   const Expr::NullPointerConstantKind RHSNullKind =
8100       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8101   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8102   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8103 
8104   if (!IsRelational && LHSIsNull != RHSIsNull) {
8105     bool IsEquality = Opc == BO_EQ;
8106     if (RHSIsNull)
8107       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8108                                    RHS.get()->getSourceRange());
8109     else
8110       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8111                                    LHS.get()->getSourceRange());
8112   }
8113 
8114   // All of the following pointer-related warnings are GCC extensions, except
8115   // when handling null pointer constants.
8116   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8117     QualType LCanPointeeTy =
8118       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8119     QualType RCanPointeeTy =
8120       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8121 
8122     if (getLangOpts().CPlusPlus) {
8123       if (LCanPointeeTy == RCanPointeeTy)
8124         return ResultTy;
8125       if (!IsRelational &&
8126           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8127         // Valid unless comparison between non-null pointer and function pointer
8128         // This is a gcc extension compatibility comparison.
8129         // In a SFINAE context, we treat this as a hard error to maintain
8130         // conformance with the C++ standard.
8131         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8132             && !LHSIsNull && !RHSIsNull) {
8133           diagnoseFunctionPointerToVoidComparison(
8134               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8135 
8136           if (isSFINAEContext())
8137             return QualType();
8138 
8139           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8140           return ResultTy;
8141         }
8142       }
8143 
8144       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8145         return QualType();
8146       else
8147         return ResultTy;
8148     }
8149     // C99 6.5.9p2 and C99 6.5.8p2
8150     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8151                                    RCanPointeeTy.getUnqualifiedType())) {
8152       // Valid unless a relational comparison of function pointers
8153       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8154         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8155           << LHSType << RHSType << LHS.get()->getSourceRange()
8156           << RHS.get()->getSourceRange();
8157       }
8158     } else if (!IsRelational &&
8159                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8160       // Valid unless comparison between non-null pointer and function pointer
8161       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8162           && !LHSIsNull && !RHSIsNull)
8163         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8164                                                 /*isError*/false);
8165     } else {
8166       // Invalid
8167       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8168     }
8169     if (LCanPointeeTy != RCanPointeeTy) {
8170       const PointerType *lhsPtr = LHSType->getAs<PointerType>();
8171       if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8172         Diag(Loc,
8173              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8174             << LHSType << RHSType << 0 /* comparison */
8175             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8176       }
8177       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8178       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8179       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8180                                                : CK_BitCast;
8181       if (LHSIsNull && !RHSIsNull)
8182         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8183       else
8184         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8185     }
8186     return ResultTy;
8187   }
8188 
8189   if (getLangOpts().CPlusPlus) {
8190     // Comparison of nullptr_t with itself.
8191     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8192       return ResultTy;
8193 
8194     // Comparison of pointers with null pointer constants and equality
8195     // comparisons of member pointers to null pointer constants.
8196     if (RHSIsNull &&
8197         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8198          (!IsRelational &&
8199           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8200       RHS = ImpCastExprToType(RHS.get(), LHSType,
8201                         LHSType->isMemberPointerType()
8202                           ? CK_NullToMemberPointer
8203                           : CK_NullToPointer);
8204       return ResultTy;
8205     }
8206     if (LHSIsNull &&
8207         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8208          (!IsRelational &&
8209           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8210       LHS = ImpCastExprToType(LHS.get(), RHSType,
8211                         RHSType->isMemberPointerType()
8212                           ? CK_NullToMemberPointer
8213                           : CK_NullToPointer);
8214       return ResultTy;
8215     }
8216 
8217     // Comparison of member pointers.
8218     if (!IsRelational &&
8219         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8220       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8221         return QualType();
8222       else
8223         return ResultTy;
8224     }
8225 
8226     // Handle scoped enumeration types specifically, since they don't promote
8227     // to integers.
8228     if (LHS.get()->getType()->isEnumeralType() &&
8229         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8230                                        RHS.get()->getType()))
8231       return ResultTy;
8232   }
8233 
8234   // Handle block pointer types.
8235   if (!IsRelational && LHSType->isBlockPointerType() &&
8236       RHSType->isBlockPointerType()) {
8237     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8238     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8239 
8240     if (!LHSIsNull && !RHSIsNull &&
8241         !Context.typesAreCompatible(lpointee, rpointee)) {
8242       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8243         << LHSType << RHSType << LHS.get()->getSourceRange()
8244         << RHS.get()->getSourceRange();
8245     }
8246     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8247     return ResultTy;
8248   }
8249 
8250   // Allow block pointers to be compared with null pointer constants.
8251   if (!IsRelational
8252       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8253           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8254     if (!LHSIsNull && !RHSIsNull) {
8255       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8256              ->getPointeeType()->isVoidType())
8257             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8258                 ->getPointeeType()->isVoidType())))
8259         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8260           << LHSType << RHSType << LHS.get()->getSourceRange()
8261           << RHS.get()->getSourceRange();
8262     }
8263     if (LHSIsNull && !RHSIsNull)
8264       LHS = ImpCastExprToType(LHS.get(), RHSType,
8265                               RHSType->isPointerType() ? CK_BitCast
8266                                 : CK_AnyPointerToBlockPointerCast);
8267     else
8268       RHS = ImpCastExprToType(RHS.get(), LHSType,
8269                               LHSType->isPointerType() ? CK_BitCast
8270                                 : CK_AnyPointerToBlockPointerCast);
8271     return ResultTy;
8272   }
8273 
8274   if (LHSType->isObjCObjectPointerType() ||
8275       RHSType->isObjCObjectPointerType()) {
8276     const PointerType *LPT = LHSType->getAs<PointerType>();
8277     const PointerType *RPT = RHSType->getAs<PointerType>();
8278     if (LPT || RPT) {
8279       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8280       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8281 
8282       if (!LPtrToVoid && !RPtrToVoid &&
8283           !Context.typesAreCompatible(LHSType, RHSType)) {
8284         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8285                                           /*isError*/false);
8286       }
8287       if (LHSIsNull && !RHSIsNull) {
8288         Expr *E = LHS.get();
8289         if (getLangOpts().ObjCAutoRefCount)
8290           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8291         LHS = ImpCastExprToType(E, RHSType,
8292                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8293       }
8294       else {
8295         Expr *E = RHS.get();
8296         if (getLangOpts().ObjCAutoRefCount)
8297           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8298                                  Opc);
8299         RHS = ImpCastExprToType(E, LHSType,
8300                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8301       }
8302       return ResultTy;
8303     }
8304     if (LHSType->isObjCObjectPointerType() &&
8305         RHSType->isObjCObjectPointerType()) {
8306       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8307         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8308                                           /*isError*/false);
8309       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8310         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8311 
8312       if (LHSIsNull && !RHSIsNull)
8313         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8314       else
8315         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8316       return ResultTy;
8317     }
8318   }
8319   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8320       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8321     unsigned DiagID = 0;
8322     bool isError = false;
8323     if (LangOpts.DebuggerSupport) {
8324       // Under a debugger, allow the comparison of pointers to integers,
8325       // since users tend to want to compare addresses.
8326     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8327         (RHSIsNull && RHSType->isIntegerType())) {
8328       if (IsRelational && !getLangOpts().CPlusPlus)
8329         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8330     } else if (IsRelational && !getLangOpts().CPlusPlus)
8331       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8332     else if (getLangOpts().CPlusPlus) {
8333       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8334       isError = true;
8335     } else
8336       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8337 
8338     if (DiagID) {
8339       Diag(Loc, DiagID)
8340         << LHSType << RHSType << LHS.get()->getSourceRange()
8341         << RHS.get()->getSourceRange();
8342       if (isError)
8343         return QualType();
8344     }
8345 
8346     if (LHSType->isIntegerType())
8347       LHS = ImpCastExprToType(LHS.get(), RHSType,
8348                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8349     else
8350       RHS = ImpCastExprToType(RHS.get(), LHSType,
8351                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8352     return ResultTy;
8353   }
8354 
8355   // Handle block pointers.
8356   if (!IsRelational && RHSIsNull
8357       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8358     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8359     return ResultTy;
8360   }
8361   if (!IsRelational && LHSIsNull
8362       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8363     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8364     return ResultTy;
8365   }
8366 
8367   return InvalidOperands(Loc, LHS, RHS);
8368 }
8369 
8370 
8371 // Return a signed type that is of identical size and number of elements.
8372 // For floating point vectors, return an integer type of identical size
8373 // and number of elements.
8374 QualType Sema::GetSignedVectorType(QualType V) {
8375   const VectorType *VTy = V->getAs<VectorType>();
8376   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8377   if (TypeSize == Context.getTypeSize(Context.CharTy))
8378     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8379   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8380     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8381   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8382     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8383   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8384     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8385   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8386          "Unhandled vector element size in vector compare");
8387   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8388 }
8389 
8390 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8391 /// operates on extended vector types.  Instead of producing an IntTy result,
8392 /// like a scalar comparison, a vector comparison produces a vector of integer
8393 /// types.
8394 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8395                                           SourceLocation Loc,
8396                                           bool IsRelational) {
8397   // Check to make sure we're operating on vectors of the same type and width,
8398   // Allowing one side to be a scalar of element type.
8399   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8400   if (vType.isNull())
8401     return vType;
8402 
8403   QualType LHSType = LHS.get()->getType();
8404 
8405   // If AltiVec, the comparison results in a numeric type, i.e.
8406   // bool for C++, int for C
8407   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8408     return Context.getLogicalOperationType();
8409 
8410   // For non-floating point types, check for self-comparisons of the form
8411   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8412   // often indicate logic errors in the program.
8413   if (!LHSType->hasFloatingRepresentation() &&
8414       ActiveTemplateInstantiations.empty()) {
8415     if (DeclRefExpr* DRL
8416           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8417       if (DeclRefExpr* DRR
8418             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8419         if (DRL->getDecl() == DRR->getDecl())
8420           DiagRuntimeBehavior(Loc, nullptr,
8421                               PDiag(diag::warn_comparison_always)
8422                                 << 0 // self-
8423                                 << 2 // "a constant"
8424                               );
8425   }
8426 
8427   // Check for comparisons of floating point operands using != and ==.
8428   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8429     assert (RHS.get()->getType()->hasFloatingRepresentation());
8430     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8431   }
8432 
8433   // Return a signed type for the vector.
8434   return GetSignedVectorType(LHSType);
8435 }
8436 
8437 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8438                                           SourceLocation Loc) {
8439   // Ensure that either both operands are of the same vector type, or
8440   // one operand is of a vector type and the other is of its element type.
8441   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8442   if (vType.isNull())
8443     return InvalidOperands(Loc, LHS, RHS);
8444   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8445       vType->hasFloatingRepresentation())
8446     return InvalidOperands(Loc, LHS, RHS);
8447 
8448   return GetSignedVectorType(LHS.get()->getType());
8449 }
8450 
8451 inline QualType Sema::CheckBitwiseOperands(
8452   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8453   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8454 
8455   if (LHS.get()->getType()->isVectorType() ||
8456       RHS.get()->getType()->isVectorType()) {
8457     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8458         RHS.get()->getType()->hasIntegerRepresentation())
8459       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8460 
8461     return InvalidOperands(Loc, LHS, RHS);
8462   }
8463 
8464   ExprResult LHSResult = LHS, RHSResult = RHS;
8465   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8466                                                  IsCompAssign);
8467   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8468     return QualType();
8469   LHS = LHSResult.get();
8470   RHS = RHSResult.get();
8471 
8472   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8473     return compType;
8474   return InvalidOperands(Loc, LHS, RHS);
8475 }
8476 
8477 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8478   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8479 
8480   // Check vector operands differently.
8481   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8482     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8483 
8484   // Diagnose cases where the user write a logical and/or but probably meant a
8485   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8486   // is a constant.
8487   if (LHS.get()->getType()->isIntegerType() &&
8488       !LHS.get()->getType()->isBooleanType() &&
8489       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8490       // Don't warn in macros or template instantiations.
8491       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8492     // If the RHS can be constant folded, and if it constant folds to something
8493     // that isn't 0 or 1 (which indicate a potential logical operation that
8494     // happened to fold to true/false) then warn.
8495     // Parens on the RHS are ignored.
8496     llvm::APSInt Result;
8497     if (RHS.get()->EvaluateAsInt(Result, Context))
8498       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8499            !RHS.get()->getExprLoc().isMacroID()) ||
8500           (Result != 0 && Result != 1)) {
8501         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8502           << RHS.get()->getSourceRange()
8503           << (Opc == BO_LAnd ? "&&" : "||");
8504         // Suggest replacing the logical operator with the bitwise version
8505         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8506             << (Opc == BO_LAnd ? "&" : "|")
8507             << FixItHint::CreateReplacement(SourceRange(
8508                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8509                                                 getLangOpts())),
8510                                             Opc == BO_LAnd ? "&" : "|");
8511         if (Opc == BO_LAnd)
8512           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8513           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8514               << FixItHint::CreateRemoval(
8515                   SourceRange(
8516                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8517                                                  0, getSourceManager(),
8518                                                  getLangOpts()),
8519                       RHS.get()->getLocEnd()));
8520       }
8521   }
8522 
8523   if (!Context.getLangOpts().CPlusPlus) {
8524     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8525     // not operate on the built-in scalar and vector float types.
8526     if (Context.getLangOpts().OpenCL &&
8527         Context.getLangOpts().OpenCLVersion < 120) {
8528       if (LHS.get()->getType()->isFloatingType() ||
8529           RHS.get()->getType()->isFloatingType())
8530         return InvalidOperands(Loc, LHS, RHS);
8531     }
8532 
8533     LHS = UsualUnaryConversions(LHS.get());
8534     if (LHS.isInvalid())
8535       return QualType();
8536 
8537     RHS = UsualUnaryConversions(RHS.get());
8538     if (RHS.isInvalid())
8539       return QualType();
8540 
8541     if (!LHS.get()->getType()->isScalarType() ||
8542         !RHS.get()->getType()->isScalarType())
8543       return InvalidOperands(Loc, LHS, RHS);
8544 
8545     return Context.IntTy;
8546   }
8547 
8548   // The following is safe because we only use this method for
8549   // non-overloadable operands.
8550 
8551   // C++ [expr.log.and]p1
8552   // C++ [expr.log.or]p1
8553   // The operands are both contextually converted to type bool.
8554   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8555   if (LHSRes.isInvalid())
8556     return InvalidOperands(Loc, LHS, RHS);
8557   LHS = LHSRes;
8558 
8559   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8560   if (RHSRes.isInvalid())
8561     return InvalidOperands(Loc, LHS, RHS);
8562   RHS = RHSRes;
8563 
8564   // C++ [expr.log.and]p2
8565   // C++ [expr.log.or]p2
8566   // The result is a bool.
8567   return Context.BoolTy;
8568 }
8569 
8570 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8571   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8572   if (!ME) return false;
8573   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8574   ObjCMessageExpr *Base =
8575     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8576   if (!Base) return false;
8577   return Base->getMethodDecl() != nullptr;
8578 }
8579 
8580 /// Is the given expression (which must be 'const') a reference to a
8581 /// variable which was originally non-const, but which has become
8582 /// 'const' due to being captured within a block?
8583 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8584 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8585   assert(E->isLValue() && E->getType().isConstQualified());
8586   E = E->IgnoreParens();
8587 
8588   // Must be a reference to a declaration from an enclosing scope.
8589   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8590   if (!DRE) return NCCK_None;
8591   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8592 
8593   // The declaration must be a variable which is not declared 'const'.
8594   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8595   if (!var) return NCCK_None;
8596   if (var->getType().isConstQualified()) return NCCK_None;
8597   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8598 
8599   // Decide whether the first capture was for a block or a lambda.
8600   DeclContext *DC = S.CurContext, *Prev = nullptr;
8601   while (DC != var->getDeclContext()) {
8602     Prev = DC;
8603     DC = DC->getParent();
8604   }
8605   // Unless we have an init-capture, we've gone one step too far.
8606   if (!var->isInitCapture())
8607     DC = Prev;
8608   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8609 }
8610 
8611 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8612 /// emit an error and return true.  If so, return false.
8613 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8614   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8615   SourceLocation OrigLoc = Loc;
8616   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8617                                                               &Loc);
8618   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8619     IsLV = Expr::MLV_InvalidMessageExpression;
8620   if (IsLV == Expr::MLV_Valid)
8621     return false;
8622 
8623   unsigned Diag = 0;
8624   bool NeedType = false;
8625   switch (IsLV) { // C99 6.5.16p2
8626   case Expr::MLV_ConstQualified:
8627     Diag = diag::err_typecheck_assign_const;
8628 
8629     // Use a specialized diagnostic when we're assigning to an object
8630     // from an enclosing function or block.
8631     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8632       if (NCCK == NCCK_Block)
8633         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8634       else
8635         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8636       break;
8637     }
8638 
8639     // In ARC, use some specialized diagnostics for occasions where we
8640     // infer 'const'.  These are always pseudo-strong variables.
8641     if (S.getLangOpts().ObjCAutoRefCount) {
8642       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8643       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8644         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8645 
8646         // Use the normal diagnostic if it's pseudo-__strong but the
8647         // user actually wrote 'const'.
8648         if (var->isARCPseudoStrong() &&
8649             (!var->getTypeSourceInfo() ||
8650              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8651           // There are two pseudo-strong cases:
8652           //  - self
8653           ObjCMethodDecl *method = S.getCurMethodDecl();
8654           if (method && var == method->getSelfDecl())
8655             Diag = method->isClassMethod()
8656               ? diag::err_typecheck_arc_assign_self_class_method
8657               : diag::err_typecheck_arc_assign_self;
8658 
8659           //  - fast enumeration variables
8660           else
8661             Diag = diag::err_typecheck_arr_assign_enumeration;
8662 
8663           SourceRange Assign;
8664           if (Loc != OrigLoc)
8665             Assign = SourceRange(OrigLoc, OrigLoc);
8666           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8667           // We need to preserve the AST regardless, so migration tool
8668           // can do its job.
8669           return false;
8670         }
8671       }
8672     }
8673 
8674     break;
8675   case Expr::MLV_ArrayType:
8676   case Expr::MLV_ArrayTemporary:
8677     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8678     NeedType = true;
8679     break;
8680   case Expr::MLV_NotObjectType:
8681     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8682     NeedType = true;
8683     break;
8684   case Expr::MLV_LValueCast:
8685     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8686     break;
8687   case Expr::MLV_Valid:
8688     llvm_unreachable("did not take early return for MLV_Valid");
8689   case Expr::MLV_InvalidExpression:
8690   case Expr::MLV_MemberFunction:
8691   case Expr::MLV_ClassTemporary:
8692     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8693     break;
8694   case Expr::MLV_IncompleteType:
8695   case Expr::MLV_IncompleteVoidType:
8696     return S.RequireCompleteType(Loc, E->getType(),
8697              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8698   case Expr::MLV_DuplicateVectorComponents:
8699     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8700     break;
8701   case Expr::MLV_NoSetterProperty:
8702     llvm_unreachable("readonly properties should be processed differently");
8703   case Expr::MLV_InvalidMessageExpression:
8704     Diag = diag::error_readonly_message_assignment;
8705     break;
8706   case Expr::MLV_SubObjCPropertySetting:
8707     Diag = diag::error_no_subobject_property_setting;
8708     break;
8709   }
8710 
8711   SourceRange Assign;
8712   if (Loc != OrigLoc)
8713     Assign = SourceRange(OrigLoc, OrigLoc);
8714   if (NeedType)
8715     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8716   else
8717     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8718   return true;
8719 }
8720 
8721 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8722                                          SourceLocation Loc,
8723                                          Sema &Sema) {
8724   // C / C++ fields
8725   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8726   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8727   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8728     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8729       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8730   }
8731 
8732   // Objective-C instance variables
8733   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8734   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8735   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8736     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8737     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8738     if (RL && RR && RL->getDecl() == RR->getDecl())
8739       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8740   }
8741 }
8742 
8743 // C99 6.5.16.1
8744 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8745                                        SourceLocation Loc,
8746                                        QualType CompoundType) {
8747   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8748 
8749   // Verify that LHS is a modifiable lvalue, and emit error if not.
8750   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8751     return QualType();
8752 
8753   QualType LHSType = LHSExpr->getType();
8754   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8755                                              CompoundType;
8756   AssignConvertType ConvTy;
8757   if (CompoundType.isNull()) {
8758     Expr *RHSCheck = RHS.get();
8759 
8760     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8761 
8762     QualType LHSTy(LHSType);
8763     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8764     if (RHS.isInvalid())
8765       return QualType();
8766     // Special case of NSObject attributes on c-style pointer types.
8767     if (ConvTy == IncompatiblePointer &&
8768         ((Context.isObjCNSObjectType(LHSType) &&
8769           RHSType->isObjCObjectPointerType()) ||
8770          (Context.isObjCNSObjectType(RHSType) &&
8771           LHSType->isObjCObjectPointerType())))
8772       ConvTy = Compatible;
8773 
8774     if (ConvTy == Compatible &&
8775         LHSType->isObjCObjectType())
8776         Diag(Loc, diag::err_objc_object_assignment)
8777           << LHSType;
8778 
8779     // If the RHS is a unary plus or minus, check to see if they = and + are
8780     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8781     // instead of "x += 4".
8782     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8783       RHSCheck = ICE->getSubExpr();
8784     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8785       if ((UO->getOpcode() == UO_Plus ||
8786            UO->getOpcode() == UO_Minus) &&
8787           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8788           // Only if the two operators are exactly adjacent.
8789           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8790           // And there is a space or other character before the subexpr of the
8791           // unary +/-.  We don't want to warn on "x=-1".
8792           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8793           UO->getSubExpr()->getLocStart().isFileID()) {
8794         Diag(Loc, diag::warn_not_compound_assign)
8795           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8796           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8797       }
8798     }
8799 
8800     if (ConvTy == Compatible) {
8801       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8802         // Warn about retain cycles where a block captures the LHS, but
8803         // not if the LHS is a simple variable into which the block is
8804         // being stored...unless that variable can be captured by reference!
8805         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8806         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8807         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8808           checkRetainCycles(LHSExpr, RHS.get());
8809 
8810         // It is safe to assign a weak reference into a strong variable.
8811         // Although this code can still have problems:
8812         //   id x = self.weakProp;
8813         //   id y = self.weakProp;
8814         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8815         // paths through the function. This should be revisited if
8816         // -Wrepeated-use-of-weak is made flow-sensitive.
8817         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8818                              RHS.get()->getLocStart()))
8819           getCurFunction()->markSafeWeakUse(RHS.get());
8820 
8821       } else if (getLangOpts().ObjCAutoRefCount) {
8822         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8823       }
8824     }
8825   } else {
8826     // Compound assignment "x += y"
8827     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8828   }
8829 
8830   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8831                                RHS.get(), AA_Assigning))
8832     return QualType();
8833 
8834   CheckForNullPointerDereference(*this, LHSExpr);
8835 
8836   // C99 6.5.16p3: The type of an assignment expression is the type of the
8837   // left operand unless the left operand has qualified type, in which case
8838   // it is the unqualified version of the type of the left operand.
8839   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8840   // is converted to the type of the assignment expression (above).
8841   // C++ 5.17p1: the type of the assignment expression is that of its left
8842   // operand.
8843   return (getLangOpts().CPlusPlus
8844           ? LHSType : LHSType.getUnqualifiedType());
8845 }
8846 
8847 // C99 6.5.17
8848 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8849                                    SourceLocation Loc) {
8850   LHS = S.CheckPlaceholderExpr(LHS.get());
8851   RHS = S.CheckPlaceholderExpr(RHS.get());
8852   if (LHS.isInvalid() || RHS.isInvalid())
8853     return QualType();
8854 
8855   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8856   // operands, but not unary promotions.
8857   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8858 
8859   // So we treat the LHS as a ignored value, and in C++ we allow the
8860   // containing site to determine what should be done with the RHS.
8861   LHS = S.IgnoredValueConversions(LHS.get());
8862   if (LHS.isInvalid())
8863     return QualType();
8864 
8865   S.DiagnoseUnusedExprResult(LHS.get());
8866 
8867   if (!S.getLangOpts().CPlusPlus) {
8868     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8869     if (RHS.isInvalid())
8870       return QualType();
8871     if (!RHS.get()->getType()->isVoidType())
8872       S.RequireCompleteType(Loc, RHS.get()->getType(),
8873                             diag::err_incomplete_type);
8874   }
8875 
8876   return RHS.get()->getType();
8877 }
8878 
8879 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8880 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8881 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8882                                                ExprValueKind &VK,
8883                                                ExprObjectKind &OK,
8884                                                SourceLocation OpLoc,
8885                                                bool IsInc, bool IsPrefix) {
8886   if (Op->isTypeDependent())
8887     return S.Context.DependentTy;
8888 
8889   QualType ResType = Op->getType();
8890   // Atomic types can be used for increment / decrement where the non-atomic
8891   // versions can, so ignore the _Atomic() specifier for the purpose of
8892   // checking.
8893   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8894     ResType = ResAtomicType->getValueType();
8895 
8896   assert(!ResType.isNull() && "no type for increment/decrement expression");
8897 
8898   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8899     // Decrement of bool is not allowed.
8900     if (!IsInc) {
8901       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8902       return QualType();
8903     }
8904     // Increment of bool sets it to true, but is deprecated.
8905     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8906   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8907     // Error on enum increments and decrements in C++ mode
8908     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8909     return QualType();
8910   } else if (ResType->isRealType()) {
8911     // OK!
8912   } else if (ResType->isPointerType()) {
8913     // C99 6.5.2.4p2, 6.5.6p2
8914     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8915       return QualType();
8916   } else if (ResType->isObjCObjectPointerType()) {
8917     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8918     // Otherwise, we just need a complete type.
8919     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8920         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8921       return QualType();
8922   } else if (ResType->isAnyComplexType()) {
8923     // C99 does not support ++/-- on complex types, we allow as an extension.
8924     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8925       << ResType << Op->getSourceRange();
8926   } else if (ResType->isPlaceholderType()) {
8927     ExprResult PR = S.CheckPlaceholderExpr(Op);
8928     if (PR.isInvalid()) return QualType();
8929     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
8930                                           IsInc, IsPrefix);
8931   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8932     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8933   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8934             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8935     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8936   } else {
8937     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8938       << ResType << int(IsInc) << Op->getSourceRange();
8939     return QualType();
8940   }
8941   // At this point, we know we have a real, complex or pointer type.
8942   // Now make sure the operand is a modifiable lvalue.
8943   if (CheckForModifiableLvalue(Op, OpLoc, S))
8944     return QualType();
8945   // In C++, a prefix increment is the same type as the operand. Otherwise
8946   // (in C or with postfix), the increment is the unqualified type of the
8947   // operand.
8948   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8949     VK = VK_LValue;
8950     OK = Op->getObjectKind();
8951     return ResType;
8952   } else {
8953     VK = VK_RValue;
8954     return ResType.getUnqualifiedType();
8955   }
8956 }
8957 
8958 
8959 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8960 /// This routine allows us to typecheck complex/recursive expressions
8961 /// where the declaration is needed for type checking. We only need to
8962 /// handle cases when the expression references a function designator
8963 /// or is an lvalue. Here are some examples:
8964 ///  - &(x) => x
8965 ///  - &*****f => f for f a function designator.
8966 ///  - &s.xx => s
8967 ///  - &s.zz[1].yy -> s, if zz is an array
8968 ///  - *(x + 1) -> x, if x is an array
8969 ///  - &"123"[2] -> 0
8970 ///  - & __real__ x -> x
8971 static ValueDecl *getPrimaryDecl(Expr *E) {
8972   switch (E->getStmtClass()) {
8973   case Stmt::DeclRefExprClass:
8974     return cast<DeclRefExpr>(E)->getDecl();
8975   case Stmt::MemberExprClass:
8976     // If this is an arrow operator, the address is an offset from
8977     // the base's value, so the object the base refers to is
8978     // irrelevant.
8979     if (cast<MemberExpr>(E)->isArrow())
8980       return nullptr;
8981     // Otherwise, the expression refers to a part of the base
8982     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8983   case Stmt::ArraySubscriptExprClass: {
8984     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8985     // promotion of register arrays earlier.
8986     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8987     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8988       if (ICE->getSubExpr()->getType()->isArrayType())
8989         return getPrimaryDecl(ICE->getSubExpr());
8990     }
8991     return nullptr;
8992   }
8993   case Stmt::UnaryOperatorClass: {
8994     UnaryOperator *UO = cast<UnaryOperator>(E);
8995 
8996     switch(UO->getOpcode()) {
8997     case UO_Real:
8998     case UO_Imag:
8999     case UO_Extension:
9000       return getPrimaryDecl(UO->getSubExpr());
9001     default:
9002       return nullptr;
9003     }
9004   }
9005   case Stmt::ParenExprClass:
9006     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
9007   case Stmt::ImplicitCastExprClass:
9008     // If the result of an implicit cast is an l-value, we care about
9009     // the sub-expression; otherwise, the result here doesn't matter.
9010     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
9011   default:
9012     return nullptr;
9013   }
9014 }
9015 
9016 namespace {
9017   enum {
9018     AO_Bit_Field = 0,
9019     AO_Vector_Element = 1,
9020     AO_Property_Expansion = 2,
9021     AO_Register_Variable = 3,
9022     AO_No_Error = 4
9023   };
9024 }
9025 /// \brief Diagnose invalid operand for address of operations.
9026 ///
9027 /// \param Type The type of operand which cannot have its address taken.
9028 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9029                                          Expr *E, unsigned Type) {
9030   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9031 }
9032 
9033 /// CheckAddressOfOperand - The operand of & must be either a function
9034 /// designator or an lvalue designating an object. If it is an lvalue, the
9035 /// object cannot be declared with storage class register or be a bit field.
9036 /// Note: The usual conversions are *not* applied to the operand of the &
9037 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9038 /// In C++, the operand might be an overloaded function name, in which case
9039 /// we allow the '&' but retain the overloaded-function type.
9040 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
9041   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9042     if (PTy->getKind() == BuiltinType::Overload) {
9043       Expr *E = OrigOp.get()->IgnoreParens();
9044       if (!isa<OverloadExpr>(E)) {
9045         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
9046         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
9047           << OrigOp.get()->getSourceRange();
9048         return QualType();
9049       }
9050 
9051       OverloadExpr *Ovl = cast<OverloadExpr>(E);
9052       if (isa<UnresolvedMemberExpr>(Ovl))
9053         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9054           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9055             << OrigOp.get()->getSourceRange();
9056           return QualType();
9057         }
9058 
9059       return Context.OverloadTy;
9060     }
9061 
9062     if (PTy->getKind() == BuiltinType::UnknownAny)
9063       return Context.UnknownAnyTy;
9064 
9065     if (PTy->getKind() == BuiltinType::BoundMember) {
9066       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9067         << OrigOp.get()->getSourceRange();
9068       return QualType();
9069     }
9070 
9071     OrigOp = CheckPlaceholderExpr(OrigOp.get());
9072     if (OrigOp.isInvalid()) return QualType();
9073   }
9074 
9075   if (OrigOp.get()->isTypeDependent())
9076     return Context.DependentTy;
9077 
9078   assert(!OrigOp.get()->getType()->isPlaceholderType());
9079 
9080   // Make sure to ignore parentheses in subsequent checks
9081   Expr *op = OrigOp.get()->IgnoreParens();
9082 
9083   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9084   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9085     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9086     return QualType();
9087   }
9088 
9089   if (getLangOpts().C99) {
9090     // Implement C99-only parts of addressof rules.
9091     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
9092       if (uOp->getOpcode() == UO_Deref)
9093         // Per C99 6.5.3.2, the address of a deref always returns a valid result
9094         // (assuming the deref expression is valid).
9095         return uOp->getSubExpr()->getType();
9096     }
9097     // Technically, there should be a check for array subscript
9098     // expressions here, but the result of one is always an lvalue anyway.
9099   }
9100   ValueDecl *dcl = getPrimaryDecl(op);
9101   Expr::LValueClassification lval = op->ClassifyLValue(Context);
9102   unsigned AddressOfError = AO_No_Error;
9103 
9104   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
9105     bool sfinae = (bool)isSFINAEContext();
9106     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9107                                   : diag::ext_typecheck_addrof_temporary)
9108       << op->getType() << op->getSourceRange();
9109     if (sfinae)
9110       return QualType();
9111     // Materialize the temporary as an lvalue so that we can take its address.
9112     OrigOp = op = new (Context)
9113         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
9114   } else if (isa<ObjCSelectorExpr>(op)) {
9115     return Context.getPointerType(op->getType());
9116   } else if (lval == Expr::LV_MemberFunction) {
9117     // If it's an instance method, make a member pointer.
9118     // The expression must have exactly the form &A::foo.
9119 
9120     // If the underlying expression isn't a decl ref, give up.
9121     if (!isa<DeclRefExpr>(op)) {
9122       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9123         << OrigOp.get()->getSourceRange();
9124       return QualType();
9125     }
9126     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9127     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9128 
9129     // The id-expression was parenthesized.
9130     if (OrigOp.get() != DRE) {
9131       Diag(OpLoc, diag::err_parens_pointer_member_function)
9132         << OrigOp.get()->getSourceRange();
9133 
9134     // The method was named without a qualifier.
9135     } else if (!DRE->getQualifier()) {
9136       if (MD->getParent()->getName().empty())
9137         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9138           << op->getSourceRange();
9139       else {
9140         SmallString<32> Str;
9141         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9142         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9143           << op->getSourceRange()
9144           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9145       }
9146     }
9147 
9148     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9149     if (isa<CXXDestructorDecl>(MD))
9150       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9151 
9152     QualType MPTy = Context.getMemberPointerType(
9153         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9154     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9155       RequireCompleteType(OpLoc, MPTy, 0);
9156     return MPTy;
9157   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9158     // C99 6.5.3.2p1
9159     // The operand must be either an l-value or a function designator
9160     if (!op->getType()->isFunctionType()) {
9161       // Use a special diagnostic for loads from property references.
9162       if (isa<PseudoObjectExpr>(op)) {
9163         AddressOfError = AO_Property_Expansion;
9164       } else {
9165         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9166           << op->getType() << op->getSourceRange();
9167         return QualType();
9168       }
9169     }
9170   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9171     // The operand cannot be a bit-field
9172     AddressOfError = AO_Bit_Field;
9173   } else if (op->getObjectKind() == OK_VectorComponent) {
9174     // The operand cannot be an element of a vector
9175     AddressOfError = AO_Vector_Element;
9176   } else if (dcl) { // C99 6.5.3.2p1
9177     // We have an lvalue with a decl. Make sure the decl is not declared
9178     // with the register storage-class specifier.
9179     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9180       // in C++ it is not error to take address of a register
9181       // variable (c++03 7.1.1P3)
9182       if (vd->getStorageClass() == SC_Register &&
9183           !getLangOpts().CPlusPlus) {
9184         AddressOfError = AO_Register_Variable;
9185       }
9186     } else if (isa<FunctionTemplateDecl>(dcl)) {
9187       return Context.OverloadTy;
9188     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9189       // Okay: we can take the address of a field.
9190       // Could be a pointer to member, though, if there is an explicit
9191       // scope qualifier for the class.
9192       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9193         DeclContext *Ctx = dcl->getDeclContext();
9194         if (Ctx && Ctx->isRecord()) {
9195           if (dcl->getType()->isReferenceType()) {
9196             Diag(OpLoc,
9197                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9198               << dcl->getDeclName() << dcl->getType();
9199             return QualType();
9200           }
9201 
9202           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9203             Ctx = Ctx->getParent();
9204 
9205           QualType MPTy = Context.getMemberPointerType(
9206               op->getType(),
9207               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9208           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9209             RequireCompleteType(OpLoc, MPTy, 0);
9210           return MPTy;
9211         }
9212       }
9213     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9214       llvm_unreachable("Unknown/unexpected decl type");
9215   }
9216 
9217   if (AddressOfError != AO_No_Error) {
9218     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9219     return QualType();
9220   }
9221 
9222   if (lval == Expr::LV_IncompleteVoidType) {
9223     // Taking the address of a void variable is technically illegal, but we
9224     // allow it in cases which are otherwise valid.
9225     // Example: "extern void x; void* y = &x;".
9226     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9227   }
9228 
9229   // If the operand has type "type", the result has type "pointer to type".
9230   if (op->getType()->isObjCObjectType())
9231     return Context.getObjCObjectPointerType(op->getType());
9232   return Context.getPointerType(op->getType());
9233 }
9234 
9235 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
9236   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
9237   if (!DRE)
9238     return;
9239   const Decl *D = DRE->getDecl();
9240   if (!D)
9241     return;
9242   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
9243   if (!Param)
9244     return;
9245   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
9246     if (!FD->hasAttr<NonNullAttr>())
9247       return;
9248   if (FunctionScopeInfo *FD = S.getCurFunction())
9249     if (!FD->ModifiedNonNullParams.count(Param))
9250       FD->ModifiedNonNullParams.insert(Param);
9251 }
9252 
9253 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9254 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9255                                         SourceLocation OpLoc) {
9256   if (Op->isTypeDependent())
9257     return S.Context.DependentTy;
9258 
9259   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9260   if (ConvResult.isInvalid())
9261     return QualType();
9262   Op = ConvResult.get();
9263   QualType OpTy = Op->getType();
9264   QualType Result;
9265 
9266   if (isa<CXXReinterpretCastExpr>(Op)) {
9267     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9268     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9269                                      Op->getSourceRange());
9270   }
9271 
9272   if (const PointerType *PT = OpTy->getAs<PointerType>())
9273     Result = PT->getPointeeType();
9274   else if (const ObjCObjectPointerType *OPT =
9275              OpTy->getAs<ObjCObjectPointerType>())
9276     Result = OPT->getPointeeType();
9277   else {
9278     ExprResult PR = S.CheckPlaceholderExpr(Op);
9279     if (PR.isInvalid()) return QualType();
9280     if (PR.get() != Op)
9281       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9282   }
9283 
9284   if (Result.isNull()) {
9285     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9286       << OpTy << Op->getSourceRange();
9287     return QualType();
9288   }
9289 
9290   // Note that per both C89 and C99, indirection is always legal, even if Result
9291   // is an incomplete type or void.  It would be possible to warn about
9292   // dereferencing a void pointer, but it's completely well-defined, and such a
9293   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9294   // for pointers to 'void' but is fine for any other pointer type:
9295   //
9296   // C++ [expr.unary.op]p1:
9297   //   [...] the expression to which [the unary * operator] is applied shall
9298   //   be a pointer to an object type, or a pointer to a function type
9299   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9300     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9301       << OpTy << Op->getSourceRange();
9302 
9303   // Dereferences are usually l-values...
9304   VK = VK_LValue;
9305 
9306   // ...except that certain expressions are never l-values in C.
9307   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9308     VK = VK_RValue;
9309 
9310   return Result;
9311 }
9312 
9313 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
9314   BinaryOperatorKind Opc;
9315   switch (Kind) {
9316   default: llvm_unreachable("Unknown binop!");
9317   case tok::periodstar:           Opc = BO_PtrMemD; break;
9318   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9319   case tok::star:                 Opc = BO_Mul; break;
9320   case tok::slash:                Opc = BO_Div; break;
9321   case tok::percent:              Opc = BO_Rem; break;
9322   case tok::plus:                 Opc = BO_Add; break;
9323   case tok::minus:                Opc = BO_Sub; break;
9324   case tok::lessless:             Opc = BO_Shl; break;
9325   case tok::greatergreater:       Opc = BO_Shr; break;
9326   case tok::lessequal:            Opc = BO_LE; break;
9327   case tok::less:                 Opc = BO_LT; break;
9328   case tok::greaterequal:         Opc = BO_GE; break;
9329   case tok::greater:              Opc = BO_GT; break;
9330   case tok::exclaimequal:         Opc = BO_NE; break;
9331   case tok::equalequal:           Opc = BO_EQ; break;
9332   case tok::amp:                  Opc = BO_And; break;
9333   case tok::caret:                Opc = BO_Xor; break;
9334   case tok::pipe:                 Opc = BO_Or; break;
9335   case tok::ampamp:               Opc = BO_LAnd; break;
9336   case tok::pipepipe:             Opc = BO_LOr; break;
9337   case tok::equal:                Opc = BO_Assign; break;
9338   case tok::starequal:            Opc = BO_MulAssign; break;
9339   case tok::slashequal:           Opc = BO_DivAssign; break;
9340   case tok::percentequal:         Opc = BO_RemAssign; break;
9341   case tok::plusequal:            Opc = BO_AddAssign; break;
9342   case tok::minusequal:           Opc = BO_SubAssign; break;
9343   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9344   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9345   case tok::ampequal:             Opc = BO_AndAssign; break;
9346   case tok::caretequal:           Opc = BO_XorAssign; break;
9347   case tok::pipeequal:            Opc = BO_OrAssign; break;
9348   case tok::comma:                Opc = BO_Comma; break;
9349   }
9350   return Opc;
9351 }
9352 
9353 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9354   tok::TokenKind Kind) {
9355   UnaryOperatorKind Opc;
9356   switch (Kind) {
9357   default: llvm_unreachable("Unknown unary op!");
9358   case tok::plusplus:     Opc = UO_PreInc; break;
9359   case tok::minusminus:   Opc = UO_PreDec; break;
9360   case tok::amp:          Opc = UO_AddrOf; break;
9361   case tok::star:         Opc = UO_Deref; break;
9362   case tok::plus:         Opc = UO_Plus; break;
9363   case tok::minus:        Opc = UO_Minus; break;
9364   case tok::tilde:        Opc = UO_Not; break;
9365   case tok::exclaim:      Opc = UO_LNot; break;
9366   case tok::kw___real:    Opc = UO_Real; break;
9367   case tok::kw___imag:    Opc = UO_Imag; break;
9368   case tok::kw___extension__: Opc = UO_Extension; break;
9369   }
9370   return Opc;
9371 }
9372 
9373 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9374 /// This warning is only emitted for builtin assignment operations. It is also
9375 /// suppressed in the event of macro expansions.
9376 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9377                                    SourceLocation OpLoc) {
9378   if (!S.ActiveTemplateInstantiations.empty())
9379     return;
9380   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9381     return;
9382   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9383   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9384   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9385   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9386   if (!LHSDeclRef || !RHSDeclRef ||
9387       LHSDeclRef->getLocation().isMacroID() ||
9388       RHSDeclRef->getLocation().isMacroID())
9389     return;
9390   const ValueDecl *LHSDecl =
9391     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9392   const ValueDecl *RHSDecl =
9393     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9394   if (LHSDecl != RHSDecl)
9395     return;
9396   if (LHSDecl->getType().isVolatileQualified())
9397     return;
9398   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9399     if (RefTy->getPointeeType().isVolatileQualified())
9400       return;
9401 
9402   S.Diag(OpLoc, diag::warn_self_assignment)
9403       << LHSDeclRef->getType()
9404       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9405 }
9406 
9407 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9408 /// is usually indicative of introspection within the Objective-C pointer.
9409 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9410                                           SourceLocation OpLoc) {
9411   if (!S.getLangOpts().ObjC1)
9412     return;
9413 
9414   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9415   const Expr *LHS = L.get();
9416   const Expr *RHS = R.get();
9417 
9418   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9419     ObjCPointerExpr = LHS;
9420     OtherExpr = RHS;
9421   }
9422   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9423     ObjCPointerExpr = RHS;
9424     OtherExpr = LHS;
9425   }
9426 
9427   // This warning is deliberately made very specific to reduce false
9428   // positives with logic that uses '&' for hashing.  This logic mainly
9429   // looks for code trying to introspect into tagged pointers, which
9430   // code should generally never do.
9431   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9432     unsigned Diag = diag::warn_objc_pointer_masking;
9433     // Determine if we are introspecting the result of performSelectorXXX.
9434     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9435     // Special case messages to -performSelector and friends, which
9436     // can return non-pointer values boxed in a pointer value.
9437     // Some clients may wish to silence warnings in this subcase.
9438     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9439       Selector S = ME->getSelector();
9440       StringRef SelArg0 = S.getNameForSlot(0);
9441       if (SelArg0.startswith("performSelector"))
9442         Diag = diag::warn_objc_pointer_masking_performSelector;
9443     }
9444 
9445     S.Diag(OpLoc, Diag)
9446       << ObjCPointerExpr->getSourceRange();
9447   }
9448 }
9449 
9450 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9451 /// operator @p Opc at location @c TokLoc. This routine only supports
9452 /// built-in operations; ActOnBinOp handles overloaded operators.
9453 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9454                                     BinaryOperatorKind Opc,
9455                                     Expr *LHSExpr, Expr *RHSExpr) {
9456   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9457     // The syntax only allows initializer lists on the RHS of assignment,
9458     // so we don't need to worry about accepting invalid code for
9459     // non-assignment operators.
9460     // C++11 5.17p9:
9461     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9462     //   of x = {} is x = T().
9463     InitializationKind Kind =
9464         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9465     InitializedEntity Entity =
9466         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9467     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9468     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9469     if (Init.isInvalid())
9470       return Init;
9471     RHSExpr = Init.get();
9472   }
9473 
9474   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9475   QualType ResultTy;     // Result type of the binary operator.
9476   // The following two variables are used for compound assignment operators
9477   QualType CompLHSTy;    // Type of LHS after promotions for computation
9478   QualType CompResultTy; // Type of computation result
9479   ExprValueKind VK = VK_RValue;
9480   ExprObjectKind OK = OK_Ordinary;
9481 
9482   if (!getLangOpts().CPlusPlus) {
9483     // C cannot handle TypoExpr nodes on either side of a binop because it
9484     // doesn't handle dependent types properly, so make sure any TypoExprs have
9485     // been dealt with before checking the operands.
9486     LHS = CorrectDelayedTyposInExpr(LHSExpr);
9487     RHS = CorrectDelayedTyposInExpr(RHSExpr);
9488     if (!LHS.isUsable() || !RHS.isUsable())
9489       return ExprError();
9490   }
9491 
9492   switch (Opc) {
9493   case BO_Assign:
9494     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9495     if (getLangOpts().CPlusPlus &&
9496         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9497       VK = LHS.get()->getValueKind();
9498       OK = LHS.get()->getObjectKind();
9499     }
9500     if (!ResultTy.isNull())
9501       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9502     RecordModifiableNonNullParam(*this, LHS.get());
9503     break;
9504   case BO_PtrMemD:
9505   case BO_PtrMemI:
9506     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9507                                             Opc == BO_PtrMemI);
9508     break;
9509   case BO_Mul:
9510   case BO_Div:
9511     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9512                                            Opc == BO_Div);
9513     break;
9514   case BO_Rem:
9515     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9516     break;
9517   case BO_Add:
9518     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9519     break;
9520   case BO_Sub:
9521     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9522     break;
9523   case BO_Shl:
9524   case BO_Shr:
9525     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9526     break;
9527   case BO_LE:
9528   case BO_LT:
9529   case BO_GE:
9530   case BO_GT:
9531     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9532     break;
9533   case BO_EQ:
9534   case BO_NE:
9535     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9536     break;
9537   case BO_And:
9538     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9539   case BO_Xor:
9540   case BO_Or:
9541     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9542     break;
9543   case BO_LAnd:
9544   case BO_LOr:
9545     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9546     break;
9547   case BO_MulAssign:
9548   case BO_DivAssign:
9549     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9550                                                Opc == BO_DivAssign);
9551     CompLHSTy = CompResultTy;
9552     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9553       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9554     break;
9555   case BO_RemAssign:
9556     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9557     CompLHSTy = CompResultTy;
9558     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9559       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9560     break;
9561   case BO_AddAssign:
9562     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9563     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9564       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9565     break;
9566   case BO_SubAssign:
9567     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9568     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9569       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9570     break;
9571   case BO_ShlAssign:
9572   case BO_ShrAssign:
9573     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9574     CompLHSTy = CompResultTy;
9575     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9576       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9577     break;
9578   case BO_AndAssign:
9579   case BO_OrAssign: // fallthrough
9580 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9581   case BO_XorAssign:
9582     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9583     CompLHSTy = CompResultTy;
9584     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9585       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9586     break;
9587   case BO_Comma:
9588     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9589     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9590       VK = RHS.get()->getValueKind();
9591       OK = RHS.get()->getObjectKind();
9592     }
9593     break;
9594   }
9595   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9596     return ExprError();
9597 
9598   // Check for array bounds violations for both sides of the BinaryOperator
9599   CheckArrayAccess(LHS.get());
9600   CheckArrayAccess(RHS.get());
9601 
9602   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9603     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9604                                                  &Context.Idents.get("object_setClass"),
9605                                                  SourceLocation(), LookupOrdinaryName);
9606     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9607       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9608       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9609       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9610       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9611       FixItHint::CreateInsertion(RHSLocEnd, ")");
9612     }
9613     else
9614       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9615   }
9616   else if (const ObjCIvarRefExpr *OIRE =
9617            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9618     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9619 
9620   if (CompResultTy.isNull())
9621     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9622                                         OK, OpLoc, FPFeatures.fp_contract);
9623   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9624       OK_ObjCProperty) {
9625     VK = VK_LValue;
9626     OK = LHS.get()->getObjectKind();
9627   }
9628   return new (Context) CompoundAssignOperator(
9629       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9630       OpLoc, FPFeatures.fp_contract);
9631 }
9632 
9633 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9634 /// operators are mixed in a way that suggests that the programmer forgot that
9635 /// comparison operators have higher precedence. The most typical example of
9636 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9637 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9638                                       SourceLocation OpLoc, Expr *LHSExpr,
9639                                       Expr *RHSExpr) {
9640   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9641   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9642 
9643   // Check that one of the sides is a comparison operator.
9644   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9645   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9646   if (!isLeftComp && !isRightComp)
9647     return;
9648 
9649   // Bitwise operations are sometimes used as eager logical ops.
9650   // Don't diagnose this.
9651   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9652   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9653   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9654     return;
9655 
9656   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9657                                                    OpLoc)
9658                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9659   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9660   SourceRange ParensRange = isLeftComp ?
9661       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9662     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
9663 
9664   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9665     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9666   SuggestParentheses(Self, OpLoc,
9667     Self.PDiag(diag::note_precedence_silence) << OpStr,
9668     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9669   SuggestParentheses(Self, OpLoc,
9670     Self.PDiag(diag::note_precedence_bitwise_first)
9671       << BinaryOperator::getOpcodeStr(Opc),
9672     ParensRange);
9673 }
9674 
9675 /// \brief It accepts a '&' expr that is inside a '|' one.
9676 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9677 /// in parentheses.
9678 static void
9679 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9680                                        BinaryOperator *Bop) {
9681   assert(Bop->getOpcode() == BO_And);
9682   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9683       << Bop->getSourceRange() << OpLoc;
9684   SuggestParentheses(Self, Bop->getOperatorLoc(),
9685     Self.PDiag(diag::note_precedence_silence)
9686       << Bop->getOpcodeStr(),
9687     Bop->getSourceRange());
9688 }
9689 
9690 /// \brief It accepts a '&&' expr that is inside a '||' one.
9691 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9692 /// in parentheses.
9693 static void
9694 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9695                                        BinaryOperator *Bop) {
9696   assert(Bop->getOpcode() == BO_LAnd);
9697   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9698       << Bop->getSourceRange() << OpLoc;
9699   SuggestParentheses(Self, Bop->getOperatorLoc(),
9700     Self.PDiag(diag::note_precedence_silence)
9701       << Bop->getOpcodeStr(),
9702     Bop->getSourceRange());
9703 }
9704 
9705 /// \brief Returns true if the given expression can be evaluated as a constant
9706 /// 'true'.
9707 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9708   bool Res;
9709   return !E->isValueDependent() &&
9710          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9711 }
9712 
9713 /// \brief Returns true if the given expression can be evaluated as a constant
9714 /// 'false'.
9715 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9716   bool Res;
9717   return !E->isValueDependent() &&
9718          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9719 }
9720 
9721 /// \brief Look for '&&' in the left hand of a '||' expr.
9722 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9723                                              Expr *LHSExpr, Expr *RHSExpr) {
9724   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9725     if (Bop->getOpcode() == BO_LAnd) {
9726       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9727       if (EvaluatesAsFalse(S, RHSExpr))
9728         return;
9729       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9730       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9731         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9732     } else if (Bop->getOpcode() == BO_LOr) {
9733       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9734         // If it's "a || b && 1 || c" we didn't warn earlier for
9735         // "a || b && 1", but warn now.
9736         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9737           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9738       }
9739     }
9740   }
9741 }
9742 
9743 /// \brief Look for '&&' in the right hand of a '||' expr.
9744 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9745                                              Expr *LHSExpr, Expr *RHSExpr) {
9746   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9747     if (Bop->getOpcode() == BO_LAnd) {
9748       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9749       if (EvaluatesAsFalse(S, LHSExpr))
9750         return;
9751       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9752       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9753         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9754     }
9755   }
9756 }
9757 
9758 /// \brief Look for '&' in the left or right hand of a '|' expr.
9759 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9760                                              Expr *OrArg) {
9761   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9762     if (Bop->getOpcode() == BO_And)
9763       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9764   }
9765 }
9766 
9767 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9768                                     Expr *SubExpr, StringRef Shift) {
9769   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9770     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9771       StringRef Op = Bop->getOpcodeStr();
9772       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9773           << Bop->getSourceRange() << OpLoc << Shift << Op;
9774       SuggestParentheses(S, Bop->getOperatorLoc(),
9775           S.PDiag(diag::note_precedence_silence) << Op,
9776           Bop->getSourceRange());
9777     }
9778   }
9779 }
9780 
9781 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9782                                  Expr *LHSExpr, Expr *RHSExpr) {
9783   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9784   if (!OCE)
9785     return;
9786 
9787   FunctionDecl *FD = OCE->getDirectCallee();
9788   if (!FD || !FD->isOverloadedOperator())
9789     return;
9790 
9791   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9792   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9793     return;
9794 
9795   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9796       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9797       << (Kind == OO_LessLess);
9798   SuggestParentheses(S, OCE->getOperatorLoc(),
9799                      S.PDiag(diag::note_precedence_silence)
9800                          << (Kind == OO_LessLess ? "<<" : ">>"),
9801                      OCE->getSourceRange());
9802   SuggestParentheses(S, OpLoc,
9803                      S.PDiag(diag::note_evaluate_comparison_first),
9804                      SourceRange(OCE->getArg(1)->getLocStart(),
9805                                  RHSExpr->getLocEnd()));
9806 }
9807 
9808 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9809 /// precedence.
9810 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9811                                     SourceLocation OpLoc, Expr *LHSExpr,
9812                                     Expr *RHSExpr){
9813   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9814   if (BinaryOperator::isBitwiseOp(Opc))
9815     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9816 
9817   // Diagnose "arg1 & arg2 | arg3"
9818   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9819     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9820     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9821   }
9822 
9823   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9824   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9825   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9826     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9827     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9828   }
9829 
9830   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9831       || Opc == BO_Shr) {
9832     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9833     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9834     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9835   }
9836 
9837   // Warn on overloaded shift operators and comparisons, such as:
9838   // cout << 5 == 4;
9839   if (BinaryOperator::isComparisonOp(Opc))
9840     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9841 }
9842 
9843 // Binary Operators.  'Tok' is the token for the operator.
9844 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9845                             tok::TokenKind Kind,
9846                             Expr *LHSExpr, Expr *RHSExpr) {
9847   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9848   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9849   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9850 
9851   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9852   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9853 
9854   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9855 }
9856 
9857 /// Build an overloaded binary operator expression in the given scope.
9858 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9859                                        BinaryOperatorKind Opc,
9860                                        Expr *LHS, Expr *RHS) {
9861   // Find all of the overloaded operators visible from this
9862   // point. We perform both an operator-name lookup from the local
9863   // scope and an argument-dependent lookup based on the types of
9864   // the arguments.
9865   UnresolvedSet<16> Functions;
9866   OverloadedOperatorKind OverOp
9867     = BinaryOperator::getOverloadedOperator(Opc);
9868   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
9869     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9870                                    RHS->getType(), Functions);
9871 
9872   // Build the (potentially-overloaded, potentially-dependent)
9873   // binary operation.
9874   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9875 }
9876 
9877 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9878                             BinaryOperatorKind Opc,
9879                             Expr *LHSExpr, Expr *RHSExpr) {
9880   // We want to end up calling one of checkPseudoObjectAssignment
9881   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9882   // both expressions are overloadable or either is type-dependent),
9883   // or CreateBuiltinBinOp (in any other case).  We also want to get
9884   // any placeholder types out of the way.
9885 
9886   // Handle pseudo-objects in the LHS.
9887   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9888     // Assignments with a pseudo-object l-value need special analysis.
9889     if (pty->getKind() == BuiltinType::PseudoObject &&
9890         BinaryOperator::isAssignmentOp(Opc))
9891       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9892 
9893     // Don't resolve overloads if the other type is overloadable.
9894     if (pty->getKind() == BuiltinType::Overload) {
9895       // We can't actually test that if we still have a placeholder,
9896       // though.  Fortunately, none of the exceptions we see in that
9897       // code below are valid when the LHS is an overload set.  Note
9898       // that an overload set can be dependently-typed, but it never
9899       // instantiates to having an overloadable type.
9900       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9901       if (resolvedRHS.isInvalid()) return ExprError();
9902       RHSExpr = resolvedRHS.get();
9903 
9904       if (RHSExpr->isTypeDependent() ||
9905           RHSExpr->getType()->isOverloadableType())
9906         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9907     }
9908 
9909     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9910     if (LHS.isInvalid()) return ExprError();
9911     LHSExpr = LHS.get();
9912   }
9913 
9914   // Handle pseudo-objects in the RHS.
9915   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9916     // An overload in the RHS can potentially be resolved by the type
9917     // being assigned to.
9918     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9919       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9920         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9921 
9922       if (LHSExpr->getType()->isOverloadableType())
9923         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9924 
9925       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9926     }
9927 
9928     // Don't resolve overloads if the other type is overloadable.
9929     if (pty->getKind() == BuiltinType::Overload &&
9930         LHSExpr->getType()->isOverloadableType())
9931       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9932 
9933     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9934     if (!resolvedRHS.isUsable()) return ExprError();
9935     RHSExpr = resolvedRHS.get();
9936   }
9937 
9938   if (getLangOpts().CPlusPlus) {
9939     // If either expression is type-dependent, always build an
9940     // overloaded op.
9941     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9942       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9943 
9944     // Otherwise, build an overloaded op if either expression has an
9945     // overloadable type.
9946     if (LHSExpr->getType()->isOverloadableType() ||
9947         RHSExpr->getType()->isOverloadableType())
9948       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9949   }
9950 
9951   // Build a built-in binary operation.
9952   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9953 }
9954 
9955 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9956                                       UnaryOperatorKind Opc,
9957                                       Expr *InputExpr) {
9958   ExprResult Input = InputExpr;
9959   ExprValueKind VK = VK_RValue;
9960   ExprObjectKind OK = OK_Ordinary;
9961   QualType resultType;
9962   switch (Opc) {
9963   case UO_PreInc:
9964   case UO_PreDec:
9965   case UO_PostInc:
9966   case UO_PostDec:
9967     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
9968                                                 OpLoc,
9969                                                 Opc == UO_PreInc ||
9970                                                 Opc == UO_PostInc,
9971                                                 Opc == UO_PreInc ||
9972                                                 Opc == UO_PreDec);
9973     break;
9974   case UO_AddrOf:
9975     resultType = CheckAddressOfOperand(Input, OpLoc);
9976     RecordModifiableNonNullParam(*this, InputExpr);
9977     break;
9978   case UO_Deref: {
9979     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9980     if (Input.isInvalid()) return ExprError();
9981     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9982     break;
9983   }
9984   case UO_Plus:
9985   case UO_Minus:
9986     Input = UsualUnaryConversions(Input.get());
9987     if (Input.isInvalid()) return ExprError();
9988     resultType = Input.get()->getType();
9989     if (resultType->isDependentType())
9990       break;
9991     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9992         resultType->isVectorType())
9993       break;
9994     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9995              Opc == UO_Plus &&
9996              resultType->isPointerType())
9997       break;
9998 
9999     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10000       << resultType << Input.get()->getSourceRange());
10001 
10002   case UO_Not: // bitwise complement
10003     Input = UsualUnaryConversions(Input.get());
10004     if (Input.isInvalid())
10005       return ExprError();
10006     resultType = Input.get()->getType();
10007     if (resultType->isDependentType())
10008       break;
10009     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10010     if (resultType->isComplexType() || resultType->isComplexIntegerType())
10011       // C99 does not support '~' for complex conjugation.
10012       Diag(OpLoc, diag::ext_integer_complement_complex)
10013           << resultType << Input.get()->getSourceRange();
10014     else if (resultType->hasIntegerRepresentation())
10015       break;
10016     else if (resultType->isExtVectorType()) {
10017       if (Context.getLangOpts().OpenCL) {
10018         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10019         // on vector float types.
10020         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10021         if (!T->isIntegerType())
10022           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10023                            << resultType << Input.get()->getSourceRange());
10024       }
10025       break;
10026     } else {
10027       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10028                        << resultType << Input.get()->getSourceRange());
10029     }
10030     break;
10031 
10032   case UO_LNot: // logical negation
10033     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
10034     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10035     if (Input.isInvalid()) return ExprError();
10036     resultType = Input.get()->getType();
10037 
10038     // Though we still have to promote half FP to float...
10039     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
10040       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
10041       resultType = Context.FloatTy;
10042     }
10043 
10044     if (resultType->isDependentType())
10045       break;
10046     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
10047       // C99 6.5.3.3p1: ok, fallthrough;
10048       if (Context.getLangOpts().CPlusPlus) {
10049         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10050         // operand contextually converted to bool.
10051         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
10052                                   ScalarTypeToBooleanCastKind(resultType));
10053       } else if (Context.getLangOpts().OpenCL &&
10054                  Context.getLangOpts().OpenCLVersion < 120) {
10055         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10056         // operate on scalar float types.
10057         if (!resultType->isIntegerType())
10058           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10059                            << resultType << Input.get()->getSourceRange());
10060       }
10061     } else if (resultType->isExtVectorType()) {
10062       if (Context.getLangOpts().OpenCL &&
10063           Context.getLangOpts().OpenCLVersion < 120) {
10064         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10065         // operate on vector float types.
10066         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10067         if (!T->isIntegerType())
10068           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10069                            << resultType << Input.get()->getSourceRange());
10070       }
10071       // Vector logical not returns the signed variant of the operand type.
10072       resultType = GetSignedVectorType(resultType);
10073       break;
10074     } else {
10075       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10076         << resultType << Input.get()->getSourceRange());
10077     }
10078 
10079     // LNot always has type int. C99 6.5.3.3p5.
10080     // In C++, it's bool. C++ 5.3.1p8
10081     resultType = Context.getLogicalOperationType();
10082     break;
10083   case UO_Real:
10084   case UO_Imag:
10085     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
10086     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10087     // complex l-values to ordinary l-values and all other values to r-values.
10088     if (Input.isInvalid()) return ExprError();
10089     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10090       if (Input.get()->getValueKind() != VK_RValue &&
10091           Input.get()->getObjectKind() == OK_Ordinary)
10092         VK = Input.get()->getValueKind();
10093     } else if (!getLangOpts().CPlusPlus) {
10094       // In C, a volatile scalar is read by __imag. In C++, it is not.
10095       Input = DefaultLvalueConversion(Input.get());
10096     }
10097     break;
10098   case UO_Extension:
10099     resultType = Input.get()->getType();
10100     VK = Input.get()->getValueKind();
10101     OK = Input.get()->getObjectKind();
10102     break;
10103   }
10104   if (resultType.isNull() || Input.isInvalid())
10105     return ExprError();
10106 
10107   // Check for array bounds violations in the operand of the UnaryOperator,
10108   // except for the '*' and '&' operators that have to be handled specially
10109   // by CheckArrayAccess (as there are special cases like &array[arraysize]
10110   // that are explicitly defined as valid by the standard).
10111   if (Opc != UO_AddrOf && Opc != UO_Deref)
10112     CheckArrayAccess(Input.get());
10113 
10114   return new (Context)
10115       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
10116 }
10117 
10118 /// \brief Determine whether the given expression is a qualified member
10119 /// access expression, of a form that could be turned into a pointer to member
10120 /// with the address-of operator.
10121 static bool isQualifiedMemberAccess(Expr *E) {
10122   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10123     if (!DRE->getQualifier())
10124       return false;
10125 
10126     ValueDecl *VD = DRE->getDecl();
10127     if (!VD->isCXXClassMember())
10128       return false;
10129 
10130     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10131       return true;
10132     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10133       return Method->isInstance();
10134 
10135     return false;
10136   }
10137 
10138   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10139     if (!ULE->getQualifier())
10140       return false;
10141 
10142     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10143                                            DEnd = ULE->decls_end();
10144          D != DEnd; ++D) {
10145       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10146         if (Method->isInstance())
10147           return true;
10148       } else {
10149         // Overload set does not contain methods.
10150         break;
10151       }
10152     }
10153 
10154     return false;
10155   }
10156 
10157   return false;
10158 }
10159 
10160 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10161                               UnaryOperatorKind Opc, Expr *Input) {
10162   // First things first: handle placeholders so that the
10163   // overloaded-operator check considers the right type.
10164   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10165     // Increment and decrement of pseudo-object references.
10166     if (pty->getKind() == BuiltinType::PseudoObject &&
10167         UnaryOperator::isIncrementDecrementOp(Opc))
10168       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10169 
10170     // extension is always a builtin operator.
10171     if (Opc == UO_Extension)
10172       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10173 
10174     // & gets special logic for several kinds of placeholder.
10175     // The builtin code knows what to do.
10176     if (Opc == UO_AddrOf &&
10177         (pty->getKind() == BuiltinType::Overload ||
10178          pty->getKind() == BuiltinType::UnknownAny ||
10179          pty->getKind() == BuiltinType::BoundMember))
10180       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10181 
10182     // Anything else needs to be handled now.
10183     ExprResult Result = CheckPlaceholderExpr(Input);
10184     if (Result.isInvalid()) return ExprError();
10185     Input = Result.get();
10186   }
10187 
10188   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10189       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10190       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10191     // Find all of the overloaded operators visible from this
10192     // point. We perform both an operator-name lookup from the local
10193     // scope and an argument-dependent lookup based on the types of
10194     // the arguments.
10195     UnresolvedSet<16> Functions;
10196     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10197     if (S && OverOp != OO_None)
10198       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10199                                    Functions);
10200 
10201     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10202   }
10203 
10204   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10205 }
10206 
10207 // Unary Operators.  'Tok' is the token for the operator.
10208 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10209                               tok::TokenKind Op, Expr *Input) {
10210   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10211 }
10212 
10213 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10214 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10215                                 LabelDecl *TheDecl) {
10216   TheDecl->markUsed(Context);
10217   // Create the AST node.  The address of a label always has type 'void*'.
10218   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10219                                      Context.getPointerType(Context.VoidTy));
10220 }
10221 
10222 /// Given the last statement in a statement-expression, check whether
10223 /// the result is a producing expression (like a call to an
10224 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10225 /// release out of the full-expression.  Otherwise, return null.
10226 /// Cannot fail.
10227 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10228   // Should always be wrapped with one of these.
10229   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10230   if (!cleanups) return nullptr;
10231 
10232   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10233   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10234     return nullptr;
10235 
10236   // Splice out the cast.  This shouldn't modify any interesting
10237   // features of the statement.
10238   Expr *producer = cast->getSubExpr();
10239   assert(producer->getType() == cast->getType());
10240   assert(producer->getValueKind() == cast->getValueKind());
10241   cleanups->setSubExpr(producer);
10242   return cleanups;
10243 }
10244 
10245 void Sema::ActOnStartStmtExpr() {
10246   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10247 }
10248 
10249 void Sema::ActOnStmtExprError() {
10250   // Note that function is also called by TreeTransform when leaving a
10251   // StmtExpr scope without rebuilding anything.
10252 
10253   DiscardCleanupsInEvaluationContext();
10254   PopExpressionEvaluationContext();
10255 }
10256 
10257 ExprResult
10258 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10259                     SourceLocation RPLoc) { // "({..})"
10260   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10261   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10262 
10263   if (hasAnyUnrecoverableErrorsInThisFunction())
10264     DiscardCleanupsInEvaluationContext();
10265   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10266   PopExpressionEvaluationContext();
10267 
10268   bool isFileScope
10269     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10270   if (isFileScope)
10271     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10272 
10273   // FIXME: there are a variety of strange constraints to enforce here, for
10274   // example, it is not possible to goto into a stmt expression apparently.
10275   // More semantic analysis is needed.
10276 
10277   // If there are sub-stmts in the compound stmt, take the type of the last one
10278   // as the type of the stmtexpr.
10279   QualType Ty = Context.VoidTy;
10280   bool StmtExprMayBindToTemp = false;
10281   if (!Compound->body_empty()) {
10282     Stmt *LastStmt = Compound->body_back();
10283     LabelStmt *LastLabelStmt = nullptr;
10284     // If LastStmt is a label, skip down through into the body.
10285     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10286       LastLabelStmt = Label;
10287       LastStmt = Label->getSubStmt();
10288     }
10289 
10290     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10291       // Do function/array conversion on the last expression, but not
10292       // lvalue-to-rvalue.  However, initialize an unqualified type.
10293       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10294       if (LastExpr.isInvalid())
10295         return ExprError();
10296       Ty = LastExpr.get()->getType().getUnqualifiedType();
10297 
10298       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10299         // In ARC, if the final expression ends in a consume, splice
10300         // the consume out and bind it later.  In the alternate case
10301         // (when dealing with a retainable type), the result
10302         // initialization will create a produce.  In both cases the
10303         // result will be +1, and we'll need to balance that out with
10304         // a bind.
10305         if (Expr *rebuiltLastStmt
10306               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10307           LastExpr = rebuiltLastStmt;
10308         } else {
10309           LastExpr = PerformCopyInitialization(
10310                             InitializedEntity::InitializeResult(LPLoc,
10311                                                                 Ty,
10312                                                                 false),
10313                                                    SourceLocation(),
10314                                                LastExpr);
10315         }
10316 
10317         if (LastExpr.isInvalid())
10318           return ExprError();
10319         if (LastExpr.get() != nullptr) {
10320           if (!LastLabelStmt)
10321             Compound->setLastStmt(LastExpr.get());
10322           else
10323             LastLabelStmt->setSubStmt(LastExpr.get());
10324           StmtExprMayBindToTemp = true;
10325         }
10326       }
10327     }
10328   }
10329 
10330   // FIXME: Check that expression type is complete/non-abstract; statement
10331   // expressions are not lvalues.
10332   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10333   if (StmtExprMayBindToTemp)
10334     return MaybeBindToTemporary(ResStmtExpr);
10335   return ResStmtExpr;
10336 }
10337 
10338 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10339                                       TypeSourceInfo *TInfo,
10340                                       OffsetOfComponent *CompPtr,
10341                                       unsigned NumComponents,
10342                                       SourceLocation RParenLoc) {
10343   QualType ArgTy = TInfo->getType();
10344   bool Dependent = ArgTy->isDependentType();
10345   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10346 
10347   // We must have at least one component that refers to the type, and the first
10348   // one is known to be a field designator.  Verify that the ArgTy represents
10349   // a struct/union/class.
10350   if (!Dependent && !ArgTy->isRecordType())
10351     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10352                        << ArgTy << TypeRange);
10353 
10354   // Type must be complete per C99 7.17p3 because a declaring a variable
10355   // with an incomplete type would be ill-formed.
10356   if (!Dependent
10357       && RequireCompleteType(BuiltinLoc, ArgTy,
10358                              diag::err_offsetof_incomplete_type, TypeRange))
10359     return ExprError();
10360 
10361   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10362   // GCC extension, diagnose them.
10363   // FIXME: This diagnostic isn't actually visible because the location is in
10364   // a system header!
10365   if (NumComponents != 1)
10366     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10367       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10368 
10369   bool DidWarnAboutNonPOD = false;
10370   QualType CurrentType = ArgTy;
10371   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10372   SmallVector<OffsetOfNode, 4> Comps;
10373   SmallVector<Expr*, 4> Exprs;
10374   for (unsigned i = 0; i != NumComponents; ++i) {
10375     const OffsetOfComponent &OC = CompPtr[i];
10376     if (OC.isBrackets) {
10377       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10378       if (!CurrentType->isDependentType()) {
10379         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10380         if(!AT)
10381           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10382                            << CurrentType);
10383         CurrentType = AT->getElementType();
10384       } else
10385         CurrentType = Context.DependentTy;
10386 
10387       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10388       if (IdxRval.isInvalid())
10389         return ExprError();
10390       Expr *Idx = IdxRval.get();
10391 
10392       // The expression must be an integral expression.
10393       // FIXME: An integral constant expression?
10394       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10395           !Idx->getType()->isIntegerType())
10396         return ExprError(Diag(Idx->getLocStart(),
10397                               diag::err_typecheck_subscript_not_integer)
10398                          << Idx->getSourceRange());
10399 
10400       // Record this array index.
10401       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10402       Exprs.push_back(Idx);
10403       continue;
10404     }
10405 
10406     // Offset of a field.
10407     if (CurrentType->isDependentType()) {
10408       // We have the offset of a field, but we can't look into the dependent
10409       // type. Just record the identifier of the field.
10410       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10411       CurrentType = Context.DependentTy;
10412       continue;
10413     }
10414 
10415     // We need to have a complete type to look into.
10416     if (RequireCompleteType(OC.LocStart, CurrentType,
10417                             diag::err_offsetof_incomplete_type))
10418       return ExprError();
10419 
10420     // Look for the designated field.
10421     const RecordType *RC = CurrentType->getAs<RecordType>();
10422     if (!RC)
10423       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10424                        << CurrentType);
10425     RecordDecl *RD = RC->getDecl();
10426 
10427     // C++ [lib.support.types]p5:
10428     //   The macro offsetof accepts a restricted set of type arguments in this
10429     //   International Standard. type shall be a POD structure or a POD union
10430     //   (clause 9).
10431     // C++11 [support.types]p4:
10432     //   If type is not a standard-layout class (Clause 9), the results are
10433     //   undefined.
10434     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10435       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10436       unsigned DiagID =
10437         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10438                             : diag::ext_offsetof_non_pod_type;
10439 
10440       if (!IsSafe && !DidWarnAboutNonPOD &&
10441           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10442                               PDiag(DiagID)
10443                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10444                               << CurrentType))
10445         DidWarnAboutNonPOD = true;
10446     }
10447 
10448     // Look for the field.
10449     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10450     LookupQualifiedName(R, RD);
10451     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10452     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10453     if (!MemberDecl) {
10454       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10455         MemberDecl = IndirectMemberDecl->getAnonField();
10456     }
10457 
10458     if (!MemberDecl)
10459       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10460                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10461                                                               OC.LocEnd));
10462 
10463     // C99 7.17p3:
10464     //   (If the specified member is a bit-field, the behavior is undefined.)
10465     //
10466     // We diagnose this as an error.
10467     if (MemberDecl->isBitField()) {
10468       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10469         << MemberDecl->getDeclName()
10470         << SourceRange(BuiltinLoc, RParenLoc);
10471       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10472       return ExprError();
10473     }
10474 
10475     RecordDecl *Parent = MemberDecl->getParent();
10476     if (IndirectMemberDecl)
10477       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10478 
10479     // If the member was found in a base class, introduce OffsetOfNodes for
10480     // the base class indirections.
10481     CXXBasePaths Paths;
10482     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10483       if (Paths.getDetectedVirtual()) {
10484         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10485           << MemberDecl->getDeclName()
10486           << SourceRange(BuiltinLoc, RParenLoc);
10487         return ExprError();
10488       }
10489 
10490       CXXBasePath &Path = Paths.front();
10491       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10492            B != BEnd; ++B)
10493         Comps.push_back(OffsetOfNode(B->Base));
10494     }
10495 
10496     if (IndirectMemberDecl) {
10497       for (auto *FI : IndirectMemberDecl->chain()) {
10498         assert(isa<FieldDecl>(FI));
10499         Comps.push_back(OffsetOfNode(OC.LocStart,
10500                                      cast<FieldDecl>(FI), OC.LocEnd));
10501       }
10502     } else
10503       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10504 
10505     CurrentType = MemberDecl->getType().getNonReferenceType();
10506   }
10507 
10508   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10509                               Comps, Exprs, RParenLoc);
10510 }
10511 
10512 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10513                                       SourceLocation BuiltinLoc,
10514                                       SourceLocation TypeLoc,
10515                                       ParsedType ParsedArgTy,
10516                                       OffsetOfComponent *CompPtr,
10517                                       unsigned NumComponents,
10518                                       SourceLocation RParenLoc) {
10519 
10520   TypeSourceInfo *ArgTInfo;
10521   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10522   if (ArgTy.isNull())
10523     return ExprError();
10524 
10525   if (!ArgTInfo)
10526     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10527 
10528   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10529                               RParenLoc);
10530 }
10531 
10532 
10533 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10534                                  Expr *CondExpr,
10535                                  Expr *LHSExpr, Expr *RHSExpr,
10536                                  SourceLocation RPLoc) {
10537   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10538 
10539   ExprValueKind VK = VK_RValue;
10540   ExprObjectKind OK = OK_Ordinary;
10541   QualType resType;
10542   bool ValueDependent = false;
10543   bool CondIsTrue = false;
10544   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10545     resType = Context.DependentTy;
10546     ValueDependent = true;
10547   } else {
10548     // The conditional expression is required to be a constant expression.
10549     llvm::APSInt condEval(32);
10550     ExprResult CondICE
10551       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10552           diag::err_typecheck_choose_expr_requires_constant, false);
10553     if (CondICE.isInvalid())
10554       return ExprError();
10555     CondExpr = CondICE.get();
10556     CondIsTrue = condEval.getZExtValue();
10557 
10558     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10559     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10560 
10561     resType = ActiveExpr->getType();
10562     ValueDependent = ActiveExpr->isValueDependent();
10563     VK = ActiveExpr->getValueKind();
10564     OK = ActiveExpr->getObjectKind();
10565   }
10566 
10567   return new (Context)
10568       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10569                  CondIsTrue, resType->isDependentType(), ValueDependent);
10570 }
10571 
10572 //===----------------------------------------------------------------------===//
10573 // Clang Extensions.
10574 //===----------------------------------------------------------------------===//
10575 
10576 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10577 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10578   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10579 
10580   if (LangOpts.CPlusPlus) {
10581     Decl *ManglingContextDecl;
10582     if (MangleNumberingContext *MCtx =
10583             getCurrentMangleNumberContext(Block->getDeclContext(),
10584                                           ManglingContextDecl)) {
10585       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10586       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10587     }
10588   }
10589 
10590   PushBlockScope(CurScope, Block);
10591   CurContext->addDecl(Block);
10592   if (CurScope)
10593     PushDeclContext(CurScope, Block);
10594   else
10595     CurContext = Block;
10596 
10597   getCurBlock()->HasImplicitReturnType = true;
10598 
10599   // Enter a new evaluation context to insulate the block from any
10600   // cleanups from the enclosing full-expression.
10601   PushExpressionEvaluationContext(PotentiallyEvaluated);
10602 }
10603 
10604 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10605                                Scope *CurScope) {
10606   assert(ParamInfo.getIdentifier() == nullptr &&
10607          "block-id should have no identifier!");
10608   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10609   BlockScopeInfo *CurBlock = getCurBlock();
10610 
10611   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10612   QualType T = Sig->getType();
10613 
10614   // FIXME: We should allow unexpanded parameter packs here, but that would,
10615   // in turn, make the block expression contain unexpanded parameter packs.
10616   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10617     // Drop the parameters.
10618     FunctionProtoType::ExtProtoInfo EPI;
10619     EPI.HasTrailingReturn = false;
10620     EPI.TypeQuals |= DeclSpec::TQ_const;
10621     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10622     Sig = Context.getTrivialTypeSourceInfo(T);
10623   }
10624 
10625   // GetTypeForDeclarator always produces a function type for a block
10626   // literal signature.  Furthermore, it is always a FunctionProtoType
10627   // unless the function was written with a typedef.
10628   assert(T->isFunctionType() &&
10629          "GetTypeForDeclarator made a non-function block signature");
10630 
10631   // Look for an explicit signature in that function type.
10632   FunctionProtoTypeLoc ExplicitSignature;
10633 
10634   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10635   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10636 
10637     // Check whether that explicit signature was synthesized by
10638     // GetTypeForDeclarator.  If so, don't save that as part of the
10639     // written signature.
10640     if (ExplicitSignature.getLocalRangeBegin() ==
10641         ExplicitSignature.getLocalRangeEnd()) {
10642       // This would be much cheaper if we stored TypeLocs instead of
10643       // TypeSourceInfos.
10644       TypeLoc Result = ExplicitSignature.getReturnLoc();
10645       unsigned Size = Result.getFullDataSize();
10646       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10647       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10648 
10649       ExplicitSignature = FunctionProtoTypeLoc();
10650     }
10651   }
10652 
10653   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10654   CurBlock->FunctionType = T;
10655 
10656   const FunctionType *Fn = T->getAs<FunctionType>();
10657   QualType RetTy = Fn->getReturnType();
10658   bool isVariadic =
10659     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10660 
10661   CurBlock->TheDecl->setIsVariadic(isVariadic);
10662 
10663   // Context.DependentTy is used as a placeholder for a missing block
10664   // return type.  TODO:  what should we do with declarators like:
10665   //   ^ * { ... }
10666   // If the answer is "apply template argument deduction"....
10667   if (RetTy != Context.DependentTy) {
10668     CurBlock->ReturnType = RetTy;
10669     CurBlock->TheDecl->setBlockMissingReturnType(false);
10670     CurBlock->HasImplicitReturnType = false;
10671   }
10672 
10673   // Push block parameters from the declarator if we had them.
10674   SmallVector<ParmVarDecl*, 8> Params;
10675   if (ExplicitSignature) {
10676     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10677       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10678       if (Param->getIdentifier() == nullptr &&
10679           !Param->isImplicit() &&
10680           !Param->isInvalidDecl() &&
10681           !getLangOpts().CPlusPlus)
10682         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10683       Params.push_back(Param);
10684     }
10685 
10686   // Fake up parameter variables if we have a typedef, like
10687   //   ^ fntype { ... }
10688   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10689     for (const auto &I : Fn->param_types()) {
10690       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10691           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10692       Params.push_back(Param);
10693     }
10694   }
10695 
10696   // Set the parameters on the block decl.
10697   if (!Params.empty()) {
10698     CurBlock->TheDecl->setParams(Params);
10699     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10700                              CurBlock->TheDecl->param_end(),
10701                              /*CheckParameterNames=*/false);
10702   }
10703 
10704   // Finally we can process decl attributes.
10705   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10706 
10707   // Put the parameter variables in scope.
10708   for (auto AI : CurBlock->TheDecl->params()) {
10709     AI->setOwningFunction(CurBlock->TheDecl);
10710 
10711     // If this has an identifier, add it to the scope stack.
10712     if (AI->getIdentifier()) {
10713       CheckShadow(CurBlock->TheScope, AI);
10714 
10715       PushOnScopeChains(AI, CurBlock->TheScope);
10716     }
10717   }
10718 }
10719 
10720 /// ActOnBlockError - If there is an error parsing a block, this callback
10721 /// is invoked to pop the information about the block from the action impl.
10722 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10723   // Leave the expression-evaluation context.
10724   DiscardCleanupsInEvaluationContext();
10725   PopExpressionEvaluationContext();
10726 
10727   // Pop off CurBlock, handle nested blocks.
10728   PopDeclContext();
10729   PopFunctionScopeInfo();
10730 }
10731 
10732 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10733 /// literal was successfully completed.  ^(int x){...}
10734 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10735                                     Stmt *Body, Scope *CurScope) {
10736   // If blocks are disabled, emit an error.
10737   if (!LangOpts.Blocks)
10738     Diag(CaretLoc, diag::err_blocks_disable);
10739 
10740   // Leave the expression-evaluation context.
10741   if (hasAnyUnrecoverableErrorsInThisFunction())
10742     DiscardCleanupsInEvaluationContext();
10743   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10744   PopExpressionEvaluationContext();
10745 
10746   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10747 
10748   if (BSI->HasImplicitReturnType)
10749     deduceClosureReturnType(*BSI);
10750 
10751   PopDeclContext();
10752 
10753   QualType RetTy = Context.VoidTy;
10754   if (!BSI->ReturnType.isNull())
10755     RetTy = BSI->ReturnType;
10756 
10757   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10758   QualType BlockTy;
10759 
10760   // Set the captured variables on the block.
10761   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10762   SmallVector<BlockDecl::Capture, 4> Captures;
10763   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10764     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10765     if (Cap.isThisCapture())
10766       continue;
10767     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10768                               Cap.isNested(), Cap.getInitExpr());
10769     Captures.push_back(NewCap);
10770   }
10771   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10772                             BSI->CXXThisCaptureIndex != 0);
10773 
10774   // If the user wrote a function type in some form, try to use that.
10775   if (!BSI->FunctionType.isNull()) {
10776     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10777 
10778     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10779     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10780 
10781     // Turn protoless block types into nullary block types.
10782     if (isa<FunctionNoProtoType>(FTy)) {
10783       FunctionProtoType::ExtProtoInfo EPI;
10784       EPI.ExtInfo = Ext;
10785       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10786 
10787     // Otherwise, if we don't need to change anything about the function type,
10788     // preserve its sugar structure.
10789     } else if (FTy->getReturnType() == RetTy &&
10790                (!NoReturn || FTy->getNoReturnAttr())) {
10791       BlockTy = BSI->FunctionType;
10792 
10793     // Otherwise, make the minimal modifications to the function type.
10794     } else {
10795       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10796       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10797       EPI.TypeQuals = 0; // FIXME: silently?
10798       EPI.ExtInfo = Ext;
10799       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10800     }
10801 
10802   // If we don't have a function type, just build one from nothing.
10803   } else {
10804     FunctionProtoType::ExtProtoInfo EPI;
10805     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10806     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10807   }
10808 
10809   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10810                            BSI->TheDecl->param_end());
10811   BlockTy = Context.getBlockPointerType(BlockTy);
10812 
10813   // If needed, diagnose invalid gotos and switches in the block.
10814   if (getCurFunction()->NeedsScopeChecking() &&
10815       !PP.isCodeCompletionEnabled())
10816     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10817 
10818   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10819 
10820   // Try to apply the named return value optimization. We have to check again
10821   // if we can do this, though, because blocks keep return statements around
10822   // to deduce an implicit return type.
10823   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10824       !BSI->TheDecl->isDependentContext())
10825     computeNRVO(Body, BSI);
10826 
10827   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10828   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10829   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10830 
10831   // If the block isn't obviously global, i.e. it captures anything at
10832   // all, then we need to do a few things in the surrounding context:
10833   if (Result->getBlockDecl()->hasCaptures()) {
10834     // First, this expression has a new cleanup object.
10835     ExprCleanupObjects.push_back(Result->getBlockDecl());
10836     ExprNeedsCleanups = true;
10837 
10838     // It also gets a branch-protected scope if any of the captured
10839     // variables needs destruction.
10840     for (const auto &CI : Result->getBlockDecl()->captures()) {
10841       const VarDecl *var = CI.getVariable();
10842       if (var->getType().isDestructedType() != QualType::DK_none) {
10843         getCurFunction()->setHasBranchProtectedScope();
10844         break;
10845       }
10846     }
10847   }
10848 
10849   return Result;
10850 }
10851 
10852 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10853                                         Expr *E, ParsedType Ty,
10854                                         SourceLocation RPLoc) {
10855   TypeSourceInfo *TInfo;
10856   GetTypeFromParser(Ty, &TInfo);
10857   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10858 }
10859 
10860 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10861                                 Expr *E, TypeSourceInfo *TInfo,
10862                                 SourceLocation RPLoc) {
10863   Expr *OrigExpr = E;
10864 
10865   // Get the va_list type
10866   QualType VaListType = Context.getBuiltinVaListType();
10867   if (VaListType->isArrayType()) {
10868     // Deal with implicit array decay; for example, on x86-64,
10869     // va_list is an array, but it's supposed to decay to
10870     // a pointer for va_arg.
10871     VaListType = Context.getArrayDecayedType(VaListType);
10872     // Make sure the input expression also decays appropriately.
10873     ExprResult Result = UsualUnaryConversions(E);
10874     if (Result.isInvalid())
10875       return ExprError();
10876     E = Result.get();
10877   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10878     // If va_list is a record type and we are compiling in C++ mode,
10879     // check the argument using reference binding.
10880     InitializedEntity Entity
10881       = InitializedEntity::InitializeParameter(Context,
10882           Context.getLValueReferenceType(VaListType), false);
10883     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10884     if (Init.isInvalid())
10885       return ExprError();
10886     E = Init.getAs<Expr>();
10887   } else {
10888     // Otherwise, the va_list argument must be an l-value because
10889     // it is modified by va_arg.
10890     if (!E->isTypeDependent() &&
10891         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10892       return ExprError();
10893   }
10894 
10895   if (!E->isTypeDependent() &&
10896       !Context.hasSameType(VaListType, E->getType())) {
10897     return ExprError(Diag(E->getLocStart(),
10898                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10899       << OrigExpr->getType() << E->getSourceRange());
10900   }
10901 
10902   if (!TInfo->getType()->isDependentType()) {
10903     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10904                             diag::err_second_parameter_to_va_arg_incomplete,
10905                             TInfo->getTypeLoc()))
10906       return ExprError();
10907 
10908     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10909                                TInfo->getType(),
10910                                diag::err_second_parameter_to_va_arg_abstract,
10911                                TInfo->getTypeLoc()))
10912       return ExprError();
10913 
10914     if (!TInfo->getType().isPODType(Context)) {
10915       Diag(TInfo->getTypeLoc().getBeginLoc(),
10916            TInfo->getType()->isObjCLifetimeType()
10917              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10918              : diag::warn_second_parameter_to_va_arg_not_pod)
10919         << TInfo->getType()
10920         << TInfo->getTypeLoc().getSourceRange();
10921     }
10922 
10923     // Check for va_arg where arguments of the given type will be promoted
10924     // (i.e. this va_arg is guaranteed to have undefined behavior).
10925     QualType PromoteType;
10926     if (TInfo->getType()->isPromotableIntegerType()) {
10927       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10928       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10929         PromoteType = QualType();
10930     }
10931     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10932       PromoteType = Context.DoubleTy;
10933     if (!PromoteType.isNull())
10934       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10935                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10936                           << TInfo->getType()
10937                           << PromoteType
10938                           << TInfo->getTypeLoc().getSourceRange());
10939   }
10940 
10941   QualType T = TInfo->getType().getNonLValueExprType(Context);
10942   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10943 }
10944 
10945 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10946   // The type of __null will be int or long, depending on the size of
10947   // pointers on the target.
10948   QualType Ty;
10949   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10950   if (pw == Context.getTargetInfo().getIntWidth())
10951     Ty = Context.IntTy;
10952   else if (pw == Context.getTargetInfo().getLongWidth())
10953     Ty = Context.LongTy;
10954   else if (pw == Context.getTargetInfo().getLongLongWidth())
10955     Ty = Context.LongLongTy;
10956   else {
10957     llvm_unreachable("I don't know size of pointer!");
10958   }
10959 
10960   return new (Context) GNUNullExpr(Ty, TokenLoc);
10961 }
10962 
10963 bool
10964 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10965   if (!getLangOpts().ObjC1)
10966     return false;
10967 
10968   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10969   if (!PT)
10970     return false;
10971 
10972   if (!PT->isObjCIdType()) {
10973     // Check if the destination is the 'NSString' interface.
10974     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10975     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10976       return false;
10977   }
10978 
10979   // Ignore any parens, implicit casts (should only be
10980   // array-to-pointer decays), and not-so-opaque values.  The last is
10981   // important for making this trigger for property assignments.
10982   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10983   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10984     if (OV->getSourceExpr())
10985       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10986 
10987   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10988   if (!SL || !SL->isAscii())
10989     return false;
10990   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10991     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10992   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10993   return true;
10994 }
10995 
10996 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10997                                     SourceLocation Loc,
10998                                     QualType DstType, QualType SrcType,
10999                                     Expr *SrcExpr, AssignmentAction Action,
11000                                     bool *Complained) {
11001   if (Complained)
11002     *Complained = false;
11003 
11004   // Decode the result (notice that AST's are still created for extensions).
11005   bool CheckInferredResultType = false;
11006   bool isInvalid = false;
11007   unsigned DiagKind = 0;
11008   FixItHint Hint;
11009   ConversionFixItGenerator ConvHints;
11010   bool MayHaveConvFixit = false;
11011   bool MayHaveFunctionDiff = false;
11012   const ObjCInterfaceDecl *IFace = nullptr;
11013   const ObjCProtocolDecl *PDecl = nullptr;
11014 
11015   switch (ConvTy) {
11016   case Compatible:
11017       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11018       return false;
11019 
11020   case PointerToInt:
11021     DiagKind = diag::ext_typecheck_convert_pointer_int;
11022     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11023     MayHaveConvFixit = true;
11024     break;
11025   case IntToPointer:
11026     DiagKind = diag::ext_typecheck_convert_int_pointer;
11027     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11028     MayHaveConvFixit = true;
11029     break;
11030   case IncompatiblePointer:
11031       DiagKind =
11032         (Action == AA_Passing_CFAudited ?
11033           diag::err_arc_typecheck_convert_incompatible_pointer :
11034           diag::ext_typecheck_convert_incompatible_pointer);
11035     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11036       SrcType->isObjCObjectPointerType();
11037     if (Hint.isNull() && !CheckInferredResultType) {
11038       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11039     }
11040     else if (CheckInferredResultType) {
11041       SrcType = SrcType.getUnqualifiedType();
11042       DstType = DstType.getUnqualifiedType();
11043     }
11044     MayHaveConvFixit = true;
11045     break;
11046   case IncompatiblePointerSign:
11047     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11048     break;
11049   case FunctionVoidPointer:
11050     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11051     break;
11052   case IncompatiblePointerDiscardsQualifiers: {
11053     // Perform array-to-pointer decay if necessary.
11054     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11055 
11056     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11057     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11058     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11059       DiagKind = diag::err_typecheck_incompatible_address_space;
11060       break;
11061 
11062 
11063     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
11064       DiagKind = diag::err_typecheck_incompatible_ownership;
11065       break;
11066     }
11067 
11068     llvm_unreachable("unknown error case for discarding qualifiers!");
11069     // fallthrough
11070   }
11071   case CompatiblePointerDiscardsQualifiers:
11072     // If the qualifiers lost were because we were applying the
11073     // (deprecated) C++ conversion from a string literal to a char*
11074     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
11075     // Ideally, this check would be performed in
11076     // checkPointerTypesForAssignment. However, that would require a
11077     // bit of refactoring (so that the second argument is an
11078     // expression, rather than a type), which should be done as part
11079     // of a larger effort to fix checkPointerTypesForAssignment for
11080     // C++ semantics.
11081     if (getLangOpts().CPlusPlus &&
11082         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11083       return false;
11084     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11085     break;
11086   case IncompatibleNestedPointerQualifiers:
11087     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
11088     break;
11089   case IntToBlockPointer:
11090     DiagKind = diag::err_int_to_block_pointer;
11091     break;
11092   case IncompatibleBlockPointer:
11093     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
11094     break;
11095   case IncompatibleObjCQualifiedId: {
11096     if (SrcType->isObjCQualifiedIdType()) {
11097       const ObjCObjectPointerType *srcOPT =
11098                 SrcType->getAs<ObjCObjectPointerType>();
11099       for (auto *srcProto : srcOPT->quals()) {
11100         PDecl = srcProto;
11101         break;
11102       }
11103       if (const ObjCInterfaceType *IFaceT =
11104             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11105         IFace = IFaceT->getDecl();
11106     }
11107     else if (DstType->isObjCQualifiedIdType()) {
11108       const ObjCObjectPointerType *dstOPT =
11109         DstType->getAs<ObjCObjectPointerType>();
11110       for (auto *dstProto : dstOPT->quals()) {
11111         PDecl = dstProto;
11112         break;
11113       }
11114       if (const ObjCInterfaceType *IFaceT =
11115             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11116         IFace = IFaceT->getDecl();
11117     }
11118     DiagKind = diag::warn_incompatible_qualified_id;
11119     break;
11120   }
11121   case IncompatibleVectors:
11122     DiagKind = diag::warn_incompatible_vectors;
11123     break;
11124   case IncompatibleObjCWeakRef:
11125     DiagKind = diag::err_arc_weak_unavailable_assign;
11126     break;
11127   case Incompatible:
11128     DiagKind = diag::err_typecheck_convert_incompatible;
11129     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11130     MayHaveConvFixit = true;
11131     isInvalid = true;
11132     MayHaveFunctionDiff = true;
11133     break;
11134   }
11135 
11136   QualType FirstType, SecondType;
11137   switch (Action) {
11138   case AA_Assigning:
11139   case AA_Initializing:
11140     // The destination type comes first.
11141     FirstType = DstType;
11142     SecondType = SrcType;
11143     break;
11144 
11145   case AA_Returning:
11146   case AA_Passing:
11147   case AA_Passing_CFAudited:
11148   case AA_Converting:
11149   case AA_Sending:
11150   case AA_Casting:
11151     // The source type comes first.
11152     FirstType = SrcType;
11153     SecondType = DstType;
11154     break;
11155   }
11156 
11157   PartialDiagnostic FDiag = PDiag(DiagKind);
11158   if (Action == AA_Passing_CFAudited)
11159     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11160   else
11161     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11162 
11163   // If we can fix the conversion, suggest the FixIts.
11164   assert(ConvHints.isNull() || Hint.isNull());
11165   if (!ConvHints.isNull()) {
11166     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11167          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11168       FDiag << *HI;
11169   } else {
11170     FDiag << Hint;
11171   }
11172   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11173 
11174   if (MayHaveFunctionDiff)
11175     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11176 
11177   Diag(Loc, FDiag);
11178   if (DiagKind == diag::warn_incompatible_qualified_id &&
11179       PDecl && IFace && !IFace->hasDefinition())
11180       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11181         << IFace->getName() << PDecl->getName();
11182 
11183   if (SecondType == Context.OverloadTy)
11184     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11185                               FirstType);
11186 
11187   if (CheckInferredResultType)
11188     EmitRelatedResultTypeNote(SrcExpr);
11189 
11190   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11191     EmitRelatedResultTypeNoteForReturn(DstType);
11192 
11193   if (Complained)
11194     *Complained = true;
11195   return isInvalid;
11196 }
11197 
11198 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11199                                                  llvm::APSInt *Result) {
11200   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11201   public:
11202     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11203       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11204     }
11205   } Diagnoser;
11206 
11207   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11208 }
11209 
11210 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11211                                                  llvm::APSInt *Result,
11212                                                  unsigned DiagID,
11213                                                  bool AllowFold) {
11214   class IDDiagnoser : public VerifyICEDiagnoser {
11215     unsigned DiagID;
11216 
11217   public:
11218     IDDiagnoser(unsigned DiagID)
11219       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11220 
11221     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11222       S.Diag(Loc, DiagID) << SR;
11223     }
11224   } Diagnoser(DiagID);
11225 
11226   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11227 }
11228 
11229 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11230                                             SourceRange SR) {
11231   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11232 }
11233 
11234 ExprResult
11235 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11236                                       VerifyICEDiagnoser &Diagnoser,
11237                                       bool AllowFold) {
11238   SourceLocation DiagLoc = E->getLocStart();
11239 
11240   if (getLangOpts().CPlusPlus11) {
11241     // C++11 [expr.const]p5:
11242     //   If an expression of literal class type is used in a context where an
11243     //   integral constant expression is required, then that class type shall
11244     //   have a single non-explicit conversion function to an integral or
11245     //   unscoped enumeration type
11246     ExprResult Converted;
11247     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11248     public:
11249       CXX11ConvertDiagnoser(bool Silent)
11250           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11251                                 Silent, true) {}
11252 
11253       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11254                                            QualType T) override {
11255         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11256       }
11257 
11258       SemaDiagnosticBuilder diagnoseIncomplete(
11259           Sema &S, SourceLocation Loc, QualType T) override {
11260         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11261       }
11262 
11263       SemaDiagnosticBuilder diagnoseExplicitConv(
11264           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11265         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11266       }
11267 
11268       SemaDiagnosticBuilder noteExplicitConv(
11269           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11270         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11271                  << ConvTy->isEnumeralType() << ConvTy;
11272       }
11273 
11274       SemaDiagnosticBuilder diagnoseAmbiguous(
11275           Sema &S, SourceLocation Loc, QualType T) override {
11276         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11277       }
11278 
11279       SemaDiagnosticBuilder noteAmbiguous(
11280           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11281         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11282                  << ConvTy->isEnumeralType() << ConvTy;
11283       }
11284 
11285       SemaDiagnosticBuilder diagnoseConversion(
11286           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11287         llvm_unreachable("conversion functions are permitted");
11288       }
11289     } ConvertDiagnoser(Diagnoser.Suppress);
11290 
11291     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11292                                                     ConvertDiagnoser);
11293     if (Converted.isInvalid())
11294       return Converted;
11295     E = Converted.get();
11296     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11297       return ExprError();
11298   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11299     // An ICE must be of integral or unscoped enumeration type.
11300     if (!Diagnoser.Suppress)
11301       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11302     return ExprError();
11303   }
11304 
11305   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11306   // in the non-ICE case.
11307   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11308     if (Result)
11309       *Result = E->EvaluateKnownConstInt(Context);
11310     return E;
11311   }
11312 
11313   Expr::EvalResult EvalResult;
11314   SmallVector<PartialDiagnosticAt, 8> Notes;
11315   EvalResult.Diag = &Notes;
11316 
11317   // Try to evaluate the expression, and produce diagnostics explaining why it's
11318   // not a constant expression as a side-effect.
11319   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11320                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11321 
11322   // In C++11, we can rely on diagnostics being produced for any expression
11323   // which is not a constant expression. If no diagnostics were produced, then
11324   // this is a constant expression.
11325   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11326     if (Result)
11327       *Result = EvalResult.Val.getInt();
11328     return E;
11329   }
11330 
11331   // If our only note is the usual "invalid subexpression" note, just point
11332   // the caret at its location rather than producing an essentially
11333   // redundant note.
11334   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11335         diag::note_invalid_subexpr_in_const_expr) {
11336     DiagLoc = Notes[0].first;
11337     Notes.clear();
11338   }
11339 
11340   if (!Folded || !AllowFold) {
11341     if (!Diagnoser.Suppress) {
11342       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11343       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11344         Diag(Notes[I].first, Notes[I].second);
11345     }
11346 
11347     return ExprError();
11348   }
11349 
11350   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11351   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11352     Diag(Notes[I].first, Notes[I].second);
11353 
11354   if (Result)
11355     *Result = EvalResult.Val.getInt();
11356   return E;
11357 }
11358 
11359 namespace {
11360   // Handle the case where we conclude a expression which we speculatively
11361   // considered to be unevaluated is actually evaluated.
11362   class TransformToPE : public TreeTransform<TransformToPE> {
11363     typedef TreeTransform<TransformToPE> BaseTransform;
11364 
11365   public:
11366     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11367 
11368     // Make sure we redo semantic analysis
11369     bool AlwaysRebuild() { return true; }
11370 
11371     // Make sure we handle LabelStmts correctly.
11372     // FIXME: This does the right thing, but maybe we need a more general
11373     // fix to TreeTransform?
11374     StmtResult TransformLabelStmt(LabelStmt *S) {
11375       S->getDecl()->setStmt(nullptr);
11376       return BaseTransform::TransformLabelStmt(S);
11377     }
11378 
11379     // We need to special-case DeclRefExprs referring to FieldDecls which
11380     // are not part of a member pointer formation; normal TreeTransforming
11381     // doesn't catch this case because of the way we represent them in the AST.
11382     // FIXME: This is a bit ugly; is it really the best way to handle this
11383     // case?
11384     //
11385     // Error on DeclRefExprs referring to FieldDecls.
11386     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11387       if (isa<FieldDecl>(E->getDecl()) &&
11388           !SemaRef.isUnevaluatedContext())
11389         return SemaRef.Diag(E->getLocation(),
11390                             diag::err_invalid_non_static_member_use)
11391             << E->getDecl() << E->getSourceRange();
11392 
11393       return BaseTransform::TransformDeclRefExpr(E);
11394     }
11395 
11396     // Exception: filter out member pointer formation
11397     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11398       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11399         return E;
11400 
11401       return BaseTransform::TransformUnaryOperator(E);
11402     }
11403 
11404     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11405       // Lambdas never need to be transformed.
11406       return E;
11407     }
11408   };
11409 }
11410 
11411 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11412   assert(isUnevaluatedContext() &&
11413          "Should only transform unevaluated expressions");
11414   ExprEvalContexts.back().Context =
11415       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11416   if (isUnevaluatedContext())
11417     return E;
11418   return TransformToPE(*this).TransformExpr(E);
11419 }
11420 
11421 void
11422 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11423                                       Decl *LambdaContextDecl,
11424                                       bool IsDecltype) {
11425   ExprEvalContexts.push_back(
11426              ExpressionEvaluationContextRecord(NewContext,
11427                                                ExprCleanupObjects.size(),
11428                                                ExprNeedsCleanups,
11429                                                LambdaContextDecl,
11430                                                IsDecltype));
11431   ExprNeedsCleanups = false;
11432   if (!MaybeODRUseExprs.empty())
11433     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11434 }
11435 
11436 void
11437 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11438                                       ReuseLambdaContextDecl_t,
11439                                       bool IsDecltype) {
11440   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11441   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11442 }
11443 
11444 void Sema::PopExpressionEvaluationContext() {
11445   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11446   unsigned NumTypos = Rec.NumTypos;
11447 
11448   if (!Rec.Lambdas.empty()) {
11449     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11450       unsigned D;
11451       if (Rec.isUnevaluated()) {
11452         // C++11 [expr.prim.lambda]p2:
11453         //   A lambda-expression shall not appear in an unevaluated operand
11454         //   (Clause 5).
11455         D = diag::err_lambda_unevaluated_operand;
11456       } else {
11457         // C++1y [expr.const]p2:
11458         //   A conditional-expression e is a core constant expression unless the
11459         //   evaluation of e, following the rules of the abstract machine, would
11460         //   evaluate [...] a lambda-expression.
11461         D = diag::err_lambda_in_constant_expression;
11462       }
11463       for (const auto *L : Rec.Lambdas)
11464         Diag(L->getLocStart(), D);
11465     } else {
11466       // Mark the capture expressions odr-used. This was deferred
11467       // during lambda expression creation.
11468       for (auto *Lambda : Rec.Lambdas) {
11469         for (auto *C : Lambda->capture_inits())
11470           MarkDeclarationsReferencedInExpr(C);
11471       }
11472     }
11473   }
11474 
11475   // When are coming out of an unevaluated context, clear out any
11476   // temporaries that we may have created as part of the evaluation of
11477   // the expression in that context: they aren't relevant because they
11478   // will never be constructed.
11479   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11480     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11481                              ExprCleanupObjects.end());
11482     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11483     CleanupVarDeclMarking();
11484     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11485   // Otherwise, merge the contexts together.
11486   } else {
11487     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11488     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11489                             Rec.SavedMaybeODRUseExprs.end());
11490   }
11491 
11492   // Pop the current expression evaluation context off the stack.
11493   ExprEvalContexts.pop_back();
11494 
11495   if (!ExprEvalContexts.empty())
11496     ExprEvalContexts.back().NumTypos += NumTypos;
11497   else
11498     assert(NumTypos == 0 && "There are outstanding typos after popping the "
11499                             "last ExpressionEvaluationContextRecord");
11500 }
11501 
11502 void Sema::DiscardCleanupsInEvaluationContext() {
11503   ExprCleanupObjects.erase(
11504          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11505          ExprCleanupObjects.end());
11506   ExprNeedsCleanups = false;
11507   MaybeODRUseExprs.clear();
11508 }
11509 
11510 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11511   if (!E->getType()->isVariablyModifiedType())
11512     return E;
11513   return TransformToPotentiallyEvaluated(E);
11514 }
11515 
11516 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11517   // Do not mark anything as "used" within a dependent context; wait for
11518   // an instantiation.
11519   if (SemaRef.CurContext->isDependentContext())
11520     return false;
11521 
11522   switch (SemaRef.ExprEvalContexts.back().Context) {
11523     case Sema::Unevaluated:
11524     case Sema::UnevaluatedAbstract:
11525       // We are in an expression that is not potentially evaluated; do nothing.
11526       // (Depending on how you read the standard, we actually do need to do
11527       // something here for null pointer constants, but the standard's
11528       // definition of a null pointer constant is completely crazy.)
11529       return false;
11530 
11531     case Sema::ConstantEvaluated:
11532     case Sema::PotentiallyEvaluated:
11533       // We are in a potentially evaluated expression (or a constant-expression
11534       // in C++03); we need to do implicit template instantiation, implicitly
11535       // define class members, and mark most declarations as used.
11536       return true;
11537 
11538     case Sema::PotentiallyEvaluatedIfUsed:
11539       // Referenced declarations will only be used if the construct in the
11540       // containing expression is used.
11541       return false;
11542   }
11543   llvm_unreachable("Invalid context");
11544 }
11545 
11546 /// \brief Mark a function referenced, and check whether it is odr-used
11547 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11548 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
11549                                   bool OdrUse) {
11550   assert(Func && "No function?");
11551 
11552   Func->setReferenced();
11553 
11554   // C++11 [basic.def.odr]p3:
11555   //   A function whose name appears as a potentially-evaluated expression is
11556   //   odr-used if it is the unique lookup result or the selected member of a
11557   //   set of overloaded functions [...].
11558   //
11559   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11560   // can just check that here. Skip the rest of this function if we've already
11561   // marked the function as used.
11562   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11563     // C++11 [temp.inst]p3:
11564     //   Unless a function template specialization has been explicitly
11565     //   instantiated or explicitly specialized, the function template
11566     //   specialization is implicitly instantiated when the specialization is
11567     //   referenced in a context that requires a function definition to exist.
11568     //
11569     // We consider constexpr function templates to be referenced in a context
11570     // that requires a definition to exist whenever they are referenced.
11571     //
11572     // FIXME: This instantiates constexpr functions too frequently. If this is
11573     // really an unevaluated context (and we're not just in the definition of a
11574     // function template or overload resolution or other cases which we
11575     // incorrectly consider to be unevaluated contexts), and we're not in a
11576     // subexpression which we actually need to evaluate (for instance, a
11577     // template argument, array bound or an expression in a braced-init-list),
11578     // we are not permitted to instantiate this constexpr function definition.
11579     //
11580     // FIXME: This also implicitly defines special members too frequently. They
11581     // are only supposed to be implicitly defined if they are odr-used, but they
11582     // are not odr-used from constant expressions in unevaluated contexts.
11583     // However, they cannot be referenced if they are deleted, and they are
11584     // deleted whenever the implicit definition of the special member would
11585     // fail.
11586     if (!Func->isConstexpr() || Func->getBody())
11587       return;
11588     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11589     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11590       return;
11591   }
11592 
11593   // Note that this declaration has been used.
11594   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11595     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11596     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11597       if (Constructor->isDefaultConstructor()) {
11598         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11599           return;
11600         DefineImplicitDefaultConstructor(Loc, Constructor);
11601       } else if (Constructor->isCopyConstructor()) {
11602         DefineImplicitCopyConstructor(Loc, Constructor);
11603       } else if (Constructor->isMoveConstructor()) {
11604         DefineImplicitMoveConstructor(Loc, Constructor);
11605       }
11606     } else if (Constructor->getInheritedConstructor()) {
11607       DefineInheritingConstructor(Loc, Constructor);
11608     }
11609   } else if (CXXDestructorDecl *Destructor =
11610                  dyn_cast<CXXDestructorDecl>(Func)) {
11611     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11612     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11613       DefineImplicitDestructor(Loc, Destructor);
11614     if (Destructor->isVirtual())
11615       MarkVTableUsed(Loc, Destructor->getParent());
11616   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11617     if (MethodDecl->isOverloadedOperator() &&
11618         MethodDecl->getOverloadedOperator() == OO_Equal) {
11619       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11620       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11621         if (MethodDecl->isCopyAssignmentOperator())
11622           DefineImplicitCopyAssignment(Loc, MethodDecl);
11623         else
11624           DefineImplicitMoveAssignment(Loc, MethodDecl);
11625       }
11626     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11627                MethodDecl->getParent()->isLambda()) {
11628       CXXConversionDecl *Conversion =
11629           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11630       if (Conversion->isLambdaToBlockPointerConversion())
11631         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11632       else
11633         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11634     } else if (MethodDecl->isVirtual())
11635       MarkVTableUsed(Loc, MethodDecl->getParent());
11636   }
11637 
11638   // Recursive functions should be marked when used from another function.
11639   // FIXME: Is this really right?
11640   if (CurContext == Func) return;
11641 
11642   // Resolve the exception specification for any function which is
11643   // used: CodeGen will need it.
11644   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11645   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11646     ResolveExceptionSpec(Loc, FPT);
11647 
11648   if (!OdrUse) return;
11649 
11650   // Implicit instantiation of function templates and member functions of
11651   // class templates.
11652   if (Func->isImplicitlyInstantiable()) {
11653     bool AlreadyInstantiated = false;
11654     SourceLocation PointOfInstantiation = Loc;
11655     if (FunctionTemplateSpecializationInfo *SpecInfo
11656                               = Func->getTemplateSpecializationInfo()) {
11657       if (SpecInfo->getPointOfInstantiation().isInvalid())
11658         SpecInfo->setPointOfInstantiation(Loc);
11659       else if (SpecInfo->getTemplateSpecializationKind()
11660                  == TSK_ImplicitInstantiation) {
11661         AlreadyInstantiated = true;
11662         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11663       }
11664     } else if (MemberSpecializationInfo *MSInfo
11665                                 = Func->getMemberSpecializationInfo()) {
11666       if (MSInfo->getPointOfInstantiation().isInvalid())
11667         MSInfo->setPointOfInstantiation(Loc);
11668       else if (MSInfo->getTemplateSpecializationKind()
11669                  == TSK_ImplicitInstantiation) {
11670         AlreadyInstantiated = true;
11671         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11672       }
11673     }
11674 
11675     if (!AlreadyInstantiated || Func->isConstexpr()) {
11676       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11677           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11678           ActiveTemplateInstantiations.size())
11679         PendingLocalImplicitInstantiations.push_back(
11680             std::make_pair(Func, PointOfInstantiation));
11681       else if (Func->isConstexpr())
11682         // Do not defer instantiations of constexpr functions, to avoid the
11683         // expression evaluator needing to call back into Sema if it sees a
11684         // call to such a function.
11685         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11686       else {
11687         PendingInstantiations.push_back(std::make_pair(Func,
11688                                                        PointOfInstantiation));
11689         // Notify the consumer that a function was implicitly instantiated.
11690         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11691       }
11692     }
11693   } else {
11694     // Walk redefinitions, as some of them may be instantiable.
11695     for (auto i : Func->redecls()) {
11696       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11697         MarkFunctionReferenced(Loc, i);
11698     }
11699   }
11700 
11701   // Keep track of used but undefined functions.
11702   if (!Func->isDefined()) {
11703     if (mightHaveNonExternalLinkage(Func))
11704       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11705     else if (Func->getMostRecentDecl()->isInlined() &&
11706              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11707              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11708       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11709   }
11710 
11711   // Normally the most current decl is marked used while processing the use and
11712   // any subsequent decls are marked used by decl merging. This fails with
11713   // template instantiation since marking can happen at the end of the file
11714   // and, because of the two phase lookup, this function is called with at
11715   // decl in the middle of a decl chain. We loop to maintain the invariant
11716   // that once a decl is used, all decls after it are also used.
11717   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11718     F->markUsed(Context);
11719     if (F == Func)
11720       break;
11721   }
11722 }
11723 
11724 static void
11725 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11726                                    VarDecl *var, DeclContext *DC) {
11727   DeclContext *VarDC = var->getDeclContext();
11728 
11729   //  If the parameter still belongs to the translation unit, then
11730   //  we're actually just using one parameter in the declaration of
11731   //  the next.
11732   if (isa<ParmVarDecl>(var) &&
11733       isa<TranslationUnitDecl>(VarDC))
11734     return;
11735 
11736   // For C code, don't diagnose about capture if we're not actually in code
11737   // right now; it's impossible to write a non-constant expression outside of
11738   // function context, so we'll get other (more useful) diagnostics later.
11739   //
11740   // For C++, things get a bit more nasty... it would be nice to suppress this
11741   // diagnostic for certain cases like using a local variable in an array bound
11742   // for a member of a local class, but the correct predicate is not obvious.
11743   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11744     return;
11745 
11746   if (isa<CXXMethodDecl>(VarDC) &&
11747       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11748     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11749       << var->getIdentifier();
11750   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11751     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11752       << var->getIdentifier() << fn->getDeclName();
11753   } else if (isa<BlockDecl>(VarDC)) {
11754     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11755       << var->getIdentifier();
11756   } else {
11757     // FIXME: Is there any other context where a local variable can be
11758     // declared?
11759     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11760       << var->getIdentifier();
11761   }
11762 
11763   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11764       << var->getIdentifier();
11765 
11766   // FIXME: Add additional diagnostic info about class etc. which prevents
11767   // capture.
11768 }
11769 
11770 
11771 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11772                                       bool &SubCapturesAreNested,
11773                                       QualType &CaptureType,
11774                                       QualType &DeclRefType) {
11775    // Check whether we've already captured it.
11776   if (CSI->CaptureMap.count(Var)) {
11777     // If we found a capture, any subcaptures are nested.
11778     SubCapturesAreNested = true;
11779 
11780     // Retrieve the capture type for this variable.
11781     CaptureType = CSI->getCapture(Var).getCaptureType();
11782 
11783     // Compute the type of an expression that refers to this variable.
11784     DeclRefType = CaptureType.getNonReferenceType();
11785 
11786     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11787     if (Cap.isCopyCapture() &&
11788         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11789       DeclRefType.addConst();
11790     return true;
11791   }
11792   return false;
11793 }
11794 
11795 // Only block literals, captured statements, and lambda expressions can
11796 // capture; other scopes don't work.
11797 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11798                                  SourceLocation Loc,
11799                                  const bool Diagnose, Sema &S) {
11800   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11801     return getLambdaAwareParentOfDeclContext(DC);
11802   else {
11803     if (Diagnose)
11804        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11805   }
11806   return nullptr;
11807 }
11808 
11809 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11810 // certain types of variables (unnamed, variably modified types etc.)
11811 // so check for eligibility.
11812 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11813                                  SourceLocation Loc,
11814                                  const bool Diagnose, Sema &S) {
11815 
11816   bool IsBlock = isa<BlockScopeInfo>(CSI);
11817   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11818 
11819   // Lambdas are not allowed to capture unnamed variables
11820   // (e.g. anonymous unions).
11821   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11822   // assuming that's the intent.
11823   if (IsLambda && !Var->getDeclName()) {
11824     if (Diagnose) {
11825       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11826       S.Diag(Var->getLocation(), diag::note_declared_at);
11827     }
11828     return false;
11829   }
11830 
11831   // Prohibit variably-modified types in blocks; they're difficult to deal with.
11832   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
11833     if (Diagnose) {
11834       S.Diag(Loc, diag::err_ref_vm_type);
11835       S.Diag(Var->getLocation(), diag::note_previous_decl)
11836         << Var->getDeclName();
11837     }
11838     return false;
11839   }
11840   // Prohibit structs with flexible array members too.
11841   // We cannot capture what is in the tail end of the struct.
11842   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11843     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11844       if (Diagnose) {
11845         if (IsBlock)
11846           S.Diag(Loc, diag::err_ref_flexarray_type);
11847         else
11848           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11849             << Var->getDeclName();
11850         S.Diag(Var->getLocation(), diag::note_previous_decl)
11851           << Var->getDeclName();
11852       }
11853       return false;
11854     }
11855   }
11856   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11857   // Lambdas and captured statements are not allowed to capture __block
11858   // variables; they don't support the expected semantics.
11859   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11860     if (Diagnose) {
11861       S.Diag(Loc, diag::err_capture_block_variable)
11862         << Var->getDeclName() << !IsLambda;
11863       S.Diag(Var->getLocation(), diag::note_previous_decl)
11864         << Var->getDeclName();
11865     }
11866     return false;
11867   }
11868 
11869   return true;
11870 }
11871 
11872 // Returns true if the capture by block was successful.
11873 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11874                                  SourceLocation Loc,
11875                                  const bool BuildAndDiagnose,
11876                                  QualType &CaptureType,
11877                                  QualType &DeclRefType,
11878                                  const bool Nested,
11879                                  Sema &S) {
11880   Expr *CopyExpr = nullptr;
11881   bool ByRef = false;
11882 
11883   // Blocks are not allowed to capture arrays.
11884   if (CaptureType->isArrayType()) {
11885     if (BuildAndDiagnose) {
11886       S.Diag(Loc, diag::err_ref_array_type);
11887       S.Diag(Var->getLocation(), diag::note_previous_decl)
11888       << Var->getDeclName();
11889     }
11890     return false;
11891   }
11892 
11893   // Forbid the block-capture of autoreleasing variables.
11894   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11895     if (BuildAndDiagnose) {
11896       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11897         << /*block*/ 0;
11898       S.Diag(Var->getLocation(), diag::note_previous_decl)
11899         << Var->getDeclName();
11900     }
11901     return false;
11902   }
11903   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11904   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11905     // Block capture by reference does not change the capture or
11906     // declaration reference types.
11907     ByRef = true;
11908   } else {
11909     // Block capture by copy introduces 'const'.
11910     CaptureType = CaptureType.getNonReferenceType().withConst();
11911     DeclRefType = CaptureType;
11912 
11913     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11914       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11915         // The capture logic needs the destructor, so make sure we mark it.
11916         // Usually this is unnecessary because most local variables have
11917         // their destructors marked at declaration time, but parameters are
11918         // an exception because it's technically only the call site that
11919         // actually requires the destructor.
11920         if (isa<ParmVarDecl>(Var))
11921           S.FinalizeVarWithDestructor(Var, Record);
11922 
11923         // Enter a new evaluation context to insulate the copy
11924         // full-expression.
11925         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11926 
11927         // According to the blocks spec, the capture of a variable from
11928         // the stack requires a const copy constructor.  This is not true
11929         // of the copy/move done to move a __block variable to the heap.
11930         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11931                                                   DeclRefType.withConst(),
11932                                                   VK_LValue, Loc);
11933 
11934         ExprResult Result
11935           = S.PerformCopyInitialization(
11936               InitializedEntity::InitializeBlock(Var->getLocation(),
11937                                                   CaptureType, false),
11938               Loc, DeclRef);
11939 
11940         // Build a full-expression copy expression if initialization
11941         // succeeded and used a non-trivial constructor.  Recover from
11942         // errors by pretending that the copy isn't necessary.
11943         if (!Result.isInvalid() &&
11944             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11945                 ->isTrivial()) {
11946           Result = S.MaybeCreateExprWithCleanups(Result);
11947           CopyExpr = Result.get();
11948         }
11949       }
11950     }
11951   }
11952 
11953   // Actually capture the variable.
11954   if (BuildAndDiagnose)
11955     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11956                     SourceLocation(), CaptureType, CopyExpr);
11957 
11958   return true;
11959 
11960 }
11961 
11962 
11963 /// \brief Capture the given variable in the captured region.
11964 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11965                                     VarDecl *Var,
11966                                     SourceLocation Loc,
11967                                     const bool BuildAndDiagnose,
11968                                     QualType &CaptureType,
11969                                     QualType &DeclRefType,
11970                                     const bool RefersToEnclosingLocal,
11971                                     Sema &S) {
11972 
11973   // By default, capture variables by reference.
11974   bool ByRef = true;
11975   // Using an LValue reference type is consistent with Lambdas (see below).
11976   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11977   Expr *CopyExpr = nullptr;
11978   if (BuildAndDiagnose) {
11979     // The current implementation assumes that all variables are captured
11980     // by references. Since there is no capture by copy, no expression
11981     // evaluation will be needed.
11982     RecordDecl *RD = RSI->TheRecordDecl;
11983 
11984     FieldDecl *Field
11985       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11986                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11987                           nullptr, false, ICIS_NoInit);
11988     Field->setImplicit(true);
11989     Field->setAccess(AS_private);
11990     RD->addDecl(Field);
11991 
11992     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11993                                             DeclRefType, VK_LValue, Loc);
11994     Var->setReferenced(true);
11995     Var->markUsed(S.Context);
11996   }
11997 
11998   // Actually capture the variable.
11999   if (BuildAndDiagnose)
12000     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
12001                     SourceLocation(), CaptureType, CopyExpr);
12002 
12003 
12004   return true;
12005 }
12006 
12007 /// \brief Create a field within the lambda class for the variable
12008 ///  being captured.  Handle Array captures.
12009 static ExprResult addAsFieldToClosureType(Sema &S,
12010                                  LambdaScopeInfo *LSI,
12011                                   VarDecl *Var, QualType FieldType,
12012                                   QualType DeclRefType,
12013                                   SourceLocation Loc,
12014                                   bool RefersToEnclosingLocal) {
12015   CXXRecordDecl *Lambda = LSI->Lambda;
12016 
12017   // Build the non-static data member.
12018   FieldDecl *Field
12019     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
12020                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
12021                         nullptr, false, ICIS_NoInit);
12022   Field->setImplicit(true);
12023   Field->setAccess(AS_private);
12024   Lambda->addDecl(Field);
12025 
12026   // C++11 [expr.prim.lambda]p21:
12027   //   When the lambda-expression is evaluated, the entities that
12028   //   are captured by copy are used to direct-initialize each
12029   //   corresponding non-static data member of the resulting closure
12030   //   object. (For array members, the array elements are
12031   //   direct-initialized in increasing subscript order.) These
12032   //   initializations are performed in the (unspecified) order in
12033   //   which the non-static data members are declared.
12034 
12035   // Introduce a new evaluation context for the initialization, so
12036   // that temporaries introduced as part of the capture are retained
12037   // to be re-"exported" from the lambda expression itself.
12038   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
12039 
12040   // C++ [expr.prim.labda]p12:
12041   //   An entity captured by a lambda-expression is odr-used (3.2) in
12042   //   the scope containing the lambda-expression.
12043   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
12044                                           DeclRefType, VK_LValue, Loc);
12045   Var->setReferenced(true);
12046   Var->markUsed(S.Context);
12047 
12048   // When the field has array type, create index variables for each
12049   // dimension of the array. We use these index variables to subscript
12050   // the source array, and other clients (e.g., CodeGen) will perform
12051   // the necessary iteration with these index variables.
12052   SmallVector<VarDecl *, 4> IndexVariables;
12053   QualType BaseType = FieldType;
12054   QualType SizeType = S.Context.getSizeType();
12055   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
12056   while (const ConstantArrayType *Array
12057                         = S.Context.getAsConstantArrayType(BaseType)) {
12058     // Create the iteration variable for this array index.
12059     IdentifierInfo *IterationVarName = nullptr;
12060     {
12061       SmallString<8> Str;
12062       llvm::raw_svector_ostream OS(Str);
12063       OS << "__i" << IndexVariables.size();
12064       IterationVarName = &S.Context.Idents.get(OS.str());
12065     }
12066     VarDecl *IterationVar
12067       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
12068                         IterationVarName, SizeType,
12069                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
12070                         SC_None);
12071     IndexVariables.push_back(IterationVar);
12072     LSI->ArrayIndexVars.push_back(IterationVar);
12073 
12074     // Create a reference to the iteration variable.
12075     ExprResult IterationVarRef
12076       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
12077     assert(!IterationVarRef.isInvalid() &&
12078            "Reference to invented variable cannot fail!");
12079     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
12080     assert(!IterationVarRef.isInvalid() &&
12081            "Conversion of invented variable cannot fail!");
12082 
12083     // Subscript the array with this iteration variable.
12084     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
12085                              Ref, Loc, IterationVarRef.get(), Loc);
12086     if (Subscript.isInvalid()) {
12087       S.CleanupVarDeclMarking();
12088       S.DiscardCleanupsInEvaluationContext();
12089       return ExprError();
12090     }
12091 
12092     Ref = Subscript.get();
12093     BaseType = Array->getElementType();
12094   }
12095 
12096   // Construct the entity that we will be initializing. For an array, this
12097   // will be first element in the array, which may require several levels
12098   // of array-subscript entities.
12099   SmallVector<InitializedEntity, 4> Entities;
12100   Entities.reserve(1 + IndexVariables.size());
12101   Entities.push_back(
12102     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
12103         Field->getType(), Loc));
12104   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
12105     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
12106                                                             0,
12107                                                             Entities.back()));
12108 
12109   InitializationKind InitKind
12110     = InitializationKind::CreateDirect(Loc, Loc, Loc);
12111   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
12112   ExprResult Result(true);
12113   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
12114     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
12115 
12116   // If this initialization requires any cleanups (e.g., due to a
12117   // default argument to a copy constructor), note that for the
12118   // lambda.
12119   if (S.ExprNeedsCleanups)
12120     LSI->ExprNeedsCleanups = true;
12121 
12122   // Exit the expression evaluation context used for the capture.
12123   S.CleanupVarDeclMarking();
12124   S.DiscardCleanupsInEvaluationContext();
12125   return Result;
12126 }
12127 
12128 
12129 
12130 /// \brief Capture the given variable in the lambda.
12131 static bool captureInLambda(LambdaScopeInfo *LSI,
12132                             VarDecl *Var,
12133                             SourceLocation Loc,
12134                             const bool BuildAndDiagnose,
12135                             QualType &CaptureType,
12136                             QualType &DeclRefType,
12137                             const bool RefersToEnclosingLocal,
12138                             const Sema::TryCaptureKind Kind,
12139                             SourceLocation EllipsisLoc,
12140                             const bool IsTopScope,
12141                             Sema &S) {
12142 
12143   // Determine whether we are capturing by reference or by value.
12144   bool ByRef = false;
12145   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12146     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12147   } else {
12148     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12149   }
12150 
12151   // Compute the type of the field that will capture this variable.
12152   if (ByRef) {
12153     // C++11 [expr.prim.lambda]p15:
12154     //   An entity is captured by reference if it is implicitly or
12155     //   explicitly captured but not captured by copy. It is
12156     //   unspecified whether additional unnamed non-static data
12157     //   members are declared in the closure type for entities
12158     //   captured by reference.
12159     //
12160     // FIXME: It is not clear whether we want to build an lvalue reference
12161     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12162     // to do the former, while EDG does the latter. Core issue 1249 will
12163     // clarify, but for now we follow GCC because it's a more permissive and
12164     // easily defensible position.
12165     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12166   } else {
12167     // C++11 [expr.prim.lambda]p14:
12168     //   For each entity captured by copy, an unnamed non-static
12169     //   data member is declared in the closure type. The
12170     //   declaration order of these members is unspecified. The type
12171     //   of such a data member is the type of the corresponding
12172     //   captured entity if the entity is not a reference to an
12173     //   object, or the referenced type otherwise. [Note: If the
12174     //   captured entity is a reference to a function, the
12175     //   corresponding data member is also a reference to a
12176     //   function. - end note ]
12177     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12178       if (!RefType->getPointeeType()->isFunctionType())
12179         CaptureType = RefType->getPointeeType();
12180     }
12181 
12182     // Forbid the lambda copy-capture of autoreleasing variables.
12183     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12184       if (BuildAndDiagnose) {
12185         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12186         S.Diag(Var->getLocation(), diag::note_previous_decl)
12187           << Var->getDeclName();
12188       }
12189       return false;
12190     }
12191 
12192     // Make sure that by-copy captures are of a complete and non-abstract type.
12193     if (BuildAndDiagnose) {
12194       if (!CaptureType->isDependentType() &&
12195           S.RequireCompleteType(Loc, CaptureType,
12196                                 diag::err_capture_of_incomplete_type,
12197                                 Var->getDeclName()))
12198         return false;
12199 
12200       if (S.RequireNonAbstractType(Loc, CaptureType,
12201                                    diag::err_capture_of_abstract_type))
12202         return false;
12203     }
12204   }
12205 
12206   // Capture this variable in the lambda.
12207   Expr *CopyExpr = nullptr;
12208   if (BuildAndDiagnose) {
12209     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12210                                         CaptureType, DeclRefType, Loc,
12211                                         RefersToEnclosingLocal);
12212     if (!Result.isInvalid())
12213       CopyExpr = Result.get();
12214   }
12215 
12216   // Compute the type of a reference to this captured variable.
12217   if (ByRef)
12218     DeclRefType = CaptureType.getNonReferenceType();
12219   else {
12220     // C++ [expr.prim.lambda]p5:
12221     //   The closure type for a lambda-expression has a public inline
12222     //   function call operator [...]. This function call operator is
12223     //   declared const (9.3.1) if and only if the lambda-expression’s
12224     //   parameter-declaration-clause is not followed by mutable.
12225     DeclRefType = CaptureType.getNonReferenceType();
12226     if (!LSI->Mutable && !CaptureType->isReferenceType())
12227       DeclRefType.addConst();
12228   }
12229 
12230   // Add the capture.
12231   if (BuildAndDiagnose)
12232     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12233                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12234 
12235   return true;
12236 }
12237 
12238 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12239                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12240                               bool BuildAndDiagnose,
12241                               QualType &CaptureType,
12242                               QualType &DeclRefType,
12243 						                const unsigned *const FunctionScopeIndexToStopAt) {
12244   bool Nested = false;
12245 
12246   DeclContext *DC = CurContext;
12247   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12248       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12249   // We need to sync up the Declaration Context with the
12250   // FunctionScopeIndexToStopAt
12251   if (FunctionScopeIndexToStopAt) {
12252     unsigned FSIndex = FunctionScopes.size() - 1;
12253     while (FSIndex != MaxFunctionScopesIndex) {
12254       DC = getLambdaAwareParentOfDeclContext(DC);
12255       --FSIndex;
12256     }
12257   }
12258 
12259 
12260   // If the variable is declared in the current context (and is not an
12261   // init-capture), there is no need to capture it.
12262   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12263   if (!Var->hasLocalStorage()) return true;
12264 
12265   // Walk up the stack to determine whether we can capture the variable,
12266   // performing the "simple" checks that don't depend on type. We stop when
12267   // we've either hit the declared scope of the variable or find an existing
12268   // capture of that variable.  We start from the innermost capturing-entity
12269   // (the DC) and ensure that all intervening capturing-entities
12270   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12271   // declcontext can either capture the variable or have already captured
12272   // the variable.
12273   CaptureType = Var->getType();
12274   DeclRefType = CaptureType.getNonReferenceType();
12275   bool Explicit = (Kind != TryCapture_Implicit);
12276   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12277   do {
12278     // Only block literals, captured statements, and lambda expressions can
12279     // capture; other scopes don't work.
12280     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12281                                                               ExprLoc,
12282                                                               BuildAndDiagnose,
12283                                                               *this);
12284     if (!ParentDC) return true;
12285 
12286     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12287     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12288 
12289 
12290     // Check whether we've already captured it.
12291     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12292                                              DeclRefType))
12293       break;
12294     // If we are instantiating a generic lambda call operator body,
12295     // we do not want to capture new variables.  What was captured
12296     // during either a lambdas transformation or initial parsing
12297     // should be used.
12298     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12299       if (BuildAndDiagnose) {
12300         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12301         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12302           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12303           Diag(Var->getLocation(), diag::note_previous_decl)
12304              << Var->getDeclName();
12305           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12306         } else
12307           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12308       }
12309       return true;
12310     }
12311     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12312     // certain types of variables (unnamed, variably modified types etc.)
12313     // so check for eligibility.
12314     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12315        return true;
12316 
12317     // Try to capture variable-length arrays types.
12318     if (Var->getType()->isVariablyModifiedType()) {
12319       // We're going to walk down into the type and look for VLA
12320       // expressions.
12321       QualType QTy = Var->getType();
12322       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12323         QTy = PVD->getOriginalType();
12324       do {
12325         const Type *Ty = QTy.getTypePtr();
12326         switch (Ty->getTypeClass()) {
12327 #define TYPE(Class, Base)
12328 #define ABSTRACT_TYPE(Class, Base)
12329 #define NON_CANONICAL_TYPE(Class, Base)
12330 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12331 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12332 #include "clang/AST/TypeNodes.def"
12333           QTy = QualType();
12334           break;
12335         // These types are never variably-modified.
12336         case Type::Builtin:
12337         case Type::Complex:
12338         case Type::Vector:
12339         case Type::ExtVector:
12340         case Type::Record:
12341         case Type::Enum:
12342         case Type::Elaborated:
12343         case Type::TemplateSpecialization:
12344         case Type::ObjCObject:
12345         case Type::ObjCInterface:
12346         case Type::ObjCObjectPointer:
12347           llvm_unreachable("type class is never variably-modified!");
12348         case Type::Adjusted:
12349           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12350           break;
12351         case Type::Decayed:
12352           QTy = cast<DecayedType>(Ty)->getPointeeType();
12353           break;
12354         case Type::Pointer:
12355           QTy = cast<PointerType>(Ty)->getPointeeType();
12356           break;
12357         case Type::BlockPointer:
12358           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12359           break;
12360         case Type::LValueReference:
12361         case Type::RValueReference:
12362           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12363           break;
12364         case Type::MemberPointer:
12365           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12366           break;
12367         case Type::ConstantArray:
12368         case Type::IncompleteArray:
12369           // Losing element qualification here is fine.
12370           QTy = cast<ArrayType>(Ty)->getElementType();
12371           break;
12372         case Type::VariableArray: {
12373           // Losing element qualification here is fine.
12374           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
12375 
12376           // Unknown size indication requires no size computation.
12377           // Otherwise, evaluate and record it.
12378           if (auto Size = VAT->getSizeExpr()) {
12379             if (!CSI->isVLATypeCaptured(VAT)) {
12380               RecordDecl *CapRecord = nullptr;
12381               if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12382                 CapRecord = LSI->Lambda;
12383               } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12384                 CapRecord = CRSI->TheRecordDecl;
12385               }
12386               if (CapRecord) {
12387                 auto ExprLoc = Size->getExprLoc();
12388                 auto SizeType = Context.getSizeType();
12389                 // Build the non-static data member.
12390                 auto Field = FieldDecl::Create(
12391                     Context, CapRecord, ExprLoc, ExprLoc,
12392                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12393                     /*BW*/ nullptr, /*Mutable*/ false,
12394                     /*InitStyle*/ ICIS_NoInit);
12395                 Field->setImplicit(true);
12396                 Field->setAccess(AS_private);
12397                 Field->setCapturedVLAType(VAT);
12398                 CapRecord->addDecl(Field);
12399 
12400                 CSI->addVLATypeCapture(ExprLoc, SizeType);
12401               }
12402             }
12403           }
12404           QTy = VAT->getElementType();
12405           break;
12406         }
12407         case Type::FunctionProto:
12408         case Type::FunctionNoProto:
12409           QTy = cast<FunctionType>(Ty)->getReturnType();
12410           break;
12411         case Type::Paren:
12412         case Type::TypeOf:
12413         case Type::UnaryTransform:
12414         case Type::Attributed:
12415         case Type::SubstTemplateTypeParm:
12416         case Type::PackExpansion:
12417           // Keep walking after single level desugaring.
12418           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12419           break;
12420         case Type::Typedef:
12421           QTy = cast<TypedefType>(Ty)->desugar();
12422           break;
12423         case Type::Decltype:
12424           QTy = cast<DecltypeType>(Ty)->desugar();
12425           break;
12426         case Type::Auto:
12427           QTy = cast<AutoType>(Ty)->getDeducedType();
12428           break;
12429         case Type::TypeOfExpr:
12430           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12431           break;
12432         case Type::Atomic:
12433           QTy = cast<AtomicType>(Ty)->getValueType();
12434           break;
12435         }
12436       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12437     }
12438 
12439     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12440       // No capture-default, and this is not an explicit capture
12441       // so cannot capture this variable.
12442       if (BuildAndDiagnose) {
12443         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12444         Diag(Var->getLocation(), diag::note_previous_decl)
12445           << Var->getDeclName();
12446         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12447              diag::note_lambda_decl);
12448         // FIXME: If we error out because an outer lambda can not implicitly
12449         // capture a variable that an inner lambda explicitly captures, we
12450         // should have the inner lambda do the explicit capture - because
12451         // it makes for cleaner diagnostics later.  This would purely be done
12452         // so that the diagnostic does not misleadingly claim that a variable
12453         // can not be captured by a lambda implicitly even though it is captured
12454         // explicitly.  Suggestion:
12455         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12456         //    at the function head
12457         //  - cache the StartingDeclContext - this must be a lambda
12458         //  - captureInLambda in the innermost lambda the variable.
12459       }
12460       return true;
12461     }
12462 
12463     FunctionScopesIndex--;
12464     DC = ParentDC;
12465     Explicit = false;
12466   } while (!Var->getDeclContext()->Equals(DC));
12467 
12468   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12469   // computing the type of the capture at each step, checking type-specific
12470   // requirements, and adding captures if requested.
12471   // If the variable had already been captured previously, we start capturing
12472   // at the lambda nested within that one.
12473   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12474        ++I) {
12475     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12476 
12477     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12478       if (!captureInBlock(BSI, Var, ExprLoc,
12479                           BuildAndDiagnose, CaptureType,
12480                           DeclRefType, Nested, *this))
12481         return true;
12482       Nested = true;
12483     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12484       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12485                                    BuildAndDiagnose, CaptureType,
12486                                    DeclRefType, Nested, *this))
12487         return true;
12488       Nested = true;
12489     } else {
12490       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12491       if (!captureInLambda(LSI, Var, ExprLoc,
12492                            BuildAndDiagnose, CaptureType,
12493                            DeclRefType, Nested, Kind, EllipsisLoc,
12494                             /*IsTopScope*/I == N - 1, *this))
12495         return true;
12496       Nested = true;
12497     }
12498   }
12499   return false;
12500 }
12501 
12502 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12503                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12504   QualType CaptureType;
12505   QualType DeclRefType;
12506   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12507                             /*BuildAndDiagnose=*/true, CaptureType,
12508                             DeclRefType, nullptr);
12509 }
12510 
12511 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12512   QualType CaptureType;
12513   QualType DeclRefType;
12514 
12515   // Determine whether we can capture this variable.
12516   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12517                          /*BuildAndDiagnose=*/false, CaptureType,
12518                          DeclRefType, nullptr))
12519     return QualType();
12520 
12521   return DeclRefType;
12522 }
12523 
12524 
12525 
12526 // If either the type of the variable or the initializer is dependent,
12527 // return false. Otherwise, determine whether the variable is a constant
12528 // expression. Use this if you need to know if a variable that might or
12529 // might not be dependent is truly a constant expression.
12530 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12531     ASTContext &Context) {
12532 
12533   if (Var->getType()->isDependentType())
12534     return false;
12535   const VarDecl *DefVD = nullptr;
12536   Var->getAnyInitializer(DefVD);
12537   if (!DefVD)
12538     return false;
12539   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12540   Expr *Init = cast<Expr>(Eval->Value);
12541   if (Init->isValueDependent())
12542     return false;
12543   return IsVariableAConstantExpression(Var, Context);
12544 }
12545 
12546 
12547 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12548   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12549   // an object that satisfies the requirements for appearing in a
12550   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12551   // is immediately applied."  This function handles the lvalue-to-rvalue
12552   // conversion part.
12553   MaybeODRUseExprs.erase(E->IgnoreParens());
12554 
12555   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12556   // to a variable that is a constant expression, and if so, identify it as
12557   // a reference to a variable that does not involve an odr-use of that
12558   // variable.
12559   if (LambdaScopeInfo *LSI = getCurLambda()) {
12560     Expr *SansParensExpr = E->IgnoreParens();
12561     VarDecl *Var = nullptr;
12562     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12563       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12564     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12565       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12566 
12567     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12568       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12569   }
12570 }
12571 
12572 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12573   Res = CorrectDelayedTyposInExpr(Res);
12574 
12575   if (!Res.isUsable())
12576     return Res;
12577 
12578   // If a constant-expression is a reference to a variable where we delay
12579   // deciding whether it is an odr-use, just assume we will apply the
12580   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12581   // (a non-type template argument), we have special handling anyway.
12582   UpdateMarkingForLValueToRValue(Res.get());
12583   return Res;
12584 }
12585 
12586 void Sema::CleanupVarDeclMarking() {
12587   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12588                                         e = MaybeODRUseExprs.end();
12589        i != e; ++i) {
12590     VarDecl *Var;
12591     SourceLocation Loc;
12592     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12593       Var = cast<VarDecl>(DRE->getDecl());
12594       Loc = DRE->getLocation();
12595     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12596       Var = cast<VarDecl>(ME->getMemberDecl());
12597       Loc = ME->getMemberLoc();
12598     } else {
12599       llvm_unreachable("Unexpected expression");
12600     }
12601 
12602     MarkVarDeclODRUsed(Var, Loc, *this,
12603                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12604   }
12605 
12606   MaybeODRUseExprs.clear();
12607 }
12608 
12609 
12610 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12611                                     VarDecl *Var, Expr *E) {
12612   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12613          "Invalid Expr argument to DoMarkVarDeclReferenced");
12614   Var->setReferenced();
12615 
12616   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12617   bool MarkODRUsed = true;
12618 
12619   // If the context is not potentially evaluated, this is not an odr-use and
12620   // does not trigger instantiation.
12621   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12622     if (SemaRef.isUnevaluatedContext())
12623       return;
12624 
12625     // If we don't yet know whether this context is going to end up being an
12626     // evaluated context, and we're referencing a variable from an enclosing
12627     // scope, add a potential capture.
12628     //
12629     // FIXME: Is this necessary? These contexts are only used for default
12630     // arguments, where local variables can't be used.
12631     const bool RefersToEnclosingScope =
12632         (SemaRef.CurContext != Var->getDeclContext() &&
12633          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
12634     if (RefersToEnclosingScope) {
12635       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12636         // If a variable could potentially be odr-used, defer marking it so
12637         // until we finish analyzing the full expression for any
12638         // lvalue-to-rvalue
12639         // or discarded value conversions that would obviate odr-use.
12640         // Add it to the list of potential captures that will be analyzed
12641         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12642         // unless the variable is a reference that was initialized by a constant
12643         // expression (this will never need to be captured or odr-used).
12644         assert(E && "Capture variable should be used in an expression.");
12645         if (!Var->getType()->isReferenceType() ||
12646             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12647           LSI->addPotentialCapture(E->IgnoreParens());
12648       }
12649     }
12650 
12651     if (!isTemplateInstantiation(TSK))
12652     	return;
12653 
12654     // Instantiate, but do not mark as odr-used, variable templates.
12655     MarkODRUsed = false;
12656   }
12657 
12658   VarTemplateSpecializationDecl *VarSpec =
12659       dyn_cast<VarTemplateSpecializationDecl>(Var);
12660   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12661          "Can't instantiate a partial template specialization.");
12662 
12663   // Perform implicit instantiation of static data members, static data member
12664   // templates of class templates, and variable template specializations. Delay
12665   // instantiations of variable templates, except for those that could be used
12666   // in a constant expression.
12667   if (isTemplateInstantiation(TSK)) {
12668     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12669 
12670     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12671       if (Var->getPointOfInstantiation().isInvalid()) {
12672         // This is a modification of an existing AST node. Notify listeners.
12673         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12674           L->StaticDataMemberInstantiated(Var);
12675       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12676         // Don't bother trying to instantiate it again, unless we might need
12677         // its initializer before we get to the end of the TU.
12678         TryInstantiating = false;
12679     }
12680 
12681     if (Var->getPointOfInstantiation().isInvalid())
12682       Var->setTemplateSpecializationKind(TSK, Loc);
12683 
12684     if (TryInstantiating) {
12685       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12686       bool InstantiationDependent = false;
12687       bool IsNonDependent =
12688           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12689                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12690                   : true;
12691 
12692       // Do not instantiate specializations that are still type-dependent.
12693       if (IsNonDependent) {
12694         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12695           // Do not defer instantiations of variables which could be used in a
12696           // constant expression.
12697           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12698         } else {
12699           SemaRef.PendingInstantiations
12700               .push_back(std::make_pair(Var, PointOfInstantiation));
12701         }
12702       }
12703     }
12704   }
12705 
12706   if(!MarkODRUsed) return;
12707 
12708   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12709   // the requirements for appearing in a constant expression (5.19) and, if
12710   // it is an object, the lvalue-to-rvalue conversion (4.1)
12711   // is immediately applied."  We check the first part here, and
12712   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12713   // Note that we use the C++11 definition everywhere because nothing in
12714   // C++03 depends on whether we get the C++03 version correct. The second
12715   // part does not apply to references, since they are not objects.
12716   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12717     // A reference initialized by a constant expression can never be
12718     // odr-used, so simply ignore it.
12719     if (!Var->getType()->isReferenceType())
12720       SemaRef.MaybeODRUseExprs.insert(E);
12721   } else
12722     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12723                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12724 }
12725 
12726 /// \brief Mark a variable referenced, and check whether it is odr-used
12727 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12728 /// used directly for normal expressions referring to VarDecl.
12729 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12730   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12731 }
12732 
12733 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12734                                Decl *D, Expr *E, bool OdrUse) {
12735   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12736     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12737     return;
12738   }
12739 
12740   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12741 
12742   // If this is a call to a method via a cast, also mark the method in the
12743   // derived class used in case codegen can devirtualize the call.
12744   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12745   if (!ME)
12746     return;
12747   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12748   if (!MD)
12749     return;
12750   // Only attempt to devirtualize if this is truly a virtual call.
12751   bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
12752   if (!IsVirtualCall)
12753     return;
12754   const Expr *Base = ME->getBase();
12755   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12756   if (!MostDerivedClassDecl)
12757     return;
12758   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12759   if (!DM || DM->isPure())
12760     return;
12761   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12762 }
12763 
12764 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12765 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12766   // TODO: update this with DR# once a defect report is filed.
12767   // C++11 defect. The address of a pure member should not be an ODR use, even
12768   // if it's a qualified reference.
12769   bool OdrUse = true;
12770   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12771     if (Method->isVirtual())
12772       OdrUse = false;
12773   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12774 }
12775 
12776 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12777 void Sema::MarkMemberReferenced(MemberExpr *E) {
12778   // C++11 [basic.def.odr]p2:
12779   //   A non-overloaded function whose name appears as a potentially-evaluated
12780   //   expression or a member of a set of candidate functions, if selected by
12781   //   overload resolution when referred to from a potentially-evaluated
12782   //   expression, is odr-used, unless it is a pure virtual function and its
12783   //   name is not explicitly qualified.
12784   bool OdrUse = true;
12785   if (!E->hasQualifier()) {
12786     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12787       if (Method->isPure())
12788         OdrUse = false;
12789   }
12790   SourceLocation Loc = E->getMemberLoc().isValid() ?
12791                             E->getMemberLoc() : E->getLocStart();
12792   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12793 }
12794 
12795 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12796 /// marks the declaration referenced, and performs odr-use checking for
12797 /// functions and variables. This method should not be used when building a
12798 /// normal expression which refers to a variable.
12799 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12800   if (OdrUse) {
12801     if (auto *VD = dyn_cast<VarDecl>(D)) {
12802       MarkVariableReferenced(Loc, VD);
12803       return;
12804     }
12805   }
12806   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
12807     MarkFunctionReferenced(Loc, FD, OdrUse);
12808     return;
12809   }
12810   D->setReferenced();
12811 }
12812 
12813 namespace {
12814   // Mark all of the declarations referenced
12815   // FIXME: Not fully implemented yet! We need to have a better understanding
12816   // of when we're entering
12817   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12818     Sema &S;
12819     SourceLocation Loc;
12820 
12821   public:
12822     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12823 
12824     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12825 
12826     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12827     bool TraverseRecordType(RecordType *T);
12828   };
12829 }
12830 
12831 bool MarkReferencedDecls::TraverseTemplateArgument(
12832     const TemplateArgument &Arg) {
12833   if (Arg.getKind() == TemplateArgument::Declaration) {
12834     if (Decl *D = Arg.getAsDecl())
12835       S.MarkAnyDeclReferenced(Loc, D, true);
12836   }
12837 
12838   return Inherited::TraverseTemplateArgument(Arg);
12839 }
12840 
12841 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12842   if (ClassTemplateSpecializationDecl *Spec
12843                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12844     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12845     return TraverseTemplateArguments(Args.data(), Args.size());
12846   }
12847 
12848   return true;
12849 }
12850 
12851 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12852   MarkReferencedDecls Marker(*this, Loc);
12853   Marker.TraverseType(Context.getCanonicalType(T));
12854 }
12855 
12856 namespace {
12857   /// \brief Helper class that marks all of the declarations referenced by
12858   /// potentially-evaluated subexpressions as "referenced".
12859   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12860     Sema &S;
12861     bool SkipLocalVariables;
12862 
12863   public:
12864     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12865 
12866     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12867       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12868 
12869     void VisitDeclRefExpr(DeclRefExpr *E) {
12870       // If we were asked not to visit local variables, don't.
12871       if (SkipLocalVariables) {
12872         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12873           if (VD->hasLocalStorage())
12874             return;
12875       }
12876 
12877       S.MarkDeclRefReferenced(E);
12878     }
12879 
12880     void VisitMemberExpr(MemberExpr *E) {
12881       S.MarkMemberReferenced(E);
12882       Inherited::VisitMemberExpr(E);
12883     }
12884 
12885     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12886       S.MarkFunctionReferenced(E->getLocStart(),
12887             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12888       Visit(E->getSubExpr());
12889     }
12890 
12891     void VisitCXXNewExpr(CXXNewExpr *E) {
12892       if (E->getOperatorNew())
12893         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12894       if (E->getOperatorDelete())
12895         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12896       Inherited::VisitCXXNewExpr(E);
12897     }
12898 
12899     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12900       if (E->getOperatorDelete())
12901         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12902       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12903       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12904         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12905         S.MarkFunctionReferenced(E->getLocStart(),
12906                                     S.LookupDestructor(Record));
12907       }
12908 
12909       Inherited::VisitCXXDeleteExpr(E);
12910     }
12911 
12912     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12913       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12914       Inherited::VisitCXXConstructExpr(E);
12915     }
12916 
12917     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12918       Visit(E->getExpr());
12919     }
12920 
12921     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12922       Inherited::VisitImplicitCastExpr(E);
12923 
12924       if (E->getCastKind() == CK_LValueToRValue)
12925         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12926     }
12927   };
12928 }
12929 
12930 /// \brief Mark any declarations that appear within this expression or any
12931 /// potentially-evaluated subexpressions as "referenced".
12932 ///
12933 /// \param SkipLocalVariables If true, don't mark local variables as
12934 /// 'referenced'.
12935 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12936                                             bool SkipLocalVariables) {
12937   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12938 }
12939 
12940 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12941 /// of the program being compiled.
12942 ///
12943 /// This routine emits the given diagnostic when the code currently being
12944 /// type-checked is "potentially evaluated", meaning that there is a
12945 /// possibility that the code will actually be executable. Code in sizeof()
12946 /// expressions, code used only during overload resolution, etc., are not
12947 /// potentially evaluated. This routine will suppress such diagnostics or,
12948 /// in the absolutely nutty case of potentially potentially evaluated
12949 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12950 /// later.
12951 ///
12952 /// This routine should be used for all diagnostics that describe the run-time
12953 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12954 /// Failure to do so will likely result in spurious diagnostics or failures
12955 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12956 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12957                                const PartialDiagnostic &PD) {
12958   switch (ExprEvalContexts.back().Context) {
12959   case Unevaluated:
12960   case UnevaluatedAbstract:
12961     // The argument will never be evaluated, so don't complain.
12962     break;
12963 
12964   case ConstantEvaluated:
12965     // Relevant diagnostics should be produced by constant evaluation.
12966     break;
12967 
12968   case PotentiallyEvaluated:
12969   case PotentiallyEvaluatedIfUsed:
12970     if (Statement && getCurFunctionOrMethodDecl()) {
12971       FunctionScopes.back()->PossiblyUnreachableDiags.
12972         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12973     }
12974     else
12975       Diag(Loc, PD);
12976 
12977     return true;
12978   }
12979 
12980   return false;
12981 }
12982 
12983 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12984                                CallExpr *CE, FunctionDecl *FD) {
12985   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12986     return false;
12987 
12988   // If we're inside a decltype's expression, don't check for a valid return
12989   // type or construct temporaries until we know whether this is the last call.
12990   if (ExprEvalContexts.back().IsDecltype) {
12991     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12992     return false;
12993   }
12994 
12995   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12996     FunctionDecl *FD;
12997     CallExpr *CE;
12998 
12999   public:
13000     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13001       : FD(FD), CE(CE) { }
13002 
13003     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
13004       if (!FD) {
13005         S.Diag(Loc, diag::err_call_incomplete_return)
13006           << T << CE->getSourceRange();
13007         return;
13008       }
13009 
13010       S.Diag(Loc, diag::err_call_function_incomplete_return)
13011         << CE->getSourceRange() << FD->getDeclName() << T;
13012       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13013           << FD->getDeclName();
13014     }
13015   } Diagnoser(FD, CE);
13016 
13017   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
13018     return true;
13019 
13020   return false;
13021 }
13022 
13023 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
13024 // will prevent this condition from triggering, which is what we want.
13025 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13026   SourceLocation Loc;
13027 
13028   unsigned diagnostic = diag::warn_condition_is_assignment;
13029   bool IsOrAssign = false;
13030 
13031   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
13032     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
13033       return;
13034 
13035     IsOrAssign = Op->getOpcode() == BO_OrAssign;
13036 
13037     // Greylist some idioms by putting them into a warning subcategory.
13038     if (ObjCMessageExpr *ME
13039           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13040       Selector Sel = ME->getSelector();
13041 
13042       // self = [<foo> init...]
13043       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13044         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13045 
13046       // <foo> = [<bar> nextObject]
13047       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13048         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13049     }
13050 
13051     Loc = Op->getOperatorLoc();
13052   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13053     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13054       return;
13055 
13056     IsOrAssign = Op->getOperator() == OO_PipeEqual;
13057     Loc = Op->getOperatorLoc();
13058   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13059     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13060   else {
13061     // Not an assignment.
13062     return;
13063   }
13064 
13065   Diag(Loc, diagnostic) << E->getSourceRange();
13066 
13067   SourceLocation Open = E->getLocStart();
13068   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
13069   Diag(Loc, diag::note_condition_assign_silence)
13070         << FixItHint::CreateInsertion(Open, "(")
13071         << FixItHint::CreateInsertion(Close, ")");
13072 
13073   if (IsOrAssign)
13074     Diag(Loc, diag::note_condition_or_assign_to_comparison)
13075       << FixItHint::CreateReplacement(Loc, "!=");
13076   else
13077     Diag(Loc, diag::note_condition_assign_to_comparison)
13078       << FixItHint::CreateReplacement(Loc, "==");
13079 }
13080 
13081 /// \brief Redundant parentheses over an equality comparison can indicate
13082 /// that the user intended an assignment used as condition.
13083 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13084   // Don't warn if the parens came from a macro.
13085   SourceLocation parenLoc = ParenE->getLocStart();
13086   if (parenLoc.isInvalid() || parenLoc.isMacroID())
13087     return;
13088   // Don't warn for dependent expressions.
13089   if (ParenE->isTypeDependent())
13090     return;
13091 
13092   Expr *E = ParenE->IgnoreParens();
13093 
13094   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13095     if (opE->getOpcode() == BO_EQ &&
13096         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13097                                                            == Expr::MLV_Valid) {
13098       SourceLocation Loc = opE->getOperatorLoc();
13099 
13100       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13101       SourceRange ParenERange = ParenE->getSourceRange();
13102       Diag(Loc, diag::note_equality_comparison_silence)
13103         << FixItHint::CreateRemoval(ParenERange.getBegin())
13104         << FixItHint::CreateRemoval(ParenERange.getEnd());
13105       Diag(Loc, diag::note_equality_comparison_to_assign)
13106         << FixItHint::CreateReplacement(Loc, "=");
13107     }
13108 }
13109 
13110 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13111   DiagnoseAssignmentAsCondition(E);
13112   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13113     DiagnoseEqualityWithExtraParens(parenE);
13114 
13115   ExprResult result = CheckPlaceholderExpr(E);
13116   if (result.isInvalid()) return ExprError();
13117   E = result.get();
13118 
13119   if (!E->isTypeDependent()) {
13120     if (getLangOpts().CPlusPlus)
13121       return CheckCXXBooleanCondition(E); // C++ 6.4p4
13122 
13123     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13124     if (ERes.isInvalid())
13125       return ExprError();
13126     E = ERes.get();
13127 
13128     QualType T = E->getType();
13129     if (!T->isScalarType()) { // C99 6.8.4.1p1
13130       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13131         << T << E->getSourceRange();
13132       return ExprError();
13133     }
13134     CheckBoolLikeConversion(E, Loc);
13135   }
13136 
13137   return E;
13138 }
13139 
13140 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
13141                                        Expr *SubExpr) {
13142   if (!SubExpr)
13143     return ExprError();
13144 
13145   return CheckBooleanCondition(SubExpr, Loc);
13146 }
13147 
13148 namespace {
13149   /// A visitor for rebuilding a call to an __unknown_any expression
13150   /// to have an appropriate type.
13151   struct RebuildUnknownAnyFunction
13152     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13153 
13154     Sema &S;
13155 
13156     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13157 
13158     ExprResult VisitStmt(Stmt *S) {
13159       llvm_unreachable("unexpected statement!");
13160     }
13161 
13162     ExprResult VisitExpr(Expr *E) {
13163       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13164         << E->getSourceRange();
13165       return ExprError();
13166     }
13167 
13168     /// Rebuild an expression which simply semantically wraps another
13169     /// expression which it shares the type and value kind of.
13170     template <class T> ExprResult rebuildSugarExpr(T *E) {
13171       ExprResult SubResult = Visit(E->getSubExpr());
13172       if (SubResult.isInvalid()) return ExprError();
13173 
13174       Expr *SubExpr = SubResult.get();
13175       E->setSubExpr(SubExpr);
13176       E->setType(SubExpr->getType());
13177       E->setValueKind(SubExpr->getValueKind());
13178       assert(E->getObjectKind() == OK_Ordinary);
13179       return E;
13180     }
13181 
13182     ExprResult VisitParenExpr(ParenExpr *E) {
13183       return rebuildSugarExpr(E);
13184     }
13185 
13186     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13187       return rebuildSugarExpr(E);
13188     }
13189 
13190     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13191       ExprResult SubResult = Visit(E->getSubExpr());
13192       if (SubResult.isInvalid()) return ExprError();
13193 
13194       Expr *SubExpr = SubResult.get();
13195       E->setSubExpr(SubExpr);
13196       E->setType(S.Context.getPointerType(SubExpr->getType()));
13197       assert(E->getValueKind() == VK_RValue);
13198       assert(E->getObjectKind() == OK_Ordinary);
13199       return E;
13200     }
13201 
13202     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13203       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13204 
13205       E->setType(VD->getType());
13206 
13207       assert(E->getValueKind() == VK_RValue);
13208       if (S.getLangOpts().CPlusPlus &&
13209           !(isa<CXXMethodDecl>(VD) &&
13210             cast<CXXMethodDecl>(VD)->isInstance()))
13211         E->setValueKind(VK_LValue);
13212 
13213       return E;
13214     }
13215 
13216     ExprResult VisitMemberExpr(MemberExpr *E) {
13217       return resolveDecl(E, E->getMemberDecl());
13218     }
13219 
13220     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13221       return resolveDecl(E, E->getDecl());
13222     }
13223   };
13224 }
13225 
13226 /// Given a function expression of unknown-any type, try to rebuild it
13227 /// to have a function type.
13228 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13229   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13230   if (Result.isInvalid()) return ExprError();
13231   return S.DefaultFunctionArrayConversion(Result.get());
13232 }
13233 
13234 namespace {
13235   /// A visitor for rebuilding an expression of type __unknown_anytype
13236   /// into one which resolves the type directly on the referring
13237   /// expression.  Strict preservation of the original source
13238   /// structure is not a goal.
13239   struct RebuildUnknownAnyExpr
13240     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13241 
13242     Sema &S;
13243 
13244     /// The current destination type.
13245     QualType DestType;
13246 
13247     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13248       : S(S), DestType(CastType) {}
13249 
13250     ExprResult VisitStmt(Stmt *S) {
13251       llvm_unreachable("unexpected statement!");
13252     }
13253 
13254     ExprResult VisitExpr(Expr *E) {
13255       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13256         << E->getSourceRange();
13257       return ExprError();
13258     }
13259 
13260     ExprResult VisitCallExpr(CallExpr *E);
13261     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13262 
13263     /// Rebuild an expression which simply semantically wraps another
13264     /// expression which it shares the type and value kind of.
13265     template <class T> ExprResult rebuildSugarExpr(T *E) {
13266       ExprResult SubResult = Visit(E->getSubExpr());
13267       if (SubResult.isInvalid()) return ExprError();
13268       Expr *SubExpr = SubResult.get();
13269       E->setSubExpr(SubExpr);
13270       E->setType(SubExpr->getType());
13271       E->setValueKind(SubExpr->getValueKind());
13272       assert(E->getObjectKind() == OK_Ordinary);
13273       return E;
13274     }
13275 
13276     ExprResult VisitParenExpr(ParenExpr *E) {
13277       return rebuildSugarExpr(E);
13278     }
13279 
13280     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13281       return rebuildSugarExpr(E);
13282     }
13283 
13284     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13285       const PointerType *Ptr = DestType->getAs<PointerType>();
13286       if (!Ptr) {
13287         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13288           << E->getSourceRange();
13289         return ExprError();
13290       }
13291       assert(E->getValueKind() == VK_RValue);
13292       assert(E->getObjectKind() == OK_Ordinary);
13293       E->setType(DestType);
13294 
13295       // Build the sub-expression as if it were an object of the pointee type.
13296       DestType = Ptr->getPointeeType();
13297       ExprResult SubResult = Visit(E->getSubExpr());
13298       if (SubResult.isInvalid()) return ExprError();
13299       E->setSubExpr(SubResult.get());
13300       return E;
13301     }
13302 
13303     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13304 
13305     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13306 
13307     ExprResult VisitMemberExpr(MemberExpr *E) {
13308       return resolveDecl(E, E->getMemberDecl());
13309     }
13310 
13311     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13312       return resolveDecl(E, E->getDecl());
13313     }
13314   };
13315 }
13316 
13317 /// Rebuilds a call expression which yielded __unknown_anytype.
13318 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13319   Expr *CalleeExpr = E->getCallee();
13320 
13321   enum FnKind {
13322     FK_MemberFunction,
13323     FK_FunctionPointer,
13324     FK_BlockPointer
13325   };
13326 
13327   FnKind Kind;
13328   QualType CalleeType = CalleeExpr->getType();
13329   if (CalleeType == S.Context.BoundMemberTy) {
13330     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13331     Kind = FK_MemberFunction;
13332     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13333   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13334     CalleeType = Ptr->getPointeeType();
13335     Kind = FK_FunctionPointer;
13336   } else {
13337     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13338     Kind = FK_BlockPointer;
13339   }
13340   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13341 
13342   // Verify that this is a legal result type of a function.
13343   if (DestType->isArrayType() || DestType->isFunctionType()) {
13344     unsigned diagID = diag::err_func_returning_array_function;
13345     if (Kind == FK_BlockPointer)
13346       diagID = diag::err_block_returning_array_function;
13347 
13348     S.Diag(E->getExprLoc(), diagID)
13349       << DestType->isFunctionType() << DestType;
13350     return ExprError();
13351   }
13352 
13353   // Otherwise, go ahead and set DestType as the call's result.
13354   E->setType(DestType.getNonLValueExprType(S.Context));
13355   E->setValueKind(Expr::getValueKindForType(DestType));
13356   assert(E->getObjectKind() == OK_Ordinary);
13357 
13358   // Rebuild the function type, replacing the result type with DestType.
13359   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13360   if (Proto) {
13361     // __unknown_anytype(...) is a special case used by the debugger when
13362     // it has no idea what a function's signature is.
13363     //
13364     // We want to build this call essentially under the K&R
13365     // unprototyped rules, but making a FunctionNoProtoType in C++
13366     // would foul up all sorts of assumptions.  However, we cannot
13367     // simply pass all arguments as variadic arguments, nor can we
13368     // portably just call the function under a non-variadic type; see
13369     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13370     // However, it turns out that in practice it is generally safe to
13371     // call a function declared as "A foo(B,C,D);" under the prototype
13372     // "A foo(B,C,D,...);".  The only known exception is with the
13373     // Windows ABI, where any variadic function is implicitly cdecl
13374     // regardless of its normal CC.  Therefore we change the parameter
13375     // types to match the types of the arguments.
13376     //
13377     // This is a hack, but it is far superior to moving the
13378     // corresponding target-specific code from IR-gen to Sema/AST.
13379 
13380     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13381     SmallVector<QualType, 8> ArgTypes;
13382     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13383       ArgTypes.reserve(E->getNumArgs());
13384       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13385         Expr *Arg = E->getArg(i);
13386         QualType ArgType = Arg->getType();
13387         if (E->isLValue()) {
13388           ArgType = S.Context.getLValueReferenceType(ArgType);
13389         } else if (E->isXValue()) {
13390           ArgType = S.Context.getRValueReferenceType(ArgType);
13391         }
13392         ArgTypes.push_back(ArgType);
13393       }
13394       ParamTypes = ArgTypes;
13395     }
13396     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13397                                          Proto->getExtProtoInfo());
13398   } else {
13399     DestType = S.Context.getFunctionNoProtoType(DestType,
13400                                                 FnType->getExtInfo());
13401   }
13402 
13403   // Rebuild the appropriate pointer-to-function type.
13404   switch (Kind) {
13405   case FK_MemberFunction:
13406     // Nothing to do.
13407     break;
13408 
13409   case FK_FunctionPointer:
13410     DestType = S.Context.getPointerType(DestType);
13411     break;
13412 
13413   case FK_BlockPointer:
13414     DestType = S.Context.getBlockPointerType(DestType);
13415     break;
13416   }
13417 
13418   // Finally, we can recurse.
13419   ExprResult CalleeResult = Visit(CalleeExpr);
13420   if (!CalleeResult.isUsable()) return ExprError();
13421   E->setCallee(CalleeResult.get());
13422 
13423   // Bind a temporary if necessary.
13424   return S.MaybeBindToTemporary(E);
13425 }
13426 
13427 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13428   // Verify that this is a legal result type of a call.
13429   if (DestType->isArrayType() || DestType->isFunctionType()) {
13430     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13431       << DestType->isFunctionType() << DestType;
13432     return ExprError();
13433   }
13434 
13435   // Rewrite the method result type if available.
13436   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13437     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13438     Method->setReturnType(DestType);
13439   }
13440 
13441   // Change the type of the message.
13442   E->setType(DestType.getNonReferenceType());
13443   E->setValueKind(Expr::getValueKindForType(DestType));
13444 
13445   return S.MaybeBindToTemporary(E);
13446 }
13447 
13448 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13449   // The only case we should ever see here is a function-to-pointer decay.
13450   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13451     assert(E->getValueKind() == VK_RValue);
13452     assert(E->getObjectKind() == OK_Ordinary);
13453 
13454     E->setType(DestType);
13455 
13456     // Rebuild the sub-expression as the pointee (function) type.
13457     DestType = DestType->castAs<PointerType>()->getPointeeType();
13458 
13459     ExprResult Result = Visit(E->getSubExpr());
13460     if (!Result.isUsable()) return ExprError();
13461 
13462     E->setSubExpr(Result.get());
13463     return E;
13464   } else if (E->getCastKind() == CK_LValueToRValue) {
13465     assert(E->getValueKind() == VK_RValue);
13466     assert(E->getObjectKind() == OK_Ordinary);
13467 
13468     assert(isa<BlockPointerType>(E->getType()));
13469 
13470     E->setType(DestType);
13471 
13472     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13473     DestType = S.Context.getLValueReferenceType(DestType);
13474 
13475     ExprResult Result = Visit(E->getSubExpr());
13476     if (!Result.isUsable()) return ExprError();
13477 
13478     E->setSubExpr(Result.get());
13479     return E;
13480   } else {
13481     llvm_unreachable("Unhandled cast type!");
13482   }
13483 }
13484 
13485 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13486   ExprValueKind ValueKind = VK_LValue;
13487   QualType Type = DestType;
13488 
13489   // We know how to make this work for certain kinds of decls:
13490 
13491   //  - functions
13492   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13493     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13494       DestType = Ptr->getPointeeType();
13495       ExprResult Result = resolveDecl(E, VD);
13496       if (Result.isInvalid()) return ExprError();
13497       return S.ImpCastExprToType(Result.get(), Type,
13498                                  CK_FunctionToPointerDecay, VK_RValue);
13499     }
13500 
13501     if (!Type->isFunctionType()) {
13502       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13503         << VD << E->getSourceRange();
13504       return ExprError();
13505     }
13506     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
13507       // We must match the FunctionDecl's type to the hack introduced in
13508       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
13509       // type. See the lengthy commentary in that routine.
13510       QualType FDT = FD->getType();
13511       const FunctionType *FnType = FDT->castAs<FunctionType>();
13512       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
13513       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13514       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
13515         SourceLocation Loc = FD->getLocation();
13516         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
13517                                       FD->getDeclContext(),
13518                                       Loc, Loc, FD->getNameInfo().getName(),
13519                                       DestType, FD->getTypeSourceInfo(),
13520                                       SC_None, false/*isInlineSpecified*/,
13521                                       FD->hasPrototype(),
13522                                       false/*isConstexprSpecified*/);
13523 
13524         if (FD->getQualifier())
13525           NewFD->setQualifierInfo(FD->getQualifierLoc());
13526 
13527         SmallVector<ParmVarDecl*, 16> Params;
13528         for (const auto &AI : FT->param_types()) {
13529           ParmVarDecl *Param =
13530             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
13531           Param->setScopeInfo(0, Params.size());
13532           Params.push_back(Param);
13533         }
13534         NewFD->setParams(Params);
13535         DRE->setDecl(NewFD);
13536         VD = DRE->getDecl();
13537       }
13538     }
13539 
13540     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13541       if (MD->isInstance()) {
13542         ValueKind = VK_RValue;
13543         Type = S.Context.BoundMemberTy;
13544       }
13545 
13546     // Function references aren't l-values in C.
13547     if (!S.getLangOpts().CPlusPlus)
13548       ValueKind = VK_RValue;
13549 
13550   //  - variables
13551   } else if (isa<VarDecl>(VD)) {
13552     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13553       Type = RefTy->getPointeeType();
13554     } else if (Type->isFunctionType()) {
13555       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13556         << VD << E->getSourceRange();
13557       return ExprError();
13558     }
13559 
13560   //  - nothing else
13561   } else {
13562     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13563       << VD << E->getSourceRange();
13564     return ExprError();
13565   }
13566 
13567   // Modifying the declaration like this is friendly to IR-gen but
13568   // also really dangerous.
13569   VD->setType(DestType);
13570   E->setType(Type);
13571   E->setValueKind(ValueKind);
13572   return E;
13573 }
13574 
13575 /// Check a cast of an unknown-any type.  We intentionally only
13576 /// trigger this for C-style casts.
13577 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13578                                      Expr *CastExpr, CastKind &CastKind,
13579                                      ExprValueKind &VK, CXXCastPath &Path) {
13580   // Rewrite the casted expression from scratch.
13581   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13582   if (!result.isUsable()) return ExprError();
13583 
13584   CastExpr = result.get();
13585   VK = CastExpr->getValueKind();
13586   CastKind = CK_NoOp;
13587 
13588   return CastExpr;
13589 }
13590 
13591 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13592   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13593 }
13594 
13595 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13596                                     Expr *arg, QualType &paramType) {
13597   // If the syntactic form of the argument is not an explicit cast of
13598   // any sort, just do default argument promotion.
13599   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13600   if (!castArg) {
13601     ExprResult result = DefaultArgumentPromotion(arg);
13602     if (result.isInvalid()) return ExprError();
13603     paramType = result.get()->getType();
13604     return result;
13605   }
13606 
13607   // Otherwise, use the type that was written in the explicit cast.
13608   assert(!arg->hasPlaceholderType());
13609   paramType = castArg->getTypeAsWritten();
13610 
13611   // Copy-initialize a parameter of that type.
13612   InitializedEntity entity =
13613     InitializedEntity::InitializeParameter(Context, paramType,
13614                                            /*consumed*/ false);
13615   return PerformCopyInitialization(entity, callLoc, arg);
13616 }
13617 
13618 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13619   Expr *orig = E;
13620   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13621   while (true) {
13622     E = E->IgnoreParenImpCasts();
13623     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13624       E = call->getCallee();
13625       diagID = diag::err_uncasted_call_of_unknown_any;
13626     } else {
13627       break;
13628     }
13629   }
13630 
13631   SourceLocation loc;
13632   NamedDecl *d;
13633   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13634     loc = ref->getLocation();
13635     d = ref->getDecl();
13636   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13637     loc = mem->getMemberLoc();
13638     d = mem->getMemberDecl();
13639   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13640     diagID = diag::err_uncasted_call_of_unknown_any;
13641     loc = msg->getSelectorStartLoc();
13642     d = msg->getMethodDecl();
13643     if (!d) {
13644       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13645         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13646         << orig->getSourceRange();
13647       return ExprError();
13648     }
13649   } else {
13650     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13651       << E->getSourceRange();
13652     return ExprError();
13653   }
13654 
13655   S.Diag(loc, diagID) << d << orig->getSourceRange();
13656 
13657   // Never recoverable.
13658   return ExprError();
13659 }
13660 
13661 /// Check for operands with placeholder types and complain if found.
13662 /// Returns true if there was an error and no recovery was possible.
13663 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13664   if (!getLangOpts().CPlusPlus) {
13665     // C cannot handle TypoExpr nodes on either side of a binop because it
13666     // doesn't handle dependent types properly, so make sure any TypoExprs have
13667     // been dealt with before checking the operands.
13668     ExprResult Result = CorrectDelayedTyposInExpr(E);
13669     if (!Result.isUsable()) return ExprError();
13670     E = Result.get();
13671   }
13672 
13673   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13674   if (!placeholderType) return E;
13675 
13676   switch (placeholderType->getKind()) {
13677 
13678   // Overloaded expressions.
13679   case BuiltinType::Overload: {
13680     // Try to resolve a single function template specialization.
13681     // This is obligatory.
13682     ExprResult result = E;
13683     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13684       return result;
13685 
13686     // If that failed, try to recover with a call.
13687     } else {
13688       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13689                            /*complain*/ true);
13690       return result;
13691     }
13692   }
13693 
13694   // Bound member functions.
13695   case BuiltinType::BoundMember: {
13696     ExprResult result = E;
13697     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13698                          /*complain*/ true);
13699     return result;
13700   }
13701 
13702   // ARC unbridged casts.
13703   case BuiltinType::ARCUnbridgedCast: {
13704     Expr *realCast = stripARCUnbridgedCast(E);
13705     diagnoseARCUnbridgedCast(realCast);
13706     return realCast;
13707   }
13708 
13709   // Expressions of unknown type.
13710   case BuiltinType::UnknownAny:
13711     return diagnoseUnknownAnyExpr(*this, E);
13712 
13713   // Pseudo-objects.
13714   case BuiltinType::PseudoObject:
13715     return checkPseudoObjectRValue(E);
13716 
13717   case BuiltinType::BuiltinFn: {
13718     // Accept __noop without parens by implicitly converting it to a call expr.
13719     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
13720     if (DRE) {
13721       auto *FD = cast<FunctionDecl>(DRE->getDecl());
13722       if (FD->getBuiltinID() == Builtin::BI__noop) {
13723         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
13724                               CK_BuiltinFnToFnPtr).get();
13725         return new (Context) CallExpr(Context, E, None, Context.IntTy,
13726                                       VK_RValue, SourceLocation());
13727       }
13728     }
13729 
13730     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13731     return ExprError();
13732   }
13733 
13734   // Everything else should be impossible.
13735 #define BUILTIN_TYPE(Id, SingletonId) \
13736   case BuiltinType::Id:
13737 #define PLACEHOLDER_TYPE(Id, SingletonId)
13738 #include "clang/AST/BuiltinTypes.def"
13739     break;
13740   }
13741 
13742   llvm_unreachable("invalid placeholder type!");
13743 }
13744 
13745 bool Sema::CheckCaseExpression(Expr *E) {
13746   if (E->isTypeDependent())
13747     return true;
13748   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13749     return E->getType()->isIntegralOrEnumerationType();
13750   return false;
13751 }
13752 
13753 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13754 ExprResult
13755 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13756   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13757          "Unknown Objective-C Boolean value!");
13758   QualType BoolT = Context.ObjCBuiltinBoolTy;
13759   if (!Context.getBOOLDecl()) {
13760     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13761                         Sema::LookupOrdinaryName);
13762     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13763       NamedDecl *ND = Result.getFoundDecl();
13764       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13765         Context.setBOOLDecl(TD);
13766     }
13767   }
13768   if (Context.getBOOLDecl())
13769     BoolT = Context.getBOOLType();
13770   return new (Context)
13771       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13772 }
13773