1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 using namespace clang;
46 using namespace sema;
47 
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54 
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59 
60     // If the function has a deduced return type, and we can't deduce it,
61     // then we can't use it either.
62     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
63         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
64       return false;
65   }
66 
67   // See if this function is unavailable.
68   if (D->getAvailability() == AR_Unavailable &&
69       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
70     return false;
71 
72   return true;
73 }
74 
75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
76   // Warn if this is used but marked unused.
77   if (D->hasAttr<UnusedAttr>()) {
78     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
79     if (!DC->hasAttr<UnusedAttr>())
80       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
81   }
82 }
83 
84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
85                               NamedDecl *D, SourceLocation Loc,
86                               const ObjCInterfaceDecl *UnknownObjCClass,
87                               bool ObjCPropertyAccess) {
88   // See if this declaration is unavailable or deprecated.
89   std::string Message;
90 
91   // Forward class declarations get their attributes from their definition.
92   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
93     if (IDecl->getDefinition())
94       D = IDecl->getDefinition();
95   }
96   AvailabilityResult Result = D->getAvailability(&Message);
97   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
98     if (Result == AR_Available) {
99       const DeclContext *DC = ECD->getDeclContext();
100       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
101         Result = TheEnumDecl->getAvailability(&Message);
102     }
103 
104   const ObjCPropertyDecl *ObjCPDecl = nullptr;
105   if (Result == AR_Deprecated || Result == AR_Unavailable) {
106     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
107       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
108         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
109         if (PDeclResult == Result)
110           ObjCPDecl = PD;
111       }
112     }
113   }
114 
115   switch (Result) {
116     case AR_Available:
117     case AR_NotYetIntroduced:
118       break;
119 
120     case AR_Deprecated:
121       if (S.getCurContextAvailability() != AR_Deprecated)
122         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
123                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
124                                   ObjCPropertyAccess);
125       break;
126 
127     case AR_Unavailable:
128       if (S.getCurContextAvailability() != AR_Unavailable)
129         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
130                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
131                                   ObjCPropertyAccess);
132       break;
133 
134     }
135     return Result;
136 }
137 
138 /// \brief Emit a note explaining that this function is deleted.
139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140   assert(Decl->isDeleted());
141 
142   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
143 
144   if (Method && Method->isDeleted() && Method->isDefaulted()) {
145     // If the method was explicitly defaulted, point at that declaration.
146     if (!Method->isImplicit())
147       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
148 
149     // Try to diagnose why this special member function was implicitly
150     // deleted. This might fail, if that reason no longer applies.
151     CXXSpecialMember CSM = getSpecialMember(Method);
152     if (CSM != CXXInvalid)
153       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
154 
155     return;
156   }
157 
158   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
159     if (CXXConstructorDecl *BaseCD =
160             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
161       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
162       if (BaseCD->isDeleted()) {
163         NoteDeletedFunction(BaseCD);
164       } else {
165         // FIXME: An explanation of why exactly it can't be inherited
166         // would be nice.
167         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
168       }
169       return;
170     }
171   }
172 
173   Diag(Decl->getLocation(), diag::note_availability_specified_here)
174     << Decl << true;
175 }
176 
177 /// \brief Determine whether a FunctionDecl was ever declared with an
178 /// explicit storage class.
179 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
180   for (auto I : D->redecls()) {
181     if (I->getStorageClass() != SC_None)
182       return true;
183   }
184   return false;
185 }
186 
187 /// \brief Check whether we're in an extern inline function and referring to a
188 /// variable or function with internal linkage (C11 6.7.4p3).
189 ///
190 /// This is only a warning because we used to silently accept this code, but
191 /// in many cases it will not behave correctly. This is not enabled in C++ mode
192 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
193 /// and so while there may still be user mistakes, most of the time we can't
194 /// prove that there are errors.
195 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
196                                                       const NamedDecl *D,
197                                                       SourceLocation Loc) {
198   // This is disabled under C++; there are too many ways for this to fire in
199   // contexts where the warning is a false positive, or where it is technically
200   // correct but benign.
201   if (S.getLangOpts().CPlusPlus)
202     return;
203 
204   // Check if this is an inlined function or method.
205   FunctionDecl *Current = S.getCurFunctionDecl();
206   if (!Current)
207     return;
208   if (!Current->isInlined())
209     return;
210   if (!Current->isExternallyVisible())
211     return;
212 
213   // Check if the decl has internal linkage.
214   if (D->getFormalLinkage() != InternalLinkage)
215     return;
216 
217   // Downgrade from ExtWarn to Extension if
218   //  (1) the supposedly external inline function is in the main file,
219   //      and probably won't be included anywhere else.
220   //  (2) the thing we're referencing is a pure function.
221   //  (3) the thing we're referencing is another inline function.
222   // This last can give us false negatives, but it's better than warning on
223   // wrappers for simple C library functions.
224   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
225   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
226   if (!DowngradeWarning && UsedFn)
227     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
228 
229   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
230                                : diag::ext_internal_in_extern_inline)
231     << /*IsVar=*/!UsedFn << D;
232 
233   S.MaybeSuggestAddingStaticToDecl(Current);
234 
235   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
236       << D;
237 }
238 
239 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
240   const FunctionDecl *First = Cur->getFirstDecl();
241 
242   // Suggest "static" on the function, if possible.
243   if (!hasAnyExplicitStorageClass(First)) {
244     SourceLocation DeclBegin = First->getSourceRange().getBegin();
245     Diag(DeclBegin, diag::note_convert_inline_to_static)
246       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
247   }
248 }
249 
250 /// \brief Determine whether the use of this declaration is valid, and
251 /// emit any corresponding diagnostics.
252 ///
253 /// This routine diagnoses various problems with referencing
254 /// declarations that can occur when using a declaration. For example,
255 /// it might warn if a deprecated or unavailable declaration is being
256 /// used, or produce an error (and return true) if a C++0x deleted
257 /// function is being used.
258 ///
259 /// \returns true if there was an error (this declaration cannot be
260 /// referenced), false otherwise.
261 ///
262 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
263                              const ObjCInterfaceDecl *UnknownObjCClass,
264                              bool ObjCPropertyAccess) {
265   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
266     // If there were any diagnostics suppressed by template argument deduction,
267     // emit them now.
268     SuppressedDiagnosticsMap::iterator
269       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
270     if (Pos != SuppressedDiagnostics.end()) {
271       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
272       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
273         Diag(Suppressed[I].first, Suppressed[I].second);
274 
275       // Clear out the list of suppressed diagnostics, so that we don't emit
276       // them again for this specialization. However, we don't obsolete this
277       // entry from the table, because we want to avoid ever emitting these
278       // diagnostics again.
279       Suppressed.clear();
280     }
281 
282     // C++ [basic.start.main]p3:
283     //   The function 'main' shall not be used within a program.
284     if (cast<FunctionDecl>(D)->isMain())
285       Diag(Loc, diag::ext_main_used);
286   }
287 
288   // See if this is an auto-typed variable whose initializer we are parsing.
289   if (ParsingInitForAutoVars.count(D)) {
290     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
291       << D->getDeclName();
292     return true;
293   }
294 
295   // See if this is a deleted function.
296   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
297     if (FD->isDeleted()) {
298       Diag(Loc, diag::err_deleted_function_use);
299       NoteDeletedFunction(FD);
300       return true;
301     }
302 
303     // If the function has a deduced return type, and we can't deduce it,
304     // then we can't use it either.
305     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
306         DeduceReturnType(FD, Loc))
307       return true;
308   }
309   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess);
310 
311   DiagnoseUnusedOfDecl(*this, D, Loc);
312 
313   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
314 
315   return false;
316 }
317 
318 /// \brief Retrieve the message suffix that should be added to a
319 /// diagnostic complaining about the given function being deleted or
320 /// unavailable.
321 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
322   std::string Message;
323   if (FD->getAvailability(&Message))
324     return ": " + Message;
325 
326   return std::string();
327 }
328 
329 /// DiagnoseSentinelCalls - This routine checks whether a call or
330 /// message-send is to a declaration with the sentinel attribute, and
331 /// if so, it checks that the requirements of the sentinel are
332 /// satisfied.
333 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
334                                  ArrayRef<Expr *> Args) {
335   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
336   if (!attr)
337     return;
338 
339   // The number of formal parameters of the declaration.
340   unsigned numFormalParams;
341 
342   // The kind of declaration.  This is also an index into a %select in
343   // the diagnostic.
344   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
345 
346   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
347     numFormalParams = MD->param_size();
348     calleeType = CT_Method;
349   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
350     numFormalParams = FD->param_size();
351     calleeType = CT_Function;
352   } else if (isa<VarDecl>(D)) {
353     QualType type = cast<ValueDecl>(D)->getType();
354     const FunctionType *fn = nullptr;
355     if (const PointerType *ptr = type->getAs<PointerType>()) {
356       fn = ptr->getPointeeType()->getAs<FunctionType>();
357       if (!fn) return;
358       calleeType = CT_Function;
359     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
360       fn = ptr->getPointeeType()->castAs<FunctionType>();
361       calleeType = CT_Block;
362     } else {
363       return;
364     }
365 
366     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
367       numFormalParams = proto->getNumParams();
368     } else {
369       numFormalParams = 0;
370     }
371   } else {
372     return;
373   }
374 
375   // "nullPos" is the number of formal parameters at the end which
376   // effectively count as part of the variadic arguments.  This is
377   // useful if you would prefer to not have *any* formal parameters,
378   // but the language forces you to have at least one.
379   unsigned nullPos = attr->getNullPos();
380   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
381   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
382 
383   // The number of arguments which should follow the sentinel.
384   unsigned numArgsAfterSentinel = attr->getSentinel();
385 
386   // If there aren't enough arguments for all the formal parameters,
387   // the sentinel, and the args after the sentinel, complain.
388   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
389     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
390     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
391     return;
392   }
393 
394   // Otherwise, find the sentinel expression.
395   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
396   if (!sentinelExpr) return;
397   if (sentinelExpr->isValueDependent()) return;
398   if (Context.isSentinelNullExpr(sentinelExpr)) return;
399 
400   // Pick a reasonable string to insert.  Optimistically use 'nil' or
401   // 'NULL' if those are actually defined in the context.  Only use
402   // 'nil' for ObjC methods, where it's much more likely that the
403   // variadic arguments form a list of object pointers.
404   SourceLocation MissingNilLoc
405     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
406   std::string NullValue;
407   if (calleeType == CT_Method &&
408       PP.getIdentifierInfo("nil")->hasMacroDefinition())
409     NullValue = "nil";
410   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
411     NullValue = "NULL";
412   else
413     NullValue = "(void*) 0";
414 
415   if (MissingNilLoc.isInvalid())
416     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
417   else
418     Diag(MissingNilLoc, diag::warn_missing_sentinel)
419       << int(calleeType)
420       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
421   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
422 }
423 
424 SourceRange Sema::getExprRange(Expr *E) const {
425   return E ? E->getSourceRange() : SourceRange();
426 }
427 
428 //===----------------------------------------------------------------------===//
429 //  Standard Promotions and Conversions
430 //===----------------------------------------------------------------------===//
431 
432 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
433 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
434   // Handle any placeholder expressions which made it here.
435   if (E->getType()->isPlaceholderType()) {
436     ExprResult result = CheckPlaceholderExpr(E);
437     if (result.isInvalid()) return ExprError();
438     E = result.get();
439   }
440 
441   QualType Ty = E->getType();
442   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
443 
444   if (Ty->isFunctionType()) {
445     // If we are here, we are not calling a function but taking
446     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
447     if (getLangOpts().OpenCL) {
448       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
449       return ExprError();
450     }
451     E = ImpCastExprToType(E, Context.getPointerType(Ty),
452                           CK_FunctionToPointerDecay).get();
453   } else if (Ty->isArrayType()) {
454     // In C90 mode, arrays only promote to pointers if the array expression is
455     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
456     // type 'array of type' is converted to an expression that has type 'pointer
457     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
458     // that has type 'array of type' ...".  The relevant change is "an lvalue"
459     // (C90) to "an expression" (C99).
460     //
461     // C++ 4.2p1:
462     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
463     // T" can be converted to an rvalue of type "pointer to T".
464     //
465     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
466       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
467                             CK_ArrayToPointerDecay).get();
468   }
469   return E;
470 }
471 
472 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
473   // Check to see if we are dereferencing a null pointer.  If so,
474   // and if not volatile-qualified, this is undefined behavior that the
475   // optimizer will delete, so warn about it.  People sometimes try to use this
476   // to get a deterministic trap and are surprised by clang's behavior.  This
477   // only handles the pattern "*null", which is a very syntactic check.
478   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
479     if (UO->getOpcode() == UO_Deref &&
480         UO->getSubExpr()->IgnoreParenCasts()->
481           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
482         !UO->getType().isVolatileQualified()) {
483     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484                           S.PDiag(diag::warn_indirection_through_null)
485                             << UO->getSubExpr()->getSourceRange());
486     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
487                         S.PDiag(diag::note_indirection_through_null));
488   }
489 }
490 
491 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
492                                     SourceLocation AssignLoc,
493                                     const Expr* RHS) {
494   const ObjCIvarDecl *IV = OIRE->getDecl();
495   if (!IV)
496     return;
497 
498   DeclarationName MemberName = IV->getDeclName();
499   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
500   if (!Member || !Member->isStr("isa"))
501     return;
502 
503   const Expr *Base = OIRE->getBase();
504   QualType BaseType = Base->getType();
505   if (OIRE->isArrow())
506     BaseType = BaseType->getPointeeType();
507   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
508     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
509       ObjCInterfaceDecl *ClassDeclared = nullptr;
510       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
511       if (!ClassDeclared->getSuperClass()
512           && (*ClassDeclared->ivar_begin()) == IV) {
513         if (RHS) {
514           NamedDecl *ObjectSetClass =
515             S.LookupSingleName(S.TUScope,
516                                &S.Context.Idents.get("object_setClass"),
517                                SourceLocation(), S.LookupOrdinaryName);
518           if (ObjectSetClass) {
519             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
520             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
521             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
522             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
523                                                      AssignLoc), ",") <<
524             FixItHint::CreateInsertion(RHSLocEnd, ")");
525           }
526           else
527             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
528         } else {
529           NamedDecl *ObjectGetClass =
530             S.LookupSingleName(S.TUScope,
531                                &S.Context.Idents.get("object_getClass"),
532                                SourceLocation(), S.LookupOrdinaryName);
533           if (ObjectGetClass)
534             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
535             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
536             FixItHint::CreateReplacement(
537                                          SourceRange(OIRE->getOpLoc(),
538                                                      OIRE->getLocEnd()), ")");
539           else
540             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
541         }
542         S.Diag(IV->getLocation(), diag::note_ivar_decl);
543       }
544     }
545 }
546 
547 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
548   // Handle any placeholder expressions which made it here.
549   if (E->getType()->isPlaceholderType()) {
550     ExprResult result = CheckPlaceholderExpr(E);
551     if (result.isInvalid()) return ExprError();
552     E = result.get();
553   }
554 
555   // C++ [conv.lval]p1:
556   //   A glvalue of a non-function, non-array type T can be
557   //   converted to a prvalue.
558   if (!E->isGLValue()) return E;
559 
560   QualType T = E->getType();
561   assert(!T.isNull() && "r-value conversion on typeless expression?");
562 
563   // We don't want to throw lvalue-to-rvalue casts on top of
564   // expressions of certain types in C++.
565   if (getLangOpts().CPlusPlus &&
566       (E->getType() == Context.OverloadTy ||
567        T->isDependentType() ||
568        T->isRecordType()))
569     return E;
570 
571   // The C standard is actually really unclear on this point, and
572   // DR106 tells us what the result should be but not why.  It's
573   // generally best to say that void types just doesn't undergo
574   // lvalue-to-rvalue at all.  Note that expressions of unqualified
575   // 'void' type are never l-values, but qualified void can be.
576   if (T->isVoidType())
577     return E;
578 
579   // OpenCL usually rejects direct accesses to values of 'half' type.
580   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
581       T->isHalfType()) {
582     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
583       << 0 << T;
584     return ExprError();
585   }
586 
587   CheckForNullPointerDereference(*this, E);
588   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
589     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
590                                      &Context.Idents.get("object_getClass"),
591                                      SourceLocation(), LookupOrdinaryName);
592     if (ObjectGetClass)
593       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
594         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
595         FixItHint::CreateReplacement(
596                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
597     else
598       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
599   }
600   else if (const ObjCIvarRefExpr *OIRE =
601             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
602     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
603 
604   // C++ [conv.lval]p1:
605   //   [...] If T is a non-class type, the type of the prvalue is the
606   //   cv-unqualified version of T. Otherwise, the type of the
607   //   rvalue is T.
608   //
609   // C99 6.3.2.1p2:
610   //   If the lvalue has qualified type, the value has the unqualified
611   //   version of the type of the lvalue; otherwise, the value has the
612   //   type of the lvalue.
613   if (T.hasQualifiers())
614     T = T.getUnqualifiedType();
615 
616   UpdateMarkingForLValueToRValue(E);
617 
618   // Loading a __weak object implicitly retains the value, so we need a cleanup to
619   // balance that.
620   if (getLangOpts().ObjCAutoRefCount &&
621       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
622     ExprNeedsCleanups = true;
623 
624   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
625                                             nullptr, VK_RValue);
626 
627   // C11 6.3.2.1p2:
628   //   ... if the lvalue has atomic type, the value has the non-atomic version
629   //   of the type of the lvalue ...
630   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
631     T = Atomic->getValueType().getUnqualifiedType();
632     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
633                                    nullptr, VK_RValue);
634   }
635 
636   return Res;
637 }
638 
639 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
640   ExprResult Res = DefaultFunctionArrayConversion(E);
641   if (Res.isInvalid())
642     return ExprError();
643   Res = DefaultLvalueConversion(Res.get());
644   if (Res.isInvalid())
645     return ExprError();
646   return Res;
647 }
648 
649 /// CallExprUnaryConversions - a special case of an unary conversion
650 /// performed on a function designator of a call expression.
651 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
652   QualType Ty = E->getType();
653   ExprResult Res = E;
654   // Only do implicit cast for a function type, but not for a pointer
655   // to function type.
656   if (Ty->isFunctionType()) {
657     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
658                             CK_FunctionToPointerDecay).get();
659     if (Res.isInvalid())
660       return ExprError();
661   }
662   Res = DefaultLvalueConversion(Res.get());
663   if (Res.isInvalid())
664     return ExprError();
665   return Res.get();
666 }
667 
668 /// UsualUnaryConversions - Performs various conversions that are common to most
669 /// operators (C99 6.3). The conversions of array and function types are
670 /// sometimes suppressed. For example, the array->pointer conversion doesn't
671 /// apply if the array is an argument to the sizeof or address (&) operators.
672 /// In these instances, this routine should *not* be called.
673 ExprResult Sema::UsualUnaryConversions(Expr *E) {
674   // First, convert to an r-value.
675   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
676   if (Res.isInvalid())
677     return ExprError();
678   E = Res.get();
679 
680   QualType Ty = E->getType();
681   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
682 
683   // Half FP have to be promoted to float unless it is natively supported
684   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
685     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
686 
687   // Try to perform integral promotions if the object has a theoretically
688   // promotable type.
689   if (Ty->isIntegralOrUnscopedEnumerationType()) {
690     // C99 6.3.1.1p2:
691     //
692     //   The following may be used in an expression wherever an int or
693     //   unsigned int may be used:
694     //     - an object or expression with an integer type whose integer
695     //       conversion rank is less than or equal to the rank of int
696     //       and unsigned int.
697     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
698     //
699     //   If an int can represent all values of the original type, the
700     //   value is converted to an int; otherwise, it is converted to an
701     //   unsigned int. These are called the integer promotions. All
702     //   other types are unchanged by the integer promotions.
703 
704     QualType PTy = Context.isPromotableBitField(E);
705     if (!PTy.isNull()) {
706       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
707       return E;
708     }
709     if (Ty->isPromotableIntegerType()) {
710       QualType PT = Context.getPromotedIntegerType(Ty);
711       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
712       return E;
713     }
714   }
715   return E;
716 }
717 
718 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
719 /// do not have a prototype. Arguments that have type float or __fp16
720 /// are promoted to double. All other argument types are converted by
721 /// UsualUnaryConversions().
722 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
723   QualType Ty = E->getType();
724   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
725 
726   ExprResult Res = UsualUnaryConversions(E);
727   if (Res.isInvalid())
728     return ExprError();
729   E = Res.get();
730 
731   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
732   // double.
733   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
734   if (BTy && (BTy->getKind() == BuiltinType::Half ||
735               BTy->getKind() == BuiltinType::Float))
736     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
737 
738   // C++ performs lvalue-to-rvalue conversion as a default argument
739   // promotion, even on class types, but note:
740   //   C++11 [conv.lval]p2:
741   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
742   //     operand or a subexpression thereof the value contained in the
743   //     referenced object is not accessed. Otherwise, if the glvalue
744   //     has a class type, the conversion copy-initializes a temporary
745   //     of type T from the glvalue and the result of the conversion
746   //     is a prvalue for the temporary.
747   // FIXME: add some way to gate this entire thing for correctness in
748   // potentially potentially evaluated contexts.
749   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
750     ExprResult Temp = PerformCopyInitialization(
751                        InitializedEntity::InitializeTemporary(E->getType()),
752                                                 E->getExprLoc(), E);
753     if (Temp.isInvalid())
754       return ExprError();
755     E = Temp.get();
756   }
757 
758   return E;
759 }
760 
761 /// Determine the degree of POD-ness for an expression.
762 /// Incomplete types are considered POD, since this check can be performed
763 /// when we're in an unevaluated context.
764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
765   if (Ty->isIncompleteType()) {
766     // C++11 [expr.call]p7:
767     //   After these conversions, if the argument does not have arithmetic,
768     //   enumeration, pointer, pointer to member, or class type, the program
769     //   is ill-formed.
770     //
771     // Since we've already performed array-to-pointer and function-to-pointer
772     // decay, the only such type in C++ is cv void. This also handles
773     // initializer lists as variadic arguments.
774     if (Ty->isVoidType())
775       return VAK_Invalid;
776 
777     if (Ty->isObjCObjectType())
778       return VAK_Invalid;
779     return VAK_Valid;
780   }
781 
782   if (Ty.isCXX98PODType(Context))
783     return VAK_Valid;
784 
785   // C++11 [expr.call]p7:
786   //   Passing a potentially-evaluated argument of class type (Clause 9)
787   //   having a non-trivial copy constructor, a non-trivial move constructor,
788   //   or a non-trivial destructor, with no corresponding parameter,
789   //   is conditionally-supported with implementation-defined semantics.
790   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
791     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
792       if (!Record->hasNonTrivialCopyConstructor() &&
793           !Record->hasNonTrivialMoveConstructor() &&
794           !Record->hasNonTrivialDestructor())
795         return VAK_ValidInCXX11;
796 
797   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
798     return VAK_Valid;
799 
800   if (Ty->isObjCObjectType())
801     return VAK_Invalid;
802 
803   if (getLangOpts().MSVCCompat)
804     return VAK_MSVCUndefined;
805 
806   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
807   // permitted to reject them. We should consider doing so.
808   return VAK_Undefined;
809 }
810 
811 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
812   // Don't allow one to pass an Objective-C interface to a vararg.
813   const QualType &Ty = E->getType();
814   VarArgKind VAK = isValidVarArgType(Ty);
815 
816   // Complain about passing non-POD types through varargs.
817   switch (VAK) {
818   case VAK_ValidInCXX11:
819     DiagRuntimeBehavior(
820         E->getLocStart(), nullptr,
821         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
822           << Ty << CT);
823     // Fall through.
824   case VAK_Valid:
825     if (Ty->isRecordType()) {
826       // This is unlikely to be what the user intended. If the class has a
827       // 'c_str' member function, the user probably meant to call that.
828       DiagRuntimeBehavior(E->getLocStart(), nullptr,
829                           PDiag(diag::warn_pass_class_arg_to_vararg)
830                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
831     }
832     break;
833 
834   case VAK_Undefined:
835   case VAK_MSVCUndefined:
836     DiagRuntimeBehavior(
837         E->getLocStart(), nullptr,
838         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
839           << getLangOpts().CPlusPlus11 << Ty << CT);
840     break;
841 
842   case VAK_Invalid:
843     if (Ty->isObjCObjectType())
844       DiagRuntimeBehavior(
845           E->getLocStart(), nullptr,
846           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
847             << Ty << CT);
848     else
849       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
850         << isa<InitListExpr>(E) << Ty << CT;
851     break;
852   }
853 }
854 
855 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
856 /// will create a trap if the resulting type is not a POD type.
857 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
858                                                   FunctionDecl *FDecl) {
859   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
860     // Strip the unbridged-cast placeholder expression off, if applicable.
861     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
862         (CT == VariadicMethod ||
863          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
864       E = stripARCUnbridgedCast(E);
865 
866     // Otherwise, do normal placeholder checking.
867     } else {
868       ExprResult ExprRes = CheckPlaceholderExpr(E);
869       if (ExprRes.isInvalid())
870         return ExprError();
871       E = ExprRes.get();
872     }
873   }
874 
875   ExprResult ExprRes = DefaultArgumentPromotion(E);
876   if (ExprRes.isInvalid())
877     return ExprError();
878   E = ExprRes.get();
879 
880   // Diagnostics regarding non-POD argument types are
881   // emitted along with format string checking in Sema::CheckFunctionCall().
882   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
883     // Turn this into a trap.
884     CXXScopeSpec SS;
885     SourceLocation TemplateKWLoc;
886     UnqualifiedId Name;
887     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
888                        E->getLocStart());
889     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
890                                           Name, true, false);
891     if (TrapFn.isInvalid())
892       return ExprError();
893 
894     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
895                                     E->getLocStart(), None,
896                                     E->getLocEnd());
897     if (Call.isInvalid())
898       return ExprError();
899 
900     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
901                                   Call.get(), E);
902     if (Comma.isInvalid())
903       return ExprError();
904     return Comma.get();
905   }
906 
907   if (!getLangOpts().CPlusPlus &&
908       RequireCompleteType(E->getExprLoc(), E->getType(),
909                           diag::err_call_incomplete_argument))
910     return ExprError();
911 
912   return E;
913 }
914 
915 /// \brief Converts an integer to complex float type.  Helper function of
916 /// UsualArithmeticConversions()
917 ///
918 /// \return false if the integer expression is an integer type and is
919 /// successfully converted to the complex type.
920 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
921                                                   ExprResult &ComplexExpr,
922                                                   QualType IntTy,
923                                                   QualType ComplexTy,
924                                                   bool SkipCast) {
925   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
926   if (SkipCast) return false;
927   if (IntTy->isIntegerType()) {
928     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
929     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
930     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
931                                   CK_FloatingRealToComplex);
932   } else {
933     assert(IntTy->isComplexIntegerType());
934     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
935                                   CK_IntegralComplexToFloatingComplex);
936   }
937   return false;
938 }
939 
940 /// \brief Takes two complex float types and converts them to the same type.
941 /// Helper function of UsualArithmeticConversions()
942 static QualType
943 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
944                                             ExprResult &RHS, QualType LHSType,
945                                             QualType RHSType,
946                                             bool IsCompAssign) {
947   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
948 
949   if (order < 0) {
950     // _Complex float -> _Complex double
951     if (!IsCompAssign)
952       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingComplexCast);
953     return RHSType;
954   }
955   if (order > 0)
956     // _Complex float -> _Complex double
957     RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingComplexCast);
958   return LHSType;
959 }
960 
961 /// \brief Converts otherExpr to complex float and promotes complexExpr if
962 /// necessary.  Helper function of UsualArithmeticConversions()
963 static QualType handleOtherComplexFloatConversion(Sema &S,
964                                                   ExprResult &ComplexExpr,
965                                                   ExprResult &OtherExpr,
966                                                   QualType ComplexTy,
967                                                   QualType OtherTy,
968                                                   bool ConvertComplexExpr,
969                                                   bool ConvertOtherExpr) {
970   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
971 
972   // If just the complexExpr is complex, the otherExpr needs to be converted,
973   // and the complexExpr might need to be promoted.
974   if (order > 0) { // complexExpr is wider
975     // float -> _Complex double
976     if (ConvertOtherExpr) {
977       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
978       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), fp, CK_FloatingCast);
979       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), ComplexTy,
980                                       CK_FloatingRealToComplex);
981     }
982     return ComplexTy;
983   }
984 
985   // otherTy is at least as wide.  Find its corresponding complex type.
986   QualType result = (order == 0 ? ComplexTy :
987                                   S.Context.getComplexType(OtherTy));
988 
989   // double -> _Complex double
990   if (ConvertOtherExpr)
991     OtherExpr = S.ImpCastExprToType(OtherExpr.get(), result,
992                                     CK_FloatingRealToComplex);
993 
994   // _Complex float -> _Complex double
995   if (ConvertComplexExpr && order < 0)
996     ComplexExpr = S.ImpCastExprToType(ComplexExpr.get(), result,
997                                       CK_FloatingComplexCast);
998 
999   return result;
1000 }
1001 
1002 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1003 /// UsualArithmeticConversions()
1004 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1005                                              ExprResult &RHS, QualType LHSType,
1006                                              QualType RHSType,
1007                                              bool IsCompAssign) {
1008   // if we have an integer operand, the result is the complex type.
1009   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1010                                              /*skipCast*/false))
1011     return LHSType;
1012   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1013                                              /*skipCast*/IsCompAssign))
1014     return RHSType;
1015 
1016   // This handles complex/complex, complex/float, or float/complex.
1017   // When both operands are complex, the shorter operand is converted to the
1018   // type of the longer, and that is the type of the result. This corresponds
1019   // to what is done when combining two real floating-point operands.
1020   // The fun begins when size promotion occur across type domains.
1021   // From H&S 6.3.4: When one operand is complex and the other is a real
1022   // floating-point type, the less precise type is converted, within it's
1023   // real or complex domain, to the precision of the other type. For example,
1024   // when combining a "long double" with a "double _Complex", the
1025   // "double _Complex" is promoted to "long double _Complex".
1026 
1027   bool LHSComplexFloat = LHSType->isComplexType();
1028   bool RHSComplexFloat = RHSType->isComplexType();
1029 
1030   // If both are complex, just cast to the more precise type.
1031   if (LHSComplexFloat && RHSComplexFloat)
1032     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1033                                                        LHSType, RHSType,
1034                                                        IsCompAssign);
1035 
1036   // If only one operand is complex, promote it if necessary and convert the
1037   // other operand to complex.
1038   if (LHSComplexFloat)
1039     return handleOtherComplexFloatConversion(
1040         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1041         /*convertOtherExpr*/ true);
1042 
1043   assert(RHSComplexFloat);
1044   return handleOtherComplexFloatConversion(
1045       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1046       /*convertOtherExpr*/ !IsCompAssign);
1047 }
1048 
1049 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1050 /// of UsualArithmeticConversions()
1051 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1052                                            ExprResult &IntExpr,
1053                                            QualType FloatTy, QualType IntTy,
1054                                            bool ConvertFloat, bool ConvertInt) {
1055   if (IntTy->isIntegerType()) {
1056     if (ConvertInt)
1057       // Convert intExpr to the lhs floating point type.
1058       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1059                                     CK_IntegralToFloating);
1060     return FloatTy;
1061   }
1062 
1063   // Convert both sides to the appropriate complex float.
1064   assert(IntTy->isComplexIntegerType());
1065   QualType result = S.Context.getComplexType(FloatTy);
1066 
1067   // _Complex int -> _Complex float
1068   if (ConvertInt)
1069     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1070                                   CK_IntegralComplexToFloatingComplex);
1071 
1072   // float -> _Complex float
1073   if (ConvertFloat)
1074     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1075                                     CK_FloatingRealToComplex);
1076 
1077   return result;
1078 }
1079 
1080 /// \brief Handle arithmethic conversion with floating point types.  Helper
1081 /// function of UsualArithmeticConversions()
1082 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1083                                       ExprResult &RHS, QualType LHSType,
1084                                       QualType RHSType, bool IsCompAssign) {
1085   bool LHSFloat = LHSType->isRealFloatingType();
1086   bool RHSFloat = RHSType->isRealFloatingType();
1087 
1088   // If we have two real floating types, convert the smaller operand
1089   // to the bigger result.
1090   if (LHSFloat && RHSFloat) {
1091     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1092     if (order > 0) {
1093       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1094       return LHSType;
1095     }
1096 
1097     assert(order < 0 && "illegal float comparison");
1098     if (!IsCompAssign)
1099       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1100     return RHSType;
1101   }
1102 
1103   if (LHSFloat)
1104     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1105                                       /*convertFloat=*/!IsCompAssign,
1106                                       /*convertInt=*/ true);
1107   assert(RHSFloat);
1108   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1109                                     /*convertInt=*/ true,
1110                                     /*convertFloat=*/!IsCompAssign);
1111 }
1112 
1113 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1114 
1115 namespace {
1116 /// These helper callbacks are placed in an anonymous namespace to
1117 /// permit their use as function template parameters.
1118 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1119   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1120 }
1121 
1122 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1123   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1124                              CK_IntegralComplexCast);
1125 }
1126 }
1127 
1128 /// \brief Handle integer arithmetic conversions.  Helper function of
1129 /// UsualArithmeticConversions()
1130 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1131 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1132                                         ExprResult &RHS, QualType LHSType,
1133                                         QualType RHSType, bool IsCompAssign) {
1134   // The rules for this case are in C99 6.3.1.8
1135   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1136   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1137   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1138   if (LHSSigned == RHSSigned) {
1139     // Same signedness; use the higher-ranked type
1140     if (order >= 0) {
1141       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1142       return LHSType;
1143     } else if (!IsCompAssign)
1144       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1145     return RHSType;
1146   } else if (order != (LHSSigned ? 1 : -1)) {
1147     // The unsigned type has greater than or equal rank to the
1148     // signed type, so use the unsigned type
1149     if (RHSSigned) {
1150       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1151       return LHSType;
1152     } else if (!IsCompAssign)
1153       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1154     return RHSType;
1155   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1156     // The two types are different widths; if we are here, that
1157     // means the signed type is larger than the unsigned type, so
1158     // use the signed type.
1159     if (LHSSigned) {
1160       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1161       return LHSType;
1162     } else if (!IsCompAssign)
1163       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1164     return RHSType;
1165   } else {
1166     // The signed type is higher-ranked than the unsigned type,
1167     // but isn't actually any bigger (like unsigned int and long
1168     // on most 32-bit systems).  Use the unsigned type corresponding
1169     // to the signed type.
1170     QualType result =
1171       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1172     RHS = (*doRHSCast)(S, RHS.get(), result);
1173     if (!IsCompAssign)
1174       LHS = (*doLHSCast)(S, LHS.get(), result);
1175     return result;
1176   }
1177 }
1178 
1179 /// \brief Handle conversions with GCC complex int extension.  Helper function
1180 /// of UsualArithmeticConversions()
1181 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1182                                            ExprResult &RHS, QualType LHSType,
1183                                            QualType RHSType,
1184                                            bool IsCompAssign) {
1185   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1186   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1187 
1188   if (LHSComplexInt && RHSComplexInt) {
1189     QualType LHSEltType = LHSComplexInt->getElementType();
1190     QualType RHSEltType = RHSComplexInt->getElementType();
1191     QualType ScalarType =
1192       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1193         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1194 
1195     return S.Context.getComplexType(ScalarType);
1196   }
1197 
1198   if (LHSComplexInt) {
1199     QualType LHSEltType = LHSComplexInt->getElementType();
1200     QualType ScalarType =
1201       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1202         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1203     QualType ComplexType = S.Context.getComplexType(ScalarType);
1204     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1205                               CK_IntegralRealToComplex);
1206 
1207     return ComplexType;
1208   }
1209 
1210   assert(RHSComplexInt);
1211 
1212   QualType RHSEltType = RHSComplexInt->getElementType();
1213   QualType ScalarType =
1214     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1215       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1216   QualType ComplexType = S.Context.getComplexType(ScalarType);
1217 
1218   if (!IsCompAssign)
1219     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1220                               CK_IntegralRealToComplex);
1221   return ComplexType;
1222 }
1223 
1224 /// UsualArithmeticConversions - Performs various conversions that are common to
1225 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1226 /// routine returns the first non-arithmetic type found. The client is
1227 /// responsible for emitting appropriate error diagnostics.
1228 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1229                                           bool IsCompAssign) {
1230   if (!IsCompAssign) {
1231     LHS = UsualUnaryConversions(LHS.get());
1232     if (LHS.isInvalid())
1233       return QualType();
1234   }
1235 
1236   RHS = UsualUnaryConversions(RHS.get());
1237   if (RHS.isInvalid())
1238     return QualType();
1239 
1240   // For conversion purposes, we ignore any qualifiers.
1241   // For example, "const float" and "float" are equivalent.
1242   QualType LHSType =
1243     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1244   QualType RHSType =
1245     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1246 
1247   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1248   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1249     LHSType = AtomicLHS->getValueType();
1250 
1251   // If both types are identical, no conversion is needed.
1252   if (LHSType == RHSType)
1253     return LHSType;
1254 
1255   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1256   // The caller can deal with this (e.g. pointer + int).
1257   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1258     return QualType();
1259 
1260   // Apply unary and bitfield promotions to the LHS's type.
1261   QualType LHSUnpromotedType = LHSType;
1262   if (LHSType->isPromotableIntegerType())
1263     LHSType = Context.getPromotedIntegerType(LHSType);
1264   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1265   if (!LHSBitfieldPromoteTy.isNull())
1266     LHSType = LHSBitfieldPromoteTy;
1267   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1268     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1269 
1270   // If both types are identical, no conversion is needed.
1271   if (LHSType == RHSType)
1272     return LHSType;
1273 
1274   // At this point, we have two different arithmetic types.
1275 
1276   // Handle complex types first (C99 6.3.1.8p1).
1277   if (LHSType->isComplexType() || RHSType->isComplexType())
1278     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1279                                         IsCompAssign);
1280 
1281   // Now handle "real" floating types (i.e. float, double, long double).
1282   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1283     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1284                                  IsCompAssign);
1285 
1286   // Handle GCC complex int extension.
1287   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1288     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1289                                       IsCompAssign);
1290 
1291   // Finally, we have two differing integer types.
1292   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1293            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1294 }
1295 
1296 
1297 //===----------------------------------------------------------------------===//
1298 //  Semantic Analysis for various Expression Types
1299 //===----------------------------------------------------------------------===//
1300 
1301 
1302 ExprResult
1303 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1304                                 SourceLocation DefaultLoc,
1305                                 SourceLocation RParenLoc,
1306                                 Expr *ControllingExpr,
1307                                 ArrayRef<ParsedType> ArgTypes,
1308                                 ArrayRef<Expr *> ArgExprs) {
1309   unsigned NumAssocs = ArgTypes.size();
1310   assert(NumAssocs == ArgExprs.size());
1311 
1312   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1313   for (unsigned i = 0; i < NumAssocs; ++i) {
1314     if (ArgTypes[i])
1315       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1316     else
1317       Types[i] = nullptr;
1318   }
1319 
1320   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1321                                              ControllingExpr,
1322                                              llvm::makeArrayRef(Types, NumAssocs),
1323                                              ArgExprs);
1324   delete [] Types;
1325   return ER;
1326 }
1327 
1328 ExprResult
1329 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1330                                  SourceLocation DefaultLoc,
1331                                  SourceLocation RParenLoc,
1332                                  Expr *ControllingExpr,
1333                                  ArrayRef<TypeSourceInfo *> Types,
1334                                  ArrayRef<Expr *> Exprs) {
1335   unsigned NumAssocs = Types.size();
1336   assert(NumAssocs == Exprs.size());
1337   if (ControllingExpr->getType()->isPlaceholderType()) {
1338     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1339     if (result.isInvalid()) return ExprError();
1340     ControllingExpr = result.get();
1341   }
1342 
1343   bool TypeErrorFound = false,
1344        IsResultDependent = ControllingExpr->isTypeDependent(),
1345        ContainsUnexpandedParameterPack
1346          = ControllingExpr->containsUnexpandedParameterPack();
1347 
1348   for (unsigned i = 0; i < NumAssocs; ++i) {
1349     if (Exprs[i]->containsUnexpandedParameterPack())
1350       ContainsUnexpandedParameterPack = true;
1351 
1352     if (Types[i]) {
1353       if (Types[i]->getType()->containsUnexpandedParameterPack())
1354         ContainsUnexpandedParameterPack = true;
1355 
1356       if (Types[i]->getType()->isDependentType()) {
1357         IsResultDependent = true;
1358       } else {
1359         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1360         // complete object type other than a variably modified type."
1361         unsigned D = 0;
1362         if (Types[i]->getType()->isIncompleteType())
1363           D = diag::err_assoc_type_incomplete;
1364         else if (!Types[i]->getType()->isObjectType())
1365           D = diag::err_assoc_type_nonobject;
1366         else if (Types[i]->getType()->isVariablyModifiedType())
1367           D = diag::err_assoc_type_variably_modified;
1368 
1369         if (D != 0) {
1370           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1371             << Types[i]->getTypeLoc().getSourceRange()
1372             << Types[i]->getType();
1373           TypeErrorFound = true;
1374         }
1375 
1376         // C11 6.5.1.1p2 "No two generic associations in the same generic
1377         // selection shall specify compatible types."
1378         for (unsigned j = i+1; j < NumAssocs; ++j)
1379           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1380               Context.typesAreCompatible(Types[i]->getType(),
1381                                          Types[j]->getType())) {
1382             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1383                  diag::err_assoc_compatible_types)
1384               << Types[j]->getTypeLoc().getSourceRange()
1385               << Types[j]->getType()
1386               << Types[i]->getType();
1387             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1388                  diag::note_compat_assoc)
1389               << Types[i]->getTypeLoc().getSourceRange()
1390               << Types[i]->getType();
1391             TypeErrorFound = true;
1392           }
1393       }
1394     }
1395   }
1396   if (TypeErrorFound)
1397     return ExprError();
1398 
1399   // If we determined that the generic selection is result-dependent, don't
1400   // try to compute the result expression.
1401   if (IsResultDependent)
1402     return new (Context) GenericSelectionExpr(
1403         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1404         ContainsUnexpandedParameterPack);
1405 
1406   SmallVector<unsigned, 1> CompatIndices;
1407   unsigned DefaultIndex = -1U;
1408   for (unsigned i = 0; i < NumAssocs; ++i) {
1409     if (!Types[i])
1410       DefaultIndex = i;
1411     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1412                                         Types[i]->getType()))
1413       CompatIndices.push_back(i);
1414   }
1415 
1416   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1417   // type compatible with at most one of the types named in its generic
1418   // association list."
1419   if (CompatIndices.size() > 1) {
1420     // We strip parens here because the controlling expression is typically
1421     // parenthesized in macro definitions.
1422     ControllingExpr = ControllingExpr->IgnoreParens();
1423     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1424       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1425       << (unsigned) CompatIndices.size();
1426     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1427          E = CompatIndices.end(); I != E; ++I) {
1428       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1429            diag::note_compat_assoc)
1430         << Types[*I]->getTypeLoc().getSourceRange()
1431         << Types[*I]->getType();
1432     }
1433     return ExprError();
1434   }
1435 
1436   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1437   // its controlling expression shall have type compatible with exactly one of
1438   // the types named in its generic association list."
1439   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1440     // We strip parens here because the controlling expression is typically
1441     // parenthesized in macro definitions.
1442     ControllingExpr = ControllingExpr->IgnoreParens();
1443     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1444       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1445     return ExprError();
1446   }
1447 
1448   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1449   // type name that is compatible with the type of the controlling expression,
1450   // then the result expression of the generic selection is the expression
1451   // in that generic association. Otherwise, the result expression of the
1452   // generic selection is the expression in the default generic association."
1453   unsigned ResultIndex =
1454     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1455 
1456   return new (Context) GenericSelectionExpr(
1457       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1458       ContainsUnexpandedParameterPack, ResultIndex);
1459 }
1460 
1461 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1462 /// location of the token and the offset of the ud-suffix within it.
1463 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1464                                      unsigned Offset) {
1465   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1466                                         S.getLangOpts());
1467 }
1468 
1469 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1470 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1471 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1472                                                  IdentifierInfo *UDSuffix,
1473                                                  SourceLocation UDSuffixLoc,
1474                                                  ArrayRef<Expr*> Args,
1475                                                  SourceLocation LitEndLoc) {
1476   assert(Args.size() <= 2 && "too many arguments for literal operator");
1477 
1478   QualType ArgTy[2];
1479   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1480     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1481     if (ArgTy[ArgIdx]->isArrayType())
1482       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1483   }
1484 
1485   DeclarationName OpName =
1486     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1487   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1488   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1489 
1490   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1491   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1492                               /*AllowRaw*/false, /*AllowTemplate*/false,
1493                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1494     return ExprError();
1495 
1496   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1497 }
1498 
1499 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1500 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1501 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1502 /// multiple tokens.  However, the common case is that StringToks points to one
1503 /// string.
1504 ///
1505 ExprResult
1506 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1507   assert(!StringToks.empty() && "Must have at least one string!");
1508 
1509   StringLiteralParser Literal(StringToks, PP);
1510   if (Literal.hadError)
1511     return ExprError();
1512 
1513   SmallVector<SourceLocation, 4> StringTokLocs;
1514   for (unsigned i = 0; i != StringToks.size(); ++i)
1515     StringTokLocs.push_back(StringToks[i].getLocation());
1516 
1517   QualType CharTy = Context.CharTy;
1518   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1519   if (Literal.isWide()) {
1520     CharTy = Context.getWideCharType();
1521     Kind = StringLiteral::Wide;
1522   } else if (Literal.isUTF8()) {
1523     Kind = StringLiteral::UTF8;
1524   } else if (Literal.isUTF16()) {
1525     CharTy = Context.Char16Ty;
1526     Kind = StringLiteral::UTF16;
1527   } else if (Literal.isUTF32()) {
1528     CharTy = Context.Char32Ty;
1529     Kind = StringLiteral::UTF32;
1530   } else if (Literal.isPascal()) {
1531     CharTy = Context.UnsignedCharTy;
1532   }
1533 
1534   QualType CharTyConst = CharTy;
1535   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1536   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1537     CharTyConst.addConst();
1538 
1539   // Get an array type for the string, according to C99 6.4.5.  This includes
1540   // the nul terminator character as well as the string length for pascal
1541   // strings.
1542   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1543                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1544                                  ArrayType::Normal, 0);
1545 
1546   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1547   if (getLangOpts().OpenCL) {
1548     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1549   }
1550 
1551   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1552   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1553                                              Kind, Literal.Pascal, StrTy,
1554                                              &StringTokLocs[0],
1555                                              StringTokLocs.size());
1556   if (Literal.getUDSuffix().empty())
1557     return Lit;
1558 
1559   // We're building a user-defined literal.
1560   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1561   SourceLocation UDSuffixLoc =
1562     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1563                    Literal.getUDSuffixOffset());
1564 
1565   // Make sure we're allowed user-defined literals here.
1566   if (!UDLScope)
1567     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1568 
1569   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1570   //   operator "" X (str, len)
1571   QualType SizeType = Context.getSizeType();
1572 
1573   DeclarationName OpName =
1574     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1575   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1576   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1577 
1578   QualType ArgTy[] = {
1579     Context.getArrayDecayedType(StrTy), SizeType
1580   };
1581 
1582   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1583   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1584                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1585                                 /*AllowStringTemplate*/true)) {
1586 
1587   case LOLR_Cooked: {
1588     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1589     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1590                                                     StringTokLocs[0]);
1591     Expr *Args[] = { Lit, LenArg };
1592 
1593     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1594   }
1595 
1596   case LOLR_StringTemplate: {
1597     TemplateArgumentListInfo ExplicitArgs;
1598 
1599     unsigned CharBits = Context.getIntWidth(CharTy);
1600     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1601     llvm::APSInt Value(CharBits, CharIsUnsigned);
1602 
1603     TemplateArgument TypeArg(CharTy);
1604     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1605     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1606 
1607     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1608       Value = Lit->getCodeUnit(I);
1609       TemplateArgument Arg(Context, Value, CharTy);
1610       TemplateArgumentLocInfo ArgInfo;
1611       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1612     }
1613     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1614                                     &ExplicitArgs);
1615   }
1616   case LOLR_Raw:
1617   case LOLR_Template:
1618     llvm_unreachable("unexpected literal operator lookup result");
1619   case LOLR_Error:
1620     return ExprError();
1621   }
1622   llvm_unreachable("unexpected literal operator lookup result");
1623 }
1624 
1625 ExprResult
1626 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1627                        SourceLocation Loc,
1628                        const CXXScopeSpec *SS) {
1629   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1630   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1631 }
1632 
1633 /// BuildDeclRefExpr - Build an expression that references a
1634 /// declaration that does not require a closure capture.
1635 ExprResult
1636 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1637                        const DeclarationNameInfo &NameInfo,
1638                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1639                        const TemplateArgumentListInfo *TemplateArgs) {
1640   if (getLangOpts().CUDA)
1641     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1642       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1643         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1644                            CalleeTarget = IdentifyCUDATarget(Callee);
1645         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1646           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1647             << CalleeTarget << D->getIdentifier() << CallerTarget;
1648           Diag(D->getLocation(), diag::note_previous_decl)
1649             << D->getIdentifier();
1650           return ExprError();
1651         }
1652       }
1653 
1654   bool refersToEnclosingScope =
1655     (CurContext != D->getDeclContext() &&
1656      D->getDeclContext()->isFunctionOrMethod()) ||
1657     (isa<VarDecl>(D) &&
1658      cast<VarDecl>(D)->isInitCapture());
1659 
1660   DeclRefExpr *E;
1661   if (isa<VarTemplateSpecializationDecl>(D)) {
1662     VarTemplateSpecializationDecl *VarSpec =
1663         cast<VarTemplateSpecializationDecl>(D);
1664 
1665     E = DeclRefExpr::Create(
1666         Context,
1667         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1668         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1669         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1670   } else {
1671     assert(!TemplateArgs && "No template arguments for non-variable"
1672                             " template specialization references");
1673     E = DeclRefExpr::Create(
1674         Context,
1675         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1676         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1677   }
1678 
1679   MarkDeclRefReferenced(E);
1680 
1681   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1682       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1683       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1684       recordUseOfEvaluatedWeak(E);
1685 
1686   // Just in case we're building an illegal pointer-to-member.
1687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688   if (FD && FD->isBitField())
1689     E->setObjectKind(OK_BitField);
1690 
1691   return E;
1692 }
1693 
1694 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1695 /// possibly a list of template arguments.
1696 ///
1697 /// If this produces template arguments, it is permitted to call
1698 /// DecomposeTemplateName.
1699 ///
1700 /// This actually loses a lot of source location information for
1701 /// non-standard name kinds; we should consider preserving that in
1702 /// some way.
1703 void
1704 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1705                              TemplateArgumentListInfo &Buffer,
1706                              DeclarationNameInfo &NameInfo,
1707                              const TemplateArgumentListInfo *&TemplateArgs) {
1708   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1709     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1710     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1711 
1712     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1713                                        Id.TemplateId->NumArgs);
1714     translateTemplateArguments(TemplateArgsPtr, Buffer);
1715 
1716     TemplateName TName = Id.TemplateId->Template.get();
1717     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1718     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1719     TemplateArgs = &Buffer;
1720   } else {
1721     NameInfo = GetNameFromUnqualifiedId(Id);
1722     TemplateArgs = nullptr;
1723   }
1724 }
1725 
1726 /// Diagnose an empty lookup.
1727 ///
1728 /// \return false if new lookup candidates were found
1729 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1730                                CorrectionCandidateCallback &CCC,
1731                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1732                                ArrayRef<Expr *> Args) {
1733   DeclarationName Name = R.getLookupName();
1734 
1735   unsigned diagnostic = diag::err_undeclared_var_use;
1736   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1737   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1738       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1739       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1740     diagnostic = diag::err_undeclared_use;
1741     diagnostic_suggest = diag::err_undeclared_use_suggest;
1742   }
1743 
1744   // If the original lookup was an unqualified lookup, fake an
1745   // unqualified lookup.  This is useful when (for example) the
1746   // original lookup would not have found something because it was a
1747   // dependent name.
1748   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1749     ? CurContext : nullptr;
1750   while (DC) {
1751     if (isa<CXXRecordDecl>(DC)) {
1752       LookupQualifiedName(R, DC);
1753 
1754       if (!R.empty()) {
1755         // Don't give errors about ambiguities in this lookup.
1756         R.suppressDiagnostics();
1757 
1758         // During a default argument instantiation the CurContext points
1759         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1760         // function parameter list, hence add an explicit check.
1761         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1762                               ActiveTemplateInstantiations.back().Kind ==
1763             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1764         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1765         bool isInstance = CurMethod &&
1766                           CurMethod->isInstance() &&
1767                           DC == CurMethod->getParent() && !isDefaultArgument;
1768 
1769 
1770         // Give a code modification hint to insert 'this->'.
1771         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1772         // Actually quite difficult!
1773         if (getLangOpts().MSVCCompat)
1774           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1775         if (isInstance) {
1776           Diag(R.getNameLoc(), diagnostic) << Name
1777             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1778           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1779               CallsUndergoingInstantiation.back()->getCallee());
1780 
1781           CXXMethodDecl *DepMethod;
1782           if (CurMethod->isDependentContext())
1783             DepMethod = CurMethod;
1784           else if (CurMethod->getTemplatedKind() ==
1785               FunctionDecl::TK_FunctionTemplateSpecialization)
1786             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1787                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1788           else
1789             DepMethod = cast<CXXMethodDecl>(
1790                 CurMethod->getInstantiatedFromMemberFunction());
1791           assert(DepMethod && "No template pattern found");
1792 
1793           QualType DepThisType = DepMethod->getThisType(Context);
1794           CheckCXXThisCapture(R.getNameLoc());
1795           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1796                                      R.getNameLoc(), DepThisType, false);
1797           TemplateArgumentListInfo TList;
1798           if (ULE->hasExplicitTemplateArgs())
1799             ULE->copyTemplateArgumentsInto(TList);
1800 
1801           CXXScopeSpec SS;
1802           SS.Adopt(ULE->getQualifierLoc());
1803           CXXDependentScopeMemberExpr *DepExpr =
1804               CXXDependentScopeMemberExpr::Create(
1805                   Context, DepThis, DepThisType, true, SourceLocation(),
1806                   SS.getWithLocInContext(Context),
1807                   ULE->getTemplateKeywordLoc(), nullptr,
1808                   R.getLookupNameInfo(),
1809                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1810           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1811         } else {
1812           Diag(R.getNameLoc(), diagnostic) << Name;
1813         }
1814 
1815         // Do we really want to note all of these?
1816         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1817           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1818 
1819         // Return true if we are inside a default argument instantiation
1820         // and the found name refers to an instance member function, otherwise
1821         // the function calling DiagnoseEmptyLookup will try to create an
1822         // implicit member call and this is wrong for default argument.
1823         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1824           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1825           return true;
1826         }
1827 
1828         // Tell the callee to try to recover.
1829         return false;
1830       }
1831 
1832       R.clear();
1833     }
1834 
1835     // In Microsoft mode, if we are performing lookup from within a friend
1836     // function definition declared at class scope then we must set
1837     // DC to the lexical parent to be able to search into the parent
1838     // class.
1839     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1840         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1841         DC->getLexicalParent()->isRecord())
1842       DC = DC->getLexicalParent();
1843     else
1844       DC = DC->getParent();
1845   }
1846 
1847   // We didn't find anything, so try to correct for a typo.
1848   TypoCorrection Corrected;
1849   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1850                                     S, &SS, CCC, CTK_ErrorRecovery))) {
1851     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1852     bool DroppedSpecifier =
1853         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1854     R.setLookupName(Corrected.getCorrection());
1855 
1856     bool AcceptableWithRecovery = false;
1857     bool AcceptableWithoutRecovery = false;
1858     NamedDecl *ND = Corrected.getCorrectionDecl();
1859     if (ND) {
1860       if (Corrected.isOverloaded()) {
1861         OverloadCandidateSet OCS(R.getNameLoc(),
1862                                  OverloadCandidateSet::CSK_Normal);
1863         OverloadCandidateSet::iterator Best;
1864         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1865                                         CDEnd = Corrected.end();
1866              CD != CDEnd; ++CD) {
1867           if (FunctionTemplateDecl *FTD =
1868                    dyn_cast<FunctionTemplateDecl>(*CD))
1869             AddTemplateOverloadCandidate(
1870                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1871                 Args, OCS);
1872           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1873             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1874               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1875                                    Args, OCS);
1876         }
1877         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1878         case OR_Success:
1879           ND = Best->Function;
1880           Corrected.setCorrectionDecl(ND);
1881           break;
1882         default:
1883           // FIXME: Arbitrarily pick the first declaration for the note.
1884           Corrected.setCorrectionDecl(ND);
1885           break;
1886         }
1887       }
1888       R.addDecl(ND);
1889       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1890         CXXRecordDecl *Record = nullptr;
1891         if (Corrected.getCorrectionSpecifier()) {
1892           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1893           Record = Ty->getAsCXXRecordDecl();
1894         }
1895         if (!Record)
1896           Record = cast<CXXRecordDecl>(
1897               ND->getDeclContext()->getRedeclContext());
1898         R.setNamingClass(Record);
1899       }
1900 
1901       AcceptableWithRecovery =
1902           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1903       // FIXME: If we ended up with a typo for a type name or
1904       // Objective-C class name, we're in trouble because the parser
1905       // is in the wrong place to recover. Suggest the typo
1906       // correction, but don't make it a fix-it since we're not going
1907       // to recover well anyway.
1908       AcceptableWithoutRecovery =
1909           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1910     } else {
1911       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1912       // because we aren't able to recover.
1913       AcceptableWithoutRecovery = true;
1914     }
1915 
1916     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1917       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1918                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1919                             ? diag::note_implicit_param_decl
1920                             : diag::note_previous_decl;
1921       if (SS.isEmpty())
1922         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1923                      PDiag(NoteID), AcceptableWithRecovery);
1924       else
1925         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1926                                   << Name << computeDeclContext(SS, false)
1927                                   << DroppedSpecifier << SS.getRange(),
1928                      PDiag(NoteID), AcceptableWithRecovery);
1929 
1930       // Tell the callee whether to try to recover.
1931       return !AcceptableWithRecovery;
1932     }
1933   }
1934   R.clear();
1935 
1936   // Emit a special diagnostic for failed member lookups.
1937   // FIXME: computing the declaration context might fail here (?)
1938   if (!SS.isEmpty()) {
1939     Diag(R.getNameLoc(), diag::err_no_member)
1940       << Name << computeDeclContext(SS, false)
1941       << SS.getRange();
1942     return true;
1943   }
1944 
1945   // Give up, we can't recover.
1946   Diag(R.getNameLoc(), diagnostic) << Name;
1947   return true;
1948 }
1949 
1950 /// In Microsoft mode, if we are inside a template class whose parent class has
1951 /// dependent base classes, and we can't resolve an unqualified identifier, then
1952 /// assume the identifier is a member of a dependent base class.  We can only
1953 /// recover successfully in static methods, instance methods, and other contexts
1954 /// where 'this' is available.  This doesn't precisely match MSVC's
1955 /// instantiation model, but it's close enough.
1956 static Expr *
1957 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1958                                DeclarationNameInfo &NameInfo,
1959                                SourceLocation TemplateKWLoc,
1960                                const TemplateArgumentListInfo *TemplateArgs) {
1961   // Only try to recover from lookup into dependent bases in static methods or
1962   // contexts where 'this' is available.
1963   QualType ThisType = S.getCurrentThisType();
1964   const CXXRecordDecl *RD = nullptr;
1965   if (!ThisType.isNull())
1966     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1967   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1968     RD = MD->getParent();
1969   if (!RD || !RD->hasAnyDependentBases())
1970     return nullptr;
1971 
1972   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1973   // is available, suggest inserting 'this->' as a fixit.
1974   SourceLocation Loc = NameInfo.getLoc();
1975   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1976   DB << NameInfo.getName() << RD;
1977 
1978   if (!ThisType.isNull()) {
1979     DB << FixItHint::CreateInsertion(Loc, "this->");
1980     return CXXDependentScopeMemberExpr::Create(
1981         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
1982         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
1983         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
1984   }
1985 
1986   // Synthesize a fake NNS that points to the derived class.  This will
1987   // perform name lookup during template instantiation.
1988   CXXScopeSpec SS;
1989   auto *NNS =
1990       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
1991   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
1992   return DependentScopeDeclRefExpr::Create(
1993       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
1994       TemplateArgs);
1995 }
1996 
1997 ExprResult Sema::ActOnIdExpression(Scope *S,
1998                                    CXXScopeSpec &SS,
1999                                    SourceLocation TemplateKWLoc,
2000                                    UnqualifiedId &Id,
2001                                    bool HasTrailingLParen,
2002                                    bool IsAddressOfOperand,
2003                                    CorrectionCandidateCallback *CCC,
2004                                    bool IsInlineAsmIdentifier) {
2005   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2006          "cannot be direct & operand and have a trailing lparen");
2007   if (SS.isInvalid())
2008     return ExprError();
2009 
2010   TemplateArgumentListInfo TemplateArgsBuffer;
2011 
2012   // Decompose the UnqualifiedId into the following data.
2013   DeclarationNameInfo NameInfo;
2014   const TemplateArgumentListInfo *TemplateArgs;
2015   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2016 
2017   DeclarationName Name = NameInfo.getName();
2018   IdentifierInfo *II = Name.getAsIdentifierInfo();
2019   SourceLocation NameLoc = NameInfo.getLoc();
2020 
2021   // C++ [temp.dep.expr]p3:
2022   //   An id-expression is type-dependent if it contains:
2023   //     -- an identifier that was declared with a dependent type,
2024   //        (note: handled after lookup)
2025   //     -- a template-id that is dependent,
2026   //        (note: handled in BuildTemplateIdExpr)
2027   //     -- a conversion-function-id that specifies a dependent type,
2028   //     -- a nested-name-specifier that contains a class-name that
2029   //        names a dependent type.
2030   // Determine whether this is a member of an unknown specialization;
2031   // we need to handle these differently.
2032   bool DependentID = false;
2033   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2034       Name.getCXXNameType()->isDependentType()) {
2035     DependentID = true;
2036   } else if (SS.isSet()) {
2037     if (DeclContext *DC = computeDeclContext(SS, false)) {
2038       if (RequireCompleteDeclContext(SS, DC))
2039         return ExprError();
2040     } else {
2041       DependentID = true;
2042     }
2043   }
2044 
2045   if (DependentID)
2046     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2047                                       IsAddressOfOperand, TemplateArgs);
2048 
2049   // Perform the required lookup.
2050   LookupResult R(*this, NameInfo,
2051                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2052                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2053   if (TemplateArgs) {
2054     // Lookup the template name again to correctly establish the context in
2055     // which it was found. This is really unfortunate as we already did the
2056     // lookup to determine that it was a template name in the first place. If
2057     // this becomes a performance hit, we can work harder to preserve those
2058     // results until we get here but it's likely not worth it.
2059     bool MemberOfUnknownSpecialization;
2060     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2061                        MemberOfUnknownSpecialization);
2062 
2063     if (MemberOfUnknownSpecialization ||
2064         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2065       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2066                                         IsAddressOfOperand, TemplateArgs);
2067   } else {
2068     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2069     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2070 
2071     // If the result might be in a dependent base class, this is a dependent
2072     // id-expression.
2073     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2074       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2075                                         IsAddressOfOperand, TemplateArgs);
2076 
2077     // If this reference is in an Objective-C method, then we need to do
2078     // some special Objective-C lookup, too.
2079     if (IvarLookupFollowUp) {
2080       ExprResult E(LookupInObjCMethod(R, S, II, true));
2081       if (E.isInvalid())
2082         return ExprError();
2083 
2084       if (Expr *Ex = E.getAs<Expr>())
2085         return Ex;
2086     }
2087   }
2088 
2089   if (R.isAmbiguous())
2090     return ExprError();
2091 
2092   // This could be an implicitly declared function reference (legal in C90,
2093   // extension in C99, forbidden in C++).
2094   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2095     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2096     if (D) R.addDecl(D);
2097   }
2098 
2099   // Determine whether this name might be a candidate for
2100   // argument-dependent lookup.
2101   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2102 
2103   if (R.empty() && !ADL) {
2104     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2105       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2106                                                    TemplateKWLoc, TemplateArgs))
2107         return E;
2108     }
2109 
2110     // Don't diagnose an empty lookup for inline assembly.
2111     if (IsInlineAsmIdentifier)
2112       return ExprError();
2113 
2114     // If this name wasn't predeclared and if this is not a function
2115     // call, diagnose the problem.
2116     CorrectionCandidateCallback DefaultValidator;
2117     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2118     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2119            "Typo correction callback misconfigured");
2120     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2121       return ExprError();
2122 
2123     assert(!R.empty() &&
2124            "DiagnoseEmptyLookup returned false but added no results");
2125 
2126     // If we found an Objective-C instance variable, let
2127     // LookupInObjCMethod build the appropriate expression to
2128     // reference the ivar.
2129     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2130       R.clear();
2131       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2132       // In a hopelessly buggy code, Objective-C instance variable
2133       // lookup fails and no expression will be built to reference it.
2134       if (!E.isInvalid() && !E.get())
2135         return ExprError();
2136       return E;
2137     }
2138   }
2139 
2140   // This is guaranteed from this point on.
2141   assert(!R.empty() || ADL);
2142 
2143   // Check whether this might be a C++ implicit instance member access.
2144   // C++ [class.mfct.non-static]p3:
2145   //   When an id-expression that is not part of a class member access
2146   //   syntax and not used to form a pointer to member is used in the
2147   //   body of a non-static member function of class X, if name lookup
2148   //   resolves the name in the id-expression to a non-static non-type
2149   //   member of some class C, the id-expression is transformed into a
2150   //   class member access expression using (*this) as the
2151   //   postfix-expression to the left of the . operator.
2152   //
2153   // But we don't actually need to do this for '&' operands if R
2154   // resolved to a function or overloaded function set, because the
2155   // expression is ill-formed if it actually works out to be a
2156   // non-static member function:
2157   //
2158   // C++ [expr.ref]p4:
2159   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2160   //   [t]he expression can be used only as the left-hand operand of a
2161   //   member function call.
2162   //
2163   // There are other safeguards against such uses, but it's important
2164   // to get this right here so that we don't end up making a
2165   // spuriously dependent expression if we're inside a dependent
2166   // instance method.
2167   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2168     bool MightBeImplicitMember;
2169     if (!IsAddressOfOperand)
2170       MightBeImplicitMember = true;
2171     else if (!SS.isEmpty())
2172       MightBeImplicitMember = false;
2173     else if (R.isOverloadedResult())
2174       MightBeImplicitMember = false;
2175     else if (R.isUnresolvableResult())
2176       MightBeImplicitMember = true;
2177     else
2178       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2179                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2180                               isa<MSPropertyDecl>(R.getFoundDecl());
2181 
2182     if (MightBeImplicitMember)
2183       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2184                                              R, TemplateArgs);
2185   }
2186 
2187   if (TemplateArgs || TemplateKWLoc.isValid()) {
2188 
2189     // In C++1y, if this is a variable template id, then check it
2190     // in BuildTemplateIdExpr().
2191     // The single lookup result must be a variable template declaration.
2192     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2193         Id.TemplateId->Kind == TNK_Var_template) {
2194       assert(R.getAsSingle<VarTemplateDecl>() &&
2195              "There should only be one declaration found.");
2196     }
2197 
2198     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2199   }
2200 
2201   return BuildDeclarationNameExpr(SS, R, ADL);
2202 }
2203 
2204 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2205 /// declaration name, generally during template instantiation.
2206 /// There's a large number of things which don't need to be done along
2207 /// this path.
2208 ExprResult
2209 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2210                                         const DeclarationNameInfo &NameInfo,
2211                                         bool IsAddressOfOperand,
2212                                         TypeSourceInfo **RecoveryTSI) {
2213   DeclContext *DC = computeDeclContext(SS, false);
2214   if (!DC)
2215     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2216                                      NameInfo, /*TemplateArgs=*/nullptr);
2217 
2218   if (RequireCompleteDeclContext(SS, DC))
2219     return ExprError();
2220 
2221   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2222   LookupQualifiedName(R, DC);
2223 
2224   if (R.isAmbiguous())
2225     return ExprError();
2226 
2227   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2228     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2229                                      NameInfo, /*TemplateArgs=*/nullptr);
2230 
2231   if (R.empty()) {
2232     Diag(NameInfo.getLoc(), diag::err_no_member)
2233       << NameInfo.getName() << DC << SS.getRange();
2234     return ExprError();
2235   }
2236 
2237   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2238     // Diagnose a missing typename if this resolved unambiguously to a type in
2239     // a dependent context.  If we can recover with a type, downgrade this to
2240     // a warning in Microsoft compatibility mode.
2241     unsigned DiagID = diag::err_typename_missing;
2242     if (RecoveryTSI && getLangOpts().MSVCCompat)
2243       DiagID = diag::ext_typename_missing;
2244     SourceLocation Loc = SS.getBeginLoc();
2245     auto D = Diag(Loc, DiagID);
2246     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2247       << SourceRange(Loc, NameInfo.getEndLoc());
2248 
2249     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2250     // context.
2251     if (!RecoveryTSI)
2252       return ExprError();
2253 
2254     // Only issue the fixit if we're prepared to recover.
2255     D << FixItHint::CreateInsertion(Loc, "typename ");
2256 
2257     // Recover by pretending this was an elaborated type.
2258     QualType Ty = Context.getTypeDeclType(TD);
2259     TypeLocBuilder TLB;
2260     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2261 
2262     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2263     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2264     QTL.setElaboratedKeywordLoc(SourceLocation());
2265     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2266 
2267     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2268 
2269     return ExprEmpty();
2270   }
2271 
2272   // Defend against this resolving to an implicit member access. We usually
2273   // won't get here if this might be a legitimate a class member (we end up in
2274   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2275   // a pointer-to-member or in an unevaluated context in C++11.
2276   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2277     return BuildPossibleImplicitMemberExpr(SS,
2278                                            /*TemplateKWLoc=*/SourceLocation(),
2279                                            R, /*TemplateArgs=*/nullptr);
2280 
2281   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2282 }
2283 
2284 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2285 /// detected that we're currently inside an ObjC method.  Perform some
2286 /// additional lookup.
2287 ///
2288 /// Ideally, most of this would be done by lookup, but there's
2289 /// actually quite a lot of extra work involved.
2290 ///
2291 /// Returns a null sentinel to indicate trivial success.
2292 ExprResult
2293 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2294                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2295   SourceLocation Loc = Lookup.getNameLoc();
2296   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2297 
2298   // Check for error condition which is already reported.
2299   if (!CurMethod)
2300     return ExprError();
2301 
2302   // There are two cases to handle here.  1) scoped lookup could have failed,
2303   // in which case we should look for an ivar.  2) scoped lookup could have
2304   // found a decl, but that decl is outside the current instance method (i.e.
2305   // a global variable).  In these two cases, we do a lookup for an ivar with
2306   // this name, if the lookup sucedes, we replace it our current decl.
2307 
2308   // If we're in a class method, we don't normally want to look for
2309   // ivars.  But if we don't find anything else, and there's an
2310   // ivar, that's an error.
2311   bool IsClassMethod = CurMethod->isClassMethod();
2312 
2313   bool LookForIvars;
2314   if (Lookup.empty())
2315     LookForIvars = true;
2316   else if (IsClassMethod)
2317     LookForIvars = false;
2318   else
2319     LookForIvars = (Lookup.isSingleResult() &&
2320                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2321   ObjCInterfaceDecl *IFace = nullptr;
2322   if (LookForIvars) {
2323     IFace = CurMethod->getClassInterface();
2324     ObjCInterfaceDecl *ClassDeclared;
2325     ObjCIvarDecl *IV = nullptr;
2326     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2327       // Diagnose using an ivar in a class method.
2328       if (IsClassMethod)
2329         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2330                          << IV->getDeclName());
2331 
2332       // If we're referencing an invalid decl, just return this as a silent
2333       // error node.  The error diagnostic was already emitted on the decl.
2334       if (IV->isInvalidDecl())
2335         return ExprError();
2336 
2337       // Check if referencing a field with __attribute__((deprecated)).
2338       if (DiagnoseUseOfDecl(IV, Loc))
2339         return ExprError();
2340 
2341       // Diagnose the use of an ivar outside of the declaring class.
2342       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2343           !declaresSameEntity(ClassDeclared, IFace) &&
2344           !getLangOpts().DebuggerSupport)
2345         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2346 
2347       // FIXME: This should use a new expr for a direct reference, don't
2348       // turn this into Self->ivar, just return a BareIVarExpr or something.
2349       IdentifierInfo &II = Context.Idents.get("self");
2350       UnqualifiedId SelfName;
2351       SelfName.setIdentifier(&II, SourceLocation());
2352       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2353       CXXScopeSpec SelfScopeSpec;
2354       SourceLocation TemplateKWLoc;
2355       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2356                                               SelfName, false, false);
2357       if (SelfExpr.isInvalid())
2358         return ExprError();
2359 
2360       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2361       if (SelfExpr.isInvalid())
2362         return ExprError();
2363 
2364       MarkAnyDeclReferenced(Loc, IV, true);
2365 
2366       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2367       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2368           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2369         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2370 
2371       ObjCIvarRefExpr *Result = new (Context)
2372           ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
2373                           SelfExpr.get(), true, true);
2374 
2375       if (getLangOpts().ObjCAutoRefCount) {
2376         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2377           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2378             recordUseOfEvaluatedWeak(Result);
2379         }
2380         if (CurContext->isClosure())
2381           Diag(Loc, diag::warn_implicitly_retains_self)
2382             << FixItHint::CreateInsertion(Loc, "self->");
2383       }
2384 
2385       return Result;
2386     }
2387   } else if (CurMethod->isInstanceMethod()) {
2388     // We should warn if a local variable hides an ivar.
2389     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2390       ObjCInterfaceDecl *ClassDeclared;
2391       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2392         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2393             declaresSameEntity(IFace, ClassDeclared))
2394           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2395       }
2396     }
2397   } else if (Lookup.isSingleResult() &&
2398              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2399     // If accessing a stand-alone ivar in a class method, this is an error.
2400     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2401       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2402                        << IV->getDeclName());
2403   }
2404 
2405   if (Lookup.empty() && II && AllowBuiltinCreation) {
2406     // FIXME. Consolidate this with similar code in LookupName.
2407     if (unsigned BuiltinID = II->getBuiltinID()) {
2408       if (!(getLangOpts().CPlusPlus &&
2409             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2410         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2411                                            S, Lookup.isForRedeclaration(),
2412                                            Lookup.getNameLoc());
2413         if (D) Lookup.addDecl(D);
2414       }
2415     }
2416   }
2417   // Sentinel value saying that we didn't do anything special.
2418   return ExprResult((Expr *)nullptr);
2419 }
2420 
2421 /// \brief Cast a base object to a member's actual type.
2422 ///
2423 /// Logically this happens in three phases:
2424 ///
2425 /// * First we cast from the base type to the naming class.
2426 ///   The naming class is the class into which we were looking
2427 ///   when we found the member;  it's the qualifier type if a
2428 ///   qualifier was provided, and otherwise it's the base type.
2429 ///
2430 /// * Next we cast from the naming class to the declaring class.
2431 ///   If the member we found was brought into a class's scope by
2432 ///   a using declaration, this is that class;  otherwise it's
2433 ///   the class declaring the member.
2434 ///
2435 /// * Finally we cast from the declaring class to the "true"
2436 ///   declaring class of the member.  This conversion does not
2437 ///   obey access control.
2438 ExprResult
2439 Sema::PerformObjectMemberConversion(Expr *From,
2440                                     NestedNameSpecifier *Qualifier,
2441                                     NamedDecl *FoundDecl,
2442                                     NamedDecl *Member) {
2443   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2444   if (!RD)
2445     return From;
2446 
2447   QualType DestRecordType;
2448   QualType DestType;
2449   QualType FromRecordType;
2450   QualType FromType = From->getType();
2451   bool PointerConversions = false;
2452   if (isa<FieldDecl>(Member)) {
2453     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2454 
2455     if (FromType->getAs<PointerType>()) {
2456       DestType = Context.getPointerType(DestRecordType);
2457       FromRecordType = FromType->getPointeeType();
2458       PointerConversions = true;
2459     } else {
2460       DestType = DestRecordType;
2461       FromRecordType = FromType;
2462     }
2463   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2464     if (Method->isStatic())
2465       return From;
2466 
2467     DestType = Method->getThisType(Context);
2468     DestRecordType = DestType->getPointeeType();
2469 
2470     if (FromType->getAs<PointerType>()) {
2471       FromRecordType = FromType->getPointeeType();
2472       PointerConversions = true;
2473     } else {
2474       FromRecordType = FromType;
2475       DestType = DestRecordType;
2476     }
2477   } else {
2478     // No conversion necessary.
2479     return From;
2480   }
2481 
2482   if (DestType->isDependentType() || FromType->isDependentType())
2483     return From;
2484 
2485   // If the unqualified types are the same, no conversion is necessary.
2486   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2487     return From;
2488 
2489   SourceRange FromRange = From->getSourceRange();
2490   SourceLocation FromLoc = FromRange.getBegin();
2491 
2492   ExprValueKind VK = From->getValueKind();
2493 
2494   // C++ [class.member.lookup]p8:
2495   //   [...] Ambiguities can often be resolved by qualifying a name with its
2496   //   class name.
2497   //
2498   // If the member was a qualified name and the qualified referred to a
2499   // specific base subobject type, we'll cast to that intermediate type
2500   // first and then to the object in which the member is declared. That allows
2501   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2502   //
2503   //   class Base { public: int x; };
2504   //   class Derived1 : public Base { };
2505   //   class Derived2 : public Base { };
2506   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2507   //
2508   //   void VeryDerived::f() {
2509   //     x = 17; // error: ambiguous base subobjects
2510   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2511   //   }
2512   if (Qualifier && Qualifier->getAsType()) {
2513     QualType QType = QualType(Qualifier->getAsType(), 0);
2514     assert(QType->isRecordType() && "lookup done with non-record type");
2515 
2516     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2517 
2518     // In C++98, the qualifier type doesn't actually have to be a base
2519     // type of the object type, in which case we just ignore it.
2520     // Otherwise build the appropriate casts.
2521     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2522       CXXCastPath BasePath;
2523       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2524                                        FromLoc, FromRange, &BasePath))
2525         return ExprError();
2526 
2527       if (PointerConversions)
2528         QType = Context.getPointerType(QType);
2529       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2530                                VK, &BasePath).get();
2531 
2532       FromType = QType;
2533       FromRecordType = QRecordType;
2534 
2535       // If the qualifier type was the same as the destination type,
2536       // we're done.
2537       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2538         return From;
2539     }
2540   }
2541 
2542   bool IgnoreAccess = false;
2543 
2544   // If we actually found the member through a using declaration, cast
2545   // down to the using declaration's type.
2546   //
2547   // Pointer equality is fine here because only one declaration of a
2548   // class ever has member declarations.
2549   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2550     assert(isa<UsingShadowDecl>(FoundDecl));
2551     QualType URecordType = Context.getTypeDeclType(
2552                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2553 
2554     // We only need to do this if the naming-class to declaring-class
2555     // conversion is non-trivial.
2556     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2557       assert(IsDerivedFrom(FromRecordType, URecordType));
2558       CXXCastPath BasePath;
2559       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2560                                        FromLoc, FromRange, &BasePath))
2561         return ExprError();
2562 
2563       QualType UType = URecordType;
2564       if (PointerConversions)
2565         UType = Context.getPointerType(UType);
2566       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2567                                VK, &BasePath).get();
2568       FromType = UType;
2569       FromRecordType = URecordType;
2570     }
2571 
2572     // We don't do access control for the conversion from the
2573     // declaring class to the true declaring class.
2574     IgnoreAccess = true;
2575   }
2576 
2577   CXXCastPath BasePath;
2578   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2579                                    FromLoc, FromRange, &BasePath,
2580                                    IgnoreAccess))
2581     return ExprError();
2582 
2583   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2584                            VK, &BasePath);
2585 }
2586 
2587 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2588                                       const LookupResult &R,
2589                                       bool HasTrailingLParen) {
2590   // Only when used directly as the postfix-expression of a call.
2591   if (!HasTrailingLParen)
2592     return false;
2593 
2594   // Never if a scope specifier was provided.
2595   if (SS.isSet())
2596     return false;
2597 
2598   // Only in C++ or ObjC++.
2599   if (!getLangOpts().CPlusPlus)
2600     return false;
2601 
2602   // Turn off ADL when we find certain kinds of declarations during
2603   // normal lookup:
2604   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2605     NamedDecl *D = *I;
2606 
2607     // C++0x [basic.lookup.argdep]p3:
2608     //     -- a declaration of a class member
2609     // Since using decls preserve this property, we check this on the
2610     // original decl.
2611     if (D->isCXXClassMember())
2612       return false;
2613 
2614     // C++0x [basic.lookup.argdep]p3:
2615     //     -- a block-scope function declaration that is not a
2616     //        using-declaration
2617     // NOTE: we also trigger this for function templates (in fact, we
2618     // don't check the decl type at all, since all other decl types
2619     // turn off ADL anyway).
2620     if (isa<UsingShadowDecl>(D))
2621       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2622     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2623       return false;
2624 
2625     // C++0x [basic.lookup.argdep]p3:
2626     //     -- a declaration that is neither a function or a function
2627     //        template
2628     // And also for builtin functions.
2629     if (isa<FunctionDecl>(D)) {
2630       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2631 
2632       // But also builtin functions.
2633       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2634         return false;
2635     } else if (!isa<FunctionTemplateDecl>(D))
2636       return false;
2637   }
2638 
2639   return true;
2640 }
2641 
2642 
2643 /// Diagnoses obvious problems with the use of the given declaration
2644 /// as an expression.  This is only actually called for lookups that
2645 /// were not overloaded, and it doesn't promise that the declaration
2646 /// will in fact be used.
2647 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2648   if (isa<TypedefNameDecl>(D)) {
2649     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2650     return true;
2651   }
2652 
2653   if (isa<ObjCInterfaceDecl>(D)) {
2654     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2655     return true;
2656   }
2657 
2658   if (isa<NamespaceDecl>(D)) {
2659     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2660     return true;
2661   }
2662 
2663   return false;
2664 }
2665 
2666 ExprResult
2667 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2668                                LookupResult &R,
2669                                bool NeedsADL) {
2670   // If this is a single, fully-resolved result and we don't need ADL,
2671   // just build an ordinary singleton decl ref.
2672   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2673     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2674                                     R.getRepresentativeDecl());
2675 
2676   // We only need to check the declaration if there's exactly one
2677   // result, because in the overloaded case the results can only be
2678   // functions and function templates.
2679   if (R.isSingleResult() &&
2680       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2681     return ExprError();
2682 
2683   // Otherwise, just build an unresolved lookup expression.  Suppress
2684   // any lookup-related diagnostics; we'll hash these out later, when
2685   // we've picked a target.
2686   R.suppressDiagnostics();
2687 
2688   UnresolvedLookupExpr *ULE
2689     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2690                                    SS.getWithLocInContext(Context),
2691                                    R.getLookupNameInfo(),
2692                                    NeedsADL, R.isOverloadedResult(),
2693                                    R.begin(), R.end());
2694 
2695   return ULE;
2696 }
2697 
2698 /// \brief Complete semantic analysis for a reference to the given declaration.
2699 ExprResult Sema::BuildDeclarationNameExpr(
2700     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2701     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2702   assert(D && "Cannot refer to a NULL declaration");
2703   assert(!isa<FunctionTemplateDecl>(D) &&
2704          "Cannot refer unambiguously to a function template");
2705 
2706   SourceLocation Loc = NameInfo.getLoc();
2707   if (CheckDeclInExpr(*this, Loc, D))
2708     return ExprError();
2709 
2710   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2711     // Specifically diagnose references to class templates that are missing
2712     // a template argument list.
2713     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2714                                            << Template << SS.getRange();
2715     Diag(Template->getLocation(), diag::note_template_decl_here);
2716     return ExprError();
2717   }
2718 
2719   // Make sure that we're referring to a value.
2720   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2721   if (!VD) {
2722     Diag(Loc, diag::err_ref_non_value)
2723       << D << SS.getRange();
2724     Diag(D->getLocation(), diag::note_declared_at);
2725     return ExprError();
2726   }
2727 
2728   // Check whether this declaration can be used. Note that we suppress
2729   // this check when we're going to perform argument-dependent lookup
2730   // on this function name, because this might not be the function
2731   // that overload resolution actually selects.
2732   if (DiagnoseUseOfDecl(VD, Loc))
2733     return ExprError();
2734 
2735   // Only create DeclRefExpr's for valid Decl's.
2736   if (VD->isInvalidDecl())
2737     return ExprError();
2738 
2739   // Handle members of anonymous structs and unions.  If we got here,
2740   // and the reference is to a class member indirect field, then this
2741   // must be the subject of a pointer-to-member expression.
2742   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2743     if (!indirectField->isCXXClassMember())
2744       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2745                                                       indirectField);
2746 
2747   {
2748     QualType type = VD->getType();
2749     ExprValueKind valueKind = VK_RValue;
2750 
2751     switch (D->getKind()) {
2752     // Ignore all the non-ValueDecl kinds.
2753 #define ABSTRACT_DECL(kind)
2754 #define VALUE(type, base)
2755 #define DECL(type, base) \
2756     case Decl::type:
2757 #include "clang/AST/DeclNodes.inc"
2758       llvm_unreachable("invalid value decl kind");
2759 
2760     // These shouldn't make it here.
2761     case Decl::ObjCAtDefsField:
2762     case Decl::ObjCIvar:
2763       llvm_unreachable("forming non-member reference to ivar?");
2764 
2765     // Enum constants are always r-values and never references.
2766     // Unresolved using declarations are dependent.
2767     case Decl::EnumConstant:
2768     case Decl::UnresolvedUsingValue:
2769       valueKind = VK_RValue;
2770       break;
2771 
2772     // Fields and indirect fields that got here must be for
2773     // pointer-to-member expressions; we just call them l-values for
2774     // internal consistency, because this subexpression doesn't really
2775     // exist in the high-level semantics.
2776     case Decl::Field:
2777     case Decl::IndirectField:
2778       assert(getLangOpts().CPlusPlus &&
2779              "building reference to field in C?");
2780 
2781       // These can't have reference type in well-formed programs, but
2782       // for internal consistency we do this anyway.
2783       type = type.getNonReferenceType();
2784       valueKind = VK_LValue;
2785       break;
2786 
2787     // Non-type template parameters are either l-values or r-values
2788     // depending on the type.
2789     case Decl::NonTypeTemplateParm: {
2790       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2791         type = reftype->getPointeeType();
2792         valueKind = VK_LValue; // even if the parameter is an r-value reference
2793         break;
2794       }
2795 
2796       // For non-references, we need to strip qualifiers just in case
2797       // the template parameter was declared as 'const int' or whatever.
2798       valueKind = VK_RValue;
2799       type = type.getUnqualifiedType();
2800       break;
2801     }
2802 
2803     case Decl::Var:
2804     case Decl::VarTemplateSpecialization:
2805     case Decl::VarTemplatePartialSpecialization:
2806       // In C, "extern void blah;" is valid and is an r-value.
2807       if (!getLangOpts().CPlusPlus &&
2808           !type.hasQualifiers() &&
2809           type->isVoidType()) {
2810         valueKind = VK_RValue;
2811         break;
2812       }
2813       // fallthrough
2814 
2815     case Decl::ImplicitParam:
2816     case Decl::ParmVar: {
2817       // These are always l-values.
2818       valueKind = VK_LValue;
2819       type = type.getNonReferenceType();
2820 
2821       // FIXME: Does the addition of const really only apply in
2822       // potentially-evaluated contexts? Since the variable isn't actually
2823       // captured in an unevaluated context, it seems that the answer is no.
2824       if (!isUnevaluatedContext()) {
2825         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2826         if (!CapturedType.isNull())
2827           type = CapturedType;
2828       }
2829 
2830       break;
2831     }
2832 
2833     case Decl::Function: {
2834       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2835         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2836           type = Context.BuiltinFnTy;
2837           valueKind = VK_RValue;
2838           break;
2839         }
2840       }
2841 
2842       const FunctionType *fty = type->castAs<FunctionType>();
2843 
2844       // If we're referring to a function with an __unknown_anytype
2845       // result type, make the entire expression __unknown_anytype.
2846       if (fty->getReturnType() == Context.UnknownAnyTy) {
2847         type = Context.UnknownAnyTy;
2848         valueKind = VK_RValue;
2849         break;
2850       }
2851 
2852       // Functions are l-values in C++.
2853       if (getLangOpts().CPlusPlus) {
2854         valueKind = VK_LValue;
2855         break;
2856       }
2857 
2858       // C99 DR 316 says that, if a function type comes from a
2859       // function definition (without a prototype), that type is only
2860       // used for checking compatibility. Therefore, when referencing
2861       // the function, we pretend that we don't have the full function
2862       // type.
2863       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2864           isa<FunctionProtoType>(fty))
2865         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2866                                               fty->getExtInfo());
2867 
2868       // Functions are r-values in C.
2869       valueKind = VK_RValue;
2870       break;
2871     }
2872 
2873     case Decl::MSProperty:
2874       valueKind = VK_LValue;
2875       break;
2876 
2877     case Decl::CXXMethod:
2878       // If we're referring to a method with an __unknown_anytype
2879       // result type, make the entire expression __unknown_anytype.
2880       // This should only be possible with a type written directly.
2881       if (const FunctionProtoType *proto
2882             = dyn_cast<FunctionProtoType>(VD->getType()))
2883         if (proto->getReturnType() == Context.UnknownAnyTy) {
2884           type = Context.UnknownAnyTy;
2885           valueKind = VK_RValue;
2886           break;
2887         }
2888 
2889       // C++ methods are l-values if static, r-values if non-static.
2890       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2891         valueKind = VK_LValue;
2892         break;
2893       }
2894       // fallthrough
2895 
2896     case Decl::CXXConversion:
2897     case Decl::CXXDestructor:
2898     case Decl::CXXConstructor:
2899       valueKind = VK_RValue;
2900       break;
2901     }
2902 
2903     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2904                             TemplateArgs);
2905   }
2906 }
2907 
2908 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2909                                      PredefinedExpr::IdentType IT) {
2910   // Pick the current block, lambda, captured statement or function.
2911   Decl *currentDecl = nullptr;
2912   if (const BlockScopeInfo *BSI = getCurBlock())
2913     currentDecl = BSI->TheDecl;
2914   else if (const LambdaScopeInfo *LSI = getCurLambda())
2915     currentDecl = LSI->CallOperator;
2916   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2917     currentDecl = CSI->TheCapturedDecl;
2918   else
2919     currentDecl = getCurFunctionOrMethodDecl();
2920 
2921   if (!currentDecl) {
2922     Diag(Loc, diag::ext_predef_outside_function);
2923     currentDecl = Context.getTranslationUnitDecl();
2924   }
2925 
2926   QualType ResTy;
2927   if (cast<DeclContext>(currentDecl)->isDependentContext())
2928     ResTy = Context.DependentTy;
2929   else {
2930     // Pre-defined identifiers are of type char[x], where x is the length of
2931     // the string.
2932     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2933 
2934     llvm::APInt LengthI(32, Length + 1);
2935     if (IT == PredefinedExpr::LFunction)
2936       ResTy = Context.WideCharTy.withConst();
2937     else
2938       ResTy = Context.CharTy.withConst();
2939     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2940   }
2941 
2942   return new (Context) PredefinedExpr(Loc, ResTy, IT);
2943 }
2944 
2945 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2946   PredefinedExpr::IdentType IT;
2947 
2948   switch (Kind) {
2949   default: llvm_unreachable("Unknown simple primary expr!");
2950   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2951   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2952   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2953   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2954   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2955   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2956   }
2957 
2958   return BuildPredefinedExpr(Loc, IT);
2959 }
2960 
2961 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2962   SmallString<16> CharBuffer;
2963   bool Invalid = false;
2964   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2965   if (Invalid)
2966     return ExprError();
2967 
2968   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2969                             PP, Tok.getKind());
2970   if (Literal.hadError())
2971     return ExprError();
2972 
2973   QualType Ty;
2974   if (Literal.isWide())
2975     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2976   else if (Literal.isUTF16())
2977     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2978   else if (Literal.isUTF32())
2979     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2980   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2981     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2982   else
2983     Ty = Context.CharTy;  // 'x' -> char in C++
2984 
2985   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2986   if (Literal.isWide())
2987     Kind = CharacterLiteral::Wide;
2988   else if (Literal.isUTF16())
2989     Kind = CharacterLiteral::UTF16;
2990   else if (Literal.isUTF32())
2991     Kind = CharacterLiteral::UTF32;
2992 
2993   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2994                                              Tok.getLocation());
2995 
2996   if (Literal.getUDSuffix().empty())
2997     return Lit;
2998 
2999   // We're building a user-defined literal.
3000   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3001   SourceLocation UDSuffixLoc =
3002     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3003 
3004   // Make sure we're allowed user-defined literals here.
3005   if (!UDLScope)
3006     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3007 
3008   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3009   //   operator "" X (ch)
3010   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3011                                         Lit, Tok.getLocation());
3012 }
3013 
3014 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3015   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3016   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3017                                 Context.IntTy, Loc);
3018 }
3019 
3020 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3021                                   QualType Ty, SourceLocation Loc) {
3022   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3023 
3024   using llvm::APFloat;
3025   APFloat Val(Format);
3026 
3027   APFloat::opStatus result = Literal.GetFloatValue(Val);
3028 
3029   // Overflow is always an error, but underflow is only an error if
3030   // we underflowed to zero (APFloat reports denormals as underflow).
3031   if ((result & APFloat::opOverflow) ||
3032       ((result & APFloat::opUnderflow) && Val.isZero())) {
3033     unsigned diagnostic;
3034     SmallString<20> buffer;
3035     if (result & APFloat::opOverflow) {
3036       diagnostic = diag::warn_float_overflow;
3037       APFloat::getLargest(Format).toString(buffer);
3038     } else {
3039       diagnostic = diag::warn_float_underflow;
3040       APFloat::getSmallest(Format).toString(buffer);
3041     }
3042 
3043     S.Diag(Loc, diagnostic)
3044       << Ty
3045       << StringRef(buffer.data(), buffer.size());
3046   }
3047 
3048   bool isExact = (result == APFloat::opOK);
3049   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3050 }
3051 
3052 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3053   // Fast path for a single digit (which is quite common).  A single digit
3054   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3055   if (Tok.getLength() == 1) {
3056     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3057     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3058   }
3059 
3060   SmallString<128> SpellingBuffer;
3061   // NumericLiteralParser wants to overread by one character.  Add padding to
3062   // the buffer in case the token is copied to the buffer.  If getSpelling()
3063   // returns a StringRef to the memory buffer, it should have a null char at
3064   // the EOF, so it is also safe.
3065   SpellingBuffer.resize(Tok.getLength() + 1);
3066 
3067   // Get the spelling of the token, which eliminates trigraphs, etc.
3068   bool Invalid = false;
3069   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3070   if (Invalid)
3071     return ExprError();
3072 
3073   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3074   if (Literal.hadError)
3075     return ExprError();
3076 
3077   if (Literal.hasUDSuffix()) {
3078     // We're building a user-defined literal.
3079     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3080     SourceLocation UDSuffixLoc =
3081       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3082 
3083     // Make sure we're allowed user-defined literals here.
3084     if (!UDLScope)
3085       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3086 
3087     QualType CookedTy;
3088     if (Literal.isFloatingLiteral()) {
3089       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3090       // long double, the literal is treated as a call of the form
3091       //   operator "" X (f L)
3092       CookedTy = Context.LongDoubleTy;
3093     } else {
3094       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3095       // unsigned long long, the literal is treated as a call of the form
3096       //   operator "" X (n ULL)
3097       CookedTy = Context.UnsignedLongLongTy;
3098     }
3099 
3100     DeclarationName OpName =
3101       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3102     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3103     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3104 
3105     SourceLocation TokLoc = Tok.getLocation();
3106 
3107     // Perform literal operator lookup to determine if we're building a raw
3108     // literal or a cooked one.
3109     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3110     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3111                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3112                                   /*AllowStringTemplate*/false)) {
3113     case LOLR_Error:
3114       return ExprError();
3115 
3116     case LOLR_Cooked: {
3117       Expr *Lit;
3118       if (Literal.isFloatingLiteral()) {
3119         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3120       } else {
3121         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3122         if (Literal.GetIntegerValue(ResultVal))
3123           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3124               << /* Unsigned */ 1;
3125         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3126                                      Tok.getLocation());
3127       }
3128       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3129     }
3130 
3131     case LOLR_Raw: {
3132       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3133       // literal is treated as a call of the form
3134       //   operator "" X ("n")
3135       unsigned Length = Literal.getUDSuffixOffset();
3136       QualType StrTy = Context.getConstantArrayType(
3137           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3138           ArrayType::Normal, 0);
3139       Expr *Lit = StringLiteral::Create(
3140           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3141           /*Pascal*/false, StrTy, &TokLoc, 1);
3142       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3143     }
3144 
3145     case LOLR_Template: {
3146       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3147       // template), L is treated as a call fo the form
3148       //   operator "" X <'c1', 'c2', ... 'ck'>()
3149       // where n is the source character sequence c1 c2 ... ck.
3150       TemplateArgumentListInfo ExplicitArgs;
3151       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3152       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3153       llvm::APSInt Value(CharBits, CharIsUnsigned);
3154       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3155         Value = TokSpelling[I];
3156         TemplateArgument Arg(Context, Value, Context.CharTy);
3157         TemplateArgumentLocInfo ArgInfo;
3158         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3159       }
3160       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3161                                       &ExplicitArgs);
3162     }
3163     case LOLR_StringTemplate:
3164       llvm_unreachable("unexpected literal operator lookup result");
3165     }
3166   }
3167 
3168   Expr *Res;
3169 
3170   if (Literal.isFloatingLiteral()) {
3171     QualType Ty;
3172     if (Literal.isFloat)
3173       Ty = Context.FloatTy;
3174     else if (!Literal.isLong)
3175       Ty = Context.DoubleTy;
3176     else
3177       Ty = Context.LongDoubleTy;
3178 
3179     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3180 
3181     if (Ty == Context.DoubleTy) {
3182       if (getLangOpts().SinglePrecisionConstants) {
3183         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3184       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3185         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3186         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3187       }
3188     }
3189   } else if (!Literal.isIntegerLiteral()) {
3190     return ExprError();
3191   } else {
3192     QualType Ty;
3193 
3194     // 'long long' is a C99 or C++11 feature.
3195     if (!getLangOpts().C99 && Literal.isLongLong) {
3196       if (getLangOpts().CPlusPlus)
3197         Diag(Tok.getLocation(),
3198              getLangOpts().CPlusPlus11 ?
3199              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3200       else
3201         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3202     }
3203 
3204     // Get the value in the widest-possible width.
3205     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3206     // The microsoft literal suffix extensions support 128-bit literals, which
3207     // may be wider than [u]intmax_t.
3208     // FIXME: Actually, they don't. We seem to have accidentally invented the
3209     //        i128 suffix.
3210     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3211         Context.getTargetInfo().hasInt128Type())
3212       MaxWidth = 128;
3213     llvm::APInt ResultVal(MaxWidth, 0);
3214 
3215     if (Literal.GetIntegerValue(ResultVal)) {
3216       // If this value didn't fit into uintmax_t, error and force to ull.
3217       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3218           << /* Unsigned */ 1;
3219       Ty = Context.UnsignedLongLongTy;
3220       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3221              "long long is not intmax_t?");
3222     } else {
3223       // If this value fits into a ULL, try to figure out what else it fits into
3224       // according to the rules of C99 6.4.4.1p5.
3225 
3226       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3227       // be an unsigned int.
3228       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3229 
3230       // Check from smallest to largest, picking the smallest type we can.
3231       unsigned Width = 0;
3232 
3233       // Microsoft specific integer suffixes are explicitly sized.
3234       if (Literal.MicrosoftInteger) {
3235         if (Literal.MicrosoftInteger > MaxWidth) {
3236           // If this target doesn't support __int128, error and force to ull.
3237           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3238           Width = MaxWidth;
3239           Ty = Context.getIntMaxType();
3240         } else {
3241           Width = Literal.MicrosoftInteger;
3242           Ty = Context.getIntTypeForBitwidth(Width,
3243                                              /*Signed=*/!Literal.isUnsigned);
3244         }
3245       }
3246 
3247       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3248         // Are int/unsigned possibilities?
3249         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3250 
3251         // Does it fit in a unsigned int?
3252         if (ResultVal.isIntN(IntSize)) {
3253           // Does it fit in a signed int?
3254           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3255             Ty = Context.IntTy;
3256           else if (AllowUnsigned)
3257             Ty = Context.UnsignedIntTy;
3258           Width = IntSize;
3259         }
3260       }
3261 
3262       // Are long/unsigned long possibilities?
3263       if (Ty.isNull() && !Literal.isLongLong) {
3264         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3265 
3266         // Does it fit in a unsigned long?
3267         if (ResultVal.isIntN(LongSize)) {
3268           // Does it fit in a signed long?
3269           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3270             Ty = Context.LongTy;
3271           else if (AllowUnsigned)
3272             Ty = Context.UnsignedLongTy;
3273           Width = LongSize;
3274         }
3275       }
3276 
3277       // Check long long if needed.
3278       if (Ty.isNull()) {
3279         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3280 
3281         // Does it fit in a unsigned long long?
3282         if (ResultVal.isIntN(LongLongSize)) {
3283           // Does it fit in a signed long long?
3284           // To be compatible with MSVC, hex integer literals ending with the
3285           // LL or i64 suffix are always signed in Microsoft mode.
3286           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3287               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3288             Ty = Context.LongLongTy;
3289           else if (AllowUnsigned)
3290             Ty = Context.UnsignedLongLongTy;
3291           Width = LongLongSize;
3292         }
3293       }
3294 
3295       // If we still couldn't decide a type, we probably have something that
3296       // does not fit in a signed long long, but has no U suffix.
3297       if (Ty.isNull()) {
3298         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3299         Ty = Context.UnsignedLongLongTy;
3300         Width = Context.getTargetInfo().getLongLongWidth();
3301       }
3302 
3303       if (ResultVal.getBitWidth() != Width)
3304         ResultVal = ResultVal.trunc(Width);
3305     }
3306     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3307   }
3308 
3309   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3310   if (Literal.isImaginary)
3311     Res = new (Context) ImaginaryLiteral(Res,
3312                                         Context.getComplexType(Res->getType()));
3313 
3314   return Res;
3315 }
3316 
3317 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3318   assert(E && "ActOnParenExpr() missing expr");
3319   return new (Context) ParenExpr(L, R, E);
3320 }
3321 
3322 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3323                                          SourceLocation Loc,
3324                                          SourceRange ArgRange) {
3325   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3326   // scalar or vector data type argument..."
3327   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3328   // type (C99 6.2.5p18) or void.
3329   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3330     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3331       << T << ArgRange;
3332     return true;
3333   }
3334 
3335   assert((T->isVoidType() || !T->isIncompleteType()) &&
3336          "Scalar types should always be complete");
3337   return false;
3338 }
3339 
3340 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3341                                            SourceLocation Loc,
3342                                            SourceRange ArgRange,
3343                                            UnaryExprOrTypeTrait TraitKind) {
3344   // Invalid types must be hard errors for SFINAE in C++.
3345   if (S.LangOpts.CPlusPlus)
3346     return true;
3347 
3348   // C99 6.5.3.4p1:
3349   if (T->isFunctionType() &&
3350       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3351     // sizeof(function)/alignof(function) is allowed as an extension.
3352     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3353       << TraitKind << ArgRange;
3354     return false;
3355   }
3356 
3357   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3358   // this is an error (OpenCL v1.1 s6.3.k)
3359   if (T->isVoidType()) {
3360     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3361                                         : diag::ext_sizeof_alignof_void_type;
3362     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3363     return false;
3364   }
3365 
3366   return true;
3367 }
3368 
3369 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3370                                              SourceLocation Loc,
3371                                              SourceRange ArgRange,
3372                                              UnaryExprOrTypeTrait TraitKind) {
3373   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3374   // runtime doesn't allow it.
3375   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3376     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3377       << T << (TraitKind == UETT_SizeOf)
3378       << ArgRange;
3379     return true;
3380   }
3381 
3382   return false;
3383 }
3384 
3385 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3386 /// pointer type is equal to T) and emit a warning if it is.
3387 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3388                                      Expr *E) {
3389   // Don't warn if the operation changed the type.
3390   if (T != E->getType())
3391     return;
3392 
3393   // Now look for array decays.
3394   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3395   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3396     return;
3397 
3398   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3399                                              << ICE->getType()
3400                                              << ICE->getSubExpr()->getType();
3401 }
3402 
3403 /// \brief Check the constraints on expression operands to unary type expression
3404 /// and type traits.
3405 ///
3406 /// Completes any types necessary and validates the constraints on the operand
3407 /// expression. The logic mostly mirrors the type-based overload, but may modify
3408 /// the expression as it completes the type for that expression through template
3409 /// instantiation, etc.
3410 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3411                                             UnaryExprOrTypeTrait ExprKind) {
3412   QualType ExprTy = E->getType();
3413   assert(!ExprTy->isReferenceType());
3414 
3415   if (ExprKind == UETT_VecStep)
3416     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3417                                         E->getSourceRange());
3418 
3419   // Whitelist some types as extensions
3420   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3421                                       E->getSourceRange(), ExprKind))
3422     return false;
3423 
3424   // 'alignof' applied to an expression only requires the base element type of
3425   // the expression to be complete. 'sizeof' requires the expression's type to
3426   // be complete (and will attempt to complete it if it's an array of unknown
3427   // bound).
3428   if (ExprKind == UETT_AlignOf) {
3429     if (RequireCompleteType(E->getExprLoc(),
3430                             Context.getBaseElementType(E->getType()),
3431                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3432                             E->getSourceRange()))
3433       return true;
3434   } else {
3435     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3436                                 ExprKind, E->getSourceRange()))
3437       return true;
3438   }
3439 
3440   // Completing the expression's type may have changed it.
3441   ExprTy = E->getType();
3442   assert(!ExprTy->isReferenceType());
3443 
3444   if (ExprTy->isFunctionType()) {
3445     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3446       << ExprKind << E->getSourceRange();
3447     return true;
3448   }
3449 
3450   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3451                                        E->getSourceRange(), ExprKind))
3452     return true;
3453 
3454   if (ExprKind == UETT_SizeOf) {
3455     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3456       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3457         QualType OType = PVD->getOriginalType();
3458         QualType Type = PVD->getType();
3459         if (Type->isPointerType() && OType->isArrayType()) {
3460           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3461             << Type << OType;
3462           Diag(PVD->getLocation(), diag::note_declared_at);
3463         }
3464       }
3465     }
3466 
3467     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3468     // decays into a pointer and returns an unintended result. This is most
3469     // likely a typo for "sizeof(array) op x".
3470     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3471       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3472                                BO->getLHS());
3473       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3474                                BO->getRHS());
3475     }
3476   }
3477 
3478   return false;
3479 }
3480 
3481 /// \brief Check the constraints on operands to unary expression and type
3482 /// traits.
3483 ///
3484 /// This will complete any types necessary, and validate the various constraints
3485 /// on those operands.
3486 ///
3487 /// The UsualUnaryConversions() function is *not* called by this routine.
3488 /// C99 6.3.2.1p[2-4] all state:
3489 ///   Except when it is the operand of the sizeof operator ...
3490 ///
3491 /// C++ [expr.sizeof]p4
3492 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3493 ///   standard conversions are not applied to the operand of sizeof.
3494 ///
3495 /// This policy is followed for all of the unary trait expressions.
3496 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3497                                             SourceLocation OpLoc,
3498                                             SourceRange ExprRange,
3499                                             UnaryExprOrTypeTrait ExprKind) {
3500   if (ExprType->isDependentType())
3501     return false;
3502 
3503   // C++ [expr.sizeof]p2:
3504   //     When applied to a reference or a reference type, the result
3505   //     is the size of the referenced type.
3506   // C++11 [expr.alignof]p3:
3507   //     When alignof is applied to a reference type, the result
3508   //     shall be the alignment of the referenced type.
3509   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3510     ExprType = Ref->getPointeeType();
3511 
3512   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3513   //   When alignof or _Alignof is applied to an array type, the result
3514   //   is the alignment of the element type.
3515   if (ExprKind == UETT_AlignOf)
3516     ExprType = Context.getBaseElementType(ExprType);
3517 
3518   if (ExprKind == UETT_VecStep)
3519     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3520 
3521   // Whitelist some types as extensions
3522   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3523                                       ExprKind))
3524     return false;
3525 
3526   if (RequireCompleteType(OpLoc, ExprType,
3527                           diag::err_sizeof_alignof_incomplete_type,
3528                           ExprKind, ExprRange))
3529     return true;
3530 
3531   if (ExprType->isFunctionType()) {
3532     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3533       << ExprKind << ExprRange;
3534     return true;
3535   }
3536 
3537   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3538                                        ExprKind))
3539     return true;
3540 
3541   return false;
3542 }
3543 
3544 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3545   E = E->IgnoreParens();
3546 
3547   // Cannot know anything else if the expression is dependent.
3548   if (E->isTypeDependent())
3549     return false;
3550 
3551   if (E->getObjectKind() == OK_BitField) {
3552     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3553        << 1 << E->getSourceRange();
3554     return true;
3555   }
3556 
3557   ValueDecl *D = nullptr;
3558   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3559     D = DRE->getDecl();
3560   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3561     D = ME->getMemberDecl();
3562   }
3563 
3564   // If it's a field, require the containing struct to have a
3565   // complete definition so that we can compute the layout.
3566   //
3567   // This can happen in C++11 onwards, either by naming the member
3568   // in a way that is not transformed into a member access expression
3569   // (in an unevaluated operand, for instance), or by naming the member
3570   // in a trailing-return-type.
3571   //
3572   // For the record, since __alignof__ on expressions is a GCC
3573   // extension, GCC seems to permit this but always gives the
3574   // nonsensical answer 0.
3575   //
3576   // We don't really need the layout here --- we could instead just
3577   // directly check for all the appropriate alignment-lowing
3578   // attributes --- but that would require duplicating a lot of
3579   // logic that just isn't worth duplicating for such a marginal
3580   // use-case.
3581   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3582     // Fast path this check, since we at least know the record has a
3583     // definition if we can find a member of it.
3584     if (!FD->getParent()->isCompleteDefinition()) {
3585       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3586         << E->getSourceRange();
3587       return true;
3588     }
3589 
3590     // Otherwise, if it's a field, and the field doesn't have
3591     // reference type, then it must have a complete type (or be a
3592     // flexible array member, which we explicitly want to
3593     // white-list anyway), which makes the following checks trivial.
3594     if (!FD->getType()->isReferenceType())
3595       return false;
3596   }
3597 
3598   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3599 }
3600 
3601 bool Sema::CheckVecStepExpr(Expr *E) {
3602   E = E->IgnoreParens();
3603 
3604   // Cannot know anything else if the expression is dependent.
3605   if (E->isTypeDependent())
3606     return false;
3607 
3608   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3609 }
3610 
3611 /// \brief Build a sizeof or alignof expression given a type operand.
3612 ExprResult
3613 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3614                                      SourceLocation OpLoc,
3615                                      UnaryExprOrTypeTrait ExprKind,
3616                                      SourceRange R) {
3617   if (!TInfo)
3618     return ExprError();
3619 
3620   QualType T = TInfo->getType();
3621 
3622   if (!T->isDependentType() &&
3623       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3624     return ExprError();
3625 
3626   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3627   return new (Context) UnaryExprOrTypeTraitExpr(
3628       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3629 }
3630 
3631 /// \brief Build a sizeof or alignof expression given an expression
3632 /// operand.
3633 ExprResult
3634 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3635                                      UnaryExprOrTypeTrait ExprKind) {
3636   ExprResult PE = CheckPlaceholderExpr(E);
3637   if (PE.isInvalid())
3638     return ExprError();
3639 
3640   E = PE.get();
3641 
3642   // Verify that the operand is valid.
3643   bool isInvalid = false;
3644   if (E->isTypeDependent()) {
3645     // Delay type-checking for type-dependent expressions.
3646   } else if (ExprKind == UETT_AlignOf) {
3647     isInvalid = CheckAlignOfExpr(*this, E);
3648   } else if (ExprKind == UETT_VecStep) {
3649     isInvalid = CheckVecStepExpr(E);
3650   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3651     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3652     isInvalid = true;
3653   } else {
3654     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3655   }
3656 
3657   if (isInvalid)
3658     return ExprError();
3659 
3660   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3661     PE = TransformToPotentiallyEvaluated(E);
3662     if (PE.isInvalid()) return ExprError();
3663     E = PE.get();
3664   }
3665 
3666   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3667   return new (Context) UnaryExprOrTypeTraitExpr(
3668       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3669 }
3670 
3671 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3672 /// expr and the same for @c alignof and @c __alignof
3673 /// Note that the ArgRange is invalid if isType is false.
3674 ExprResult
3675 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3676                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3677                                     void *TyOrEx, const SourceRange &ArgRange) {
3678   // If error parsing type, ignore.
3679   if (!TyOrEx) return ExprError();
3680 
3681   if (IsType) {
3682     TypeSourceInfo *TInfo;
3683     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3684     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3685   }
3686 
3687   Expr *ArgEx = (Expr *)TyOrEx;
3688   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3689   return Result;
3690 }
3691 
3692 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3693                                      bool IsReal) {
3694   if (V.get()->isTypeDependent())
3695     return S.Context.DependentTy;
3696 
3697   // _Real and _Imag are only l-values for normal l-values.
3698   if (V.get()->getObjectKind() != OK_Ordinary) {
3699     V = S.DefaultLvalueConversion(V.get());
3700     if (V.isInvalid())
3701       return QualType();
3702   }
3703 
3704   // These operators return the element type of a complex type.
3705   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3706     return CT->getElementType();
3707 
3708   // Otherwise they pass through real integer and floating point types here.
3709   if (V.get()->getType()->isArithmeticType())
3710     return V.get()->getType();
3711 
3712   // Test for placeholders.
3713   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3714   if (PR.isInvalid()) return QualType();
3715   if (PR.get() != V.get()) {
3716     V = PR;
3717     return CheckRealImagOperand(S, V, Loc, IsReal);
3718   }
3719 
3720   // Reject anything else.
3721   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3722     << (IsReal ? "__real" : "__imag");
3723   return QualType();
3724 }
3725 
3726 
3727 
3728 ExprResult
3729 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3730                           tok::TokenKind Kind, Expr *Input) {
3731   UnaryOperatorKind Opc;
3732   switch (Kind) {
3733   default: llvm_unreachable("Unknown unary op!");
3734   case tok::plusplus:   Opc = UO_PostInc; break;
3735   case tok::minusminus: Opc = UO_PostDec; break;
3736   }
3737 
3738   // Since this might is a postfix expression, get rid of ParenListExprs.
3739   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3740   if (Result.isInvalid()) return ExprError();
3741   Input = Result.get();
3742 
3743   return BuildUnaryOp(S, OpLoc, Opc, Input);
3744 }
3745 
3746 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3747 ///
3748 /// \return true on error
3749 static bool checkArithmeticOnObjCPointer(Sema &S,
3750                                          SourceLocation opLoc,
3751                                          Expr *op) {
3752   assert(op->getType()->isObjCObjectPointerType());
3753   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3754       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3755     return false;
3756 
3757   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3758     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3759     << op->getSourceRange();
3760   return true;
3761 }
3762 
3763 ExprResult
3764 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3765                               Expr *idx, SourceLocation rbLoc) {
3766   // Since this might be a postfix expression, get rid of ParenListExprs.
3767   if (isa<ParenListExpr>(base)) {
3768     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3769     if (result.isInvalid()) return ExprError();
3770     base = result.get();
3771   }
3772 
3773   // Handle any non-overload placeholder types in the base and index
3774   // expressions.  We can't handle overloads here because the other
3775   // operand might be an overloadable type, in which case the overload
3776   // resolution for the operator overload should get the first crack
3777   // at the overload.
3778   if (base->getType()->isNonOverloadPlaceholderType()) {
3779     ExprResult result = CheckPlaceholderExpr(base);
3780     if (result.isInvalid()) return ExprError();
3781     base = result.get();
3782   }
3783   if (idx->getType()->isNonOverloadPlaceholderType()) {
3784     ExprResult result = CheckPlaceholderExpr(idx);
3785     if (result.isInvalid()) return ExprError();
3786     idx = result.get();
3787   }
3788 
3789   // Build an unanalyzed expression if either operand is type-dependent.
3790   if (getLangOpts().CPlusPlus &&
3791       (base->isTypeDependent() || idx->isTypeDependent())) {
3792     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3793                                             VK_LValue, OK_Ordinary, rbLoc);
3794   }
3795 
3796   // Use C++ overloaded-operator rules if either operand has record
3797   // type.  The spec says to do this if either type is *overloadable*,
3798   // but enum types can't declare subscript operators or conversion
3799   // operators, so there's nothing interesting for overload resolution
3800   // to do if there aren't any record types involved.
3801   //
3802   // ObjC pointers have their own subscripting logic that is not tied
3803   // to overload resolution and so should not take this path.
3804   if (getLangOpts().CPlusPlus &&
3805       (base->getType()->isRecordType() ||
3806        (!base->getType()->isObjCObjectPointerType() &&
3807         idx->getType()->isRecordType()))) {
3808     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3809   }
3810 
3811   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3812 }
3813 
3814 ExprResult
3815 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3816                                       Expr *Idx, SourceLocation RLoc) {
3817   Expr *LHSExp = Base;
3818   Expr *RHSExp = Idx;
3819 
3820   // Perform default conversions.
3821   if (!LHSExp->getType()->getAs<VectorType>()) {
3822     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3823     if (Result.isInvalid())
3824       return ExprError();
3825     LHSExp = Result.get();
3826   }
3827   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3828   if (Result.isInvalid())
3829     return ExprError();
3830   RHSExp = Result.get();
3831 
3832   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3833   ExprValueKind VK = VK_LValue;
3834   ExprObjectKind OK = OK_Ordinary;
3835 
3836   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3837   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3838   // in the subscript position. As a result, we need to derive the array base
3839   // and index from the expression types.
3840   Expr *BaseExpr, *IndexExpr;
3841   QualType ResultType;
3842   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3843     BaseExpr = LHSExp;
3844     IndexExpr = RHSExp;
3845     ResultType = Context.DependentTy;
3846   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3847     BaseExpr = LHSExp;
3848     IndexExpr = RHSExp;
3849     ResultType = PTy->getPointeeType();
3850   } else if (const ObjCObjectPointerType *PTy =
3851                LHSTy->getAs<ObjCObjectPointerType>()) {
3852     BaseExpr = LHSExp;
3853     IndexExpr = RHSExp;
3854 
3855     // Use custom logic if this should be the pseudo-object subscript
3856     // expression.
3857     if (!LangOpts.isSubscriptPointerArithmetic())
3858       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3859                                           nullptr);
3860 
3861     ResultType = PTy->getPointeeType();
3862   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3863      // Handle the uncommon case of "123[Ptr]".
3864     BaseExpr = RHSExp;
3865     IndexExpr = LHSExp;
3866     ResultType = PTy->getPointeeType();
3867   } else if (const ObjCObjectPointerType *PTy =
3868                RHSTy->getAs<ObjCObjectPointerType>()) {
3869      // Handle the uncommon case of "123[Ptr]".
3870     BaseExpr = RHSExp;
3871     IndexExpr = LHSExp;
3872     ResultType = PTy->getPointeeType();
3873     if (!LangOpts.isSubscriptPointerArithmetic()) {
3874       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3875         << ResultType << BaseExpr->getSourceRange();
3876       return ExprError();
3877     }
3878   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3879     BaseExpr = LHSExp;    // vectors: V[123]
3880     IndexExpr = RHSExp;
3881     VK = LHSExp->getValueKind();
3882     if (VK != VK_RValue)
3883       OK = OK_VectorComponent;
3884 
3885     // FIXME: need to deal with const...
3886     ResultType = VTy->getElementType();
3887   } else if (LHSTy->isArrayType()) {
3888     // If we see an array that wasn't promoted by
3889     // DefaultFunctionArrayLvalueConversion, it must be an array that
3890     // wasn't promoted because of the C90 rule that doesn't
3891     // allow promoting non-lvalue arrays.  Warn, then
3892     // force the promotion here.
3893     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3894         LHSExp->getSourceRange();
3895     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3896                                CK_ArrayToPointerDecay).get();
3897     LHSTy = LHSExp->getType();
3898 
3899     BaseExpr = LHSExp;
3900     IndexExpr = RHSExp;
3901     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3902   } else if (RHSTy->isArrayType()) {
3903     // Same as previous, except for 123[f().a] case
3904     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3905         RHSExp->getSourceRange();
3906     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3907                                CK_ArrayToPointerDecay).get();
3908     RHSTy = RHSExp->getType();
3909 
3910     BaseExpr = RHSExp;
3911     IndexExpr = LHSExp;
3912     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3913   } else {
3914     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3915        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3916   }
3917   // C99 6.5.2.1p1
3918   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3919     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3920                      << IndexExpr->getSourceRange());
3921 
3922   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3923        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3924          && !IndexExpr->isTypeDependent())
3925     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3926 
3927   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3928   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3929   // type. Note that Functions are not objects, and that (in C99 parlance)
3930   // incomplete types are not object types.
3931   if (ResultType->isFunctionType()) {
3932     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3933       << ResultType << BaseExpr->getSourceRange();
3934     return ExprError();
3935   }
3936 
3937   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3938     // GNU extension: subscripting on pointer to void
3939     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3940       << BaseExpr->getSourceRange();
3941 
3942     // C forbids expressions of unqualified void type from being l-values.
3943     // See IsCForbiddenLValueType.
3944     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3945   } else if (!ResultType->isDependentType() &&
3946       RequireCompleteType(LLoc, ResultType,
3947                           diag::err_subscript_incomplete_type, BaseExpr))
3948     return ExprError();
3949 
3950   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3951          !ResultType.isCForbiddenLValueType());
3952 
3953   return new (Context)
3954       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
3955 }
3956 
3957 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3958                                         FunctionDecl *FD,
3959                                         ParmVarDecl *Param) {
3960   if (Param->hasUnparsedDefaultArg()) {
3961     Diag(CallLoc,
3962          diag::err_use_of_default_argument_to_function_declared_later) <<
3963       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3964     Diag(UnparsedDefaultArgLocs[Param],
3965          diag::note_default_argument_declared_here);
3966     return ExprError();
3967   }
3968 
3969   if (Param->hasUninstantiatedDefaultArg()) {
3970     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3971 
3972     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3973                                                  Param);
3974 
3975     // Instantiate the expression.
3976     MultiLevelTemplateArgumentList MutiLevelArgList
3977       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
3978 
3979     InstantiatingTemplate Inst(*this, CallLoc, Param,
3980                                MutiLevelArgList.getInnermost());
3981     if (Inst.isInvalid())
3982       return ExprError();
3983 
3984     ExprResult Result;
3985     {
3986       // C++ [dcl.fct.default]p5:
3987       //   The names in the [default argument] expression are bound, and
3988       //   the semantic constraints are checked, at the point where the
3989       //   default argument expression appears.
3990       ContextRAII SavedContext(*this, FD);
3991       LocalInstantiationScope Local(*this);
3992       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3993     }
3994     if (Result.isInvalid())
3995       return ExprError();
3996 
3997     // Check the expression as an initializer for the parameter.
3998     InitializedEntity Entity
3999       = InitializedEntity::InitializeParameter(Context, Param);
4000     InitializationKind Kind
4001       = InitializationKind::CreateCopy(Param->getLocation(),
4002              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4003     Expr *ResultE = Result.getAs<Expr>();
4004 
4005     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4006     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4007     if (Result.isInvalid())
4008       return ExprError();
4009 
4010     Expr *Arg = Result.getAs<Expr>();
4011     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4012     // Build the default argument expression.
4013     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4014   }
4015 
4016   // If the default expression creates temporaries, we need to
4017   // push them to the current stack of expression temporaries so they'll
4018   // be properly destroyed.
4019   // FIXME: We should really be rebuilding the default argument with new
4020   // bound temporaries; see the comment in PR5810.
4021   // We don't need to do that with block decls, though, because
4022   // blocks in default argument expression can never capture anything.
4023   if (isa<ExprWithCleanups>(Param->getInit())) {
4024     // Set the "needs cleanups" bit regardless of whether there are
4025     // any explicit objects.
4026     ExprNeedsCleanups = true;
4027 
4028     // Append all the objects to the cleanup list.  Right now, this
4029     // should always be a no-op, because blocks in default argument
4030     // expressions should never be able to capture anything.
4031     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4032            "default argument expression has capturing blocks?");
4033   }
4034 
4035   // We already type-checked the argument, so we know it works.
4036   // Just mark all of the declarations in this potentially-evaluated expression
4037   // as being "referenced".
4038   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4039                                    /*SkipLocalVariables=*/true);
4040   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4041 }
4042 
4043 
4044 Sema::VariadicCallType
4045 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4046                           Expr *Fn) {
4047   if (Proto && Proto->isVariadic()) {
4048     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4049       return VariadicConstructor;
4050     else if (Fn && Fn->getType()->isBlockPointerType())
4051       return VariadicBlock;
4052     else if (FDecl) {
4053       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4054         if (Method->isInstance())
4055           return VariadicMethod;
4056     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4057       return VariadicMethod;
4058     return VariadicFunction;
4059   }
4060   return VariadicDoesNotApply;
4061 }
4062 
4063 namespace {
4064 class FunctionCallCCC : public FunctionCallFilterCCC {
4065 public:
4066   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4067                   unsigned NumArgs, MemberExpr *ME)
4068       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4069         FunctionName(FuncName) {}
4070 
4071   bool ValidateCandidate(const TypoCorrection &candidate) override {
4072     if (!candidate.getCorrectionSpecifier() ||
4073         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4074       return false;
4075     }
4076 
4077     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4078   }
4079 
4080 private:
4081   const IdentifierInfo *const FunctionName;
4082 };
4083 }
4084 
4085 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4086                                                FunctionDecl *FDecl,
4087                                                ArrayRef<Expr *> Args) {
4088   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4089   DeclarationName FuncName = FDecl->getDeclName();
4090   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4091   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4092 
4093   if (TypoCorrection Corrected = S.CorrectTypo(
4094           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4095           S.getScopeForContext(S.CurContext), nullptr, CCC,
4096           Sema::CTK_ErrorRecovery)) {
4097     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4098       if (Corrected.isOverloaded()) {
4099         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4100         OverloadCandidateSet::iterator Best;
4101         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4102                                            CDEnd = Corrected.end();
4103              CD != CDEnd; ++CD) {
4104           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4105             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4106                                    OCS);
4107         }
4108         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4109         case OR_Success:
4110           ND = Best->Function;
4111           Corrected.setCorrectionDecl(ND);
4112           break;
4113         default:
4114           break;
4115         }
4116       }
4117       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4118         return Corrected;
4119       }
4120     }
4121   }
4122   return TypoCorrection();
4123 }
4124 
4125 /// ConvertArgumentsForCall - Converts the arguments specified in
4126 /// Args/NumArgs to the parameter types of the function FDecl with
4127 /// function prototype Proto. Call is the call expression itself, and
4128 /// Fn is the function expression. For a C++ member function, this
4129 /// routine does not attempt to convert the object argument. Returns
4130 /// true if the call is ill-formed.
4131 bool
4132 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4133                               FunctionDecl *FDecl,
4134                               const FunctionProtoType *Proto,
4135                               ArrayRef<Expr *> Args,
4136                               SourceLocation RParenLoc,
4137                               bool IsExecConfig) {
4138   // Bail out early if calling a builtin with custom typechecking.
4139   // We don't need to do this in the
4140   if (FDecl)
4141     if (unsigned ID = FDecl->getBuiltinID())
4142       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4143         return false;
4144 
4145   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4146   // assignment, to the types of the corresponding parameter, ...
4147   unsigned NumParams = Proto->getNumParams();
4148   bool Invalid = false;
4149   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4150   unsigned FnKind = Fn->getType()->isBlockPointerType()
4151                        ? 1 /* block */
4152                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4153                                        : 0 /* function */);
4154 
4155   // If too few arguments are available (and we don't have default
4156   // arguments for the remaining parameters), don't make the call.
4157   if (Args.size() < NumParams) {
4158     if (Args.size() < MinArgs) {
4159       TypoCorrection TC;
4160       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4161         unsigned diag_id =
4162             MinArgs == NumParams && !Proto->isVariadic()
4163                 ? diag::err_typecheck_call_too_few_args_suggest
4164                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4165         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4166                                         << static_cast<unsigned>(Args.size())
4167                                         << TC.getCorrectionRange());
4168       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4169         Diag(RParenLoc,
4170              MinArgs == NumParams && !Proto->isVariadic()
4171                  ? diag::err_typecheck_call_too_few_args_one
4172                  : diag::err_typecheck_call_too_few_args_at_least_one)
4173             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4174       else
4175         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4176                             ? diag::err_typecheck_call_too_few_args
4177                             : diag::err_typecheck_call_too_few_args_at_least)
4178             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4179             << Fn->getSourceRange();
4180 
4181       // Emit the location of the prototype.
4182       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4183         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4184           << FDecl;
4185 
4186       return true;
4187     }
4188     Call->setNumArgs(Context, NumParams);
4189   }
4190 
4191   // If too many are passed and not variadic, error on the extras and drop
4192   // them.
4193   if (Args.size() > NumParams) {
4194     if (!Proto->isVariadic()) {
4195       TypoCorrection TC;
4196       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4197         unsigned diag_id =
4198             MinArgs == NumParams && !Proto->isVariadic()
4199                 ? diag::err_typecheck_call_too_many_args_suggest
4200                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4201         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4202                                         << static_cast<unsigned>(Args.size())
4203                                         << TC.getCorrectionRange());
4204       } else if (NumParams == 1 && FDecl &&
4205                  FDecl->getParamDecl(0)->getDeclName())
4206         Diag(Args[NumParams]->getLocStart(),
4207              MinArgs == NumParams
4208                  ? diag::err_typecheck_call_too_many_args_one
4209                  : diag::err_typecheck_call_too_many_args_at_most_one)
4210             << FnKind << FDecl->getParamDecl(0)
4211             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4212             << SourceRange(Args[NumParams]->getLocStart(),
4213                            Args.back()->getLocEnd());
4214       else
4215         Diag(Args[NumParams]->getLocStart(),
4216              MinArgs == NumParams
4217                  ? diag::err_typecheck_call_too_many_args
4218                  : diag::err_typecheck_call_too_many_args_at_most)
4219             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4220             << Fn->getSourceRange()
4221             << SourceRange(Args[NumParams]->getLocStart(),
4222                            Args.back()->getLocEnd());
4223 
4224       // Emit the location of the prototype.
4225       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4226         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4227           << FDecl;
4228 
4229       // This deletes the extra arguments.
4230       Call->setNumArgs(Context, NumParams);
4231       return true;
4232     }
4233   }
4234   SmallVector<Expr *, 8> AllArgs;
4235   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4236 
4237   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4238                                    Proto, 0, Args, AllArgs, CallType);
4239   if (Invalid)
4240     return true;
4241   unsigned TotalNumArgs = AllArgs.size();
4242   for (unsigned i = 0; i < TotalNumArgs; ++i)
4243     Call->setArg(i, AllArgs[i]);
4244 
4245   return false;
4246 }
4247 
4248 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4249                                   const FunctionProtoType *Proto,
4250                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4251                                   SmallVectorImpl<Expr *> &AllArgs,
4252                                   VariadicCallType CallType, bool AllowExplicit,
4253                                   bool IsListInitialization) {
4254   unsigned NumParams = Proto->getNumParams();
4255   bool Invalid = false;
4256   unsigned ArgIx = 0;
4257   // Continue to check argument types (even if we have too few/many args).
4258   for (unsigned i = FirstParam; i < NumParams; i++) {
4259     QualType ProtoArgType = Proto->getParamType(i);
4260 
4261     Expr *Arg;
4262     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4263     if (ArgIx < Args.size()) {
4264       Arg = Args[ArgIx++];
4265 
4266       if (RequireCompleteType(Arg->getLocStart(),
4267                               ProtoArgType,
4268                               diag::err_call_incomplete_argument, Arg))
4269         return true;
4270 
4271       // Strip the unbridged-cast placeholder expression off, if applicable.
4272       bool CFAudited = false;
4273       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4274           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4275           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4276         Arg = stripARCUnbridgedCast(Arg);
4277       else if (getLangOpts().ObjCAutoRefCount &&
4278                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4279                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4280         CFAudited = true;
4281 
4282       InitializedEntity Entity =
4283           Param ? InitializedEntity::InitializeParameter(Context, Param,
4284                                                          ProtoArgType)
4285                 : InitializedEntity::InitializeParameter(
4286                       Context, ProtoArgType, Proto->isParamConsumed(i));
4287 
4288       // Remember that parameter belongs to a CF audited API.
4289       if (CFAudited)
4290         Entity.setParameterCFAudited();
4291 
4292       ExprResult ArgE = PerformCopyInitialization(
4293           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4294       if (ArgE.isInvalid())
4295         return true;
4296 
4297       Arg = ArgE.getAs<Expr>();
4298     } else {
4299       assert(Param && "can't use default arguments without a known callee");
4300 
4301       ExprResult ArgExpr =
4302         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4303       if (ArgExpr.isInvalid())
4304         return true;
4305 
4306       Arg = ArgExpr.getAs<Expr>();
4307     }
4308 
4309     // Check for array bounds violations for each argument to the call. This
4310     // check only triggers warnings when the argument isn't a more complex Expr
4311     // with its own checking, such as a BinaryOperator.
4312     CheckArrayAccess(Arg);
4313 
4314     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4315     CheckStaticArrayArgument(CallLoc, Param, Arg);
4316 
4317     AllArgs.push_back(Arg);
4318   }
4319 
4320   // If this is a variadic call, handle args passed through "...".
4321   if (CallType != VariadicDoesNotApply) {
4322     // Assume that extern "C" functions with variadic arguments that
4323     // return __unknown_anytype aren't *really* variadic.
4324     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4325         FDecl->isExternC()) {
4326       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4327         QualType paramType; // ignored
4328         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4329         Invalid |= arg.isInvalid();
4330         AllArgs.push_back(arg.get());
4331       }
4332 
4333     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4334     } else {
4335       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4336         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4337                                                           FDecl);
4338         Invalid |= Arg.isInvalid();
4339         AllArgs.push_back(Arg.get());
4340       }
4341     }
4342 
4343     // Check for array bounds violations.
4344     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4345       CheckArrayAccess(Args[i]);
4346   }
4347   return Invalid;
4348 }
4349 
4350 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4351   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4352   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4353     TL = DTL.getOriginalLoc();
4354   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4355     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4356       << ATL.getLocalSourceRange();
4357 }
4358 
4359 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4360 /// array parameter, check that it is non-null, and that if it is formed by
4361 /// array-to-pointer decay, the underlying array is sufficiently large.
4362 ///
4363 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4364 /// array type derivation, then for each call to the function, the value of the
4365 /// corresponding actual argument shall provide access to the first element of
4366 /// an array with at least as many elements as specified by the size expression.
4367 void
4368 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4369                                ParmVarDecl *Param,
4370                                const Expr *ArgExpr) {
4371   // Static array parameters are not supported in C++.
4372   if (!Param || getLangOpts().CPlusPlus)
4373     return;
4374 
4375   QualType OrigTy = Param->getOriginalType();
4376 
4377   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4378   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4379     return;
4380 
4381   if (ArgExpr->isNullPointerConstant(Context,
4382                                      Expr::NPC_NeverValueDependent)) {
4383     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4384     DiagnoseCalleeStaticArrayParam(*this, Param);
4385     return;
4386   }
4387 
4388   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4389   if (!CAT)
4390     return;
4391 
4392   const ConstantArrayType *ArgCAT =
4393     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4394   if (!ArgCAT)
4395     return;
4396 
4397   if (ArgCAT->getSize().ult(CAT->getSize())) {
4398     Diag(CallLoc, diag::warn_static_array_too_small)
4399       << ArgExpr->getSourceRange()
4400       << (unsigned) ArgCAT->getSize().getZExtValue()
4401       << (unsigned) CAT->getSize().getZExtValue();
4402     DiagnoseCalleeStaticArrayParam(*this, Param);
4403   }
4404 }
4405 
4406 /// Given a function expression of unknown-any type, try to rebuild it
4407 /// to have a function type.
4408 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4409 
4410 /// Is the given type a placeholder that we need to lower out
4411 /// immediately during argument processing?
4412 static bool isPlaceholderToRemoveAsArg(QualType type) {
4413   // Placeholders are never sugared.
4414   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4415   if (!placeholder) return false;
4416 
4417   switch (placeholder->getKind()) {
4418   // Ignore all the non-placeholder types.
4419 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4420 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4421 #include "clang/AST/BuiltinTypes.def"
4422     return false;
4423 
4424   // We cannot lower out overload sets; they might validly be resolved
4425   // by the call machinery.
4426   case BuiltinType::Overload:
4427     return false;
4428 
4429   // Unbridged casts in ARC can be handled in some call positions and
4430   // should be left in place.
4431   case BuiltinType::ARCUnbridgedCast:
4432     return false;
4433 
4434   // Pseudo-objects should be converted as soon as possible.
4435   case BuiltinType::PseudoObject:
4436     return true;
4437 
4438   // The debugger mode could theoretically but currently does not try
4439   // to resolve unknown-typed arguments based on known parameter types.
4440   case BuiltinType::UnknownAny:
4441     return true;
4442 
4443   // These are always invalid as call arguments and should be reported.
4444   case BuiltinType::BoundMember:
4445   case BuiltinType::BuiltinFn:
4446     return true;
4447   }
4448   llvm_unreachable("bad builtin type kind");
4449 }
4450 
4451 /// Check an argument list for placeholders that we won't try to
4452 /// handle later.
4453 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4454   // Apply this processing to all the arguments at once instead of
4455   // dying at the first failure.
4456   bool hasInvalid = false;
4457   for (size_t i = 0, e = args.size(); i != e; i++) {
4458     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4459       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4460       if (result.isInvalid()) hasInvalid = true;
4461       else args[i] = result.get();
4462     }
4463   }
4464   return hasInvalid;
4465 }
4466 
4467 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4468 /// This provides the location of the left/right parens and a list of comma
4469 /// locations.
4470 ExprResult
4471 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4472                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4473                     Expr *ExecConfig, bool IsExecConfig) {
4474   // Since this might be a postfix expression, get rid of ParenListExprs.
4475   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4476   if (Result.isInvalid()) return ExprError();
4477   Fn = Result.get();
4478 
4479   if (checkArgsForPlaceholders(*this, ArgExprs))
4480     return ExprError();
4481 
4482   if (getLangOpts().CPlusPlus) {
4483     // If this is a pseudo-destructor expression, build the call immediately.
4484     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4485       if (!ArgExprs.empty()) {
4486         // Pseudo-destructor calls should not have any arguments.
4487         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4488           << FixItHint::CreateRemoval(
4489                                     SourceRange(ArgExprs[0]->getLocStart(),
4490                                                 ArgExprs.back()->getLocEnd()));
4491       }
4492 
4493       return new (Context)
4494           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4495     }
4496     if (Fn->getType() == Context.PseudoObjectTy) {
4497       ExprResult result = CheckPlaceholderExpr(Fn);
4498       if (result.isInvalid()) return ExprError();
4499       Fn = result.get();
4500     }
4501 
4502     // Determine whether this is a dependent call inside a C++ template,
4503     // in which case we won't do any semantic analysis now.
4504     // FIXME: Will need to cache the results of name lookup (including ADL) in
4505     // Fn.
4506     bool Dependent = false;
4507     if (Fn->isTypeDependent())
4508       Dependent = true;
4509     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4510       Dependent = true;
4511 
4512     if (Dependent) {
4513       if (ExecConfig) {
4514         return new (Context) CUDAKernelCallExpr(
4515             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4516             Context.DependentTy, VK_RValue, RParenLoc);
4517       } else {
4518         return new (Context) CallExpr(
4519             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4520       }
4521     }
4522 
4523     // Determine whether this is a call to an object (C++ [over.call.object]).
4524     if (Fn->getType()->isRecordType())
4525       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4526                                           RParenLoc);
4527 
4528     if (Fn->getType() == Context.UnknownAnyTy) {
4529       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4530       if (result.isInvalid()) return ExprError();
4531       Fn = result.get();
4532     }
4533 
4534     if (Fn->getType() == Context.BoundMemberTy) {
4535       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4536     }
4537   }
4538 
4539   // Check for overloaded calls.  This can happen even in C due to extensions.
4540   if (Fn->getType() == Context.OverloadTy) {
4541     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4542 
4543     // We aren't supposed to apply this logic for if there's an '&' involved.
4544     if (!find.HasFormOfMemberPointer) {
4545       OverloadExpr *ovl = find.Expression;
4546       if (isa<UnresolvedLookupExpr>(ovl)) {
4547         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4548         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4549                                        RParenLoc, ExecConfig);
4550       } else {
4551         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4552                                          RParenLoc);
4553       }
4554     }
4555   }
4556 
4557   // If we're directly calling a function, get the appropriate declaration.
4558   if (Fn->getType() == Context.UnknownAnyTy) {
4559     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4560     if (result.isInvalid()) return ExprError();
4561     Fn = result.get();
4562   }
4563 
4564   Expr *NakedFn = Fn->IgnoreParens();
4565 
4566   NamedDecl *NDecl = nullptr;
4567   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4568     if (UnOp->getOpcode() == UO_AddrOf)
4569       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4570 
4571   if (isa<DeclRefExpr>(NakedFn))
4572     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4573   else if (isa<MemberExpr>(NakedFn))
4574     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4575 
4576   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4577     if (FD->hasAttr<EnableIfAttr>()) {
4578       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4579         Diag(Fn->getLocStart(),
4580              isa<CXXMethodDecl>(FD) ?
4581                  diag::err_ovl_no_viable_member_function_in_call :
4582                  diag::err_ovl_no_viable_function_in_call)
4583           << FD << FD->getSourceRange();
4584         Diag(FD->getLocation(),
4585              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4586             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4587       }
4588     }
4589   }
4590 
4591   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4592                                ExecConfig, IsExecConfig);
4593 }
4594 
4595 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4596 ///
4597 /// __builtin_astype( value, dst type )
4598 ///
4599 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4600                                  SourceLocation BuiltinLoc,
4601                                  SourceLocation RParenLoc) {
4602   ExprValueKind VK = VK_RValue;
4603   ExprObjectKind OK = OK_Ordinary;
4604   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4605   QualType SrcTy = E->getType();
4606   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4607     return ExprError(Diag(BuiltinLoc,
4608                           diag::err_invalid_astype_of_different_size)
4609                      << DstTy
4610                      << SrcTy
4611                      << E->getSourceRange());
4612   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4613 }
4614 
4615 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4616 /// provided arguments.
4617 ///
4618 /// __builtin_convertvector( value, dst type )
4619 ///
4620 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4621                                         SourceLocation BuiltinLoc,
4622                                         SourceLocation RParenLoc) {
4623   TypeSourceInfo *TInfo;
4624   GetTypeFromParser(ParsedDestTy, &TInfo);
4625   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4626 }
4627 
4628 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4629 /// i.e. an expression not of \p OverloadTy.  The expression should
4630 /// unary-convert to an expression of function-pointer or
4631 /// block-pointer type.
4632 ///
4633 /// \param NDecl the declaration being called, if available
4634 ExprResult
4635 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4636                             SourceLocation LParenLoc,
4637                             ArrayRef<Expr *> Args,
4638                             SourceLocation RParenLoc,
4639                             Expr *Config, bool IsExecConfig) {
4640   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4641   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4642 
4643   // Promote the function operand.
4644   // We special-case function promotion here because we only allow promoting
4645   // builtin functions to function pointers in the callee of a call.
4646   ExprResult Result;
4647   if (BuiltinID &&
4648       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4649     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4650                                CK_BuiltinFnToFnPtr).get();
4651   } else {
4652     Result = CallExprUnaryConversions(Fn);
4653   }
4654   if (Result.isInvalid())
4655     return ExprError();
4656   Fn = Result.get();
4657 
4658   // Make the call expr early, before semantic checks.  This guarantees cleanup
4659   // of arguments and function on error.
4660   CallExpr *TheCall;
4661   if (Config)
4662     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4663                                                cast<CallExpr>(Config), Args,
4664                                                Context.BoolTy, VK_RValue,
4665                                                RParenLoc);
4666   else
4667     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4668                                      VK_RValue, RParenLoc);
4669 
4670   // Bail out early if calling a builtin with custom typechecking.
4671   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4672     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4673 
4674  retry:
4675   const FunctionType *FuncT;
4676   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4677     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4678     // have type pointer to function".
4679     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4680     if (!FuncT)
4681       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4682                          << Fn->getType() << Fn->getSourceRange());
4683   } else if (const BlockPointerType *BPT =
4684                Fn->getType()->getAs<BlockPointerType>()) {
4685     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4686   } else {
4687     // Handle calls to expressions of unknown-any type.
4688     if (Fn->getType() == Context.UnknownAnyTy) {
4689       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4690       if (rewrite.isInvalid()) return ExprError();
4691       Fn = rewrite.get();
4692       TheCall->setCallee(Fn);
4693       goto retry;
4694     }
4695 
4696     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4697       << Fn->getType() << Fn->getSourceRange());
4698   }
4699 
4700   if (getLangOpts().CUDA) {
4701     if (Config) {
4702       // CUDA: Kernel calls must be to global functions
4703       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4704         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4705             << FDecl->getName() << Fn->getSourceRange());
4706 
4707       // CUDA: Kernel function must have 'void' return type
4708       if (!FuncT->getReturnType()->isVoidType())
4709         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4710             << Fn->getType() << Fn->getSourceRange());
4711     } else {
4712       // CUDA: Calls to global functions must be configured
4713       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4714         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4715             << FDecl->getName() << Fn->getSourceRange());
4716     }
4717   }
4718 
4719   // Check for a valid return type
4720   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4721                           FDecl))
4722     return ExprError();
4723 
4724   // We know the result type of the call, set it.
4725   TheCall->setType(FuncT->getCallResultType(Context));
4726   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4727 
4728   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4729   if (Proto) {
4730     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4731                                 IsExecConfig))
4732       return ExprError();
4733   } else {
4734     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4735 
4736     if (FDecl) {
4737       // Check if we have too few/too many template arguments, based
4738       // on our knowledge of the function definition.
4739       const FunctionDecl *Def = nullptr;
4740       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4741         Proto = Def->getType()->getAs<FunctionProtoType>();
4742        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4743           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4744           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4745       }
4746 
4747       // If the function we're calling isn't a function prototype, but we have
4748       // a function prototype from a prior declaratiom, use that prototype.
4749       if (!FDecl->hasPrototype())
4750         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4751     }
4752 
4753     // Promote the arguments (C99 6.5.2.2p6).
4754     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4755       Expr *Arg = Args[i];
4756 
4757       if (Proto && i < Proto->getNumParams()) {
4758         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4759             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4760         ExprResult ArgE =
4761             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4762         if (ArgE.isInvalid())
4763           return true;
4764 
4765         Arg = ArgE.getAs<Expr>();
4766 
4767       } else {
4768         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4769 
4770         if (ArgE.isInvalid())
4771           return true;
4772 
4773         Arg = ArgE.getAs<Expr>();
4774       }
4775 
4776       if (RequireCompleteType(Arg->getLocStart(),
4777                               Arg->getType(),
4778                               diag::err_call_incomplete_argument, Arg))
4779         return ExprError();
4780 
4781       TheCall->setArg(i, Arg);
4782     }
4783   }
4784 
4785   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4786     if (!Method->isStatic())
4787       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4788         << Fn->getSourceRange());
4789 
4790   // Check for sentinels
4791   if (NDecl)
4792     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4793 
4794   // Do special checking on direct calls to functions.
4795   if (FDecl) {
4796     if (CheckFunctionCall(FDecl, TheCall, Proto))
4797       return ExprError();
4798 
4799     if (BuiltinID)
4800       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4801   } else if (NDecl) {
4802     if (CheckPointerCall(NDecl, TheCall, Proto))
4803       return ExprError();
4804   } else {
4805     if (CheckOtherCall(TheCall, Proto))
4806       return ExprError();
4807   }
4808 
4809   return MaybeBindToTemporary(TheCall);
4810 }
4811 
4812 ExprResult
4813 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4814                            SourceLocation RParenLoc, Expr *InitExpr) {
4815   assert(Ty && "ActOnCompoundLiteral(): missing type");
4816   // FIXME: put back this assert when initializers are worked out.
4817   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4818 
4819   TypeSourceInfo *TInfo;
4820   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4821   if (!TInfo)
4822     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4823 
4824   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4825 }
4826 
4827 ExprResult
4828 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4829                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4830   QualType literalType = TInfo->getType();
4831 
4832   if (literalType->isArrayType()) {
4833     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4834           diag::err_illegal_decl_array_incomplete_type,
4835           SourceRange(LParenLoc,
4836                       LiteralExpr->getSourceRange().getEnd())))
4837       return ExprError();
4838     if (literalType->isVariableArrayType())
4839       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4840         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4841   } else if (!literalType->isDependentType() &&
4842              RequireCompleteType(LParenLoc, literalType,
4843                diag::err_typecheck_decl_incomplete_type,
4844                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4845     return ExprError();
4846 
4847   InitializedEntity Entity
4848     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4849   InitializationKind Kind
4850     = InitializationKind::CreateCStyleCast(LParenLoc,
4851                                            SourceRange(LParenLoc, RParenLoc),
4852                                            /*InitList=*/true);
4853   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4854   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4855                                       &literalType);
4856   if (Result.isInvalid())
4857     return ExprError();
4858   LiteralExpr = Result.get();
4859 
4860   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4861   if (isFileScope &&
4862       !LiteralExpr->isTypeDependent() &&
4863       !LiteralExpr->isValueDependent() &&
4864       !literalType->isDependentType()) { // 6.5.2.5p3
4865     if (CheckForConstantInitializer(LiteralExpr, literalType))
4866       return ExprError();
4867   }
4868 
4869   // In C, compound literals are l-values for some reason.
4870   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4871 
4872   return MaybeBindToTemporary(
4873            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4874                                              VK, LiteralExpr, isFileScope));
4875 }
4876 
4877 ExprResult
4878 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4879                     SourceLocation RBraceLoc) {
4880   // Immediately handle non-overload placeholders.  Overloads can be
4881   // resolved contextually, but everything else here can't.
4882   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4883     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4884       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4885 
4886       // Ignore failures; dropping the entire initializer list because
4887       // of one failure would be terrible for indexing/etc.
4888       if (result.isInvalid()) continue;
4889 
4890       InitArgList[I] = result.get();
4891     }
4892   }
4893 
4894   // Semantic analysis for initializers is done by ActOnDeclarator() and
4895   // CheckInitializer() - it requires knowledge of the object being intialized.
4896 
4897   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4898                                                RBraceLoc);
4899   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4900   return E;
4901 }
4902 
4903 /// Do an explicit extend of the given block pointer if we're in ARC.
4904 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4905   assert(E.get()->getType()->isBlockPointerType());
4906   assert(E.get()->isRValue());
4907 
4908   // Only do this in an r-value context.
4909   if (!S.getLangOpts().ObjCAutoRefCount) return;
4910 
4911   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4912                                CK_ARCExtendBlockObject, E.get(),
4913                                /*base path*/ nullptr, VK_RValue);
4914   S.ExprNeedsCleanups = true;
4915 }
4916 
4917 /// Prepare a conversion of the given expression to an ObjC object
4918 /// pointer type.
4919 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4920   QualType type = E.get()->getType();
4921   if (type->isObjCObjectPointerType()) {
4922     return CK_BitCast;
4923   } else if (type->isBlockPointerType()) {
4924     maybeExtendBlockObject(*this, E);
4925     return CK_BlockPointerToObjCPointerCast;
4926   } else {
4927     assert(type->isPointerType());
4928     return CK_CPointerToObjCPointerCast;
4929   }
4930 }
4931 
4932 /// Prepares for a scalar cast, performing all the necessary stages
4933 /// except the final cast and returning the kind required.
4934 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4935   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4936   // Also, callers should have filtered out the invalid cases with
4937   // pointers.  Everything else should be possible.
4938 
4939   QualType SrcTy = Src.get()->getType();
4940   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4941     return CK_NoOp;
4942 
4943   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4944   case Type::STK_MemberPointer:
4945     llvm_unreachable("member pointer type in C");
4946 
4947   case Type::STK_CPointer:
4948   case Type::STK_BlockPointer:
4949   case Type::STK_ObjCObjectPointer:
4950     switch (DestTy->getScalarTypeKind()) {
4951     case Type::STK_CPointer: {
4952       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4953       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4954       if (SrcAS != DestAS)
4955         return CK_AddressSpaceConversion;
4956       return CK_BitCast;
4957     }
4958     case Type::STK_BlockPointer:
4959       return (SrcKind == Type::STK_BlockPointer
4960                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4961     case Type::STK_ObjCObjectPointer:
4962       if (SrcKind == Type::STK_ObjCObjectPointer)
4963         return CK_BitCast;
4964       if (SrcKind == Type::STK_CPointer)
4965         return CK_CPointerToObjCPointerCast;
4966       maybeExtendBlockObject(*this, Src);
4967       return CK_BlockPointerToObjCPointerCast;
4968     case Type::STK_Bool:
4969       return CK_PointerToBoolean;
4970     case Type::STK_Integral:
4971       return CK_PointerToIntegral;
4972     case Type::STK_Floating:
4973     case Type::STK_FloatingComplex:
4974     case Type::STK_IntegralComplex:
4975     case Type::STK_MemberPointer:
4976       llvm_unreachable("illegal cast from pointer");
4977     }
4978     llvm_unreachable("Should have returned before this");
4979 
4980   case Type::STK_Bool: // casting from bool is like casting from an integer
4981   case Type::STK_Integral:
4982     switch (DestTy->getScalarTypeKind()) {
4983     case Type::STK_CPointer:
4984     case Type::STK_ObjCObjectPointer:
4985     case Type::STK_BlockPointer:
4986       if (Src.get()->isNullPointerConstant(Context,
4987                                            Expr::NPC_ValueDependentIsNull))
4988         return CK_NullToPointer;
4989       return CK_IntegralToPointer;
4990     case Type::STK_Bool:
4991       return CK_IntegralToBoolean;
4992     case Type::STK_Integral:
4993       return CK_IntegralCast;
4994     case Type::STK_Floating:
4995       return CK_IntegralToFloating;
4996     case Type::STK_IntegralComplex:
4997       Src = ImpCastExprToType(Src.get(),
4998                               DestTy->castAs<ComplexType>()->getElementType(),
4999                               CK_IntegralCast);
5000       return CK_IntegralRealToComplex;
5001     case Type::STK_FloatingComplex:
5002       Src = ImpCastExprToType(Src.get(),
5003                               DestTy->castAs<ComplexType>()->getElementType(),
5004                               CK_IntegralToFloating);
5005       return CK_FloatingRealToComplex;
5006     case Type::STK_MemberPointer:
5007       llvm_unreachable("member pointer type in C");
5008     }
5009     llvm_unreachable("Should have returned before this");
5010 
5011   case Type::STK_Floating:
5012     switch (DestTy->getScalarTypeKind()) {
5013     case Type::STK_Floating:
5014       return CK_FloatingCast;
5015     case Type::STK_Bool:
5016       return CK_FloatingToBoolean;
5017     case Type::STK_Integral:
5018       return CK_FloatingToIntegral;
5019     case Type::STK_FloatingComplex:
5020       Src = ImpCastExprToType(Src.get(),
5021                               DestTy->castAs<ComplexType>()->getElementType(),
5022                               CK_FloatingCast);
5023       return CK_FloatingRealToComplex;
5024     case Type::STK_IntegralComplex:
5025       Src = ImpCastExprToType(Src.get(),
5026                               DestTy->castAs<ComplexType>()->getElementType(),
5027                               CK_FloatingToIntegral);
5028       return CK_IntegralRealToComplex;
5029     case Type::STK_CPointer:
5030     case Type::STK_ObjCObjectPointer:
5031     case Type::STK_BlockPointer:
5032       llvm_unreachable("valid float->pointer cast?");
5033     case Type::STK_MemberPointer:
5034       llvm_unreachable("member pointer type in C");
5035     }
5036     llvm_unreachable("Should have returned before this");
5037 
5038   case Type::STK_FloatingComplex:
5039     switch (DestTy->getScalarTypeKind()) {
5040     case Type::STK_FloatingComplex:
5041       return CK_FloatingComplexCast;
5042     case Type::STK_IntegralComplex:
5043       return CK_FloatingComplexToIntegralComplex;
5044     case Type::STK_Floating: {
5045       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5046       if (Context.hasSameType(ET, DestTy))
5047         return CK_FloatingComplexToReal;
5048       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5049       return CK_FloatingCast;
5050     }
5051     case Type::STK_Bool:
5052       return CK_FloatingComplexToBoolean;
5053     case Type::STK_Integral:
5054       Src = ImpCastExprToType(Src.get(),
5055                               SrcTy->castAs<ComplexType>()->getElementType(),
5056                               CK_FloatingComplexToReal);
5057       return CK_FloatingToIntegral;
5058     case Type::STK_CPointer:
5059     case Type::STK_ObjCObjectPointer:
5060     case Type::STK_BlockPointer:
5061       llvm_unreachable("valid complex float->pointer cast?");
5062     case Type::STK_MemberPointer:
5063       llvm_unreachable("member pointer type in C");
5064     }
5065     llvm_unreachable("Should have returned before this");
5066 
5067   case Type::STK_IntegralComplex:
5068     switch (DestTy->getScalarTypeKind()) {
5069     case Type::STK_FloatingComplex:
5070       return CK_IntegralComplexToFloatingComplex;
5071     case Type::STK_IntegralComplex:
5072       return CK_IntegralComplexCast;
5073     case Type::STK_Integral: {
5074       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5075       if (Context.hasSameType(ET, DestTy))
5076         return CK_IntegralComplexToReal;
5077       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5078       return CK_IntegralCast;
5079     }
5080     case Type::STK_Bool:
5081       return CK_IntegralComplexToBoolean;
5082     case Type::STK_Floating:
5083       Src = ImpCastExprToType(Src.get(),
5084                               SrcTy->castAs<ComplexType>()->getElementType(),
5085                               CK_IntegralComplexToReal);
5086       return CK_IntegralToFloating;
5087     case Type::STK_CPointer:
5088     case Type::STK_ObjCObjectPointer:
5089     case Type::STK_BlockPointer:
5090       llvm_unreachable("valid complex int->pointer cast?");
5091     case Type::STK_MemberPointer:
5092       llvm_unreachable("member pointer type in C");
5093     }
5094     llvm_unreachable("Should have returned before this");
5095   }
5096 
5097   llvm_unreachable("Unhandled scalar cast");
5098 }
5099 
5100 static bool breakDownVectorType(QualType type, uint64_t &len,
5101                                 QualType &eltType) {
5102   // Vectors are simple.
5103   if (const VectorType *vecType = type->getAs<VectorType>()) {
5104     len = vecType->getNumElements();
5105     eltType = vecType->getElementType();
5106     assert(eltType->isScalarType());
5107     return true;
5108   }
5109 
5110   // We allow lax conversion to and from non-vector types, but only if
5111   // they're real types (i.e. non-complex, non-pointer scalar types).
5112   if (!type->isRealType()) return false;
5113 
5114   len = 1;
5115   eltType = type;
5116   return true;
5117 }
5118 
5119 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5120   uint64_t srcLen, destLen;
5121   QualType srcElt, destElt;
5122   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5123   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5124 
5125   // ASTContext::getTypeSize will return the size rounded up to a
5126   // power of 2, so instead of using that, we need to use the raw
5127   // element size multiplied by the element count.
5128   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5129   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5130 
5131   return (srcLen * srcEltSize == destLen * destEltSize);
5132 }
5133 
5134 /// Is this a legal conversion between two known vector types?
5135 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5136   assert(destTy->isVectorType() || srcTy->isVectorType());
5137 
5138   if (!Context.getLangOpts().LaxVectorConversions)
5139     return false;
5140   return VectorTypesMatch(*this, srcTy, destTy);
5141 }
5142 
5143 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5144                            CastKind &Kind) {
5145   assert(VectorTy->isVectorType() && "Not a vector type!");
5146 
5147   if (Ty->isVectorType() || Ty->isIntegerType()) {
5148     if (!VectorTypesMatch(*this, Ty, VectorTy))
5149       return Diag(R.getBegin(),
5150                   Ty->isVectorType() ?
5151                   diag::err_invalid_conversion_between_vectors :
5152                   diag::err_invalid_conversion_between_vector_and_integer)
5153         << VectorTy << Ty << R;
5154   } else
5155     return Diag(R.getBegin(),
5156                 diag::err_invalid_conversion_between_vector_and_scalar)
5157       << VectorTy << Ty << R;
5158 
5159   Kind = CK_BitCast;
5160   return false;
5161 }
5162 
5163 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5164                                     Expr *CastExpr, CastKind &Kind) {
5165   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5166 
5167   QualType SrcTy = CastExpr->getType();
5168 
5169   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5170   // an ExtVectorType.
5171   // In OpenCL, casts between vectors of different types are not allowed.
5172   // (See OpenCL 6.2).
5173   if (SrcTy->isVectorType()) {
5174     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5175         || (getLangOpts().OpenCL &&
5176             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5177       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5178         << DestTy << SrcTy << R;
5179       return ExprError();
5180     }
5181     Kind = CK_BitCast;
5182     return CastExpr;
5183   }
5184 
5185   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5186   // conversion will take place first from scalar to elt type, and then
5187   // splat from elt type to vector.
5188   if (SrcTy->isPointerType())
5189     return Diag(R.getBegin(),
5190                 diag::err_invalid_conversion_between_vector_and_scalar)
5191       << DestTy << SrcTy << R;
5192 
5193   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5194   ExprResult CastExprRes = CastExpr;
5195   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5196   if (CastExprRes.isInvalid())
5197     return ExprError();
5198   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5199 
5200   Kind = CK_VectorSplat;
5201   return CastExpr;
5202 }
5203 
5204 ExprResult
5205 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5206                     Declarator &D, ParsedType &Ty,
5207                     SourceLocation RParenLoc, Expr *CastExpr) {
5208   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5209          "ActOnCastExpr(): missing type or expr");
5210 
5211   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5212   if (D.isInvalidType())
5213     return ExprError();
5214 
5215   if (getLangOpts().CPlusPlus) {
5216     // Check that there are no default arguments (C++ only).
5217     CheckExtraCXXDefaultArguments(D);
5218   }
5219 
5220   checkUnusedDeclAttributes(D);
5221 
5222   QualType castType = castTInfo->getType();
5223   Ty = CreateParsedType(castType, castTInfo);
5224 
5225   bool isVectorLiteral = false;
5226 
5227   // Check for an altivec or OpenCL literal,
5228   // i.e. all the elements are integer constants.
5229   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5230   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5231   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5232        && castType->isVectorType() && (PE || PLE)) {
5233     if (PLE && PLE->getNumExprs() == 0) {
5234       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5235       return ExprError();
5236     }
5237     if (PE || PLE->getNumExprs() == 1) {
5238       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5239       if (!E->getType()->isVectorType())
5240         isVectorLiteral = true;
5241     }
5242     else
5243       isVectorLiteral = true;
5244   }
5245 
5246   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5247   // then handle it as such.
5248   if (isVectorLiteral)
5249     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5250 
5251   // If the Expr being casted is a ParenListExpr, handle it specially.
5252   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5253   // sequence of BinOp comma operators.
5254   if (isa<ParenListExpr>(CastExpr)) {
5255     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5256     if (Result.isInvalid()) return ExprError();
5257     CastExpr = Result.get();
5258   }
5259 
5260   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5261       !getSourceManager().isInSystemMacro(LParenLoc))
5262     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5263 
5264   CheckTollFreeBridgeCast(castType, CastExpr);
5265 
5266   CheckObjCBridgeRelatedCast(castType, CastExpr);
5267 
5268   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5269 }
5270 
5271 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5272                                     SourceLocation RParenLoc, Expr *E,
5273                                     TypeSourceInfo *TInfo) {
5274   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5275          "Expected paren or paren list expression");
5276 
5277   Expr **exprs;
5278   unsigned numExprs;
5279   Expr *subExpr;
5280   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5281   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5282     LiteralLParenLoc = PE->getLParenLoc();
5283     LiteralRParenLoc = PE->getRParenLoc();
5284     exprs = PE->getExprs();
5285     numExprs = PE->getNumExprs();
5286   } else { // isa<ParenExpr> by assertion at function entrance
5287     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5288     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5289     subExpr = cast<ParenExpr>(E)->getSubExpr();
5290     exprs = &subExpr;
5291     numExprs = 1;
5292   }
5293 
5294   QualType Ty = TInfo->getType();
5295   assert(Ty->isVectorType() && "Expected vector type");
5296 
5297   SmallVector<Expr *, 8> initExprs;
5298   const VectorType *VTy = Ty->getAs<VectorType>();
5299   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5300 
5301   // '(...)' form of vector initialization in AltiVec: the number of
5302   // initializers must be one or must match the size of the vector.
5303   // If a single value is specified in the initializer then it will be
5304   // replicated to all the components of the vector
5305   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5306     // The number of initializers must be one or must match the size of the
5307     // vector. If a single value is specified in the initializer then it will
5308     // be replicated to all the components of the vector
5309     if (numExprs == 1) {
5310       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5311       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5312       if (Literal.isInvalid())
5313         return ExprError();
5314       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5315                                   PrepareScalarCast(Literal, ElemTy));
5316       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5317     }
5318     else if (numExprs < numElems) {
5319       Diag(E->getExprLoc(),
5320            diag::err_incorrect_number_of_vector_initializers);
5321       return ExprError();
5322     }
5323     else
5324       initExprs.append(exprs, exprs + numExprs);
5325   }
5326   else {
5327     // For OpenCL, when the number of initializers is a single value,
5328     // it will be replicated to all components of the vector.
5329     if (getLangOpts().OpenCL &&
5330         VTy->getVectorKind() == VectorType::GenericVector &&
5331         numExprs == 1) {
5332         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5333         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5334         if (Literal.isInvalid())
5335           return ExprError();
5336         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5337                                     PrepareScalarCast(Literal, ElemTy));
5338         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5339     }
5340 
5341     initExprs.append(exprs, exprs + numExprs);
5342   }
5343   // FIXME: This means that pretty-printing the final AST will produce curly
5344   // braces instead of the original commas.
5345   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5346                                                    initExprs, LiteralRParenLoc);
5347   initE->setType(Ty);
5348   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5349 }
5350 
5351 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5352 /// the ParenListExpr into a sequence of comma binary operators.
5353 ExprResult
5354 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5355   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5356   if (!E)
5357     return OrigExpr;
5358 
5359   ExprResult Result(E->getExpr(0));
5360 
5361   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5362     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5363                         E->getExpr(i));
5364 
5365   if (Result.isInvalid()) return ExprError();
5366 
5367   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5368 }
5369 
5370 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5371                                     SourceLocation R,
5372                                     MultiExprArg Val) {
5373   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5374   return expr;
5375 }
5376 
5377 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5378 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5379 /// emitted.
5380 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5381                                       SourceLocation QuestionLoc) {
5382   Expr *NullExpr = LHSExpr;
5383   Expr *NonPointerExpr = RHSExpr;
5384   Expr::NullPointerConstantKind NullKind =
5385       NullExpr->isNullPointerConstant(Context,
5386                                       Expr::NPC_ValueDependentIsNotNull);
5387 
5388   if (NullKind == Expr::NPCK_NotNull) {
5389     NullExpr = RHSExpr;
5390     NonPointerExpr = LHSExpr;
5391     NullKind =
5392         NullExpr->isNullPointerConstant(Context,
5393                                         Expr::NPC_ValueDependentIsNotNull);
5394   }
5395 
5396   if (NullKind == Expr::NPCK_NotNull)
5397     return false;
5398 
5399   if (NullKind == Expr::NPCK_ZeroExpression)
5400     return false;
5401 
5402   if (NullKind == Expr::NPCK_ZeroLiteral) {
5403     // In this case, check to make sure that we got here from a "NULL"
5404     // string in the source code.
5405     NullExpr = NullExpr->IgnoreParenImpCasts();
5406     SourceLocation loc = NullExpr->getExprLoc();
5407     if (!findMacroSpelling(loc, "NULL"))
5408       return false;
5409   }
5410 
5411   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5412   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5413       << NonPointerExpr->getType() << DiagType
5414       << NonPointerExpr->getSourceRange();
5415   return true;
5416 }
5417 
5418 /// \brief Return false if the condition expression is valid, true otherwise.
5419 static bool checkCondition(Sema &S, Expr *Cond) {
5420   QualType CondTy = Cond->getType();
5421 
5422   // C99 6.5.15p2
5423   if (CondTy->isScalarType()) return false;
5424 
5425   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5426   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5427     return false;
5428 
5429   // Emit the proper error message.
5430   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5431                               diag::err_typecheck_cond_expect_scalar :
5432                               diag::err_typecheck_cond_expect_scalar_or_vector)
5433     << CondTy;
5434   return true;
5435 }
5436 
5437 /// \brief Return false if the two expressions can be converted to a vector,
5438 /// true otherwise
5439 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5440                                                     ExprResult &RHS,
5441                                                     QualType CondTy) {
5442   // Both operands should be of scalar type.
5443   if (!LHS.get()->getType()->isScalarType()) {
5444     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5445       << CondTy;
5446     return true;
5447   }
5448   if (!RHS.get()->getType()->isScalarType()) {
5449     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5450       << CondTy;
5451     return true;
5452   }
5453 
5454   // Implicity convert these scalars to the type of the condition.
5455   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5456   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5457   return false;
5458 }
5459 
5460 /// \brief Handle when one or both operands are void type.
5461 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5462                                          ExprResult &RHS) {
5463     Expr *LHSExpr = LHS.get();
5464     Expr *RHSExpr = RHS.get();
5465 
5466     if (!LHSExpr->getType()->isVoidType())
5467       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5468         << RHSExpr->getSourceRange();
5469     if (!RHSExpr->getType()->isVoidType())
5470       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5471         << LHSExpr->getSourceRange();
5472     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5473     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5474     return S.Context.VoidTy;
5475 }
5476 
5477 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5478 /// true otherwise.
5479 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5480                                         QualType PointerTy) {
5481   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5482       !NullExpr.get()->isNullPointerConstant(S.Context,
5483                                             Expr::NPC_ValueDependentIsNull))
5484     return true;
5485 
5486   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5487   return false;
5488 }
5489 
5490 /// \brief Checks compatibility between two pointers and return the resulting
5491 /// type.
5492 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5493                                                      ExprResult &RHS,
5494                                                      SourceLocation Loc) {
5495   QualType LHSTy = LHS.get()->getType();
5496   QualType RHSTy = RHS.get()->getType();
5497 
5498   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5499     // Two identical pointers types are always compatible.
5500     return LHSTy;
5501   }
5502 
5503   QualType lhptee, rhptee;
5504 
5505   // Get the pointee types.
5506   bool IsBlockPointer = false;
5507   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5508     lhptee = LHSBTy->getPointeeType();
5509     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5510     IsBlockPointer = true;
5511   } else {
5512     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5513     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5514   }
5515 
5516   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5517   // differently qualified versions of compatible types, the result type is
5518   // a pointer to an appropriately qualified version of the composite
5519   // type.
5520 
5521   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5522   // clause doesn't make sense for our extensions. E.g. address space 2 should
5523   // be incompatible with address space 3: they may live on different devices or
5524   // anything.
5525   Qualifiers lhQual = lhptee.getQualifiers();
5526   Qualifiers rhQual = rhptee.getQualifiers();
5527 
5528   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5529   lhQual.removeCVRQualifiers();
5530   rhQual.removeCVRQualifiers();
5531 
5532   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5533   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5534 
5535   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5536 
5537   if (CompositeTy.isNull()) {
5538     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5539       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5540       << RHS.get()->getSourceRange();
5541     // In this situation, we assume void* type. No especially good
5542     // reason, but this is what gcc does, and we do have to pick
5543     // to get a consistent AST.
5544     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5545     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5546     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5547     return incompatTy;
5548   }
5549 
5550   // The pointer types are compatible.
5551   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5552   if (IsBlockPointer)
5553     ResultTy = S.Context.getBlockPointerType(ResultTy);
5554   else
5555     ResultTy = S.Context.getPointerType(ResultTy);
5556 
5557   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5558   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5559   return ResultTy;
5560 }
5561 
5562 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5563 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5564 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5565 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5566   if (QT->isObjCIdType())
5567     return true;
5568 
5569   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5570   if (!OPT)
5571     return false;
5572 
5573   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5574     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5575       return false;
5576 
5577   ObjCProtocolDecl* PNSCopying =
5578     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5579   ObjCProtocolDecl* PNSObject =
5580     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5581 
5582   for (auto *Proto : OPT->quals()) {
5583     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5584         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5585       ;
5586     else
5587       return false;
5588   }
5589   return true;
5590 }
5591 
5592 /// \brief Return the resulting type when the operands are both block pointers.
5593 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5594                                                           ExprResult &LHS,
5595                                                           ExprResult &RHS,
5596                                                           SourceLocation Loc) {
5597   QualType LHSTy = LHS.get()->getType();
5598   QualType RHSTy = RHS.get()->getType();
5599 
5600   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5601     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5602       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5603       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5604       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5605       return destType;
5606     }
5607     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5608       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5609       << RHS.get()->getSourceRange();
5610     return QualType();
5611   }
5612 
5613   // We have 2 block pointer types.
5614   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5615 }
5616 
5617 /// \brief Return the resulting type when the operands are both pointers.
5618 static QualType
5619 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5620                                             ExprResult &RHS,
5621                                             SourceLocation Loc) {
5622   // get the pointer types
5623   QualType LHSTy = LHS.get()->getType();
5624   QualType RHSTy = RHS.get()->getType();
5625 
5626   // get the "pointed to" types
5627   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5628   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5629 
5630   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5631   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5632     // Figure out necessary qualifiers (C99 6.5.15p6)
5633     QualType destPointee
5634       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5635     QualType destType = S.Context.getPointerType(destPointee);
5636     // Add qualifiers if necessary.
5637     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5638     // Promote to void*.
5639     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5640     return destType;
5641   }
5642   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5643     QualType destPointee
5644       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5645     QualType destType = S.Context.getPointerType(destPointee);
5646     // Add qualifiers if necessary.
5647     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5648     // Promote to void*.
5649     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5650     return destType;
5651   }
5652 
5653   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5654 }
5655 
5656 /// \brief Return false if the first expression is not an integer and the second
5657 /// expression is not a pointer, true otherwise.
5658 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5659                                         Expr* PointerExpr, SourceLocation Loc,
5660                                         bool IsIntFirstExpr) {
5661   if (!PointerExpr->getType()->isPointerType() ||
5662       !Int.get()->getType()->isIntegerType())
5663     return false;
5664 
5665   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5666   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5667 
5668   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
5669     << Expr1->getType() << Expr2->getType()
5670     << Expr1->getSourceRange() << Expr2->getSourceRange();
5671   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5672                             CK_IntegralToPointer);
5673   return true;
5674 }
5675 
5676 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5677 /// In that case, LHS = cond.
5678 /// C99 6.5.15
5679 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5680                                         ExprResult &RHS, ExprValueKind &VK,
5681                                         ExprObjectKind &OK,
5682                                         SourceLocation QuestionLoc) {
5683 
5684   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5685   if (!LHSResult.isUsable()) return QualType();
5686   LHS = LHSResult;
5687 
5688   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5689   if (!RHSResult.isUsable()) return QualType();
5690   RHS = RHSResult;
5691 
5692   // C++ is sufficiently different to merit its own checker.
5693   if (getLangOpts().CPlusPlus)
5694     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5695 
5696   VK = VK_RValue;
5697   OK = OK_Ordinary;
5698 
5699   // First, check the condition.
5700   Cond = UsualUnaryConversions(Cond.get());
5701   if (Cond.isInvalid())
5702     return QualType();
5703   if (checkCondition(*this, Cond.get()))
5704     return QualType();
5705 
5706   // Now check the two expressions.
5707   if (LHS.get()->getType()->isVectorType() ||
5708       RHS.get()->getType()->isVectorType())
5709     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5710 
5711   UsualArithmeticConversions(LHS, RHS);
5712   if (LHS.isInvalid() || RHS.isInvalid())
5713     return QualType();
5714 
5715   QualType CondTy = Cond.get()->getType();
5716   QualType LHSTy = LHS.get()->getType();
5717   QualType RHSTy = RHS.get()->getType();
5718 
5719   // If the condition is a vector, and both operands are scalar,
5720   // attempt to implicity convert them to the vector type to act like the
5721   // built in select. (OpenCL v1.1 s6.3.i)
5722   if (getLangOpts().OpenCL && CondTy->isVectorType())
5723     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5724       return QualType();
5725 
5726   // If both operands have arithmetic type, do the usual arithmetic conversions
5727   // to find a common type: C99 6.5.15p3,5.
5728   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5729     return LHS.get()->getType();
5730 
5731   // If both operands are the same structure or union type, the result is that
5732   // type.
5733   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5734     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5735       if (LHSRT->getDecl() == RHSRT->getDecl())
5736         // "If both the operands have structure or union type, the result has
5737         // that type."  This implies that CV qualifiers are dropped.
5738         return LHSTy.getUnqualifiedType();
5739     // FIXME: Type of conditional expression must be complete in C mode.
5740   }
5741 
5742   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5743   // The following || allows only one side to be void (a GCC-ism).
5744   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5745     return checkConditionalVoidType(*this, LHS, RHS);
5746   }
5747 
5748   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5749   // the type of the other operand."
5750   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5751   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5752 
5753   // All objective-c pointer type analysis is done here.
5754   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5755                                                         QuestionLoc);
5756   if (LHS.isInvalid() || RHS.isInvalid())
5757     return QualType();
5758   if (!compositeType.isNull())
5759     return compositeType;
5760 
5761 
5762   // Handle block pointer types.
5763   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5764     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5765                                                      QuestionLoc);
5766 
5767   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5768   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5769     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5770                                                        QuestionLoc);
5771 
5772   // GCC compatibility: soften pointer/integer mismatch.  Note that
5773   // null pointers have been filtered out by this point.
5774   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5775       /*isIntFirstExpr=*/true))
5776     return RHSTy;
5777   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5778       /*isIntFirstExpr=*/false))
5779     return LHSTy;
5780 
5781   // Emit a better diagnostic if one of the expressions is a null pointer
5782   // constant and the other is not a pointer type. In this case, the user most
5783   // likely forgot to take the address of the other expression.
5784   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5785     return QualType();
5786 
5787   // Otherwise, the operands are not compatible.
5788   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5789     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5790     << RHS.get()->getSourceRange();
5791   return QualType();
5792 }
5793 
5794 /// FindCompositeObjCPointerType - Helper method to find composite type of
5795 /// two objective-c pointer types of the two input expressions.
5796 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5797                                             SourceLocation QuestionLoc) {
5798   QualType LHSTy = LHS.get()->getType();
5799   QualType RHSTy = RHS.get()->getType();
5800 
5801   // Handle things like Class and struct objc_class*.  Here we case the result
5802   // to the pseudo-builtin, because that will be implicitly cast back to the
5803   // redefinition type if an attempt is made to access its fields.
5804   if (LHSTy->isObjCClassType() &&
5805       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5806     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5807     return LHSTy;
5808   }
5809   if (RHSTy->isObjCClassType() &&
5810       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5811     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5812     return RHSTy;
5813   }
5814   // And the same for struct objc_object* / id
5815   if (LHSTy->isObjCIdType() &&
5816       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5817     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5818     return LHSTy;
5819   }
5820   if (RHSTy->isObjCIdType() &&
5821       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5822     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5823     return RHSTy;
5824   }
5825   // And the same for struct objc_selector* / SEL
5826   if (Context.isObjCSelType(LHSTy) &&
5827       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5828     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5829     return LHSTy;
5830   }
5831   if (Context.isObjCSelType(RHSTy) &&
5832       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5833     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5834     return RHSTy;
5835   }
5836   // Check constraints for Objective-C object pointers types.
5837   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5838 
5839     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5840       // Two identical object pointer types are always compatible.
5841       return LHSTy;
5842     }
5843     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5844     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5845     QualType compositeType = LHSTy;
5846 
5847     // If both operands are interfaces and either operand can be
5848     // assigned to the other, use that type as the composite
5849     // type. This allows
5850     //   xxx ? (A*) a : (B*) b
5851     // where B is a subclass of A.
5852     //
5853     // Additionally, as for assignment, if either type is 'id'
5854     // allow silent coercion. Finally, if the types are
5855     // incompatible then make sure to use 'id' as the composite
5856     // type so the result is acceptable for sending messages to.
5857 
5858     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5859     // It could return the composite type.
5860     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5861       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5862     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5863       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5864     } else if ((LHSTy->isObjCQualifiedIdType() ||
5865                 RHSTy->isObjCQualifiedIdType()) &&
5866                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5867       // Need to handle "id<xx>" explicitly.
5868       // GCC allows qualified id and any Objective-C type to devolve to
5869       // id. Currently localizing to here until clear this should be
5870       // part of ObjCQualifiedIdTypesAreCompatible.
5871       compositeType = Context.getObjCIdType();
5872     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5873       compositeType = Context.getObjCIdType();
5874     } else if (!(compositeType =
5875                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5876       ;
5877     else {
5878       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5879       << LHSTy << RHSTy
5880       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5881       QualType incompatTy = Context.getObjCIdType();
5882       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5883       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5884       return incompatTy;
5885     }
5886     // The object pointer types are compatible.
5887     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5888     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5889     return compositeType;
5890   }
5891   // Check Objective-C object pointer types and 'void *'
5892   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5893     if (getLangOpts().ObjCAutoRefCount) {
5894       // ARC forbids the implicit conversion of object pointers to 'void *',
5895       // so these types are not compatible.
5896       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5897           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5898       LHS = RHS = true;
5899       return QualType();
5900     }
5901     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5902     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5903     QualType destPointee
5904     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5905     QualType destType = Context.getPointerType(destPointee);
5906     // Add qualifiers if necessary.
5907     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5908     // Promote to void*.
5909     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5910     return destType;
5911   }
5912   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5913     if (getLangOpts().ObjCAutoRefCount) {
5914       // ARC forbids the implicit conversion of object pointers to 'void *',
5915       // so these types are not compatible.
5916       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5917           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5918       LHS = RHS = true;
5919       return QualType();
5920     }
5921     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5922     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5923     QualType destPointee
5924     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5925     QualType destType = Context.getPointerType(destPointee);
5926     // Add qualifiers if necessary.
5927     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5928     // Promote to void*.
5929     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5930     return destType;
5931   }
5932   return QualType();
5933 }
5934 
5935 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5936 /// ParenRange in parentheses.
5937 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5938                                const PartialDiagnostic &Note,
5939                                SourceRange ParenRange) {
5940   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5941   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5942       EndLoc.isValid()) {
5943     Self.Diag(Loc, Note)
5944       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5945       << FixItHint::CreateInsertion(EndLoc, ")");
5946   } else {
5947     // We can't display the parentheses, so just show the bare note.
5948     Self.Diag(Loc, Note) << ParenRange;
5949   }
5950 }
5951 
5952 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5953   return Opc >= BO_Mul && Opc <= BO_Shr;
5954 }
5955 
5956 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5957 /// expression, either using a built-in or overloaded operator,
5958 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5959 /// expression.
5960 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5961                                    Expr **RHSExprs) {
5962   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5963   E = E->IgnoreImpCasts();
5964   E = E->IgnoreConversionOperator();
5965   E = E->IgnoreImpCasts();
5966 
5967   // Built-in binary operator.
5968   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5969     if (IsArithmeticOp(OP->getOpcode())) {
5970       *Opcode = OP->getOpcode();
5971       *RHSExprs = OP->getRHS();
5972       return true;
5973     }
5974   }
5975 
5976   // Overloaded operator.
5977   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5978     if (Call->getNumArgs() != 2)
5979       return false;
5980 
5981     // Make sure this is really a binary operator that is safe to pass into
5982     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5983     OverloadedOperatorKind OO = Call->getOperator();
5984     if (OO < OO_Plus || OO > OO_Arrow ||
5985         OO == OO_PlusPlus || OO == OO_MinusMinus)
5986       return false;
5987 
5988     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5989     if (IsArithmeticOp(OpKind)) {
5990       *Opcode = OpKind;
5991       *RHSExprs = Call->getArg(1);
5992       return true;
5993     }
5994   }
5995 
5996   return false;
5997 }
5998 
5999 static bool IsLogicOp(BinaryOperatorKind Opc) {
6000   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6001 }
6002 
6003 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6004 /// or is a logical expression such as (x==y) which has int type, but is
6005 /// commonly interpreted as boolean.
6006 static bool ExprLooksBoolean(Expr *E) {
6007   E = E->IgnoreParenImpCasts();
6008 
6009   if (E->getType()->isBooleanType())
6010     return true;
6011   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6012     return IsLogicOp(OP->getOpcode());
6013   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6014     return OP->getOpcode() == UO_LNot;
6015 
6016   return false;
6017 }
6018 
6019 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6020 /// and binary operator are mixed in a way that suggests the programmer assumed
6021 /// the conditional operator has higher precedence, for example:
6022 /// "int x = a + someBinaryCondition ? 1 : 2".
6023 static void DiagnoseConditionalPrecedence(Sema &Self,
6024                                           SourceLocation OpLoc,
6025                                           Expr *Condition,
6026                                           Expr *LHSExpr,
6027                                           Expr *RHSExpr) {
6028   BinaryOperatorKind CondOpcode;
6029   Expr *CondRHS;
6030 
6031   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6032     return;
6033   if (!ExprLooksBoolean(CondRHS))
6034     return;
6035 
6036   // The condition is an arithmetic binary expression, with a right-
6037   // hand side that looks boolean, so warn.
6038 
6039   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6040       << Condition->getSourceRange()
6041       << BinaryOperator::getOpcodeStr(CondOpcode);
6042 
6043   SuggestParentheses(Self, OpLoc,
6044     Self.PDiag(diag::note_precedence_silence)
6045       << BinaryOperator::getOpcodeStr(CondOpcode),
6046     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6047 
6048   SuggestParentheses(Self, OpLoc,
6049     Self.PDiag(diag::note_precedence_conditional_first),
6050     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6051 }
6052 
6053 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6054 /// in the case of a the GNU conditional expr extension.
6055 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6056                                     SourceLocation ColonLoc,
6057                                     Expr *CondExpr, Expr *LHSExpr,
6058                                     Expr *RHSExpr) {
6059   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6060   // was the condition.
6061   OpaqueValueExpr *opaqueValue = nullptr;
6062   Expr *commonExpr = nullptr;
6063   if (!LHSExpr) {
6064     commonExpr = CondExpr;
6065     // Lower out placeholder types first.  This is important so that we don't
6066     // try to capture a placeholder. This happens in few cases in C++; such
6067     // as Objective-C++'s dictionary subscripting syntax.
6068     if (commonExpr->hasPlaceholderType()) {
6069       ExprResult result = CheckPlaceholderExpr(commonExpr);
6070       if (!result.isUsable()) return ExprError();
6071       commonExpr = result.get();
6072     }
6073     // We usually want to apply unary conversions *before* saving, except
6074     // in the special case of a C++ l-value conditional.
6075     if (!(getLangOpts().CPlusPlus
6076           && !commonExpr->isTypeDependent()
6077           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6078           && commonExpr->isGLValue()
6079           && commonExpr->isOrdinaryOrBitFieldObject()
6080           && RHSExpr->isOrdinaryOrBitFieldObject()
6081           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6082       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6083       if (commonRes.isInvalid())
6084         return ExprError();
6085       commonExpr = commonRes.get();
6086     }
6087 
6088     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6089                                                 commonExpr->getType(),
6090                                                 commonExpr->getValueKind(),
6091                                                 commonExpr->getObjectKind(),
6092                                                 commonExpr);
6093     LHSExpr = CondExpr = opaqueValue;
6094   }
6095 
6096   ExprValueKind VK = VK_RValue;
6097   ExprObjectKind OK = OK_Ordinary;
6098   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6099   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6100                                              VK, OK, QuestionLoc);
6101   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6102       RHS.isInvalid())
6103     return ExprError();
6104 
6105   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6106                                 RHS.get());
6107 
6108   if (!commonExpr)
6109     return new (Context)
6110         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6111                             RHS.get(), result, VK, OK);
6112 
6113   return new (Context) BinaryConditionalOperator(
6114       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6115       ColonLoc, result, VK, OK);
6116 }
6117 
6118 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6119 // being closely modeled after the C99 spec:-). The odd characteristic of this
6120 // routine is it effectively iqnores the qualifiers on the top level pointee.
6121 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6122 // FIXME: add a couple examples in this comment.
6123 static Sema::AssignConvertType
6124 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6125   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6126   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6127 
6128   // get the "pointed to" type (ignoring qualifiers at the top level)
6129   const Type *lhptee, *rhptee;
6130   Qualifiers lhq, rhq;
6131   std::tie(lhptee, lhq) =
6132       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6133   std::tie(rhptee, rhq) =
6134       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6135 
6136   Sema::AssignConvertType ConvTy = Sema::Compatible;
6137 
6138   // C99 6.5.16.1p1: This following citation is common to constraints
6139   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6140   // qualifiers of the type *pointed to* by the right;
6141 
6142   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6143   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6144       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6145     // Ignore lifetime for further calculation.
6146     lhq.removeObjCLifetime();
6147     rhq.removeObjCLifetime();
6148   }
6149 
6150   if (!lhq.compatiblyIncludes(rhq)) {
6151     // Treat address-space mismatches as fatal.  TODO: address subspaces
6152     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6153       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6154 
6155     // It's okay to add or remove GC or lifetime qualifiers when converting to
6156     // and from void*.
6157     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6158                         .compatiblyIncludes(
6159                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6160              && (lhptee->isVoidType() || rhptee->isVoidType()))
6161       ; // keep old
6162 
6163     // Treat lifetime mismatches as fatal.
6164     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6165       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6166 
6167     // For GCC compatibility, other qualifier mismatches are treated
6168     // as still compatible in C.
6169     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6170   }
6171 
6172   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6173   // incomplete type and the other is a pointer to a qualified or unqualified
6174   // version of void...
6175   if (lhptee->isVoidType()) {
6176     if (rhptee->isIncompleteOrObjectType())
6177       return ConvTy;
6178 
6179     // As an extension, we allow cast to/from void* to function pointer.
6180     assert(rhptee->isFunctionType());
6181     return Sema::FunctionVoidPointer;
6182   }
6183 
6184   if (rhptee->isVoidType()) {
6185     if (lhptee->isIncompleteOrObjectType())
6186       return ConvTy;
6187 
6188     // As an extension, we allow cast to/from void* to function pointer.
6189     assert(lhptee->isFunctionType());
6190     return Sema::FunctionVoidPointer;
6191   }
6192 
6193   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6194   // unqualified versions of compatible types, ...
6195   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6196   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6197     // Check if the pointee types are compatible ignoring the sign.
6198     // We explicitly check for char so that we catch "char" vs
6199     // "unsigned char" on systems where "char" is unsigned.
6200     if (lhptee->isCharType())
6201       ltrans = S.Context.UnsignedCharTy;
6202     else if (lhptee->hasSignedIntegerRepresentation())
6203       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6204 
6205     if (rhptee->isCharType())
6206       rtrans = S.Context.UnsignedCharTy;
6207     else if (rhptee->hasSignedIntegerRepresentation())
6208       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6209 
6210     if (ltrans == rtrans) {
6211       // Types are compatible ignoring the sign. Qualifier incompatibility
6212       // takes priority over sign incompatibility because the sign
6213       // warning can be disabled.
6214       if (ConvTy != Sema::Compatible)
6215         return ConvTy;
6216 
6217       return Sema::IncompatiblePointerSign;
6218     }
6219 
6220     // If we are a multi-level pointer, it's possible that our issue is simply
6221     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6222     // the eventual target type is the same and the pointers have the same
6223     // level of indirection, this must be the issue.
6224     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6225       do {
6226         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6227         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6228       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6229 
6230       if (lhptee == rhptee)
6231         return Sema::IncompatibleNestedPointerQualifiers;
6232     }
6233 
6234     // General pointer incompatibility takes priority over qualifiers.
6235     return Sema::IncompatiblePointer;
6236   }
6237   if (!S.getLangOpts().CPlusPlus &&
6238       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6239     return Sema::IncompatiblePointer;
6240   return ConvTy;
6241 }
6242 
6243 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6244 /// block pointer types are compatible or whether a block and normal pointer
6245 /// are compatible. It is more restrict than comparing two function pointer
6246 // types.
6247 static Sema::AssignConvertType
6248 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6249                                     QualType RHSType) {
6250   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6251   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6252 
6253   QualType lhptee, rhptee;
6254 
6255   // get the "pointed to" type (ignoring qualifiers at the top level)
6256   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6257   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6258 
6259   // In C++, the types have to match exactly.
6260   if (S.getLangOpts().CPlusPlus)
6261     return Sema::IncompatibleBlockPointer;
6262 
6263   Sema::AssignConvertType ConvTy = Sema::Compatible;
6264 
6265   // For blocks we enforce that qualifiers are identical.
6266   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6267     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6268 
6269   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6270     return Sema::IncompatibleBlockPointer;
6271 
6272   return ConvTy;
6273 }
6274 
6275 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6276 /// for assignment compatibility.
6277 static Sema::AssignConvertType
6278 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6279                                    QualType RHSType) {
6280   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6281   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6282 
6283   if (LHSType->isObjCBuiltinType()) {
6284     // Class is not compatible with ObjC object pointers.
6285     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6286         !RHSType->isObjCQualifiedClassType())
6287       return Sema::IncompatiblePointer;
6288     return Sema::Compatible;
6289   }
6290   if (RHSType->isObjCBuiltinType()) {
6291     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6292         !LHSType->isObjCQualifiedClassType())
6293       return Sema::IncompatiblePointer;
6294     return Sema::Compatible;
6295   }
6296   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6297   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6298 
6299   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6300       // make an exception for id<P>
6301       !LHSType->isObjCQualifiedIdType())
6302     return Sema::CompatiblePointerDiscardsQualifiers;
6303 
6304   if (S.Context.typesAreCompatible(LHSType, RHSType))
6305     return Sema::Compatible;
6306   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6307     return Sema::IncompatibleObjCQualifiedId;
6308   return Sema::IncompatiblePointer;
6309 }
6310 
6311 Sema::AssignConvertType
6312 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6313                                  QualType LHSType, QualType RHSType) {
6314   // Fake up an opaque expression.  We don't actually care about what
6315   // cast operations are required, so if CheckAssignmentConstraints
6316   // adds casts to this they'll be wasted, but fortunately that doesn't
6317   // usually happen on valid code.
6318   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6319   ExprResult RHSPtr = &RHSExpr;
6320   CastKind K = CK_Invalid;
6321 
6322   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6323 }
6324 
6325 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6326 /// has code to accommodate several GCC extensions when type checking
6327 /// pointers. Here are some objectionable examples that GCC considers warnings:
6328 ///
6329 ///  int a, *pint;
6330 ///  short *pshort;
6331 ///  struct foo *pfoo;
6332 ///
6333 ///  pint = pshort; // warning: assignment from incompatible pointer type
6334 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6335 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6336 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6337 ///
6338 /// As a result, the code for dealing with pointers is more complex than the
6339 /// C99 spec dictates.
6340 ///
6341 /// Sets 'Kind' for any result kind except Incompatible.
6342 Sema::AssignConvertType
6343 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6344                                  CastKind &Kind) {
6345   QualType RHSType = RHS.get()->getType();
6346   QualType OrigLHSType = LHSType;
6347 
6348   // Get canonical types.  We're not formatting these types, just comparing
6349   // them.
6350   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6351   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6352 
6353   // Common case: no conversion required.
6354   if (LHSType == RHSType) {
6355     Kind = CK_NoOp;
6356     return Compatible;
6357   }
6358 
6359   // If we have an atomic type, try a non-atomic assignment, then just add an
6360   // atomic qualification step.
6361   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6362     Sema::AssignConvertType result =
6363       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6364     if (result != Compatible)
6365       return result;
6366     if (Kind != CK_NoOp)
6367       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6368     Kind = CK_NonAtomicToAtomic;
6369     return Compatible;
6370   }
6371 
6372   // If the left-hand side is a reference type, then we are in a
6373   // (rare!) case where we've allowed the use of references in C,
6374   // e.g., as a parameter type in a built-in function. In this case,
6375   // just make sure that the type referenced is compatible with the
6376   // right-hand side type. The caller is responsible for adjusting
6377   // LHSType so that the resulting expression does not have reference
6378   // type.
6379   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6380     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6381       Kind = CK_LValueBitCast;
6382       return Compatible;
6383     }
6384     return Incompatible;
6385   }
6386 
6387   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6388   // to the same ExtVector type.
6389   if (LHSType->isExtVectorType()) {
6390     if (RHSType->isExtVectorType())
6391       return Incompatible;
6392     if (RHSType->isArithmeticType()) {
6393       // CK_VectorSplat does T -> vector T, so first cast to the
6394       // element type.
6395       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6396       if (elType != RHSType) {
6397         Kind = PrepareScalarCast(RHS, elType);
6398         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6399       }
6400       Kind = CK_VectorSplat;
6401       return Compatible;
6402     }
6403   }
6404 
6405   // Conversions to or from vector type.
6406   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6407     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6408       // Allow assignments of an AltiVec vector type to an equivalent GCC
6409       // vector type and vice versa
6410       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6411         Kind = CK_BitCast;
6412         return Compatible;
6413       }
6414 
6415       // If we are allowing lax vector conversions, and LHS and RHS are both
6416       // vectors, the total size only needs to be the same. This is a bitcast;
6417       // no bits are changed but the result type is different.
6418       if (isLaxVectorConversion(RHSType, LHSType)) {
6419         Kind = CK_BitCast;
6420         return IncompatibleVectors;
6421       }
6422     }
6423     return Incompatible;
6424   }
6425 
6426   // Arithmetic conversions.
6427   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6428       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6429     Kind = PrepareScalarCast(RHS, LHSType);
6430     return Compatible;
6431   }
6432 
6433   // Conversions to normal pointers.
6434   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6435     // U* -> T*
6436     if (isa<PointerType>(RHSType)) {
6437       Kind = CK_BitCast;
6438       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6439     }
6440 
6441     // int -> T*
6442     if (RHSType->isIntegerType()) {
6443       Kind = CK_IntegralToPointer; // FIXME: null?
6444       return IntToPointer;
6445     }
6446 
6447     // C pointers are not compatible with ObjC object pointers,
6448     // with two exceptions:
6449     if (isa<ObjCObjectPointerType>(RHSType)) {
6450       //  - conversions to void*
6451       if (LHSPointer->getPointeeType()->isVoidType()) {
6452         Kind = CK_BitCast;
6453         return Compatible;
6454       }
6455 
6456       //  - conversions from 'Class' to the redefinition type
6457       if (RHSType->isObjCClassType() &&
6458           Context.hasSameType(LHSType,
6459                               Context.getObjCClassRedefinitionType())) {
6460         Kind = CK_BitCast;
6461         return Compatible;
6462       }
6463 
6464       Kind = CK_BitCast;
6465       return IncompatiblePointer;
6466     }
6467 
6468     // U^ -> void*
6469     if (RHSType->getAs<BlockPointerType>()) {
6470       if (LHSPointer->getPointeeType()->isVoidType()) {
6471         Kind = CK_BitCast;
6472         return Compatible;
6473       }
6474     }
6475 
6476     return Incompatible;
6477   }
6478 
6479   // Conversions to block pointers.
6480   if (isa<BlockPointerType>(LHSType)) {
6481     // U^ -> T^
6482     if (RHSType->isBlockPointerType()) {
6483       Kind = CK_BitCast;
6484       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6485     }
6486 
6487     // int or null -> T^
6488     if (RHSType->isIntegerType()) {
6489       Kind = CK_IntegralToPointer; // FIXME: null
6490       return IntToBlockPointer;
6491     }
6492 
6493     // id -> T^
6494     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6495       Kind = CK_AnyPointerToBlockPointerCast;
6496       return Compatible;
6497     }
6498 
6499     // void* -> T^
6500     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6501       if (RHSPT->getPointeeType()->isVoidType()) {
6502         Kind = CK_AnyPointerToBlockPointerCast;
6503         return Compatible;
6504       }
6505 
6506     return Incompatible;
6507   }
6508 
6509   // Conversions to Objective-C pointers.
6510   if (isa<ObjCObjectPointerType>(LHSType)) {
6511     // A* -> B*
6512     if (RHSType->isObjCObjectPointerType()) {
6513       Kind = CK_BitCast;
6514       Sema::AssignConvertType result =
6515         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6516       if (getLangOpts().ObjCAutoRefCount &&
6517           result == Compatible &&
6518           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6519         result = IncompatibleObjCWeakRef;
6520       return result;
6521     }
6522 
6523     // int or null -> A*
6524     if (RHSType->isIntegerType()) {
6525       Kind = CK_IntegralToPointer; // FIXME: null
6526       return IntToPointer;
6527     }
6528 
6529     // In general, C pointers are not compatible with ObjC object pointers,
6530     // with two exceptions:
6531     if (isa<PointerType>(RHSType)) {
6532       Kind = CK_CPointerToObjCPointerCast;
6533 
6534       //  - conversions from 'void*'
6535       if (RHSType->isVoidPointerType()) {
6536         return Compatible;
6537       }
6538 
6539       //  - conversions to 'Class' from its redefinition type
6540       if (LHSType->isObjCClassType() &&
6541           Context.hasSameType(RHSType,
6542                               Context.getObjCClassRedefinitionType())) {
6543         return Compatible;
6544       }
6545 
6546       return IncompatiblePointer;
6547     }
6548 
6549     // Only under strict condition T^ is compatible with an Objective-C pointer.
6550     if (RHSType->isBlockPointerType() &&
6551         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6552       maybeExtendBlockObject(*this, RHS);
6553       Kind = CK_BlockPointerToObjCPointerCast;
6554       return Compatible;
6555     }
6556 
6557     return Incompatible;
6558   }
6559 
6560   // Conversions from pointers that are not covered by the above.
6561   if (isa<PointerType>(RHSType)) {
6562     // T* -> _Bool
6563     if (LHSType == Context.BoolTy) {
6564       Kind = CK_PointerToBoolean;
6565       return Compatible;
6566     }
6567 
6568     // T* -> int
6569     if (LHSType->isIntegerType()) {
6570       Kind = CK_PointerToIntegral;
6571       return PointerToInt;
6572     }
6573 
6574     return Incompatible;
6575   }
6576 
6577   // Conversions from Objective-C pointers that are not covered by the above.
6578   if (isa<ObjCObjectPointerType>(RHSType)) {
6579     // T* -> _Bool
6580     if (LHSType == Context.BoolTy) {
6581       Kind = CK_PointerToBoolean;
6582       return Compatible;
6583     }
6584 
6585     // T* -> int
6586     if (LHSType->isIntegerType()) {
6587       Kind = CK_PointerToIntegral;
6588       return PointerToInt;
6589     }
6590 
6591     return Incompatible;
6592   }
6593 
6594   // struct A -> struct B
6595   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6596     if (Context.typesAreCompatible(LHSType, RHSType)) {
6597       Kind = CK_NoOp;
6598       return Compatible;
6599     }
6600   }
6601 
6602   return Incompatible;
6603 }
6604 
6605 /// \brief Constructs a transparent union from an expression that is
6606 /// used to initialize the transparent union.
6607 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6608                                       ExprResult &EResult, QualType UnionType,
6609                                       FieldDecl *Field) {
6610   // Build an initializer list that designates the appropriate member
6611   // of the transparent union.
6612   Expr *E = EResult.get();
6613   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6614                                                    E, SourceLocation());
6615   Initializer->setType(UnionType);
6616   Initializer->setInitializedFieldInUnion(Field);
6617 
6618   // Build a compound literal constructing a value of the transparent
6619   // union type from this initializer list.
6620   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6621   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6622                                         VK_RValue, Initializer, false);
6623 }
6624 
6625 Sema::AssignConvertType
6626 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6627                                                ExprResult &RHS) {
6628   QualType RHSType = RHS.get()->getType();
6629 
6630   // If the ArgType is a Union type, we want to handle a potential
6631   // transparent_union GCC extension.
6632   const RecordType *UT = ArgType->getAsUnionType();
6633   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6634     return Incompatible;
6635 
6636   // The field to initialize within the transparent union.
6637   RecordDecl *UD = UT->getDecl();
6638   FieldDecl *InitField = nullptr;
6639   // It's compatible if the expression matches any of the fields.
6640   for (auto *it : UD->fields()) {
6641     if (it->getType()->isPointerType()) {
6642       // If the transparent union contains a pointer type, we allow:
6643       // 1) void pointer
6644       // 2) null pointer constant
6645       if (RHSType->isPointerType())
6646         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6647           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6648           InitField = it;
6649           break;
6650         }
6651 
6652       if (RHS.get()->isNullPointerConstant(Context,
6653                                            Expr::NPC_ValueDependentIsNull)) {
6654         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6655                                 CK_NullToPointer);
6656         InitField = it;
6657         break;
6658       }
6659     }
6660 
6661     CastKind Kind = CK_Invalid;
6662     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6663           == Compatible) {
6664       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6665       InitField = it;
6666       break;
6667     }
6668   }
6669 
6670   if (!InitField)
6671     return Incompatible;
6672 
6673   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6674   return Compatible;
6675 }
6676 
6677 Sema::AssignConvertType
6678 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6679                                        bool Diagnose,
6680                                        bool DiagnoseCFAudited) {
6681   if (getLangOpts().CPlusPlus) {
6682     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6683       // C++ 5.17p3: If the left operand is not of class type, the
6684       // expression is implicitly converted (C++ 4) to the
6685       // cv-unqualified type of the left operand.
6686       ExprResult Res;
6687       if (Diagnose) {
6688         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6689                                         AA_Assigning);
6690       } else {
6691         ImplicitConversionSequence ICS =
6692             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6693                                   /*SuppressUserConversions=*/false,
6694                                   /*AllowExplicit=*/false,
6695                                   /*InOverloadResolution=*/false,
6696                                   /*CStyle=*/false,
6697                                   /*AllowObjCWritebackConversion=*/false);
6698         if (ICS.isFailure())
6699           return Incompatible;
6700         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6701                                         ICS, AA_Assigning);
6702       }
6703       if (Res.isInvalid())
6704         return Incompatible;
6705       Sema::AssignConvertType result = Compatible;
6706       if (getLangOpts().ObjCAutoRefCount &&
6707           !CheckObjCARCUnavailableWeakConversion(LHSType,
6708                                                  RHS.get()->getType()))
6709         result = IncompatibleObjCWeakRef;
6710       RHS = Res;
6711       return result;
6712     }
6713 
6714     // FIXME: Currently, we fall through and treat C++ classes like C
6715     // structures.
6716     // FIXME: We also fall through for atomics; not sure what should
6717     // happen there, though.
6718   }
6719 
6720   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6721   // a null pointer constant.
6722   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6723        LHSType->isBlockPointerType()) &&
6724       RHS.get()->isNullPointerConstant(Context,
6725                                        Expr::NPC_ValueDependentIsNull)) {
6726     CastKind Kind;
6727     CXXCastPath Path;
6728     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6729     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6730     return Compatible;
6731   }
6732 
6733   // This check seems unnatural, however it is necessary to ensure the proper
6734   // conversion of functions/arrays. If the conversion were done for all
6735   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6736   // expressions that suppress this implicit conversion (&, sizeof).
6737   //
6738   // Suppress this for references: C++ 8.5.3p5.
6739   if (!LHSType->isReferenceType()) {
6740     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6741     if (RHS.isInvalid())
6742       return Incompatible;
6743   }
6744 
6745   Expr *PRE = RHS.get()->IgnoreParenCasts();
6746   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
6747     ObjCProtocolDecl *PDecl = OPE->getProtocol();
6748     if (PDecl && !PDecl->hasDefinition()) {
6749       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
6750       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
6751     }
6752   }
6753 
6754   CastKind Kind = CK_Invalid;
6755   Sema::AssignConvertType result =
6756     CheckAssignmentConstraints(LHSType, RHS, Kind);
6757 
6758   // C99 6.5.16.1p2: The value of the right operand is converted to the
6759   // type of the assignment expression.
6760   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6761   // so that we can use references in built-in functions even in C.
6762   // The getNonReferenceType() call makes sure that the resulting expression
6763   // does not have reference type.
6764   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6765     QualType Ty = LHSType.getNonLValueExprType(Context);
6766     Expr *E = RHS.get();
6767     if (getLangOpts().ObjCAutoRefCount)
6768       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6769                              DiagnoseCFAudited);
6770     if (getLangOpts().ObjC1 &&
6771         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6772                                           LHSType, E->getType(), E) ||
6773          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6774       RHS = E;
6775       return Compatible;
6776     }
6777 
6778     RHS = ImpCastExprToType(E, Ty, Kind);
6779   }
6780   return result;
6781 }
6782 
6783 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6784                                ExprResult &RHS) {
6785   Diag(Loc, diag::err_typecheck_invalid_operands)
6786     << LHS.get()->getType() << RHS.get()->getType()
6787     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6788   return QualType();
6789 }
6790 
6791 /// Try to convert a value of non-vector type to a vector type by converting
6792 /// the type to the element type of the vector and then performing a splat.
6793 /// If the language is OpenCL, we only use conversions that promote scalar
6794 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6795 /// for float->int.
6796 ///
6797 /// \param scalar - if non-null, actually perform the conversions
6798 /// \return true if the operation fails (but without diagnosing the failure)
6799 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6800                                      QualType scalarTy,
6801                                      QualType vectorEltTy,
6802                                      QualType vectorTy) {
6803   // The conversion to apply to the scalar before splatting it,
6804   // if necessary.
6805   CastKind scalarCast = CK_Invalid;
6806 
6807   if (vectorEltTy->isIntegralType(S.Context)) {
6808     if (!scalarTy->isIntegralType(S.Context))
6809       return true;
6810     if (S.getLangOpts().OpenCL &&
6811         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6812       return true;
6813     scalarCast = CK_IntegralCast;
6814   } else if (vectorEltTy->isRealFloatingType()) {
6815     if (scalarTy->isRealFloatingType()) {
6816       if (S.getLangOpts().OpenCL &&
6817           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6818         return true;
6819       scalarCast = CK_FloatingCast;
6820     }
6821     else if (scalarTy->isIntegralType(S.Context))
6822       scalarCast = CK_IntegralToFloating;
6823     else
6824       return true;
6825   } else {
6826     return true;
6827   }
6828 
6829   // Adjust scalar if desired.
6830   if (scalar) {
6831     if (scalarCast != CK_Invalid)
6832       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6833     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6834   }
6835   return false;
6836 }
6837 
6838 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6839                                    SourceLocation Loc, bool IsCompAssign) {
6840   if (!IsCompAssign) {
6841     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6842     if (LHS.isInvalid())
6843       return QualType();
6844   }
6845   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6846   if (RHS.isInvalid())
6847     return QualType();
6848 
6849   // For conversion purposes, we ignore any qualifiers.
6850   // For example, "const float" and "float" are equivalent.
6851   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6852   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6853 
6854   // If the vector types are identical, return.
6855   if (Context.hasSameType(LHSType, RHSType))
6856     return LHSType;
6857 
6858   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6859   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6860   assert(LHSVecType || RHSVecType);
6861 
6862   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6863   if (LHSVecType && RHSVecType &&
6864       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6865     if (isa<ExtVectorType>(LHSVecType)) {
6866       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6867       return LHSType;
6868     }
6869 
6870     if (!IsCompAssign)
6871       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6872     return RHSType;
6873   }
6874 
6875   // If there's an ext-vector type and a scalar, try to convert the scalar to
6876   // the vector element type and splat.
6877   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6878     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6879                                   LHSVecType->getElementType(), LHSType))
6880       return LHSType;
6881   }
6882   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6883     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6884                                   LHSType, RHSVecType->getElementType(),
6885                                   RHSType))
6886       return RHSType;
6887   }
6888 
6889   // If we're allowing lax vector conversions, only the total (data) size
6890   // needs to be the same.
6891   // FIXME: Should we really be allowing this?
6892   // FIXME: We really just pick the LHS type arbitrarily?
6893   if (isLaxVectorConversion(RHSType, LHSType)) {
6894     QualType resultType = LHSType;
6895     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
6896     return resultType;
6897   }
6898 
6899   // Okay, the expression is invalid.
6900 
6901   // If there's a non-vector, non-real operand, diagnose that.
6902   if ((!RHSVecType && !RHSType->isRealType()) ||
6903       (!LHSVecType && !LHSType->isRealType())) {
6904     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6905       << LHSType << RHSType
6906       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6907     return QualType();
6908   }
6909 
6910   // Otherwise, use the generic diagnostic.
6911   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6912     << LHSType << RHSType
6913     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6914   return QualType();
6915 }
6916 
6917 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6918 // expression.  These are mainly cases where the null pointer is used as an
6919 // integer instead of a pointer.
6920 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6921                                 SourceLocation Loc, bool IsCompare) {
6922   // The canonical way to check for a GNU null is with isNullPointerConstant,
6923   // but we use a bit of a hack here for speed; this is a relatively
6924   // hot path, and isNullPointerConstant is slow.
6925   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6926   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6927 
6928   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6929 
6930   // Avoid analyzing cases where the result will either be invalid (and
6931   // diagnosed as such) or entirely valid and not something to warn about.
6932   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6933       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6934     return;
6935 
6936   // Comparison operations would not make sense with a null pointer no matter
6937   // what the other expression is.
6938   if (!IsCompare) {
6939     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6940         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6941         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6942     return;
6943   }
6944 
6945   // The rest of the operations only make sense with a null pointer
6946   // if the other expression is a pointer.
6947   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6948       NonNullType->canDecayToPointerType())
6949     return;
6950 
6951   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6952       << LHSNull /* LHS is NULL */ << NonNullType
6953       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6954 }
6955 
6956 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6957                                            SourceLocation Loc,
6958                                            bool IsCompAssign, bool IsDiv) {
6959   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6960 
6961   if (LHS.get()->getType()->isVectorType() ||
6962       RHS.get()->getType()->isVectorType())
6963     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6964 
6965   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6966   if (LHS.isInvalid() || RHS.isInvalid())
6967     return QualType();
6968 
6969 
6970   if (compType.isNull() || !compType->isArithmeticType())
6971     return InvalidOperands(Loc, LHS, RHS);
6972 
6973   // Check for division by zero.
6974   llvm::APSInt RHSValue;
6975   if (IsDiv && !RHS.get()->isValueDependent() &&
6976       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6977     DiagRuntimeBehavior(Loc, RHS.get(),
6978                         PDiag(diag::warn_division_by_zero)
6979                           << RHS.get()->getSourceRange());
6980 
6981   return compType;
6982 }
6983 
6984 QualType Sema::CheckRemainderOperands(
6985   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6986   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6987 
6988   if (LHS.get()->getType()->isVectorType() ||
6989       RHS.get()->getType()->isVectorType()) {
6990     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6991         RHS.get()->getType()->hasIntegerRepresentation())
6992       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6993     return InvalidOperands(Loc, LHS, RHS);
6994   }
6995 
6996   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6997   if (LHS.isInvalid() || RHS.isInvalid())
6998     return QualType();
6999 
7000   if (compType.isNull() || !compType->isIntegerType())
7001     return InvalidOperands(Loc, LHS, RHS);
7002 
7003   // Check for remainder by zero.
7004   llvm::APSInt RHSValue;
7005   if (!RHS.get()->isValueDependent() &&
7006       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7007     DiagRuntimeBehavior(Loc, RHS.get(),
7008                         PDiag(diag::warn_remainder_by_zero)
7009                           << RHS.get()->getSourceRange());
7010 
7011   return compType;
7012 }
7013 
7014 /// \brief Diagnose invalid arithmetic on two void pointers.
7015 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7016                                                 Expr *LHSExpr, Expr *RHSExpr) {
7017   S.Diag(Loc, S.getLangOpts().CPlusPlus
7018                 ? diag::err_typecheck_pointer_arith_void_type
7019                 : diag::ext_gnu_void_ptr)
7020     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7021                             << RHSExpr->getSourceRange();
7022 }
7023 
7024 /// \brief Diagnose invalid arithmetic on a void pointer.
7025 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7026                                             Expr *Pointer) {
7027   S.Diag(Loc, S.getLangOpts().CPlusPlus
7028                 ? diag::err_typecheck_pointer_arith_void_type
7029                 : diag::ext_gnu_void_ptr)
7030     << 0 /* one pointer */ << Pointer->getSourceRange();
7031 }
7032 
7033 /// \brief Diagnose invalid arithmetic on two function pointers.
7034 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7035                                                     Expr *LHS, Expr *RHS) {
7036   assert(LHS->getType()->isAnyPointerType());
7037   assert(RHS->getType()->isAnyPointerType());
7038   S.Diag(Loc, S.getLangOpts().CPlusPlus
7039                 ? diag::err_typecheck_pointer_arith_function_type
7040                 : diag::ext_gnu_ptr_func_arith)
7041     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7042     // We only show the second type if it differs from the first.
7043     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7044                                                    RHS->getType())
7045     << RHS->getType()->getPointeeType()
7046     << LHS->getSourceRange() << RHS->getSourceRange();
7047 }
7048 
7049 /// \brief Diagnose invalid arithmetic on a function pointer.
7050 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7051                                                 Expr *Pointer) {
7052   assert(Pointer->getType()->isAnyPointerType());
7053   S.Diag(Loc, S.getLangOpts().CPlusPlus
7054                 ? diag::err_typecheck_pointer_arith_function_type
7055                 : diag::ext_gnu_ptr_func_arith)
7056     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7057     << 0 /* one pointer, so only one type */
7058     << Pointer->getSourceRange();
7059 }
7060 
7061 /// \brief Emit error if Operand is incomplete pointer type
7062 ///
7063 /// \returns True if pointer has incomplete type
7064 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7065                                                  Expr *Operand) {
7066   assert(Operand->getType()->isAnyPointerType() &&
7067          !Operand->getType()->isDependentType());
7068   QualType PointeeTy = Operand->getType()->getPointeeType();
7069   return S.RequireCompleteType(Loc, PointeeTy,
7070                                diag::err_typecheck_arithmetic_incomplete_type,
7071                                PointeeTy, Operand->getSourceRange());
7072 }
7073 
7074 /// \brief Check the validity of an arithmetic pointer operand.
7075 ///
7076 /// If the operand has pointer type, this code will check for pointer types
7077 /// which are invalid in arithmetic operations. These will be diagnosed
7078 /// appropriately, including whether or not the use is supported as an
7079 /// extension.
7080 ///
7081 /// \returns True when the operand is valid to use (even if as an extension).
7082 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7083                                             Expr *Operand) {
7084   if (!Operand->getType()->isAnyPointerType()) return true;
7085 
7086   QualType PointeeTy = Operand->getType()->getPointeeType();
7087   if (PointeeTy->isVoidType()) {
7088     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7089     return !S.getLangOpts().CPlusPlus;
7090   }
7091   if (PointeeTy->isFunctionType()) {
7092     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7093     return !S.getLangOpts().CPlusPlus;
7094   }
7095 
7096   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7097 
7098   return true;
7099 }
7100 
7101 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7102 /// operands.
7103 ///
7104 /// This routine will diagnose any invalid arithmetic on pointer operands much
7105 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7106 /// for emitting a single diagnostic even for operations where both LHS and RHS
7107 /// are (potentially problematic) pointers.
7108 ///
7109 /// \returns True when the operand is valid to use (even if as an extension).
7110 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7111                                                 Expr *LHSExpr, Expr *RHSExpr) {
7112   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7113   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7114   if (!isLHSPointer && !isRHSPointer) return true;
7115 
7116   QualType LHSPointeeTy, RHSPointeeTy;
7117   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7118   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7119 
7120   // Check for arithmetic on pointers to incomplete types.
7121   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7122   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7123   if (isLHSVoidPtr || isRHSVoidPtr) {
7124     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7125     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7126     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7127 
7128     return !S.getLangOpts().CPlusPlus;
7129   }
7130 
7131   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7132   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7133   if (isLHSFuncPtr || isRHSFuncPtr) {
7134     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7135     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7136                                                                 RHSExpr);
7137     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7138 
7139     return !S.getLangOpts().CPlusPlus;
7140   }
7141 
7142   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7143     return false;
7144   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7145     return false;
7146 
7147   return true;
7148 }
7149 
7150 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7151 /// literal.
7152 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7153                                   Expr *LHSExpr, Expr *RHSExpr) {
7154   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7155   Expr* IndexExpr = RHSExpr;
7156   if (!StrExpr) {
7157     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7158     IndexExpr = LHSExpr;
7159   }
7160 
7161   bool IsStringPlusInt = StrExpr &&
7162       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7163   if (!IsStringPlusInt)
7164     return;
7165 
7166   llvm::APSInt index;
7167   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7168     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7169     if (index.isNonNegative() &&
7170         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7171                               index.isUnsigned()))
7172       return;
7173   }
7174 
7175   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7176   Self.Diag(OpLoc, diag::warn_string_plus_int)
7177       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7178 
7179   // Only print a fixit for "str" + int, not for int + "str".
7180   if (IndexExpr == RHSExpr) {
7181     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7182     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7183         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7184         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7185         << FixItHint::CreateInsertion(EndLoc, "]");
7186   } else
7187     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7188 }
7189 
7190 /// \brief Emit a warning when adding a char literal to a string.
7191 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7192                                    Expr *LHSExpr, Expr *RHSExpr) {
7193   const DeclRefExpr *StringRefExpr =
7194       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7195   const CharacterLiteral *CharExpr =
7196       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7197   if (!StringRefExpr) {
7198     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7199     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7200   }
7201 
7202   if (!CharExpr || !StringRefExpr)
7203     return;
7204 
7205   const QualType StringType = StringRefExpr->getType();
7206 
7207   // Return if not a PointerType.
7208   if (!StringType->isAnyPointerType())
7209     return;
7210 
7211   // Return if not a CharacterType.
7212   if (!StringType->getPointeeType()->isAnyCharacterType())
7213     return;
7214 
7215   ASTContext &Ctx = Self.getASTContext();
7216   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7217 
7218   const QualType CharType = CharExpr->getType();
7219   if (!CharType->isAnyCharacterType() &&
7220       CharType->isIntegerType() &&
7221       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7222     Self.Diag(OpLoc, diag::warn_string_plus_char)
7223         << DiagRange << Ctx.CharTy;
7224   } else {
7225     Self.Diag(OpLoc, diag::warn_string_plus_char)
7226         << DiagRange << CharExpr->getType();
7227   }
7228 
7229   // Only print a fixit for str + char, not for char + str.
7230   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7231     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7232     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7233         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7234         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7235         << FixItHint::CreateInsertion(EndLoc, "]");
7236   } else {
7237     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7238   }
7239 }
7240 
7241 /// \brief Emit error when two pointers are incompatible.
7242 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7243                                            Expr *LHSExpr, Expr *RHSExpr) {
7244   assert(LHSExpr->getType()->isAnyPointerType());
7245   assert(RHSExpr->getType()->isAnyPointerType());
7246   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7247     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7248     << RHSExpr->getSourceRange();
7249 }
7250 
7251 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7252     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7253     QualType* CompLHSTy) {
7254   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7255 
7256   if (LHS.get()->getType()->isVectorType() ||
7257       RHS.get()->getType()->isVectorType()) {
7258     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7259     if (CompLHSTy) *CompLHSTy = compType;
7260     return compType;
7261   }
7262 
7263   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7264   if (LHS.isInvalid() || RHS.isInvalid())
7265     return QualType();
7266 
7267   // Diagnose "string literal" '+' int and string '+' "char literal".
7268   if (Opc == BO_Add) {
7269     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7270     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7271   }
7272 
7273   // handle the common case first (both operands are arithmetic).
7274   if (!compType.isNull() && compType->isArithmeticType()) {
7275     if (CompLHSTy) *CompLHSTy = compType;
7276     return compType;
7277   }
7278 
7279   // Type-checking.  Ultimately the pointer's going to be in PExp;
7280   // note that we bias towards the LHS being the pointer.
7281   Expr *PExp = LHS.get(), *IExp = RHS.get();
7282 
7283   bool isObjCPointer;
7284   if (PExp->getType()->isPointerType()) {
7285     isObjCPointer = false;
7286   } else if (PExp->getType()->isObjCObjectPointerType()) {
7287     isObjCPointer = true;
7288   } else {
7289     std::swap(PExp, IExp);
7290     if (PExp->getType()->isPointerType()) {
7291       isObjCPointer = false;
7292     } else if (PExp->getType()->isObjCObjectPointerType()) {
7293       isObjCPointer = true;
7294     } else {
7295       return InvalidOperands(Loc, LHS, RHS);
7296     }
7297   }
7298   assert(PExp->getType()->isAnyPointerType());
7299 
7300   if (!IExp->getType()->isIntegerType())
7301     return InvalidOperands(Loc, LHS, RHS);
7302 
7303   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7304     return QualType();
7305 
7306   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7307     return QualType();
7308 
7309   // Check array bounds for pointer arithemtic
7310   CheckArrayAccess(PExp, IExp);
7311 
7312   if (CompLHSTy) {
7313     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7314     if (LHSTy.isNull()) {
7315       LHSTy = LHS.get()->getType();
7316       if (LHSTy->isPromotableIntegerType())
7317         LHSTy = Context.getPromotedIntegerType(LHSTy);
7318     }
7319     *CompLHSTy = LHSTy;
7320   }
7321 
7322   return PExp->getType();
7323 }
7324 
7325 // C99 6.5.6
7326 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7327                                         SourceLocation Loc,
7328                                         QualType* CompLHSTy) {
7329   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7330 
7331   if (LHS.get()->getType()->isVectorType() ||
7332       RHS.get()->getType()->isVectorType()) {
7333     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7334     if (CompLHSTy) *CompLHSTy = compType;
7335     return compType;
7336   }
7337 
7338   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7339   if (LHS.isInvalid() || RHS.isInvalid())
7340     return QualType();
7341 
7342   // Enforce type constraints: C99 6.5.6p3.
7343 
7344   // Handle the common case first (both operands are arithmetic).
7345   if (!compType.isNull() && compType->isArithmeticType()) {
7346     if (CompLHSTy) *CompLHSTy = compType;
7347     return compType;
7348   }
7349 
7350   // Either ptr - int   or   ptr - ptr.
7351   if (LHS.get()->getType()->isAnyPointerType()) {
7352     QualType lpointee = LHS.get()->getType()->getPointeeType();
7353 
7354     // Diagnose bad cases where we step over interface counts.
7355     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7356         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7357       return QualType();
7358 
7359     // The result type of a pointer-int computation is the pointer type.
7360     if (RHS.get()->getType()->isIntegerType()) {
7361       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7362         return QualType();
7363 
7364       // Check array bounds for pointer arithemtic
7365       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7366                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7367 
7368       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7369       return LHS.get()->getType();
7370     }
7371 
7372     // Handle pointer-pointer subtractions.
7373     if (const PointerType *RHSPTy
7374           = RHS.get()->getType()->getAs<PointerType>()) {
7375       QualType rpointee = RHSPTy->getPointeeType();
7376 
7377       if (getLangOpts().CPlusPlus) {
7378         // Pointee types must be the same: C++ [expr.add]
7379         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7380           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7381         }
7382       } else {
7383         // Pointee types must be compatible C99 6.5.6p3
7384         if (!Context.typesAreCompatible(
7385                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7386                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7387           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7388           return QualType();
7389         }
7390       }
7391 
7392       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7393                                                LHS.get(), RHS.get()))
7394         return QualType();
7395 
7396       // The pointee type may have zero size.  As an extension, a structure or
7397       // union may have zero size or an array may have zero length.  In this
7398       // case subtraction does not make sense.
7399       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7400         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7401         if (ElementSize.isZero()) {
7402           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7403             << rpointee.getUnqualifiedType()
7404             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7405         }
7406       }
7407 
7408       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7409       return Context.getPointerDiffType();
7410     }
7411   }
7412 
7413   return InvalidOperands(Loc, LHS, RHS);
7414 }
7415 
7416 static bool isScopedEnumerationType(QualType T) {
7417   if (const EnumType *ET = dyn_cast<EnumType>(T))
7418     return ET->getDecl()->isScoped();
7419   return false;
7420 }
7421 
7422 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7423                                    SourceLocation Loc, unsigned Opc,
7424                                    QualType LHSType) {
7425   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7426   // so skip remaining warnings as we don't want to modify values within Sema.
7427   if (S.getLangOpts().OpenCL)
7428     return;
7429 
7430   llvm::APSInt Right;
7431   // Check right/shifter operand
7432   if (RHS.get()->isValueDependent() ||
7433       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7434     return;
7435 
7436   if (Right.isNegative()) {
7437     S.DiagRuntimeBehavior(Loc, RHS.get(),
7438                           S.PDiag(diag::warn_shift_negative)
7439                             << RHS.get()->getSourceRange());
7440     return;
7441   }
7442   llvm::APInt LeftBits(Right.getBitWidth(),
7443                        S.Context.getTypeSize(LHS.get()->getType()));
7444   if (Right.uge(LeftBits)) {
7445     S.DiagRuntimeBehavior(Loc, RHS.get(),
7446                           S.PDiag(diag::warn_shift_gt_typewidth)
7447                             << RHS.get()->getSourceRange());
7448     return;
7449   }
7450   if (Opc != BO_Shl)
7451     return;
7452 
7453   // When left shifting an ICE which is signed, we can check for overflow which
7454   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7455   // integers have defined behavior modulo one more than the maximum value
7456   // representable in the result type, so never warn for those.
7457   llvm::APSInt Left;
7458   if (LHS.get()->isValueDependent() ||
7459       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7460       LHSType->hasUnsignedIntegerRepresentation())
7461     return;
7462   llvm::APInt ResultBits =
7463       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7464   if (LeftBits.uge(ResultBits))
7465     return;
7466   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7467   Result = Result.shl(Right);
7468 
7469   // Print the bit representation of the signed integer as an unsigned
7470   // hexadecimal number.
7471   SmallString<40> HexResult;
7472   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7473 
7474   // If we are only missing a sign bit, this is less likely to result in actual
7475   // bugs -- if the result is cast back to an unsigned type, it will have the
7476   // expected value. Thus we place this behind a different warning that can be
7477   // turned off separately if needed.
7478   if (LeftBits == ResultBits - 1) {
7479     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7480         << HexResult.str() << LHSType
7481         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7482     return;
7483   }
7484 
7485   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7486     << HexResult.str() << Result.getMinSignedBits() << LHSType
7487     << Left.getBitWidth() << LHS.get()->getSourceRange()
7488     << RHS.get()->getSourceRange();
7489 }
7490 
7491 // C99 6.5.7
7492 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7493                                   SourceLocation Loc, unsigned Opc,
7494                                   bool IsCompAssign) {
7495   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7496 
7497   // Vector shifts promote their scalar inputs to vector type.
7498   if (LHS.get()->getType()->isVectorType() ||
7499       RHS.get()->getType()->isVectorType())
7500     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7501 
7502   // Shifts don't perform usual arithmetic conversions, they just do integer
7503   // promotions on each operand. C99 6.5.7p3
7504 
7505   // For the LHS, do usual unary conversions, but then reset them away
7506   // if this is a compound assignment.
7507   ExprResult OldLHS = LHS;
7508   LHS = UsualUnaryConversions(LHS.get());
7509   if (LHS.isInvalid())
7510     return QualType();
7511   QualType LHSType = LHS.get()->getType();
7512   if (IsCompAssign) LHS = OldLHS;
7513 
7514   // The RHS is simpler.
7515   RHS = UsualUnaryConversions(RHS.get());
7516   if (RHS.isInvalid())
7517     return QualType();
7518   QualType RHSType = RHS.get()->getType();
7519 
7520   // C99 6.5.7p2: Each of the operands shall have integer type.
7521   if (!LHSType->hasIntegerRepresentation() ||
7522       !RHSType->hasIntegerRepresentation())
7523     return InvalidOperands(Loc, LHS, RHS);
7524 
7525   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7526   // hasIntegerRepresentation() above instead of this.
7527   if (isScopedEnumerationType(LHSType) ||
7528       isScopedEnumerationType(RHSType)) {
7529     return InvalidOperands(Loc, LHS, RHS);
7530   }
7531   // Sanity-check shift operands
7532   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7533 
7534   // "The type of the result is that of the promoted left operand."
7535   return LHSType;
7536 }
7537 
7538 static bool IsWithinTemplateSpecialization(Decl *D) {
7539   if (DeclContext *DC = D->getDeclContext()) {
7540     if (isa<ClassTemplateSpecializationDecl>(DC))
7541       return true;
7542     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7543       return FD->isFunctionTemplateSpecialization();
7544   }
7545   return false;
7546 }
7547 
7548 /// If two different enums are compared, raise a warning.
7549 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7550                                 Expr *RHS) {
7551   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7552   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7553 
7554   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7555   if (!LHSEnumType)
7556     return;
7557   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7558   if (!RHSEnumType)
7559     return;
7560 
7561   // Ignore anonymous enums.
7562   if (!LHSEnumType->getDecl()->getIdentifier())
7563     return;
7564   if (!RHSEnumType->getDecl()->getIdentifier())
7565     return;
7566 
7567   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7568     return;
7569 
7570   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7571       << LHSStrippedType << RHSStrippedType
7572       << LHS->getSourceRange() << RHS->getSourceRange();
7573 }
7574 
7575 /// \brief Diagnose bad pointer comparisons.
7576 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7577                                               ExprResult &LHS, ExprResult &RHS,
7578                                               bool IsError) {
7579   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7580                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7581     << LHS.get()->getType() << RHS.get()->getType()
7582     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7583 }
7584 
7585 /// \brief Returns false if the pointers are converted to a composite type,
7586 /// true otherwise.
7587 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7588                                            ExprResult &LHS, ExprResult &RHS) {
7589   // C++ [expr.rel]p2:
7590   //   [...] Pointer conversions (4.10) and qualification
7591   //   conversions (4.4) are performed on pointer operands (or on
7592   //   a pointer operand and a null pointer constant) to bring
7593   //   them to their composite pointer type. [...]
7594   //
7595   // C++ [expr.eq]p1 uses the same notion for (in)equality
7596   // comparisons of pointers.
7597 
7598   // C++ [expr.eq]p2:
7599   //   In addition, pointers to members can be compared, or a pointer to
7600   //   member and a null pointer constant. Pointer to member conversions
7601   //   (4.11) and qualification conversions (4.4) are performed to bring
7602   //   them to a common type. If one operand is a null pointer constant,
7603   //   the common type is the type of the other operand. Otherwise, the
7604   //   common type is a pointer to member type similar (4.4) to the type
7605   //   of one of the operands, with a cv-qualification signature (4.4)
7606   //   that is the union of the cv-qualification signatures of the operand
7607   //   types.
7608 
7609   QualType LHSType = LHS.get()->getType();
7610   QualType RHSType = RHS.get()->getType();
7611   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7612          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7613 
7614   bool NonStandardCompositeType = false;
7615   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7616   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7617   if (T.isNull()) {
7618     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7619     return true;
7620   }
7621 
7622   if (NonStandardCompositeType)
7623     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7624       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7625       << RHS.get()->getSourceRange();
7626 
7627   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7628   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7629   return false;
7630 }
7631 
7632 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7633                                                     ExprResult &LHS,
7634                                                     ExprResult &RHS,
7635                                                     bool IsError) {
7636   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7637                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7638     << LHS.get()->getType() << RHS.get()->getType()
7639     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7640 }
7641 
7642 static bool isObjCObjectLiteral(ExprResult &E) {
7643   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7644   case Stmt::ObjCArrayLiteralClass:
7645   case Stmt::ObjCDictionaryLiteralClass:
7646   case Stmt::ObjCStringLiteralClass:
7647   case Stmt::ObjCBoxedExprClass:
7648     return true;
7649   default:
7650     // Note that ObjCBoolLiteral is NOT an object literal!
7651     return false;
7652   }
7653 }
7654 
7655 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7656   const ObjCObjectPointerType *Type =
7657     LHS->getType()->getAs<ObjCObjectPointerType>();
7658 
7659   // If this is not actually an Objective-C object, bail out.
7660   if (!Type)
7661     return false;
7662 
7663   // Get the LHS object's interface type.
7664   QualType InterfaceType = Type->getPointeeType();
7665   if (const ObjCObjectType *iQFaceTy =
7666       InterfaceType->getAsObjCQualifiedInterfaceType())
7667     InterfaceType = iQFaceTy->getBaseType();
7668 
7669   // If the RHS isn't an Objective-C object, bail out.
7670   if (!RHS->getType()->isObjCObjectPointerType())
7671     return false;
7672 
7673   // Try to find the -isEqual: method.
7674   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7675   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7676                                                       InterfaceType,
7677                                                       /*instance=*/true);
7678   if (!Method) {
7679     if (Type->isObjCIdType()) {
7680       // For 'id', just check the global pool.
7681       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7682                                                   /*receiverId=*/true,
7683                                                   /*warn=*/false);
7684     } else {
7685       // Check protocols.
7686       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7687                                              /*instance=*/true);
7688     }
7689   }
7690 
7691   if (!Method)
7692     return false;
7693 
7694   QualType T = Method->parameters()[0]->getType();
7695   if (!T->isObjCObjectPointerType())
7696     return false;
7697 
7698   QualType R = Method->getReturnType();
7699   if (!R->isScalarType())
7700     return false;
7701 
7702   return true;
7703 }
7704 
7705 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7706   FromE = FromE->IgnoreParenImpCasts();
7707   switch (FromE->getStmtClass()) {
7708     default:
7709       break;
7710     case Stmt::ObjCStringLiteralClass:
7711       // "string literal"
7712       return LK_String;
7713     case Stmt::ObjCArrayLiteralClass:
7714       // "array literal"
7715       return LK_Array;
7716     case Stmt::ObjCDictionaryLiteralClass:
7717       // "dictionary literal"
7718       return LK_Dictionary;
7719     case Stmt::BlockExprClass:
7720       return LK_Block;
7721     case Stmt::ObjCBoxedExprClass: {
7722       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7723       switch (Inner->getStmtClass()) {
7724         case Stmt::IntegerLiteralClass:
7725         case Stmt::FloatingLiteralClass:
7726         case Stmt::CharacterLiteralClass:
7727         case Stmt::ObjCBoolLiteralExprClass:
7728         case Stmt::CXXBoolLiteralExprClass:
7729           // "numeric literal"
7730           return LK_Numeric;
7731         case Stmt::ImplicitCastExprClass: {
7732           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7733           // Boolean literals can be represented by implicit casts.
7734           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7735             return LK_Numeric;
7736           break;
7737         }
7738         default:
7739           break;
7740       }
7741       return LK_Boxed;
7742     }
7743   }
7744   return LK_None;
7745 }
7746 
7747 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7748                                           ExprResult &LHS, ExprResult &RHS,
7749                                           BinaryOperator::Opcode Opc){
7750   Expr *Literal;
7751   Expr *Other;
7752   if (isObjCObjectLiteral(LHS)) {
7753     Literal = LHS.get();
7754     Other = RHS.get();
7755   } else {
7756     Literal = RHS.get();
7757     Other = LHS.get();
7758   }
7759 
7760   // Don't warn on comparisons against nil.
7761   Other = Other->IgnoreParenCasts();
7762   if (Other->isNullPointerConstant(S.getASTContext(),
7763                                    Expr::NPC_ValueDependentIsNotNull))
7764     return;
7765 
7766   // This should be kept in sync with warn_objc_literal_comparison.
7767   // LK_String should always be after the other literals, since it has its own
7768   // warning flag.
7769   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7770   assert(LiteralKind != Sema::LK_Block);
7771   if (LiteralKind == Sema::LK_None) {
7772     llvm_unreachable("Unknown Objective-C object literal kind");
7773   }
7774 
7775   if (LiteralKind == Sema::LK_String)
7776     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7777       << Literal->getSourceRange();
7778   else
7779     S.Diag(Loc, diag::warn_objc_literal_comparison)
7780       << LiteralKind << Literal->getSourceRange();
7781 
7782   if (BinaryOperator::isEqualityOp(Opc) &&
7783       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7784     SourceLocation Start = LHS.get()->getLocStart();
7785     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7786     CharSourceRange OpRange =
7787       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7788 
7789     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7790       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7791       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7792       << FixItHint::CreateInsertion(End, "]");
7793   }
7794 }
7795 
7796 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7797                                                 ExprResult &RHS,
7798                                                 SourceLocation Loc,
7799                                                 unsigned OpaqueOpc) {
7800   // This checking requires bools.
7801   if (!S.getLangOpts().Bool) return;
7802 
7803   // Check that left hand side is !something.
7804   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7805   if (!UO || UO->getOpcode() != UO_LNot) return;
7806 
7807   // Only check if the right hand side is non-bool arithmetic type.
7808   if (RHS.get()->getType()->isBooleanType()) return;
7809 
7810   // Make sure that the something in !something is not bool.
7811   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7812   if (SubExpr->getType()->isBooleanType()) return;
7813 
7814   // Emit warning.
7815   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7816       << Loc;
7817 
7818   // First note suggest !(x < y)
7819   SourceLocation FirstOpen = SubExpr->getLocStart();
7820   SourceLocation FirstClose = RHS.get()->getLocEnd();
7821   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7822   if (FirstClose.isInvalid())
7823     FirstOpen = SourceLocation();
7824   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7825       << FixItHint::CreateInsertion(FirstOpen, "(")
7826       << FixItHint::CreateInsertion(FirstClose, ")");
7827 
7828   // Second note suggests (!x) < y
7829   SourceLocation SecondOpen = LHS.get()->getLocStart();
7830   SourceLocation SecondClose = LHS.get()->getLocEnd();
7831   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7832   if (SecondClose.isInvalid())
7833     SecondOpen = SourceLocation();
7834   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7835       << FixItHint::CreateInsertion(SecondOpen, "(")
7836       << FixItHint::CreateInsertion(SecondClose, ")");
7837 }
7838 
7839 // Get the decl for a simple expression: a reference to a variable,
7840 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7841 static ValueDecl *getCompareDecl(Expr *E) {
7842   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7843     return DR->getDecl();
7844   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7845     if (Ivar->isFreeIvar())
7846       return Ivar->getDecl();
7847   }
7848   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7849     if (Mem->isImplicitAccess())
7850       return Mem->getMemberDecl();
7851   }
7852   return nullptr;
7853 }
7854 
7855 // C99 6.5.8, C++ [expr.rel]
7856 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7857                                     SourceLocation Loc, unsigned OpaqueOpc,
7858                                     bool IsRelational) {
7859   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7860 
7861   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7862 
7863   // Handle vector comparisons separately.
7864   if (LHS.get()->getType()->isVectorType() ||
7865       RHS.get()->getType()->isVectorType())
7866     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7867 
7868   QualType LHSType = LHS.get()->getType();
7869   QualType RHSType = RHS.get()->getType();
7870 
7871   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7872   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7873 
7874   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7875   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7876 
7877   if (!LHSType->hasFloatingRepresentation() &&
7878       !(LHSType->isBlockPointerType() && IsRelational) &&
7879       !LHS.get()->getLocStart().isMacroID() &&
7880       !RHS.get()->getLocStart().isMacroID() &&
7881       ActiveTemplateInstantiations.empty()) {
7882     // For non-floating point types, check for self-comparisons of the form
7883     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7884     // often indicate logic errors in the program.
7885     //
7886     // NOTE: Don't warn about comparison expressions resulting from macro
7887     // expansion. Also don't warn about comparisons which are only self
7888     // comparisons within a template specialization. The warnings should catch
7889     // obvious cases in the definition of the template anyways. The idea is to
7890     // warn when the typed comparison operator will always evaluate to the same
7891     // result.
7892     ValueDecl *DL = getCompareDecl(LHSStripped);
7893     ValueDecl *DR = getCompareDecl(RHSStripped);
7894     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7895       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7896                           << 0 // self-
7897                           << (Opc == BO_EQ
7898                               || Opc == BO_LE
7899                               || Opc == BO_GE));
7900     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7901                !DL->getType()->isReferenceType() &&
7902                !DR->getType()->isReferenceType()) {
7903         // what is it always going to eval to?
7904         char always_evals_to;
7905         switch(Opc) {
7906         case BO_EQ: // e.g. array1 == array2
7907           always_evals_to = 0; // false
7908           break;
7909         case BO_NE: // e.g. array1 != array2
7910           always_evals_to = 1; // true
7911           break;
7912         default:
7913           // best we can say is 'a constant'
7914           always_evals_to = 2; // e.g. array1 <= array2
7915           break;
7916         }
7917         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7918                             << 1 // array
7919                             << always_evals_to);
7920     }
7921 
7922     if (isa<CastExpr>(LHSStripped))
7923       LHSStripped = LHSStripped->IgnoreParenCasts();
7924     if (isa<CastExpr>(RHSStripped))
7925       RHSStripped = RHSStripped->IgnoreParenCasts();
7926 
7927     // Warn about comparisons against a string constant (unless the other
7928     // operand is null), the user probably wants strcmp.
7929     Expr *literalString = nullptr;
7930     Expr *literalStringStripped = nullptr;
7931     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7932         !RHSStripped->isNullPointerConstant(Context,
7933                                             Expr::NPC_ValueDependentIsNull)) {
7934       literalString = LHS.get();
7935       literalStringStripped = LHSStripped;
7936     } else if ((isa<StringLiteral>(RHSStripped) ||
7937                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7938                !LHSStripped->isNullPointerConstant(Context,
7939                                             Expr::NPC_ValueDependentIsNull)) {
7940       literalString = RHS.get();
7941       literalStringStripped = RHSStripped;
7942     }
7943 
7944     if (literalString) {
7945       DiagRuntimeBehavior(Loc, nullptr,
7946         PDiag(diag::warn_stringcompare)
7947           << isa<ObjCEncodeExpr>(literalStringStripped)
7948           << literalString->getSourceRange());
7949     }
7950   }
7951 
7952   // C99 6.5.8p3 / C99 6.5.9p4
7953   UsualArithmeticConversions(LHS, RHS);
7954   if (LHS.isInvalid() || RHS.isInvalid())
7955     return QualType();
7956 
7957   LHSType = LHS.get()->getType();
7958   RHSType = RHS.get()->getType();
7959 
7960   // The result of comparisons is 'bool' in C++, 'int' in C.
7961   QualType ResultTy = Context.getLogicalOperationType();
7962 
7963   if (IsRelational) {
7964     if (LHSType->isRealType() && RHSType->isRealType())
7965       return ResultTy;
7966   } else {
7967     // Check for comparisons of floating point operands using != and ==.
7968     if (LHSType->hasFloatingRepresentation())
7969       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7970 
7971     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7972       return ResultTy;
7973   }
7974 
7975   const Expr::NullPointerConstantKind LHSNullKind =
7976       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7977   const Expr::NullPointerConstantKind RHSNullKind =
7978       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7979   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7980   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7981 
7982   if (!IsRelational && LHSIsNull != RHSIsNull) {
7983     bool IsEquality = Opc == BO_EQ;
7984     if (RHSIsNull)
7985       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7986                                    RHS.get()->getSourceRange());
7987     else
7988       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7989                                    LHS.get()->getSourceRange());
7990   }
7991 
7992   // All of the following pointer-related warnings are GCC extensions, except
7993   // when handling null pointer constants.
7994   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7995     QualType LCanPointeeTy =
7996       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7997     QualType RCanPointeeTy =
7998       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7999 
8000     if (getLangOpts().CPlusPlus) {
8001       if (LCanPointeeTy == RCanPointeeTy)
8002         return ResultTy;
8003       if (!IsRelational &&
8004           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8005         // Valid unless comparison between non-null pointer and function pointer
8006         // This is a gcc extension compatibility comparison.
8007         // In a SFINAE context, we treat this as a hard error to maintain
8008         // conformance with the C++ standard.
8009         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8010             && !LHSIsNull && !RHSIsNull) {
8011           diagnoseFunctionPointerToVoidComparison(
8012               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8013 
8014           if (isSFINAEContext())
8015             return QualType();
8016 
8017           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8018           return ResultTy;
8019         }
8020       }
8021 
8022       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8023         return QualType();
8024       else
8025         return ResultTy;
8026     }
8027     // C99 6.5.9p2 and C99 6.5.8p2
8028     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8029                                    RCanPointeeTy.getUnqualifiedType())) {
8030       // Valid unless a relational comparison of function pointers
8031       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8032         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8033           << LHSType << RHSType << LHS.get()->getSourceRange()
8034           << RHS.get()->getSourceRange();
8035       }
8036     } else if (!IsRelational &&
8037                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8038       // Valid unless comparison between non-null pointer and function pointer
8039       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8040           && !LHSIsNull && !RHSIsNull)
8041         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8042                                                 /*isError*/false);
8043     } else {
8044       // Invalid
8045       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8046     }
8047     if (LCanPointeeTy != RCanPointeeTy) {
8048       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8049       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8050       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8051                                                : CK_BitCast;
8052       if (LHSIsNull && !RHSIsNull)
8053         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8054       else
8055         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8056     }
8057     return ResultTy;
8058   }
8059 
8060   if (getLangOpts().CPlusPlus) {
8061     // Comparison of nullptr_t with itself.
8062     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8063       return ResultTy;
8064 
8065     // Comparison of pointers with null pointer constants and equality
8066     // comparisons of member pointers to null pointer constants.
8067     if (RHSIsNull &&
8068         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8069          (!IsRelational &&
8070           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8071       RHS = ImpCastExprToType(RHS.get(), LHSType,
8072                         LHSType->isMemberPointerType()
8073                           ? CK_NullToMemberPointer
8074                           : CK_NullToPointer);
8075       return ResultTy;
8076     }
8077     if (LHSIsNull &&
8078         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8079          (!IsRelational &&
8080           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8081       LHS = ImpCastExprToType(LHS.get(), RHSType,
8082                         RHSType->isMemberPointerType()
8083                           ? CK_NullToMemberPointer
8084                           : CK_NullToPointer);
8085       return ResultTy;
8086     }
8087 
8088     // Comparison of member pointers.
8089     if (!IsRelational &&
8090         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8091       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8092         return QualType();
8093       else
8094         return ResultTy;
8095     }
8096 
8097     // Handle scoped enumeration types specifically, since they don't promote
8098     // to integers.
8099     if (LHS.get()->getType()->isEnumeralType() &&
8100         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8101                                        RHS.get()->getType()))
8102       return ResultTy;
8103   }
8104 
8105   // Handle block pointer types.
8106   if (!IsRelational && LHSType->isBlockPointerType() &&
8107       RHSType->isBlockPointerType()) {
8108     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8109     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8110 
8111     if (!LHSIsNull && !RHSIsNull &&
8112         !Context.typesAreCompatible(lpointee, rpointee)) {
8113       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8114         << LHSType << RHSType << LHS.get()->getSourceRange()
8115         << RHS.get()->getSourceRange();
8116     }
8117     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8118     return ResultTy;
8119   }
8120 
8121   // Allow block pointers to be compared with null pointer constants.
8122   if (!IsRelational
8123       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8124           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8125     if (!LHSIsNull && !RHSIsNull) {
8126       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8127              ->getPointeeType()->isVoidType())
8128             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8129                 ->getPointeeType()->isVoidType())))
8130         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8131           << LHSType << RHSType << LHS.get()->getSourceRange()
8132           << RHS.get()->getSourceRange();
8133     }
8134     if (LHSIsNull && !RHSIsNull)
8135       LHS = ImpCastExprToType(LHS.get(), RHSType,
8136                               RHSType->isPointerType() ? CK_BitCast
8137                                 : CK_AnyPointerToBlockPointerCast);
8138     else
8139       RHS = ImpCastExprToType(RHS.get(), LHSType,
8140                               LHSType->isPointerType() ? CK_BitCast
8141                                 : CK_AnyPointerToBlockPointerCast);
8142     return ResultTy;
8143   }
8144 
8145   if (LHSType->isObjCObjectPointerType() ||
8146       RHSType->isObjCObjectPointerType()) {
8147     const PointerType *LPT = LHSType->getAs<PointerType>();
8148     const PointerType *RPT = RHSType->getAs<PointerType>();
8149     if (LPT || RPT) {
8150       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8151       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8152 
8153       if (!LPtrToVoid && !RPtrToVoid &&
8154           !Context.typesAreCompatible(LHSType, RHSType)) {
8155         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8156                                           /*isError*/false);
8157       }
8158       if (LHSIsNull && !RHSIsNull) {
8159         Expr *E = LHS.get();
8160         if (getLangOpts().ObjCAutoRefCount)
8161           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8162         LHS = ImpCastExprToType(E, RHSType,
8163                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8164       }
8165       else {
8166         Expr *E = RHS.get();
8167         if (getLangOpts().ObjCAutoRefCount)
8168           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8169                                  Opc);
8170         RHS = ImpCastExprToType(E, LHSType,
8171                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8172       }
8173       return ResultTy;
8174     }
8175     if (LHSType->isObjCObjectPointerType() &&
8176         RHSType->isObjCObjectPointerType()) {
8177       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8178         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8179                                           /*isError*/false);
8180       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8181         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8182 
8183       if (LHSIsNull && !RHSIsNull)
8184         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8185       else
8186         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8187       return ResultTy;
8188     }
8189   }
8190   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8191       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8192     unsigned DiagID = 0;
8193     bool isError = false;
8194     if (LangOpts.DebuggerSupport) {
8195       // Under a debugger, allow the comparison of pointers to integers,
8196       // since users tend to want to compare addresses.
8197     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8198         (RHSIsNull && RHSType->isIntegerType())) {
8199       if (IsRelational && !getLangOpts().CPlusPlus)
8200         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8201     } else if (IsRelational && !getLangOpts().CPlusPlus)
8202       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8203     else if (getLangOpts().CPlusPlus) {
8204       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8205       isError = true;
8206     } else
8207       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8208 
8209     if (DiagID) {
8210       Diag(Loc, DiagID)
8211         << LHSType << RHSType << LHS.get()->getSourceRange()
8212         << RHS.get()->getSourceRange();
8213       if (isError)
8214         return QualType();
8215     }
8216 
8217     if (LHSType->isIntegerType())
8218       LHS = ImpCastExprToType(LHS.get(), RHSType,
8219                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8220     else
8221       RHS = ImpCastExprToType(RHS.get(), LHSType,
8222                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8223     return ResultTy;
8224   }
8225 
8226   // Handle block pointers.
8227   if (!IsRelational && RHSIsNull
8228       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8229     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8230     return ResultTy;
8231   }
8232   if (!IsRelational && LHSIsNull
8233       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8234     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8235     return ResultTy;
8236   }
8237 
8238   return InvalidOperands(Loc, LHS, RHS);
8239 }
8240 
8241 
8242 // Return a signed type that is of identical size and number of elements.
8243 // For floating point vectors, return an integer type of identical size
8244 // and number of elements.
8245 QualType Sema::GetSignedVectorType(QualType V) {
8246   const VectorType *VTy = V->getAs<VectorType>();
8247   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8248   if (TypeSize == Context.getTypeSize(Context.CharTy))
8249     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8250   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8251     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8252   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8253     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8254   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8255     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8256   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8257          "Unhandled vector element size in vector compare");
8258   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8259 }
8260 
8261 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8262 /// operates on extended vector types.  Instead of producing an IntTy result,
8263 /// like a scalar comparison, a vector comparison produces a vector of integer
8264 /// types.
8265 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8266                                           SourceLocation Loc,
8267                                           bool IsRelational) {
8268   // Check to make sure we're operating on vectors of the same type and width,
8269   // Allowing one side to be a scalar of element type.
8270   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8271   if (vType.isNull())
8272     return vType;
8273 
8274   QualType LHSType = LHS.get()->getType();
8275 
8276   // If AltiVec, the comparison results in a numeric type, i.e.
8277   // bool for C++, int for C
8278   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8279     return Context.getLogicalOperationType();
8280 
8281   // For non-floating point types, check for self-comparisons of the form
8282   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8283   // often indicate logic errors in the program.
8284   if (!LHSType->hasFloatingRepresentation() &&
8285       ActiveTemplateInstantiations.empty()) {
8286     if (DeclRefExpr* DRL
8287           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8288       if (DeclRefExpr* DRR
8289             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8290         if (DRL->getDecl() == DRR->getDecl())
8291           DiagRuntimeBehavior(Loc, nullptr,
8292                               PDiag(diag::warn_comparison_always)
8293                                 << 0 // self-
8294                                 << 2 // "a constant"
8295                               );
8296   }
8297 
8298   // Check for comparisons of floating point operands using != and ==.
8299   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8300     assert (RHS.get()->getType()->hasFloatingRepresentation());
8301     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8302   }
8303 
8304   // Return a signed type for the vector.
8305   return GetSignedVectorType(LHSType);
8306 }
8307 
8308 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8309                                           SourceLocation Loc) {
8310   // Ensure that either both operands are of the same vector type, or
8311   // one operand is of a vector type and the other is of its element type.
8312   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8313   if (vType.isNull())
8314     return InvalidOperands(Loc, LHS, RHS);
8315   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8316       vType->hasFloatingRepresentation())
8317     return InvalidOperands(Loc, LHS, RHS);
8318 
8319   return GetSignedVectorType(LHS.get()->getType());
8320 }
8321 
8322 inline QualType Sema::CheckBitwiseOperands(
8323   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8324   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8325 
8326   if (LHS.get()->getType()->isVectorType() ||
8327       RHS.get()->getType()->isVectorType()) {
8328     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8329         RHS.get()->getType()->hasIntegerRepresentation())
8330       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8331 
8332     return InvalidOperands(Loc, LHS, RHS);
8333   }
8334 
8335   ExprResult LHSResult = LHS, RHSResult = RHS;
8336   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8337                                                  IsCompAssign);
8338   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8339     return QualType();
8340   LHS = LHSResult.get();
8341   RHS = RHSResult.get();
8342 
8343   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8344     return compType;
8345   return InvalidOperands(Loc, LHS, RHS);
8346 }
8347 
8348 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8349   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8350 
8351   // Check vector operands differently.
8352   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8353     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8354 
8355   // Diagnose cases where the user write a logical and/or but probably meant a
8356   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8357   // is a constant.
8358   if (LHS.get()->getType()->isIntegerType() &&
8359       !LHS.get()->getType()->isBooleanType() &&
8360       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8361       // Don't warn in macros or template instantiations.
8362       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8363     // If the RHS can be constant folded, and if it constant folds to something
8364     // that isn't 0 or 1 (which indicate a potential logical operation that
8365     // happened to fold to true/false) then warn.
8366     // Parens on the RHS are ignored.
8367     llvm::APSInt Result;
8368     if (RHS.get()->EvaluateAsInt(Result, Context))
8369       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8370            !RHS.get()->getExprLoc().isMacroID()) ||
8371           (Result != 0 && Result != 1)) {
8372         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8373           << RHS.get()->getSourceRange()
8374           << (Opc == BO_LAnd ? "&&" : "||");
8375         // Suggest replacing the logical operator with the bitwise version
8376         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8377             << (Opc == BO_LAnd ? "&" : "|")
8378             << FixItHint::CreateReplacement(SourceRange(
8379                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8380                                                 getLangOpts())),
8381                                             Opc == BO_LAnd ? "&" : "|");
8382         if (Opc == BO_LAnd)
8383           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8384           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8385               << FixItHint::CreateRemoval(
8386                   SourceRange(
8387                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8388                                                  0, getSourceManager(),
8389                                                  getLangOpts()),
8390                       RHS.get()->getLocEnd()));
8391       }
8392   }
8393 
8394   if (!Context.getLangOpts().CPlusPlus) {
8395     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8396     // not operate on the built-in scalar and vector float types.
8397     if (Context.getLangOpts().OpenCL &&
8398         Context.getLangOpts().OpenCLVersion < 120) {
8399       if (LHS.get()->getType()->isFloatingType() ||
8400           RHS.get()->getType()->isFloatingType())
8401         return InvalidOperands(Loc, LHS, RHS);
8402     }
8403 
8404     LHS = UsualUnaryConversions(LHS.get());
8405     if (LHS.isInvalid())
8406       return QualType();
8407 
8408     RHS = UsualUnaryConversions(RHS.get());
8409     if (RHS.isInvalid())
8410       return QualType();
8411 
8412     if (!LHS.get()->getType()->isScalarType() ||
8413         !RHS.get()->getType()->isScalarType())
8414       return InvalidOperands(Loc, LHS, RHS);
8415 
8416     return Context.IntTy;
8417   }
8418 
8419   // The following is safe because we only use this method for
8420   // non-overloadable operands.
8421 
8422   // C++ [expr.log.and]p1
8423   // C++ [expr.log.or]p1
8424   // The operands are both contextually converted to type bool.
8425   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8426   if (LHSRes.isInvalid())
8427     return InvalidOperands(Loc, LHS, RHS);
8428   LHS = LHSRes;
8429 
8430   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8431   if (RHSRes.isInvalid())
8432     return InvalidOperands(Loc, LHS, RHS);
8433   RHS = RHSRes;
8434 
8435   // C++ [expr.log.and]p2
8436   // C++ [expr.log.or]p2
8437   // The result is a bool.
8438   return Context.BoolTy;
8439 }
8440 
8441 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8442   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8443   if (!ME) return false;
8444   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8445   ObjCMessageExpr *Base =
8446     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8447   if (!Base) return false;
8448   return Base->getMethodDecl() != nullptr;
8449 }
8450 
8451 /// Is the given expression (which must be 'const') a reference to a
8452 /// variable which was originally non-const, but which has become
8453 /// 'const' due to being captured within a block?
8454 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8455 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8456   assert(E->isLValue() && E->getType().isConstQualified());
8457   E = E->IgnoreParens();
8458 
8459   // Must be a reference to a declaration from an enclosing scope.
8460   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8461   if (!DRE) return NCCK_None;
8462   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8463 
8464   // The declaration must be a variable which is not declared 'const'.
8465   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8466   if (!var) return NCCK_None;
8467   if (var->getType().isConstQualified()) return NCCK_None;
8468   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8469 
8470   // Decide whether the first capture was for a block or a lambda.
8471   DeclContext *DC = S.CurContext, *Prev = nullptr;
8472   while (DC != var->getDeclContext()) {
8473     Prev = DC;
8474     DC = DC->getParent();
8475   }
8476   // Unless we have an init-capture, we've gone one step too far.
8477   if (!var->isInitCapture())
8478     DC = Prev;
8479   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8480 }
8481 
8482 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8483 /// emit an error and return true.  If so, return false.
8484 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8485   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8486   SourceLocation OrigLoc = Loc;
8487   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8488                                                               &Loc);
8489   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8490     IsLV = Expr::MLV_InvalidMessageExpression;
8491   if (IsLV == Expr::MLV_Valid)
8492     return false;
8493 
8494   unsigned Diag = 0;
8495   bool NeedType = false;
8496   switch (IsLV) { // C99 6.5.16p2
8497   case Expr::MLV_ConstQualified:
8498     Diag = diag::err_typecheck_assign_const;
8499 
8500     // Use a specialized diagnostic when we're assigning to an object
8501     // from an enclosing function or block.
8502     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8503       if (NCCK == NCCK_Block)
8504         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8505       else
8506         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8507       break;
8508     }
8509 
8510     // In ARC, use some specialized diagnostics for occasions where we
8511     // infer 'const'.  These are always pseudo-strong variables.
8512     if (S.getLangOpts().ObjCAutoRefCount) {
8513       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8514       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8515         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8516 
8517         // Use the normal diagnostic if it's pseudo-__strong but the
8518         // user actually wrote 'const'.
8519         if (var->isARCPseudoStrong() &&
8520             (!var->getTypeSourceInfo() ||
8521              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8522           // There are two pseudo-strong cases:
8523           //  - self
8524           ObjCMethodDecl *method = S.getCurMethodDecl();
8525           if (method && var == method->getSelfDecl())
8526             Diag = method->isClassMethod()
8527               ? diag::err_typecheck_arc_assign_self_class_method
8528               : diag::err_typecheck_arc_assign_self;
8529 
8530           //  - fast enumeration variables
8531           else
8532             Diag = diag::err_typecheck_arr_assign_enumeration;
8533 
8534           SourceRange Assign;
8535           if (Loc != OrigLoc)
8536             Assign = SourceRange(OrigLoc, OrigLoc);
8537           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8538           // We need to preserve the AST regardless, so migration tool
8539           // can do its job.
8540           return false;
8541         }
8542       }
8543     }
8544 
8545     break;
8546   case Expr::MLV_ArrayType:
8547   case Expr::MLV_ArrayTemporary:
8548     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8549     NeedType = true;
8550     break;
8551   case Expr::MLV_NotObjectType:
8552     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8553     NeedType = true;
8554     break;
8555   case Expr::MLV_LValueCast:
8556     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8557     break;
8558   case Expr::MLV_Valid:
8559     llvm_unreachable("did not take early return for MLV_Valid");
8560   case Expr::MLV_InvalidExpression:
8561   case Expr::MLV_MemberFunction:
8562   case Expr::MLV_ClassTemporary:
8563     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8564     break;
8565   case Expr::MLV_IncompleteType:
8566   case Expr::MLV_IncompleteVoidType:
8567     return S.RequireCompleteType(Loc, E->getType(),
8568              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8569   case Expr::MLV_DuplicateVectorComponents:
8570     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8571     break;
8572   case Expr::MLV_NoSetterProperty:
8573     llvm_unreachable("readonly properties should be processed differently");
8574   case Expr::MLV_InvalidMessageExpression:
8575     Diag = diag::error_readonly_message_assignment;
8576     break;
8577   case Expr::MLV_SubObjCPropertySetting:
8578     Diag = diag::error_no_subobject_property_setting;
8579     break;
8580   }
8581 
8582   SourceRange Assign;
8583   if (Loc != OrigLoc)
8584     Assign = SourceRange(OrigLoc, OrigLoc);
8585   if (NeedType)
8586     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8587   else
8588     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8589   return true;
8590 }
8591 
8592 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8593                                          SourceLocation Loc,
8594                                          Sema &Sema) {
8595   // C / C++ fields
8596   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8597   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8598   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8599     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8600       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8601   }
8602 
8603   // Objective-C instance variables
8604   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8605   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8606   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8607     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8608     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8609     if (RL && RR && RL->getDecl() == RR->getDecl())
8610       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8611   }
8612 }
8613 
8614 // C99 6.5.16.1
8615 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8616                                        SourceLocation Loc,
8617                                        QualType CompoundType) {
8618   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8619 
8620   // Verify that LHS is a modifiable lvalue, and emit error if not.
8621   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8622     return QualType();
8623 
8624   QualType LHSType = LHSExpr->getType();
8625   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8626                                              CompoundType;
8627   AssignConvertType ConvTy;
8628   if (CompoundType.isNull()) {
8629     Expr *RHSCheck = RHS.get();
8630 
8631     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8632 
8633     QualType LHSTy(LHSType);
8634     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8635     if (RHS.isInvalid())
8636       return QualType();
8637     // Special case of NSObject attributes on c-style pointer types.
8638     if (ConvTy == IncompatiblePointer &&
8639         ((Context.isObjCNSObjectType(LHSType) &&
8640           RHSType->isObjCObjectPointerType()) ||
8641          (Context.isObjCNSObjectType(RHSType) &&
8642           LHSType->isObjCObjectPointerType())))
8643       ConvTy = Compatible;
8644 
8645     if (ConvTy == Compatible &&
8646         LHSType->isObjCObjectType())
8647         Diag(Loc, diag::err_objc_object_assignment)
8648           << LHSType;
8649 
8650     // If the RHS is a unary plus or minus, check to see if they = and + are
8651     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8652     // instead of "x += 4".
8653     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8654       RHSCheck = ICE->getSubExpr();
8655     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8656       if ((UO->getOpcode() == UO_Plus ||
8657            UO->getOpcode() == UO_Minus) &&
8658           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8659           // Only if the two operators are exactly adjacent.
8660           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8661           // And there is a space or other character before the subexpr of the
8662           // unary +/-.  We don't want to warn on "x=-1".
8663           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8664           UO->getSubExpr()->getLocStart().isFileID()) {
8665         Diag(Loc, diag::warn_not_compound_assign)
8666           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8667           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8668       }
8669     }
8670 
8671     if (ConvTy == Compatible) {
8672       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8673         // Warn about retain cycles where a block captures the LHS, but
8674         // not if the LHS is a simple variable into which the block is
8675         // being stored...unless that variable can be captured by reference!
8676         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8677         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8678         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8679           checkRetainCycles(LHSExpr, RHS.get());
8680 
8681         // It is safe to assign a weak reference into a strong variable.
8682         // Although this code can still have problems:
8683         //   id x = self.weakProp;
8684         //   id y = self.weakProp;
8685         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8686         // paths through the function. This should be revisited if
8687         // -Wrepeated-use-of-weak is made flow-sensitive.
8688         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
8689                              RHS.get()->getLocStart()))
8690           getCurFunction()->markSafeWeakUse(RHS.get());
8691 
8692       } else if (getLangOpts().ObjCAutoRefCount) {
8693         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8694       }
8695     }
8696   } else {
8697     // Compound assignment "x += y"
8698     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8699   }
8700 
8701   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8702                                RHS.get(), AA_Assigning))
8703     return QualType();
8704 
8705   CheckForNullPointerDereference(*this, LHSExpr);
8706 
8707   // C99 6.5.16p3: The type of an assignment expression is the type of the
8708   // left operand unless the left operand has qualified type, in which case
8709   // it is the unqualified version of the type of the left operand.
8710   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8711   // is converted to the type of the assignment expression (above).
8712   // C++ 5.17p1: the type of the assignment expression is that of its left
8713   // operand.
8714   return (getLangOpts().CPlusPlus
8715           ? LHSType : LHSType.getUnqualifiedType());
8716 }
8717 
8718 // C99 6.5.17
8719 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8720                                    SourceLocation Loc) {
8721   LHS = S.CheckPlaceholderExpr(LHS.get());
8722   RHS = S.CheckPlaceholderExpr(RHS.get());
8723   if (LHS.isInvalid() || RHS.isInvalid())
8724     return QualType();
8725 
8726   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8727   // operands, but not unary promotions.
8728   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8729 
8730   // So we treat the LHS as a ignored value, and in C++ we allow the
8731   // containing site to determine what should be done with the RHS.
8732   LHS = S.IgnoredValueConversions(LHS.get());
8733   if (LHS.isInvalid())
8734     return QualType();
8735 
8736   S.DiagnoseUnusedExprResult(LHS.get());
8737 
8738   if (!S.getLangOpts().CPlusPlus) {
8739     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8740     if (RHS.isInvalid())
8741       return QualType();
8742     if (!RHS.get()->getType()->isVoidType())
8743       S.RequireCompleteType(Loc, RHS.get()->getType(),
8744                             diag::err_incomplete_type);
8745   }
8746 
8747   return RHS.get()->getType();
8748 }
8749 
8750 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8751 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8752 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8753                                                ExprValueKind &VK,
8754                                                ExprObjectKind &OK,
8755                                                SourceLocation OpLoc,
8756                                                bool IsInc, bool IsPrefix) {
8757   if (Op->isTypeDependent())
8758     return S.Context.DependentTy;
8759 
8760   QualType ResType = Op->getType();
8761   // Atomic types can be used for increment / decrement where the non-atomic
8762   // versions can, so ignore the _Atomic() specifier for the purpose of
8763   // checking.
8764   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8765     ResType = ResAtomicType->getValueType();
8766 
8767   assert(!ResType.isNull() && "no type for increment/decrement expression");
8768 
8769   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8770     // Decrement of bool is not allowed.
8771     if (!IsInc) {
8772       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8773       return QualType();
8774     }
8775     // Increment of bool sets it to true, but is deprecated.
8776     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8777   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8778     // Error on enum increments and decrements in C++ mode
8779     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8780     return QualType();
8781   } else if (ResType->isRealType()) {
8782     // OK!
8783   } else if (ResType->isPointerType()) {
8784     // C99 6.5.2.4p2, 6.5.6p2
8785     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8786       return QualType();
8787   } else if (ResType->isObjCObjectPointerType()) {
8788     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8789     // Otherwise, we just need a complete type.
8790     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8791         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8792       return QualType();
8793   } else if (ResType->isAnyComplexType()) {
8794     // C99 does not support ++/-- on complex types, we allow as an extension.
8795     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8796       << ResType << Op->getSourceRange();
8797   } else if (ResType->isPlaceholderType()) {
8798     ExprResult PR = S.CheckPlaceholderExpr(Op);
8799     if (PR.isInvalid()) return QualType();
8800     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
8801                                           IsInc, IsPrefix);
8802   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8803     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8804   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8805             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8806     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8807   } else {
8808     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8809       << ResType << int(IsInc) << Op->getSourceRange();
8810     return QualType();
8811   }
8812   // At this point, we know we have a real, complex or pointer type.
8813   // Now make sure the operand is a modifiable lvalue.
8814   if (CheckForModifiableLvalue(Op, OpLoc, S))
8815     return QualType();
8816   // In C++, a prefix increment is the same type as the operand. Otherwise
8817   // (in C or with postfix), the increment is the unqualified type of the
8818   // operand.
8819   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8820     VK = VK_LValue;
8821     OK = Op->getObjectKind();
8822     return ResType;
8823   } else {
8824     VK = VK_RValue;
8825     return ResType.getUnqualifiedType();
8826   }
8827 }
8828 
8829 
8830 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8831 /// This routine allows us to typecheck complex/recursive expressions
8832 /// where the declaration is needed for type checking. We only need to
8833 /// handle cases when the expression references a function designator
8834 /// or is an lvalue. Here are some examples:
8835 ///  - &(x) => x
8836 ///  - &*****f => f for f a function designator.
8837 ///  - &s.xx => s
8838 ///  - &s.zz[1].yy -> s, if zz is an array
8839 ///  - *(x + 1) -> x, if x is an array
8840 ///  - &"123"[2] -> 0
8841 ///  - & __real__ x -> x
8842 static ValueDecl *getPrimaryDecl(Expr *E) {
8843   switch (E->getStmtClass()) {
8844   case Stmt::DeclRefExprClass:
8845     return cast<DeclRefExpr>(E)->getDecl();
8846   case Stmt::MemberExprClass:
8847     // If this is an arrow operator, the address is an offset from
8848     // the base's value, so the object the base refers to is
8849     // irrelevant.
8850     if (cast<MemberExpr>(E)->isArrow())
8851       return nullptr;
8852     // Otherwise, the expression refers to a part of the base
8853     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8854   case Stmt::ArraySubscriptExprClass: {
8855     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8856     // promotion of register arrays earlier.
8857     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8858     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8859       if (ICE->getSubExpr()->getType()->isArrayType())
8860         return getPrimaryDecl(ICE->getSubExpr());
8861     }
8862     return nullptr;
8863   }
8864   case Stmt::UnaryOperatorClass: {
8865     UnaryOperator *UO = cast<UnaryOperator>(E);
8866 
8867     switch(UO->getOpcode()) {
8868     case UO_Real:
8869     case UO_Imag:
8870     case UO_Extension:
8871       return getPrimaryDecl(UO->getSubExpr());
8872     default:
8873       return nullptr;
8874     }
8875   }
8876   case Stmt::ParenExprClass:
8877     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8878   case Stmt::ImplicitCastExprClass:
8879     // If the result of an implicit cast is an l-value, we care about
8880     // the sub-expression; otherwise, the result here doesn't matter.
8881     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8882   default:
8883     return nullptr;
8884   }
8885 }
8886 
8887 namespace {
8888   enum {
8889     AO_Bit_Field = 0,
8890     AO_Vector_Element = 1,
8891     AO_Property_Expansion = 2,
8892     AO_Register_Variable = 3,
8893     AO_No_Error = 4
8894   };
8895 }
8896 /// \brief Diagnose invalid operand for address of operations.
8897 ///
8898 /// \param Type The type of operand which cannot have its address taken.
8899 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8900                                          Expr *E, unsigned Type) {
8901   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8902 }
8903 
8904 /// CheckAddressOfOperand - The operand of & must be either a function
8905 /// designator or an lvalue designating an object. If it is an lvalue, the
8906 /// object cannot be declared with storage class register or be a bit field.
8907 /// Note: The usual conversions are *not* applied to the operand of the &
8908 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8909 /// In C++, the operand might be an overloaded function name, in which case
8910 /// we allow the '&' but retain the overloaded-function type.
8911 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8912   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8913     if (PTy->getKind() == BuiltinType::Overload) {
8914       Expr *E = OrigOp.get()->IgnoreParens();
8915       if (!isa<OverloadExpr>(E)) {
8916         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8917         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8918           << OrigOp.get()->getSourceRange();
8919         return QualType();
8920       }
8921 
8922       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8923       if (isa<UnresolvedMemberExpr>(Ovl))
8924         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8925           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8926             << OrigOp.get()->getSourceRange();
8927           return QualType();
8928         }
8929 
8930       return Context.OverloadTy;
8931     }
8932 
8933     if (PTy->getKind() == BuiltinType::UnknownAny)
8934       return Context.UnknownAnyTy;
8935 
8936     if (PTy->getKind() == BuiltinType::BoundMember) {
8937       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8938         << OrigOp.get()->getSourceRange();
8939       return QualType();
8940     }
8941 
8942     OrigOp = CheckPlaceholderExpr(OrigOp.get());
8943     if (OrigOp.isInvalid()) return QualType();
8944   }
8945 
8946   if (OrigOp.get()->isTypeDependent())
8947     return Context.DependentTy;
8948 
8949   assert(!OrigOp.get()->getType()->isPlaceholderType());
8950 
8951   // Make sure to ignore parentheses in subsequent checks
8952   Expr *op = OrigOp.get()->IgnoreParens();
8953 
8954   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8955   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8956     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8957     return QualType();
8958   }
8959 
8960   if (getLangOpts().C99) {
8961     // Implement C99-only parts of addressof rules.
8962     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8963       if (uOp->getOpcode() == UO_Deref)
8964         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8965         // (assuming the deref expression is valid).
8966         return uOp->getSubExpr()->getType();
8967     }
8968     // Technically, there should be a check for array subscript
8969     // expressions here, but the result of one is always an lvalue anyway.
8970   }
8971   ValueDecl *dcl = getPrimaryDecl(op);
8972   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8973   unsigned AddressOfError = AO_No_Error;
8974 
8975   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8976     bool sfinae = (bool)isSFINAEContext();
8977     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8978                                   : diag::ext_typecheck_addrof_temporary)
8979       << op->getType() << op->getSourceRange();
8980     if (sfinae)
8981       return QualType();
8982     // Materialize the temporary as an lvalue so that we can take its address.
8983     OrigOp = op = new (Context)
8984         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
8985   } else if (isa<ObjCSelectorExpr>(op)) {
8986     return Context.getPointerType(op->getType());
8987   } else if (lval == Expr::LV_MemberFunction) {
8988     // If it's an instance method, make a member pointer.
8989     // The expression must have exactly the form &A::foo.
8990 
8991     // If the underlying expression isn't a decl ref, give up.
8992     if (!isa<DeclRefExpr>(op)) {
8993       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8994         << OrigOp.get()->getSourceRange();
8995       return QualType();
8996     }
8997     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8998     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8999 
9000     // The id-expression was parenthesized.
9001     if (OrigOp.get() != DRE) {
9002       Diag(OpLoc, diag::err_parens_pointer_member_function)
9003         << OrigOp.get()->getSourceRange();
9004 
9005     // The method was named without a qualifier.
9006     } else if (!DRE->getQualifier()) {
9007       if (MD->getParent()->getName().empty())
9008         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9009           << op->getSourceRange();
9010       else {
9011         SmallString<32> Str;
9012         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9013         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9014           << op->getSourceRange()
9015           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9016       }
9017     }
9018 
9019     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9020     if (isa<CXXDestructorDecl>(MD))
9021       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9022 
9023     QualType MPTy = Context.getMemberPointerType(
9024         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9025     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9026       RequireCompleteType(OpLoc, MPTy, 0);
9027     return MPTy;
9028   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9029     // C99 6.5.3.2p1
9030     // The operand must be either an l-value or a function designator
9031     if (!op->getType()->isFunctionType()) {
9032       // Use a special diagnostic for loads from property references.
9033       if (isa<PseudoObjectExpr>(op)) {
9034         AddressOfError = AO_Property_Expansion;
9035       } else {
9036         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9037           << op->getType() << op->getSourceRange();
9038         return QualType();
9039       }
9040     }
9041   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9042     // The operand cannot be a bit-field
9043     AddressOfError = AO_Bit_Field;
9044   } else if (op->getObjectKind() == OK_VectorComponent) {
9045     // The operand cannot be an element of a vector
9046     AddressOfError = AO_Vector_Element;
9047   } else if (dcl) { // C99 6.5.3.2p1
9048     // We have an lvalue with a decl. Make sure the decl is not declared
9049     // with the register storage-class specifier.
9050     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9051       // in C++ it is not error to take address of a register
9052       // variable (c++03 7.1.1P3)
9053       if (vd->getStorageClass() == SC_Register &&
9054           !getLangOpts().CPlusPlus) {
9055         AddressOfError = AO_Register_Variable;
9056       }
9057     } else if (isa<FunctionTemplateDecl>(dcl)) {
9058       return Context.OverloadTy;
9059     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9060       // Okay: we can take the address of a field.
9061       // Could be a pointer to member, though, if there is an explicit
9062       // scope qualifier for the class.
9063       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9064         DeclContext *Ctx = dcl->getDeclContext();
9065         if (Ctx && Ctx->isRecord()) {
9066           if (dcl->getType()->isReferenceType()) {
9067             Diag(OpLoc,
9068                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9069               << dcl->getDeclName() << dcl->getType();
9070             return QualType();
9071           }
9072 
9073           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9074             Ctx = Ctx->getParent();
9075 
9076           QualType MPTy = Context.getMemberPointerType(
9077               op->getType(),
9078               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9079           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9080             RequireCompleteType(OpLoc, MPTy, 0);
9081           return MPTy;
9082         }
9083       }
9084     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9085       llvm_unreachable("Unknown/unexpected decl type");
9086   }
9087 
9088   if (AddressOfError != AO_No_Error) {
9089     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9090     return QualType();
9091   }
9092 
9093   if (lval == Expr::LV_IncompleteVoidType) {
9094     // Taking the address of a void variable is technically illegal, but we
9095     // allow it in cases which are otherwise valid.
9096     // Example: "extern void x; void* y = &x;".
9097     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9098   }
9099 
9100   // If the operand has type "type", the result has type "pointer to type".
9101   if (op->getType()->isObjCObjectType())
9102     return Context.getObjCObjectPointerType(op->getType());
9103   return Context.getPointerType(op->getType());
9104 }
9105 
9106 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9107 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9108                                         SourceLocation OpLoc) {
9109   if (Op->isTypeDependent())
9110     return S.Context.DependentTy;
9111 
9112   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9113   if (ConvResult.isInvalid())
9114     return QualType();
9115   Op = ConvResult.get();
9116   QualType OpTy = Op->getType();
9117   QualType Result;
9118 
9119   if (isa<CXXReinterpretCastExpr>(Op)) {
9120     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9121     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9122                                      Op->getSourceRange());
9123   }
9124 
9125   if (const PointerType *PT = OpTy->getAs<PointerType>())
9126     Result = PT->getPointeeType();
9127   else if (const ObjCObjectPointerType *OPT =
9128              OpTy->getAs<ObjCObjectPointerType>())
9129     Result = OPT->getPointeeType();
9130   else {
9131     ExprResult PR = S.CheckPlaceholderExpr(Op);
9132     if (PR.isInvalid()) return QualType();
9133     if (PR.get() != Op)
9134       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9135   }
9136 
9137   if (Result.isNull()) {
9138     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9139       << OpTy << Op->getSourceRange();
9140     return QualType();
9141   }
9142 
9143   // Note that per both C89 and C99, indirection is always legal, even if Result
9144   // is an incomplete type or void.  It would be possible to warn about
9145   // dereferencing a void pointer, but it's completely well-defined, and such a
9146   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9147   // for pointers to 'void' but is fine for any other pointer type:
9148   //
9149   // C++ [expr.unary.op]p1:
9150   //   [...] the expression to which [the unary * operator] is applied shall
9151   //   be a pointer to an object type, or a pointer to a function type
9152   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9153     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9154       << OpTy << Op->getSourceRange();
9155 
9156   // Dereferences are usually l-values...
9157   VK = VK_LValue;
9158 
9159   // ...except that certain expressions are never l-values in C.
9160   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9161     VK = VK_RValue;
9162 
9163   return Result;
9164 }
9165 
9166 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9167   tok::TokenKind Kind) {
9168   BinaryOperatorKind Opc;
9169   switch (Kind) {
9170   default: llvm_unreachable("Unknown binop!");
9171   case tok::periodstar:           Opc = BO_PtrMemD; break;
9172   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9173   case tok::star:                 Opc = BO_Mul; break;
9174   case tok::slash:                Opc = BO_Div; break;
9175   case tok::percent:              Opc = BO_Rem; break;
9176   case tok::plus:                 Opc = BO_Add; break;
9177   case tok::minus:                Opc = BO_Sub; break;
9178   case tok::lessless:             Opc = BO_Shl; break;
9179   case tok::greatergreater:       Opc = BO_Shr; break;
9180   case tok::lessequal:            Opc = BO_LE; break;
9181   case tok::less:                 Opc = BO_LT; break;
9182   case tok::greaterequal:         Opc = BO_GE; break;
9183   case tok::greater:              Opc = BO_GT; break;
9184   case tok::exclaimequal:         Opc = BO_NE; break;
9185   case tok::equalequal:           Opc = BO_EQ; break;
9186   case tok::amp:                  Opc = BO_And; break;
9187   case tok::caret:                Opc = BO_Xor; break;
9188   case tok::pipe:                 Opc = BO_Or; break;
9189   case tok::ampamp:               Opc = BO_LAnd; break;
9190   case tok::pipepipe:             Opc = BO_LOr; break;
9191   case tok::equal:                Opc = BO_Assign; break;
9192   case tok::starequal:            Opc = BO_MulAssign; break;
9193   case tok::slashequal:           Opc = BO_DivAssign; break;
9194   case tok::percentequal:         Opc = BO_RemAssign; break;
9195   case tok::plusequal:            Opc = BO_AddAssign; break;
9196   case tok::minusequal:           Opc = BO_SubAssign; break;
9197   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9198   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9199   case tok::ampequal:             Opc = BO_AndAssign; break;
9200   case tok::caretequal:           Opc = BO_XorAssign; break;
9201   case tok::pipeequal:            Opc = BO_OrAssign; break;
9202   case tok::comma:                Opc = BO_Comma; break;
9203   }
9204   return Opc;
9205 }
9206 
9207 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9208   tok::TokenKind Kind) {
9209   UnaryOperatorKind Opc;
9210   switch (Kind) {
9211   default: llvm_unreachable("Unknown unary op!");
9212   case tok::plusplus:     Opc = UO_PreInc; break;
9213   case tok::minusminus:   Opc = UO_PreDec; break;
9214   case tok::amp:          Opc = UO_AddrOf; break;
9215   case tok::star:         Opc = UO_Deref; break;
9216   case tok::plus:         Opc = UO_Plus; break;
9217   case tok::minus:        Opc = UO_Minus; break;
9218   case tok::tilde:        Opc = UO_Not; break;
9219   case tok::exclaim:      Opc = UO_LNot; break;
9220   case tok::kw___real:    Opc = UO_Real; break;
9221   case tok::kw___imag:    Opc = UO_Imag; break;
9222   case tok::kw___extension__: Opc = UO_Extension; break;
9223   }
9224   return Opc;
9225 }
9226 
9227 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9228 /// This warning is only emitted for builtin assignment operations. It is also
9229 /// suppressed in the event of macro expansions.
9230 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9231                                    SourceLocation OpLoc) {
9232   if (!S.ActiveTemplateInstantiations.empty())
9233     return;
9234   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9235     return;
9236   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9237   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9238   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9239   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9240   if (!LHSDeclRef || !RHSDeclRef ||
9241       LHSDeclRef->getLocation().isMacroID() ||
9242       RHSDeclRef->getLocation().isMacroID())
9243     return;
9244   const ValueDecl *LHSDecl =
9245     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9246   const ValueDecl *RHSDecl =
9247     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9248   if (LHSDecl != RHSDecl)
9249     return;
9250   if (LHSDecl->getType().isVolatileQualified())
9251     return;
9252   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9253     if (RefTy->getPointeeType().isVolatileQualified())
9254       return;
9255 
9256   S.Diag(OpLoc, diag::warn_self_assignment)
9257       << LHSDeclRef->getType()
9258       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9259 }
9260 
9261 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9262 /// is usually indicative of introspection within the Objective-C pointer.
9263 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9264                                           SourceLocation OpLoc) {
9265   if (!S.getLangOpts().ObjC1)
9266     return;
9267 
9268   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9269   const Expr *LHS = L.get();
9270   const Expr *RHS = R.get();
9271 
9272   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9273     ObjCPointerExpr = LHS;
9274     OtherExpr = RHS;
9275   }
9276   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9277     ObjCPointerExpr = RHS;
9278     OtherExpr = LHS;
9279   }
9280 
9281   // This warning is deliberately made very specific to reduce false
9282   // positives with logic that uses '&' for hashing.  This logic mainly
9283   // looks for code trying to introspect into tagged pointers, which
9284   // code should generally never do.
9285   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9286     unsigned Diag = diag::warn_objc_pointer_masking;
9287     // Determine if we are introspecting the result of performSelectorXXX.
9288     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9289     // Special case messages to -performSelector and friends, which
9290     // can return non-pointer values boxed in a pointer value.
9291     // Some clients may wish to silence warnings in this subcase.
9292     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9293       Selector S = ME->getSelector();
9294       StringRef SelArg0 = S.getNameForSlot(0);
9295       if (SelArg0.startswith("performSelector"))
9296         Diag = diag::warn_objc_pointer_masking_performSelector;
9297     }
9298 
9299     S.Diag(OpLoc, Diag)
9300       << ObjCPointerExpr->getSourceRange();
9301   }
9302 }
9303 
9304 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9305 /// operator @p Opc at location @c TokLoc. This routine only supports
9306 /// built-in operations; ActOnBinOp handles overloaded operators.
9307 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9308                                     BinaryOperatorKind Opc,
9309                                     Expr *LHSExpr, Expr *RHSExpr) {
9310   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9311     // The syntax only allows initializer lists on the RHS of assignment,
9312     // so we don't need to worry about accepting invalid code for
9313     // non-assignment operators.
9314     // C++11 5.17p9:
9315     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9316     //   of x = {} is x = T().
9317     InitializationKind Kind =
9318         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9319     InitializedEntity Entity =
9320         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9321     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9322     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9323     if (Init.isInvalid())
9324       return Init;
9325     RHSExpr = Init.get();
9326   }
9327 
9328   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9329   QualType ResultTy;     // Result type of the binary operator.
9330   // The following two variables are used for compound assignment operators
9331   QualType CompLHSTy;    // Type of LHS after promotions for computation
9332   QualType CompResultTy; // Type of computation result
9333   ExprValueKind VK = VK_RValue;
9334   ExprObjectKind OK = OK_Ordinary;
9335 
9336   switch (Opc) {
9337   case BO_Assign:
9338     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9339     if (getLangOpts().CPlusPlus &&
9340         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9341       VK = LHS.get()->getValueKind();
9342       OK = LHS.get()->getObjectKind();
9343     }
9344     if (!ResultTy.isNull())
9345       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9346     break;
9347   case BO_PtrMemD:
9348   case BO_PtrMemI:
9349     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9350                                             Opc == BO_PtrMemI);
9351     break;
9352   case BO_Mul:
9353   case BO_Div:
9354     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9355                                            Opc == BO_Div);
9356     break;
9357   case BO_Rem:
9358     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9359     break;
9360   case BO_Add:
9361     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9362     break;
9363   case BO_Sub:
9364     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9365     break;
9366   case BO_Shl:
9367   case BO_Shr:
9368     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9369     break;
9370   case BO_LE:
9371   case BO_LT:
9372   case BO_GE:
9373   case BO_GT:
9374     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9375     break;
9376   case BO_EQ:
9377   case BO_NE:
9378     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9379     break;
9380   case BO_And:
9381     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9382   case BO_Xor:
9383   case BO_Or:
9384     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9385     break;
9386   case BO_LAnd:
9387   case BO_LOr:
9388     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9389     break;
9390   case BO_MulAssign:
9391   case BO_DivAssign:
9392     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9393                                                Opc == BO_DivAssign);
9394     CompLHSTy = CompResultTy;
9395     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9396       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9397     break;
9398   case BO_RemAssign:
9399     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9400     CompLHSTy = CompResultTy;
9401     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9402       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9403     break;
9404   case BO_AddAssign:
9405     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9406     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9407       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9408     break;
9409   case BO_SubAssign:
9410     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9411     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9412       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9413     break;
9414   case BO_ShlAssign:
9415   case BO_ShrAssign:
9416     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9417     CompLHSTy = CompResultTy;
9418     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9419       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9420     break;
9421   case BO_AndAssign:
9422   case BO_OrAssign: // fallthrough
9423 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9424   case BO_XorAssign:
9425     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9426     CompLHSTy = CompResultTy;
9427     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9428       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9429     break;
9430   case BO_Comma:
9431     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9432     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9433       VK = RHS.get()->getValueKind();
9434       OK = RHS.get()->getObjectKind();
9435     }
9436     break;
9437   }
9438   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9439     return ExprError();
9440 
9441   // Check for array bounds violations for both sides of the BinaryOperator
9442   CheckArrayAccess(LHS.get());
9443   CheckArrayAccess(RHS.get());
9444 
9445   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9446     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9447                                                  &Context.Idents.get("object_setClass"),
9448                                                  SourceLocation(), LookupOrdinaryName);
9449     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9450       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9451       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9452       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9453       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9454       FixItHint::CreateInsertion(RHSLocEnd, ")");
9455     }
9456     else
9457       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9458   }
9459   else if (const ObjCIvarRefExpr *OIRE =
9460            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9461     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9462 
9463   if (CompResultTy.isNull())
9464     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9465                                         OK, OpLoc, FPFeatures.fp_contract);
9466   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9467       OK_ObjCProperty) {
9468     VK = VK_LValue;
9469     OK = LHS.get()->getObjectKind();
9470   }
9471   return new (Context) CompoundAssignOperator(
9472       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9473       OpLoc, FPFeatures.fp_contract);
9474 }
9475 
9476 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9477 /// operators are mixed in a way that suggests that the programmer forgot that
9478 /// comparison operators have higher precedence. The most typical example of
9479 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9480 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9481                                       SourceLocation OpLoc, Expr *LHSExpr,
9482                                       Expr *RHSExpr) {
9483   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9484   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9485 
9486   // Check that one of the sides is a comparison operator.
9487   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9488   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9489   if (!isLeftComp && !isRightComp)
9490     return;
9491 
9492   // Bitwise operations are sometimes used as eager logical ops.
9493   // Don't diagnose this.
9494   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9495   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9496   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9497     return;
9498 
9499   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9500                                                    OpLoc)
9501                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9502   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9503   SourceRange ParensRange = isLeftComp ?
9504       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9505     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
9506 
9507   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9508     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9509   SuggestParentheses(Self, OpLoc,
9510     Self.PDiag(diag::note_precedence_silence) << OpStr,
9511     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9512   SuggestParentheses(Self, OpLoc,
9513     Self.PDiag(diag::note_precedence_bitwise_first)
9514       << BinaryOperator::getOpcodeStr(Opc),
9515     ParensRange);
9516 }
9517 
9518 /// \brief It accepts a '&' expr that is inside a '|' one.
9519 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9520 /// in parentheses.
9521 static void
9522 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9523                                        BinaryOperator *Bop) {
9524   assert(Bop->getOpcode() == BO_And);
9525   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9526       << Bop->getSourceRange() << OpLoc;
9527   SuggestParentheses(Self, Bop->getOperatorLoc(),
9528     Self.PDiag(diag::note_precedence_silence)
9529       << Bop->getOpcodeStr(),
9530     Bop->getSourceRange());
9531 }
9532 
9533 /// \brief It accepts a '&&' expr that is inside a '||' one.
9534 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9535 /// in parentheses.
9536 static void
9537 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9538                                        BinaryOperator *Bop) {
9539   assert(Bop->getOpcode() == BO_LAnd);
9540   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9541       << Bop->getSourceRange() << OpLoc;
9542   SuggestParentheses(Self, Bop->getOperatorLoc(),
9543     Self.PDiag(diag::note_precedence_silence)
9544       << Bop->getOpcodeStr(),
9545     Bop->getSourceRange());
9546 }
9547 
9548 /// \brief Returns true if the given expression can be evaluated as a constant
9549 /// 'true'.
9550 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9551   bool Res;
9552   return !E->isValueDependent() &&
9553          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9554 }
9555 
9556 /// \brief Returns true if the given expression can be evaluated as a constant
9557 /// 'false'.
9558 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9559   bool Res;
9560   return !E->isValueDependent() &&
9561          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9562 }
9563 
9564 /// \brief Look for '&&' in the left hand of a '||' expr.
9565 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9566                                              Expr *LHSExpr, Expr *RHSExpr) {
9567   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9568     if (Bop->getOpcode() == BO_LAnd) {
9569       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9570       if (EvaluatesAsFalse(S, RHSExpr))
9571         return;
9572       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9573       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9574         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9575     } else if (Bop->getOpcode() == BO_LOr) {
9576       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9577         // If it's "a || b && 1 || c" we didn't warn earlier for
9578         // "a || b && 1", but warn now.
9579         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9580           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9581       }
9582     }
9583   }
9584 }
9585 
9586 /// \brief Look for '&&' in the right hand of a '||' expr.
9587 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9588                                              Expr *LHSExpr, Expr *RHSExpr) {
9589   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9590     if (Bop->getOpcode() == BO_LAnd) {
9591       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9592       if (EvaluatesAsFalse(S, LHSExpr))
9593         return;
9594       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9595       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9596         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9597     }
9598   }
9599 }
9600 
9601 /// \brief Look for '&' in the left or right hand of a '|' expr.
9602 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9603                                              Expr *OrArg) {
9604   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9605     if (Bop->getOpcode() == BO_And)
9606       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9607   }
9608 }
9609 
9610 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9611                                     Expr *SubExpr, StringRef Shift) {
9612   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9613     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9614       StringRef Op = Bop->getOpcodeStr();
9615       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9616           << Bop->getSourceRange() << OpLoc << Shift << Op;
9617       SuggestParentheses(S, Bop->getOperatorLoc(),
9618           S.PDiag(diag::note_precedence_silence) << Op,
9619           Bop->getSourceRange());
9620     }
9621   }
9622 }
9623 
9624 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9625                                  Expr *LHSExpr, Expr *RHSExpr) {
9626   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9627   if (!OCE)
9628     return;
9629 
9630   FunctionDecl *FD = OCE->getDirectCallee();
9631   if (!FD || !FD->isOverloadedOperator())
9632     return;
9633 
9634   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9635   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9636     return;
9637 
9638   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9639       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9640       << (Kind == OO_LessLess);
9641   SuggestParentheses(S, OCE->getOperatorLoc(),
9642                      S.PDiag(diag::note_precedence_silence)
9643                          << (Kind == OO_LessLess ? "<<" : ">>"),
9644                      OCE->getSourceRange());
9645   SuggestParentheses(S, OpLoc,
9646                      S.PDiag(diag::note_evaluate_comparison_first),
9647                      SourceRange(OCE->getArg(1)->getLocStart(),
9648                                  RHSExpr->getLocEnd()));
9649 }
9650 
9651 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9652 /// precedence.
9653 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9654                                     SourceLocation OpLoc, Expr *LHSExpr,
9655                                     Expr *RHSExpr){
9656   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9657   if (BinaryOperator::isBitwiseOp(Opc))
9658     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9659 
9660   // Diagnose "arg1 & arg2 | arg3"
9661   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9662     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9663     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9664   }
9665 
9666   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9667   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9668   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9669     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9670     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9671   }
9672 
9673   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9674       || Opc == BO_Shr) {
9675     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9676     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9677     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9678   }
9679 
9680   // Warn on overloaded shift operators and comparisons, such as:
9681   // cout << 5 == 4;
9682   if (BinaryOperator::isComparisonOp(Opc))
9683     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9684 }
9685 
9686 // Binary Operators.  'Tok' is the token for the operator.
9687 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9688                             tok::TokenKind Kind,
9689                             Expr *LHSExpr, Expr *RHSExpr) {
9690   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9691   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9692   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9693 
9694   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9695   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9696 
9697   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9698 }
9699 
9700 /// Build an overloaded binary operator expression in the given scope.
9701 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9702                                        BinaryOperatorKind Opc,
9703                                        Expr *LHS, Expr *RHS) {
9704   // Find all of the overloaded operators visible from this
9705   // point. We perform both an operator-name lookup from the local
9706   // scope and an argument-dependent lookup based on the types of
9707   // the arguments.
9708   UnresolvedSet<16> Functions;
9709   OverloadedOperatorKind OverOp
9710     = BinaryOperator::getOverloadedOperator(Opc);
9711   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
9712     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9713                                    RHS->getType(), Functions);
9714 
9715   // Build the (potentially-overloaded, potentially-dependent)
9716   // binary operation.
9717   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9718 }
9719 
9720 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9721                             BinaryOperatorKind Opc,
9722                             Expr *LHSExpr, Expr *RHSExpr) {
9723   // We want to end up calling one of checkPseudoObjectAssignment
9724   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9725   // both expressions are overloadable or either is type-dependent),
9726   // or CreateBuiltinBinOp (in any other case).  We also want to get
9727   // any placeholder types out of the way.
9728 
9729   // Handle pseudo-objects in the LHS.
9730   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9731     // Assignments with a pseudo-object l-value need special analysis.
9732     if (pty->getKind() == BuiltinType::PseudoObject &&
9733         BinaryOperator::isAssignmentOp(Opc))
9734       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9735 
9736     // Don't resolve overloads if the other type is overloadable.
9737     if (pty->getKind() == BuiltinType::Overload) {
9738       // We can't actually test that if we still have a placeholder,
9739       // though.  Fortunately, none of the exceptions we see in that
9740       // code below are valid when the LHS is an overload set.  Note
9741       // that an overload set can be dependently-typed, but it never
9742       // instantiates to having an overloadable type.
9743       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9744       if (resolvedRHS.isInvalid()) return ExprError();
9745       RHSExpr = resolvedRHS.get();
9746 
9747       if (RHSExpr->isTypeDependent() ||
9748           RHSExpr->getType()->isOverloadableType())
9749         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9750     }
9751 
9752     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9753     if (LHS.isInvalid()) return ExprError();
9754     LHSExpr = LHS.get();
9755   }
9756 
9757   // Handle pseudo-objects in the RHS.
9758   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9759     // An overload in the RHS can potentially be resolved by the type
9760     // being assigned to.
9761     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9762       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9763         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9764 
9765       if (LHSExpr->getType()->isOverloadableType())
9766         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9767 
9768       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9769     }
9770 
9771     // Don't resolve overloads if the other type is overloadable.
9772     if (pty->getKind() == BuiltinType::Overload &&
9773         LHSExpr->getType()->isOverloadableType())
9774       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9775 
9776     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9777     if (!resolvedRHS.isUsable()) return ExprError();
9778     RHSExpr = resolvedRHS.get();
9779   }
9780 
9781   if (getLangOpts().CPlusPlus) {
9782     // If either expression is type-dependent, always build an
9783     // overloaded op.
9784     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9785       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9786 
9787     // Otherwise, build an overloaded op if either expression has an
9788     // overloadable type.
9789     if (LHSExpr->getType()->isOverloadableType() ||
9790         RHSExpr->getType()->isOverloadableType())
9791       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9792   }
9793 
9794   // Build a built-in binary operation.
9795   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9796 }
9797 
9798 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9799                                       UnaryOperatorKind Opc,
9800                                       Expr *InputExpr) {
9801   ExprResult Input = InputExpr;
9802   ExprValueKind VK = VK_RValue;
9803   ExprObjectKind OK = OK_Ordinary;
9804   QualType resultType;
9805   switch (Opc) {
9806   case UO_PreInc:
9807   case UO_PreDec:
9808   case UO_PostInc:
9809   case UO_PostDec:
9810     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
9811                                                 OpLoc,
9812                                                 Opc == UO_PreInc ||
9813                                                 Opc == UO_PostInc,
9814                                                 Opc == UO_PreInc ||
9815                                                 Opc == UO_PreDec);
9816     break;
9817   case UO_AddrOf:
9818     resultType = CheckAddressOfOperand(Input, OpLoc);
9819     break;
9820   case UO_Deref: {
9821     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9822     if (Input.isInvalid()) return ExprError();
9823     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9824     break;
9825   }
9826   case UO_Plus:
9827   case UO_Minus:
9828     Input = UsualUnaryConversions(Input.get());
9829     if (Input.isInvalid()) return ExprError();
9830     resultType = Input.get()->getType();
9831     if (resultType->isDependentType())
9832       break;
9833     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9834         resultType->isVectorType())
9835       break;
9836     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9837              Opc == UO_Plus &&
9838              resultType->isPointerType())
9839       break;
9840 
9841     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9842       << resultType << Input.get()->getSourceRange());
9843 
9844   case UO_Not: // bitwise complement
9845     Input = UsualUnaryConversions(Input.get());
9846     if (Input.isInvalid())
9847       return ExprError();
9848     resultType = Input.get()->getType();
9849     if (resultType->isDependentType())
9850       break;
9851     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9852     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9853       // C99 does not support '~' for complex conjugation.
9854       Diag(OpLoc, diag::ext_integer_complement_complex)
9855           << resultType << Input.get()->getSourceRange();
9856     else if (resultType->hasIntegerRepresentation())
9857       break;
9858     else if (resultType->isExtVectorType()) {
9859       if (Context.getLangOpts().OpenCL) {
9860         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9861         // on vector float types.
9862         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9863         if (!T->isIntegerType())
9864           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9865                            << resultType << Input.get()->getSourceRange());
9866       }
9867       break;
9868     } else {
9869       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9870                        << resultType << Input.get()->getSourceRange());
9871     }
9872     break;
9873 
9874   case UO_LNot: // logical negation
9875     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9876     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9877     if (Input.isInvalid()) return ExprError();
9878     resultType = Input.get()->getType();
9879 
9880     // Though we still have to promote half FP to float...
9881     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9882       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9883       resultType = Context.FloatTy;
9884     }
9885 
9886     if (resultType->isDependentType())
9887       break;
9888     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9889       // C99 6.5.3.3p1: ok, fallthrough;
9890       if (Context.getLangOpts().CPlusPlus) {
9891         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9892         // operand contextually converted to bool.
9893         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
9894                                   ScalarTypeToBooleanCastKind(resultType));
9895       } else if (Context.getLangOpts().OpenCL &&
9896                  Context.getLangOpts().OpenCLVersion < 120) {
9897         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9898         // operate on scalar float types.
9899         if (!resultType->isIntegerType())
9900           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9901                            << resultType << Input.get()->getSourceRange());
9902       }
9903     } else if (resultType->isExtVectorType()) {
9904       if (Context.getLangOpts().OpenCL &&
9905           Context.getLangOpts().OpenCLVersion < 120) {
9906         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9907         // operate on vector float types.
9908         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9909         if (!T->isIntegerType())
9910           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9911                            << resultType << Input.get()->getSourceRange());
9912       }
9913       // Vector logical not returns the signed variant of the operand type.
9914       resultType = GetSignedVectorType(resultType);
9915       break;
9916     } else {
9917       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9918         << resultType << Input.get()->getSourceRange());
9919     }
9920 
9921     // LNot always has type int. C99 6.5.3.3p5.
9922     // In C++, it's bool. C++ 5.3.1p8
9923     resultType = Context.getLogicalOperationType();
9924     break;
9925   case UO_Real:
9926   case UO_Imag:
9927     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9928     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9929     // complex l-values to ordinary l-values and all other values to r-values.
9930     if (Input.isInvalid()) return ExprError();
9931     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9932       if (Input.get()->getValueKind() != VK_RValue &&
9933           Input.get()->getObjectKind() == OK_Ordinary)
9934         VK = Input.get()->getValueKind();
9935     } else if (!getLangOpts().CPlusPlus) {
9936       // In C, a volatile scalar is read by __imag. In C++, it is not.
9937       Input = DefaultLvalueConversion(Input.get());
9938     }
9939     break;
9940   case UO_Extension:
9941     resultType = Input.get()->getType();
9942     VK = Input.get()->getValueKind();
9943     OK = Input.get()->getObjectKind();
9944     break;
9945   }
9946   if (resultType.isNull() || Input.isInvalid())
9947     return ExprError();
9948 
9949   // Check for array bounds violations in the operand of the UnaryOperator,
9950   // except for the '*' and '&' operators that have to be handled specially
9951   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9952   // that are explicitly defined as valid by the standard).
9953   if (Opc != UO_AddrOf && Opc != UO_Deref)
9954     CheckArrayAccess(Input.get());
9955 
9956   return new (Context)
9957       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
9958 }
9959 
9960 /// \brief Determine whether the given expression is a qualified member
9961 /// access expression, of a form that could be turned into a pointer to member
9962 /// with the address-of operator.
9963 static bool isQualifiedMemberAccess(Expr *E) {
9964   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9965     if (!DRE->getQualifier())
9966       return false;
9967 
9968     ValueDecl *VD = DRE->getDecl();
9969     if (!VD->isCXXClassMember())
9970       return false;
9971 
9972     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9973       return true;
9974     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9975       return Method->isInstance();
9976 
9977     return false;
9978   }
9979 
9980   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9981     if (!ULE->getQualifier())
9982       return false;
9983 
9984     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9985                                            DEnd = ULE->decls_end();
9986          D != DEnd; ++D) {
9987       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9988         if (Method->isInstance())
9989           return true;
9990       } else {
9991         // Overload set does not contain methods.
9992         break;
9993       }
9994     }
9995 
9996     return false;
9997   }
9998 
9999   return false;
10000 }
10001 
10002 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10003                               UnaryOperatorKind Opc, Expr *Input) {
10004   // First things first: handle placeholders so that the
10005   // overloaded-operator check considers the right type.
10006   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10007     // Increment and decrement of pseudo-object references.
10008     if (pty->getKind() == BuiltinType::PseudoObject &&
10009         UnaryOperator::isIncrementDecrementOp(Opc))
10010       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10011 
10012     // extension is always a builtin operator.
10013     if (Opc == UO_Extension)
10014       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10015 
10016     // & gets special logic for several kinds of placeholder.
10017     // The builtin code knows what to do.
10018     if (Opc == UO_AddrOf &&
10019         (pty->getKind() == BuiltinType::Overload ||
10020          pty->getKind() == BuiltinType::UnknownAny ||
10021          pty->getKind() == BuiltinType::BoundMember))
10022       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10023 
10024     // Anything else needs to be handled now.
10025     ExprResult Result = CheckPlaceholderExpr(Input);
10026     if (Result.isInvalid()) return ExprError();
10027     Input = Result.get();
10028   }
10029 
10030   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10031       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10032       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10033     // Find all of the overloaded operators visible from this
10034     // point. We perform both an operator-name lookup from the local
10035     // scope and an argument-dependent lookup based on the types of
10036     // the arguments.
10037     UnresolvedSet<16> Functions;
10038     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10039     if (S && OverOp != OO_None)
10040       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10041                                    Functions);
10042 
10043     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10044   }
10045 
10046   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10047 }
10048 
10049 // Unary Operators.  'Tok' is the token for the operator.
10050 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10051                               tok::TokenKind Op, Expr *Input) {
10052   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10053 }
10054 
10055 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10056 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10057                                 LabelDecl *TheDecl) {
10058   TheDecl->markUsed(Context);
10059   // Create the AST node.  The address of a label always has type 'void*'.
10060   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10061                                      Context.getPointerType(Context.VoidTy));
10062 }
10063 
10064 /// Given the last statement in a statement-expression, check whether
10065 /// the result is a producing expression (like a call to an
10066 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10067 /// release out of the full-expression.  Otherwise, return null.
10068 /// Cannot fail.
10069 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10070   // Should always be wrapped with one of these.
10071   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10072   if (!cleanups) return nullptr;
10073 
10074   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10075   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10076     return nullptr;
10077 
10078   // Splice out the cast.  This shouldn't modify any interesting
10079   // features of the statement.
10080   Expr *producer = cast->getSubExpr();
10081   assert(producer->getType() == cast->getType());
10082   assert(producer->getValueKind() == cast->getValueKind());
10083   cleanups->setSubExpr(producer);
10084   return cleanups;
10085 }
10086 
10087 void Sema::ActOnStartStmtExpr() {
10088   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10089 }
10090 
10091 void Sema::ActOnStmtExprError() {
10092   // Note that function is also called by TreeTransform when leaving a
10093   // StmtExpr scope without rebuilding anything.
10094 
10095   DiscardCleanupsInEvaluationContext();
10096   PopExpressionEvaluationContext();
10097 }
10098 
10099 ExprResult
10100 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10101                     SourceLocation RPLoc) { // "({..})"
10102   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10103   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10104 
10105   if (hasAnyUnrecoverableErrorsInThisFunction())
10106     DiscardCleanupsInEvaluationContext();
10107   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10108   PopExpressionEvaluationContext();
10109 
10110   bool isFileScope
10111     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10112   if (isFileScope)
10113     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10114 
10115   // FIXME: there are a variety of strange constraints to enforce here, for
10116   // example, it is not possible to goto into a stmt expression apparently.
10117   // More semantic analysis is needed.
10118 
10119   // If there are sub-stmts in the compound stmt, take the type of the last one
10120   // as the type of the stmtexpr.
10121   QualType Ty = Context.VoidTy;
10122   bool StmtExprMayBindToTemp = false;
10123   if (!Compound->body_empty()) {
10124     Stmt *LastStmt = Compound->body_back();
10125     LabelStmt *LastLabelStmt = nullptr;
10126     // If LastStmt is a label, skip down through into the body.
10127     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10128       LastLabelStmt = Label;
10129       LastStmt = Label->getSubStmt();
10130     }
10131 
10132     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10133       // Do function/array conversion on the last expression, but not
10134       // lvalue-to-rvalue.  However, initialize an unqualified type.
10135       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10136       if (LastExpr.isInvalid())
10137         return ExprError();
10138       Ty = LastExpr.get()->getType().getUnqualifiedType();
10139 
10140       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10141         // In ARC, if the final expression ends in a consume, splice
10142         // the consume out and bind it later.  In the alternate case
10143         // (when dealing with a retainable type), the result
10144         // initialization will create a produce.  In both cases the
10145         // result will be +1, and we'll need to balance that out with
10146         // a bind.
10147         if (Expr *rebuiltLastStmt
10148               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10149           LastExpr = rebuiltLastStmt;
10150         } else {
10151           LastExpr = PerformCopyInitialization(
10152                             InitializedEntity::InitializeResult(LPLoc,
10153                                                                 Ty,
10154                                                                 false),
10155                                                    SourceLocation(),
10156                                                LastExpr);
10157         }
10158 
10159         if (LastExpr.isInvalid())
10160           return ExprError();
10161         if (LastExpr.get() != nullptr) {
10162           if (!LastLabelStmt)
10163             Compound->setLastStmt(LastExpr.get());
10164           else
10165             LastLabelStmt->setSubStmt(LastExpr.get());
10166           StmtExprMayBindToTemp = true;
10167         }
10168       }
10169     }
10170   }
10171 
10172   // FIXME: Check that expression type is complete/non-abstract; statement
10173   // expressions are not lvalues.
10174   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10175   if (StmtExprMayBindToTemp)
10176     return MaybeBindToTemporary(ResStmtExpr);
10177   return ResStmtExpr;
10178 }
10179 
10180 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10181                                       TypeSourceInfo *TInfo,
10182                                       OffsetOfComponent *CompPtr,
10183                                       unsigned NumComponents,
10184                                       SourceLocation RParenLoc) {
10185   QualType ArgTy = TInfo->getType();
10186   bool Dependent = ArgTy->isDependentType();
10187   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10188 
10189   // We must have at least one component that refers to the type, and the first
10190   // one is known to be a field designator.  Verify that the ArgTy represents
10191   // a struct/union/class.
10192   if (!Dependent && !ArgTy->isRecordType())
10193     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10194                        << ArgTy << TypeRange);
10195 
10196   // Type must be complete per C99 7.17p3 because a declaring a variable
10197   // with an incomplete type would be ill-formed.
10198   if (!Dependent
10199       && RequireCompleteType(BuiltinLoc, ArgTy,
10200                              diag::err_offsetof_incomplete_type, TypeRange))
10201     return ExprError();
10202 
10203   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10204   // GCC extension, diagnose them.
10205   // FIXME: This diagnostic isn't actually visible because the location is in
10206   // a system header!
10207   if (NumComponents != 1)
10208     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10209       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10210 
10211   bool DidWarnAboutNonPOD = false;
10212   QualType CurrentType = ArgTy;
10213   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10214   SmallVector<OffsetOfNode, 4> Comps;
10215   SmallVector<Expr*, 4> Exprs;
10216   for (unsigned i = 0; i != NumComponents; ++i) {
10217     const OffsetOfComponent &OC = CompPtr[i];
10218     if (OC.isBrackets) {
10219       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10220       if (!CurrentType->isDependentType()) {
10221         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10222         if(!AT)
10223           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10224                            << CurrentType);
10225         CurrentType = AT->getElementType();
10226       } else
10227         CurrentType = Context.DependentTy;
10228 
10229       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10230       if (IdxRval.isInvalid())
10231         return ExprError();
10232       Expr *Idx = IdxRval.get();
10233 
10234       // The expression must be an integral expression.
10235       // FIXME: An integral constant expression?
10236       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10237           !Idx->getType()->isIntegerType())
10238         return ExprError(Diag(Idx->getLocStart(),
10239                               diag::err_typecheck_subscript_not_integer)
10240                          << Idx->getSourceRange());
10241 
10242       // Record this array index.
10243       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10244       Exprs.push_back(Idx);
10245       continue;
10246     }
10247 
10248     // Offset of a field.
10249     if (CurrentType->isDependentType()) {
10250       // We have the offset of a field, but we can't look into the dependent
10251       // type. Just record the identifier of the field.
10252       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10253       CurrentType = Context.DependentTy;
10254       continue;
10255     }
10256 
10257     // We need to have a complete type to look into.
10258     if (RequireCompleteType(OC.LocStart, CurrentType,
10259                             diag::err_offsetof_incomplete_type))
10260       return ExprError();
10261 
10262     // Look for the designated field.
10263     const RecordType *RC = CurrentType->getAs<RecordType>();
10264     if (!RC)
10265       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10266                        << CurrentType);
10267     RecordDecl *RD = RC->getDecl();
10268 
10269     // C++ [lib.support.types]p5:
10270     //   The macro offsetof accepts a restricted set of type arguments in this
10271     //   International Standard. type shall be a POD structure or a POD union
10272     //   (clause 9).
10273     // C++11 [support.types]p4:
10274     //   If type is not a standard-layout class (Clause 9), the results are
10275     //   undefined.
10276     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10277       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10278       unsigned DiagID =
10279         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10280                             : diag::ext_offsetof_non_pod_type;
10281 
10282       if (!IsSafe && !DidWarnAboutNonPOD &&
10283           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10284                               PDiag(DiagID)
10285                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10286                               << CurrentType))
10287         DidWarnAboutNonPOD = true;
10288     }
10289 
10290     // Look for the field.
10291     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10292     LookupQualifiedName(R, RD);
10293     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10294     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10295     if (!MemberDecl) {
10296       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10297         MemberDecl = IndirectMemberDecl->getAnonField();
10298     }
10299 
10300     if (!MemberDecl)
10301       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10302                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10303                                                               OC.LocEnd));
10304 
10305     // C99 7.17p3:
10306     //   (If the specified member is a bit-field, the behavior is undefined.)
10307     //
10308     // We diagnose this as an error.
10309     if (MemberDecl->isBitField()) {
10310       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10311         << MemberDecl->getDeclName()
10312         << SourceRange(BuiltinLoc, RParenLoc);
10313       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10314       return ExprError();
10315     }
10316 
10317     RecordDecl *Parent = MemberDecl->getParent();
10318     if (IndirectMemberDecl)
10319       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10320 
10321     // If the member was found in a base class, introduce OffsetOfNodes for
10322     // the base class indirections.
10323     CXXBasePaths Paths;
10324     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10325       if (Paths.getDetectedVirtual()) {
10326         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10327           << MemberDecl->getDeclName()
10328           << SourceRange(BuiltinLoc, RParenLoc);
10329         return ExprError();
10330       }
10331 
10332       CXXBasePath &Path = Paths.front();
10333       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10334            B != BEnd; ++B)
10335         Comps.push_back(OffsetOfNode(B->Base));
10336     }
10337 
10338     if (IndirectMemberDecl) {
10339       for (auto *FI : IndirectMemberDecl->chain()) {
10340         assert(isa<FieldDecl>(FI));
10341         Comps.push_back(OffsetOfNode(OC.LocStart,
10342                                      cast<FieldDecl>(FI), OC.LocEnd));
10343       }
10344     } else
10345       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10346 
10347     CurrentType = MemberDecl->getType().getNonReferenceType();
10348   }
10349 
10350   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10351                               Comps, Exprs, RParenLoc);
10352 }
10353 
10354 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10355                                       SourceLocation BuiltinLoc,
10356                                       SourceLocation TypeLoc,
10357                                       ParsedType ParsedArgTy,
10358                                       OffsetOfComponent *CompPtr,
10359                                       unsigned NumComponents,
10360                                       SourceLocation RParenLoc) {
10361 
10362   TypeSourceInfo *ArgTInfo;
10363   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10364   if (ArgTy.isNull())
10365     return ExprError();
10366 
10367   if (!ArgTInfo)
10368     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10369 
10370   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10371                               RParenLoc);
10372 }
10373 
10374 
10375 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10376                                  Expr *CondExpr,
10377                                  Expr *LHSExpr, Expr *RHSExpr,
10378                                  SourceLocation RPLoc) {
10379   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10380 
10381   ExprValueKind VK = VK_RValue;
10382   ExprObjectKind OK = OK_Ordinary;
10383   QualType resType;
10384   bool ValueDependent = false;
10385   bool CondIsTrue = false;
10386   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10387     resType = Context.DependentTy;
10388     ValueDependent = true;
10389   } else {
10390     // The conditional expression is required to be a constant expression.
10391     llvm::APSInt condEval(32);
10392     ExprResult CondICE
10393       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10394           diag::err_typecheck_choose_expr_requires_constant, false);
10395     if (CondICE.isInvalid())
10396       return ExprError();
10397     CondExpr = CondICE.get();
10398     CondIsTrue = condEval.getZExtValue();
10399 
10400     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10401     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10402 
10403     resType = ActiveExpr->getType();
10404     ValueDependent = ActiveExpr->isValueDependent();
10405     VK = ActiveExpr->getValueKind();
10406     OK = ActiveExpr->getObjectKind();
10407   }
10408 
10409   return new (Context)
10410       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10411                  CondIsTrue, resType->isDependentType(), ValueDependent);
10412 }
10413 
10414 //===----------------------------------------------------------------------===//
10415 // Clang Extensions.
10416 //===----------------------------------------------------------------------===//
10417 
10418 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10419 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10420   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10421 
10422   if (LangOpts.CPlusPlus) {
10423     Decl *ManglingContextDecl;
10424     if (MangleNumberingContext *MCtx =
10425             getCurrentMangleNumberContext(Block->getDeclContext(),
10426                                           ManglingContextDecl)) {
10427       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10428       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10429     }
10430   }
10431 
10432   PushBlockScope(CurScope, Block);
10433   CurContext->addDecl(Block);
10434   if (CurScope)
10435     PushDeclContext(CurScope, Block);
10436   else
10437     CurContext = Block;
10438 
10439   getCurBlock()->HasImplicitReturnType = true;
10440 
10441   // Enter a new evaluation context to insulate the block from any
10442   // cleanups from the enclosing full-expression.
10443   PushExpressionEvaluationContext(PotentiallyEvaluated);
10444 }
10445 
10446 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10447                                Scope *CurScope) {
10448   assert(ParamInfo.getIdentifier() == nullptr &&
10449          "block-id should have no identifier!");
10450   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10451   BlockScopeInfo *CurBlock = getCurBlock();
10452 
10453   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10454   QualType T = Sig->getType();
10455 
10456   // FIXME: We should allow unexpanded parameter packs here, but that would,
10457   // in turn, make the block expression contain unexpanded parameter packs.
10458   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10459     // Drop the parameters.
10460     FunctionProtoType::ExtProtoInfo EPI;
10461     EPI.HasTrailingReturn = false;
10462     EPI.TypeQuals |= DeclSpec::TQ_const;
10463     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10464     Sig = Context.getTrivialTypeSourceInfo(T);
10465   }
10466 
10467   // GetTypeForDeclarator always produces a function type for a block
10468   // literal signature.  Furthermore, it is always a FunctionProtoType
10469   // unless the function was written with a typedef.
10470   assert(T->isFunctionType() &&
10471          "GetTypeForDeclarator made a non-function block signature");
10472 
10473   // Look for an explicit signature in that function type.
10474   FunctionProtoTypeLoc ExplicitSignature;
10475 
10476   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10477   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10478 
10479     // Check whether that explicit signature was synthesized by
10480     // GetTypeForDeclarator.  If so, don't save that as part of the
10481     // written signature.
10482     if (ExplicitSignature.getLocalRangeBegin() ==
10483         ExplicitSignature.getLocalRangeEnd()) {
10484       // This would be much cheaper if we stored TypeLocs instead of
10485       // TypeSourceInfos.
10486       TypeLoc Result = ExplicitSignature.getReturnLoc();
10487       unsigned Size = Result.getFullDataSize();
10488       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10489       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10490 
10491       ExplicitSignature = FunctionProtoTypeLoc();
10492     }
10493   }
10494 
10495   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10496   CurBlock->FunctionType = T;
10497 
10498   const FunctionType *Fn = T->getAs<FunctionType>();
10499   QualType RetTy = Fn->getReturnType();
10500   bool isVariadic =
10501     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10502 
10503   CurBlock->TheDecl->setIsVariadic(isVariadic);
10504 
10505   // Context.DependentTy is used as a placeholder for a missing block
10506   // return type.  TODO:  what should we do with declarators like:
10507   //   ^ * { ... }
10508   // If the answer is "apply template argument deduction"....
10509   if (RetTy != Context.DependentTy) {
10510     CurBlock->ReturnType = RetTy;
10511     CurBlock->TheDecl->setBlockMissingReturnType(false);
10512     CurBlock->HasImplicitReturnType = false;
10513   }
10514 
10515   // Push block parameters from the declarator if we had them.
10516   SmallVector<ParmVarDecl*, 8> Params;
10517   if (ExplicitSignature) {
10518     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10519       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10520       if (Param->getIdentifier() == nullptr &&
10521           !Param->isImplicit() &&
10522           !Param->isInvalidDecl() &&
10523           !getLangOpts().CPlusPlus)
10524         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10525       Params.push_back(Param);
10526     }
10527 
10528   // Fake up parameter variables if we have a typedef, like
10529   //   ^ fntype { ... }
10530   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10531     for (const auto &I : Fn->param_types()) {
10532       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10533           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10534       Params.push_back(Param);
10535     }
10536   }
10537 
10538   // Set the parameters on the block decl.
10539   if (!Params.empty()) {
10540     CurBlock->TheDecl->setParams(Params);
10541     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10542                              CurBlock->TheDecl->param_end(),
10543                              /*CheckParameterNames=*/false);
10544   }
10545 
10546   // Finally we can process decl attributes.
10547   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10548 
10549   // Put the parameter variables in scope.
10550   for (auto AI : CurBlock->TheDecl->params()) {
10551     AI->setOwningFunction(CurBlock->TheDecl);
10552 
10553     // If this has an identifier, add it to the scope stack.
10554     if (AI->getIdentifier()) {
10555       CheckShadow(CurBlock->TheScope, AI);
10556 
10557       PushOnScopeChains(AI, CurBlock->TheScope);
10558     }
10559   }
10560 }
10561 
10562 /// ActOnBlockError - If there is an error parsing a block, this callback
10563 /// is invoked to pop the information about the block from the action impl.
10564 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10565   // Leave the expression-evaluation context.
10566   DiscardCleanupsInEvaluationContext();
10567   PopExpressionEvaluationContext();
10568 
10569   // Pop off CurBlock, handle nested blocks.
10570   PopDeclContext();
10571   PopFunctionScopeInfo();
10572 }
10573 
10574 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10575 /// literal was successfully completed.  ^(int x){...}
10576 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10577                                     Stmt *Body, Scope *CurScope) {
10578   // If blocks are disabled, emit an error.
10579   if (!LangOpts.Blocks)
10580     Diag(CaretLoc, diag::err_blocks_disable);
10581 
10582   // Leave the expression-evaluation context.
10583   if (hasAnyUnrecoverableErrorsInThisFunction())
10584     DiscardCleanupsInEvaluationContext();
10585   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10586   PopExpressionEvaluationContext();
10587 
10588   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10589 
10590   if (BSI->HasImplicitReturnType)
10591     deduceClosureReturnType(*BSI);
10592 
10593   PopDeclContext();
10594 
10595   QualType RetTy = Context.VoidTy;
10596   if (!BSI->ReturnType.isNull())
10597     RetTy = BSI->ReturnType;
10598 
10599   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10600   QualType BlockTy;
10601 
10602   // Set the captured variables on the block.
10603   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10604   SmallVector<BlockDecl::Capture, 4> Captures;
10605   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10606     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10607     if (Cap.isThisCapture())
10608       continue;
10609     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10610                               Cap.isNested(), Cap.getInitExpr());
10611     Captures.push_back(NewCap);
10612   }
10613   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10614                             BSI->CXXThisCaptureIndex != 0);
10615 
10616   // If the user wrote a function type in some form, try to use that.
10617   if (!BSI->FunctionType.isNull()) {
10618     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10619 
10620     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10621     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10622 
10623     // Turn protoless block types into nullary block types.
10624     if (isa<FunctionNoProtoType>(FTy)) {
10625       FunctionProtoType::ExtProtoInfo EPI;
10626       EPI.ExtInfo = Ext;
10627       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10628 
10629     // Otherwise, if we don't need to change anything about the function type,
10630     // preserve its sugar structure.
10631     } else if (FTy->getReturnType() == RetTy &&
10632                (!NoReturn || FTy->getNoReturnAttr())) {
10633       BlockTy = BSI->FunctionType;
10634 
10635     // Otherwise, make the minimal modifications to the function type.
10636     } else {
10637       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10638       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10639       EPI.TypeQuals = 0; // FIXME: silently?
10640       EPI.ExtInfo = Ext;
10641       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10642     }
10643 
10644   // If we don't have a function type, just build one from nothing.
10645   } else {
10646     FunctionProtoType::ExtProtoInfo EPI;
10647     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10648     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10649   }
10650 
10651   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10652                            BSI->TheDecl->param_end());
10653   BlockTy = Context.getBlockPointerType(BlockTy);
10654 
10655   // If needed, diagnose invalid gotos and switches in the block.
10656   if (getCurFunction()->NeedsScopeChecking() &&
10657       !PP.isCodeCompletionEnabled())
10658     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10659 
10660   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10661 
10662   // Try to apply the named return value optimization. We have to check again
10663   // if we can do this, though, because blocks keep return statements around
10664   // to deduce an implicit return type.
10665   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10666       !BSI->TheDecl->isDependentContext())
10667     computeNRVO(Body, BSI);
10668 
10669   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10670   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10671   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10672 
10673   // If the block isn't obviously global, i.e. it captures anything at
10674   // all, then we need to do a few things in the surrounding context:
10675   if (Result->getBlockDecl()->hasCaptures()) {
10676     // First, this expression has a new cleanup object.
10677     ExprCleanupObjects.push_back(Result->getBlockDecl());
10678     ExprNeedsCleanups = true;
10679 
10680     // It also gets a branch-protected scope if any of the captured
10681     // variables needs destruction.
10682     for (const auto &CI : Result->getBlockDecl()->captures()) {
10683       const VarDecl *var = CI.getVariable();
10684       if (var->getType().isDestructedType() != QualType::DK_none) {
10685         getCurFunction()->setHasBranchProtectedScope();
10686         break;
10687       }
10688     }
10689   }
10690 
10691   return Result;
10692 }
10693 
10694 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10695                                         Expr *E, ParsedType Ty,
10696                                         SourceLocation RPLoc) {
10697   TypeSourceInfo *TInfo;
10698   GetTypeFromParser(Ty, &TInfo);
10699   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10700 }
10701 
10702 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10703                                 Expr *E, TypeSourceInfo *TInfo,
10704                                 SourceLocation RPLoc) {
10705   Expr *OrigExpr = E;
10706 
10707   // Get the va_list type
10708   QualType VaListType = Context.getBuiltinVaListType();
10709   if (VaListType->isArrayType()) {
10710     // Deal with implicit array decay; for example, on x86-64,
10711     // va_list is an array, but it's supposed to decay to
10712     // a pointer for va_arg.
10713     VaListType = Context.getArrayDecayedType(VaListType);
10714     // Make sure the input expression also decays appropriately.
10715     ExprResult Result = UsualUnaryConversions(E);
10716     if (Result.isInvalid())
10717       return ExprError();
10718     E = Result.get();
10719   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10720     // If va_list is a record type and we are compiling in C++ mode,
10721     // check the argument using reference binding.
10722     InitializedEntity Entity
10723       = InitializedEntity::InitializeParameter(Context,
10724           Context.getLValueReferenceType(VaListType), false);
10725     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10726     if (Init.isInvalid())
10727       return ExprError();
10728     E = Init.getAs<Expr>();
10729   } else {
10730     // Otherwise, the va_list argument must be an l-value because
10731     // it is modified by va_arg.
10732     if (!E->isTypeDependent() &&
10733         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10734       return ExprError();
10735   }
10736 
10737   if (!E->isTypeDependent() &&
10738       !Context.hasSameType(VaListType, E->getType())) {
10739     return ExprError(Diag(E->getLocStart(),
10740                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10741       << OrigExpr->getType() << E->getSourceRange());
10742   }
10743 
10744   if (!TInfo->getType()->isDependentType()) {
10745     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10746                             diag::err_second_parameter_to_va_arg_incomplete,
10747                             TInfo->getTypeLoc()))
10748       return ExprError();
10749 
10750     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10751                                TInfo->getType(),
10752                                diag::err_second_parameter_to_va_arg_abstract,
10753                                TInfo->getTypeLoc()))
10754       return ExprError();
10755 
10756     if (!TInfo->getType().isPODType(Context)) {
10757       Diag(TInfo->getTypeLoc().getBeginLoc(),
10758            TInfo->getType()->isObjCLifetimeType()
10759              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10760              : diag::warn_second_parameter_to_va_arg_not_pod)
10761         << TInfo->getType()
10762         << TInfo->getTypeLoc().getSourceRange();
10763     }
10764 
10765     // Check for va_arg where arguments of the given type will be promoted
10766     // (i.e. this va_arg is guaranteed to have undefined behavior).
10767     QualType PromoteType;
10768     if (TInfo->getType()->isPromotableIntegerType()) {
10769       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10770       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10771         PromoteType = QualType();
10772     }
10773     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10774       PromoteType = Context.DoubleTy;
10775     if (!PromoteType.isNull())
10776       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10777                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10778                           << TInfo->getType()
10779                           << PromoteType
10780                           << TInfo->getTypeLoc().getSourceRange());
10781   }
10782 
10783   QualType T = TInfo->getType().getNonLValueExprType(Context);
10784   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10785 }
10786 
10787 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10788   // The type of __null will be int or long, depending on the size of
10789   // pointers on the target.
10790   QualType Ty;
10791   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10792   if (pw == Context.getTargetInfo().getIntWidth())
10793     Ty = Context.IntTy;
10794   else if (pw == Context.getTargetInfo().getLongWidth())
10795     Ty = Context.LongTy;
10796   else if (pw == Context.getTargetInfo().getLongLongWidth())
10797     Ty = Context.LongLongTy;
10798   else {
10799     llvm_unreachable("I don't know size of pointer!");
10800   }
10801 
10802   return new (Context) GNUNullExpr(Ty, TokenLoc);
10803 }
10804 
10805 bool
10806 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10807   if (!getLangOpts().ObjC1)
10808     return false;
10809 
10810   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10811   if (!PT)
10812     return false;
10813 
10814   if (!PT->isObjCIdType()) {
10815     // Check if the destination is the 'NSString' interface.
10816     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10817     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10818       return false;
10819   }
10820 
10821   // Ignore any parens, implicit casts (should only be
10822   // array-to-pointer decays), and not-so-opaque values.  The last is
10823   // important for making this trigger for property assignments.
10824   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10825   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10826     if (OV->getSourceExpr())
10827       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10828 
10829   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10830   if (!SL || !SL->isAscii())
10831     return false;
10832   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10833     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10834   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10835   return true;
10836 }
10837 
10838 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10839                                     SourceLocation Loc,
10840                                     QualType DstType, QualType SrcType,
10841                                     Expr *SrcExpr, AssignmentAction Action,
10842                                     bool *Complained) {
10843   if (Complained)
10844     *Complained = false;
10845 
10846   // Decode the result (notice that AST's are still created for extensions).
10847   bool CheckInferredResultType = false;
10848   bool isInvalid = false;
10849   unsigned DiagKind = 0;
10850   FixItHint Hint;
10851   ConversionFixItGenerator ConvHints;
10852   bool MayHaveConvFixit = false;
10853   bool MayHaveFunctionDiff = false;
10854   const ObjCInterfaceDecl *IFace = nullptr;
10855   const ObjCProtocolDecl *PDecl = nullptr;
10856 
10857   switch (ConvTy) {
10858   case Compatible:
10859       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10860       return false;
10861 
10862   case PointerToInt:
10863     DiagKind = diag::ext_typecheck_convert_pointer_int;
10864     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10865     MayHaveConvFixit = true;
10866     break;
10867   case IntToPointer:
10868     DiagKind = diag::ext_typecheck_convert_int_pointer;
10869     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10870     MayHaveConvFixit = true;
10871     break;
10872   case IncompatiblePointer:
10873       DiagKind =
10874         (Action == AA_Passing_CFAudited ?
10875           diag::err_arc_typecheck_convert_incompatible_pointer :
10876           diag::ext_typecheck_convert_incompatible_pointer);
10877     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10878       SrcType->isObjCObjectPointerType();
10879     if (Hint.isNull() && !CheckInferredResultType) {
10880       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10881     }
10882     else if (CheckInferredResultType) {
10883       SrcType = SrcType.getUnqualifiedType();
10884       DstType = DstType.getUnqualifiedType();
10885     }
10886     MayHaveConvFixit = true;
10887     break;
10888   case IncompatiblePointerSign:
10889     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10890     break;
10891   case FunctionVoidPointer:
10892     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10893     break;
10894   case IncompatiblePointerDiscardsQualifiers: {
10895     // Perform array-to-pointer decay if necessary.
10896     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10897 
10898     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10899     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10900     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10901       DiagKind = diag::err_typecheck_incompatible_address_space;
10902       break;
10903 
10904 
10905     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10906       DiagKind = diag::err_typecheck_incompatible_ownership;
10907       break;
10908     }
10909 
10910     llvm_unreachable("unknown error case for discarding qualifiers!");
10911     // fallthrough
10912   }
10913   case CompatiblePointerDiscardsQualifiers:
10914     // If the qualifiers lost were because we were applying the
10915     // (deprecated) C++ conversion from a string literal to a char*
10916     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10917     // Ideally, this check would be performed in
10918     // checkPointerTypesForAssignment. However, that would require a
10919     // bit of refactoring (so that the second argument is an
10920     // expression, rather than a type), which should be done as part
10921     // of a larger effort to fix checkPointerTypesForAssignment for
10922     // C++ semantics.
10923     if (getLangOpts().CPlusPlus &&
10924         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10925       return false;
10926     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10927     break;
10928   case IncompatibleNestedPointerQualifiers:
10929     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10930     break;
10931   case IntToBlockPointer:
10932     DiagKind = diag::err_int_to_block_pointer;
10933     break;
10934   case IncompatibleBlockPointer:
10935     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10936     break;
10937   case IncompatibleObjCQualifiedId: {
10938     if (SrcType->isObjCQualifiedIdType()) {
10939       const ObjCObjectPointerType *srcOPT =
10940                 SrcType->getAs<ObjCObjectPointerType>();
10941       for (auto *srcProto : srcOPT->quals()) {
10942         PDecl = srcProto;
10943         break;
10944       }
10945       if (const ObjCInterfaceType *IFaceT =
10946             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10947         IFace = IFaceT->getDecl();
10948     }
10949     else if (DstType->isObjCQualifiedIdType()) {
10950       const ObjCObjectPointerType *dstOPT =
10951         DstType->getAs<ObjCObjectPointerType>();
10952       for (auto *dstProto : dstOPT->quals()) {
10953         PDecl = dstProto;
10954         break;
10955       }
10956       if (const ObjCInterfaceType *IFaceT =
10957             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
10958         IFace = IFaceT->getDecl();
10959     }
10960     DiagKind = diag::warn_incompatible_qualified_id;
10961     break;
10962   }
10963   case IncompatibleVectors:
10964     DiagKind = diag::warn_incompatible_vectors;
10965     break;
10966   case IncompatibleObjCWeakRef:
10967     DiagKind = diag::err_arc_weak_unavailable_assign;
10968     break;
10969   case Incompatible:
10970     DiagKind = diag::err_typecheck_convert_incompatible;
10971     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10972     MayHaveConvFixit = true;
10973     isInvalid = true;
10974     MayHaveFunctionDiff = true;
10975     break;
10976   }
10977 
10978   QualType FirstType, SecondType;
10979   switch (Action) {
10980   case AA_Assigning:
10981   case AA_Initializing:
10982     // The destination type comes first.
10983     FirstType = DstType;
10984     SecondType = SrcType;
10985     break;
10986 
10987   case AA_Returning:
10988   case AA_Passing:
10989   case AA_Passing_CFAudited:
10990   case AA_Converting:
10991   case AA_Sending:
10992   case AA_Casting:
10993     // The source type comes first.
10994     FirstType = SrcType;
10995     SecondType = DstType;
10996     break;
10997   }
10998 
10999   PartialDiagnostic FDiag = PDiag(DiagKind);
11000   if (Action == AA_Passing_CFAudited)
11001     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11002   else
11003     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11004 
11005   // If we can fix the conversion, suggest the FixIts.
11006   assert(ConvHints.isNull() || Hint.isNull());
11007   if (!ConvHints.isNull()) {
11008     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11009          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11010       FDiag << *HI;
11011   } else {
11012     FDiag << Hint;
11013   }
11014   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11015 
11016   if (MayHaveFunctionDiff)
11017     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11018 
11019   Diag(Loc, FDiag);
11020   if (DiagKind == diag::warn_incompatible_qualified_id &&
11021       PDecl && IFace && !IFace->hasDefinition())
11022       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11023         << IFace->getName() << PDecl->getName();
11024 
11025   if (SecondType == Context.OverloadTy)
11026     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11027                               FirstType);
11028 
11029   if (CheckInferredResultType)
11030     EmitRelatedResultTypeNote(SrcExpr);
11031 
11032   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11033     EmitRelatedResultTypeNoteForReturn(DstType);
11034 
11035   if (Complained)
11036     *Complained = true;
11037   return isInvalid;
11038 }
11039 
11040 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11041                                                  llvm::APSInt *Result) {
11042   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11043   public:
11044     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11045       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11046     }
11047   } Diagnoser;
11048 
11049   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11050 }
11051 
11052 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11053                                                  llvm::APSInt *Result,
11054                                                  unsigned DiagID,
11055                                                  bool AllowFold) {
11056   class IDDiagnoser : public VerifyICEDiagnoser {
11057     unsigned DiagID;
11058 
11059   public:
11060     IDDiagnoser(unsigned DiagID)
11061       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11062 
11063     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11064       S.Diag(Loc, DiagID) << SR;
11065     }
11066   } Diagnoser(DiagID);
11067 
11068   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11069 }
11070 
11071 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11072                                             SourceRange SR) {
11073   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11074 }
11075 
11076 ExprResult
11077 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11078                                       VerifyICEDiagnoser &Diagnoser,
11079                                       bool AllowFold) {
11080   SourceLocation DiagLoc = E->getLocStart();
11081 
11082   if (getLangOpts().CPlusPlus11) {
11083     // C++11 [expr.const]p5:
11084     //   If an expression of literal class type is used in a context where an
11085     //   integral constant expression is required, then that class type shall
11086     //   have a single non-explicit conversion function to an integral or
11087     //   unscoped enumeration type
11088     ExprResult Converted;
11089     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11090     public:
11091       CXX11ConvertDiagnoser(bool Silent)
11092           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11093                                 Silent, true) {}
11094 
11095       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11096                                            QualType T) override {
11097         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11098       }
11099 
11100       SemaDiagnosticBuilder diagnoseIncomplete(
11101           Sema &S, SourceLocation Loc, QualType T) override {
11102         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11103       }
11104 
11105       SemaDiagnosticBuilder diagnoseExplicitConv(
11106           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11107         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11108       }
11109 
11110       SemaDiagnosticBuilder noteExplicitConv(
11111           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11112         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11113                  << ConvTy->isEnumeralType() << ConvTy;
11114       }
11115 
11116       SemaDiagnosticBuilder diagnoseAmbiguous(
11117           Sema &S, SourceLocation Loc, QualType T) override {
11118         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11119       }
11120 
11121       SemaDiagnosticBuilder noteAmbiguous(
11122           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11123         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11124                  << ConvTy->isEnumeralType() << ConvTy;
11125       }
11126 
11127       SemaDiagnosticBuilder diagnoseConversion(
11128           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11129         llvm_unreachable("conversion functions are permitted");
11130       }
11131     } ConvertDiagnoser(Diagnoser.Suppress);
11132 
11133     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11134                                                     ConvertDiagnoser);
11135     if (Converted.isInvalid())
11136       return Converted;
11137     E = Converted.get();
11138     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11139       return ExprError();
11140   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11141     // An ICE must be of integral or unscoped enumeration type.
11142     if (!Diagnoser.Suppress)
11143       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11144     return ExprError();
11145   }
11146 
11147   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11148   // in the non-ICE case.
11149   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11150     if (Result)
11151       *Result = E->EvaluateKnownConstInt(Context);
11152     return E;
11153   }
11154 
11155   Expr::EvalResult EvalResult;
11156   SmallVector<PartialDiagnosticAt, 8> Notes;
11157   EvalResult.Diag = &Notes;
11158 
11159   // Try to evaluate the expression, and produce diagnostics explaining why it's
11160   // not a constant expression as a side-effect.
11161   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11162                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11163 
11164   // In C++11, we can rely on diagnostics being produced for any expression
11165   // which is not a constant expression. If no diagnostics were produced, then
11166   // this is a constant expression.
11167   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11168     if (Result)
11169       *Result = EvalResult.Val.getInt();
11170     return E;
11171   }
11172 
11173   // If our only note is the usual "invalid subexpression" note, just point
11174   // the caret at its location rather than producing an essentially
11175   // redundant note.
11176   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11177         diag::note_invalid_subexpr_in_const_expr) {
11178     DiagLoc = Notes[0].first;
11179     Notes.clear();
11180   }
11181 
11182   if (!Folded || !AllowFold) {
11183     if (!Diagnoser.Suppress) {
11184       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11185       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11186         Diag(Notes[I].first, Notes[I].second);
11187     }
11188 
11189     return ExprError();
11190   }
11191 
11192   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11193   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11194     Diag(Notes[I].first, Notes[I].second);
11195 
11196   if (Result)
11197     *Result = EvalResult.Val.getInt();
11198   return E;
11199 }
11200 
11201 namespace {
11202   // Handle the case where we conclude a expression which we speculatively
11203   // considered to be unevaluated is actually evaluated.
11204   class TransformToPE : public TreeTransform<TransformToPE> {
11205     typedef TreeTransform<TransformToPE> BaseTransform;
11206 
11207   public:
11208     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11209 
11210     // Make sure we redo semantic analysis
11211     bool AlwaysRebuild() { return true; }
11212 
11213     // Make sure we handle LabelStmts correctly.
11214     // FIXME: This does the right thing, but maybe we need a more general
11215     // fix to TreeTransform?
11216     StmtResult TransformLabelStmt(LabelStmt *S) {
11217       S->getDecl()->setStmt(nullptr);
11218       return BaseTransform::TransformLabelStmt(S);
11219     }
11220 
11221     // We need to special-case DeclRefExprs referring to FieldDecls which
11222     // are not part of a member pointer formation; normal TreeTransforming
11223     // doesn't catch this case because of the way we represent them in the AST.
11224     // FIXME: This is a bit ugly; is it really the best way to handle this
11225     // case?
11226     //
11227     // Error on DeclRefExprs referring to FieldDecls.
11228     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11229       if (isa<FieldDecl>(E->getDecl()) &&
11230           !SemaRef.isUnevaluatedContext())
11231         return SemaRef.Diag(E->getLocation(),
11232                             diag::err_invalid_non_static_member_use)
11233             << E->getDecl() << E->getSourceRange();
11234 
11235       return BaseTransform::TransformDeclRefExpr(E);
11236     }
11237 
11238     // Exception: filter out member pointer formation
11239     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11240       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11241         return E;
11242 
11243       return BaseTransform::TransformUnaryOperator(E);
11244     }
11245 
11246     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11247       // Lambdas never need to be transformed.
11248       return E;
11249     }
11250   };
11251 }
11252 
11253 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11254   assert(isUnevaluatedContext() &&
11255          "Should only transform unevaluated expressions");
11256   ExprEvalContexts.back().Context =
11257       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11258   if (isUnevaluatedContext())
11259     return E;
11260   return TransformToPE(*this).TransformExpr(E);
11261 }
11262 
11263 void
11264 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11265                                       Decl *LambdaContextDecl,
11266                                       bool IsDecltype) {
11267   ExprEvalContexts.push_back(
11268              ExpressionEvaluationContextRecord(NewContext,
11269                                                ExprCleanupObjects.size(),
11270                                                ExprNeedsCleanups,
11271                                                LambdaContextDecl,
11272                                                IsDecltype));
11273   ExprNeedsCleanups = false;
11274   if (!MaybeODRUseExprs.empty())
11275     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11276 }
11277 
11278 void
11279 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11280                                       ReuseLambdaContextDecl_t,
11281                                       bool IsDecltype) {
11282   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11283   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11284 }
11285 
11286 void Sema::PopExpressionEvaluationContext() {
11287   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11288 
11289   if (!Rec.Lambdas.empty()) {
11290     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11291       unsigned D;
11292       if (Rec.isUnevaluated()) {
11293         // C++11 [expr.prim.lambda]p2:
11294         //   A lambda-expression shall not appear in an unevaluated operand
11295         //   (Clause 5).
11296         D = diag::err_lambda_unevaluated_operand;
11297       } else {
11298         // C++1y [expr.const]p2:
11299         //   A conditional-expression e is a core constant expression unless the
11300         //   evaluation of e, following the rules of the abstract machine, would
11301         //   evaluate [...] a lambda-expression.
11302         D = diag::err_lambda_in_constant_expression;
11303       }
11304       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11305         Diag(Rec.Lambdas[I]->getLocStart(), D);
11306     } else {
11307       // Mark the capture expressions odr-used. This was deferred
11308       // during lambda expression creation.
11309       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11310         LambdaExpr *Lambda = Rec.Lambdas[I];
11311         for (LambdaExpr::capture_init_iterator
11312                   C = Lambda->capture_init_begin(),
11313                CEnd = Lambda->capture_init_end();
11314              C != CEnd; ++C) {
11315           MarkDeclarationsReferencedInExpr(*C);
11316         }
11317       }
11318     }
11319   }
11320 
11321   // When are coming out of an unevaluated context, clear out any
11322   // temporaries that we may have created as part of the evaluation of
11323   // the expression in that context: they aren't relevant because they
11324   // will never be constructed.
11325   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11326     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11327                              ExprCleanupObjects.end());
11328     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11329     CleanupVarDeclMarking();
11330     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11331   // Otherwise, merge the contexts together.
11332   } else {
11333     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11334     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11335                             Rec.SavedMaybeODRUseExprs.end());
11336   }
11337 
11338   // Pop the current expression evaluation context off the stack.
11339   ExprEvalContexts.pop_back();
11340 }
11341 
11342 void Sema::DiscardCleanupsInEvaluationContext() {
11343   ExprCleanupObjects.erase(
11344          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11345          ExprCleanupObjects.end());
11346   ExprNeedsCleanups = false;
11347   MaybeODRUseExprs.clear();
11348 }
11349 
11350 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11351   if (!E->getType()->isVariablyModifiedType())
11352     return E;
11353   return TransformToPotentiallyEvaluated(E);
11354 }
11355 
11356 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11357   // Do not mark anything as "used" within a dependent context; wait for
11358   // an instantiation.
11359   if (SemaRef.CurContext->isDependentContext())
11360     return false;
11361 
11362   switch (SemaRef.ExprEvalContexts.back().Context) {
11363     case Sema::Unevaluated:
11364     case Sema::UnevaluatedAbstract:
11365       // We are in an expression that is not potentially evaluated; do nothing.
11366       // (Depending on how you read the standard, we actually do need to do
11367       // something here for null pointer constants, but the standard's
11368       // definition of a null pointer constant is completely crazy.)
11369       return false;
11370 
11371     case Sema::ConstantEvaluated:
11372     case Sema::PotentiallyEvaluated:
11373       // We are in a potentially evaluated expression (or a constant-expression
11374       // in C++03); we need to do implicit template instantiation, implicitly
11375       // define class members, and mark most declarations as used.
11376       return true;
11377 
11378     case Sema::PotentiallyEvaluatedIfUsed:
11379       // Referenced declarations will only be used if the construct in the
11380       // containing expression is used.
11381       return false;
11382   }
11383   llvm_unreachable("Invalid context");
11384 }
11385 
11386 /// \brief Mark a function referenced, and check whether it is odr-used
11387 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11388 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
11389                                   bool OdrUse) {
11390   assert(Func && "No function?");
11391 
11392   Func->setReferenced();
11393 
11394   // C++11 [basic.def.odr]p3:
11395   //   A function whose name appears as a potentially-evaluated expression is
11396   //   odr-used if it is the unique lookup result or the selected member of a
11397   //   set of overloaded functions [...].
11398   //
11399   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11400   // can just check that here. Skip the rest of this function if we've already
11401   // marked the function as used.
11402   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11403     // C++11 [temp.inst]p3:
11404     //   Unless a function template specialization has been explicitly
11405     //   instantiated or explicitly specialized, the function template
11406     //   specialization is implicitly instantiated when the specialization is
11407     //   referenced in a context that requires a function definition to exist.
11408     //
11409     // We consider constexpr function templates to be referenced in a context
11410     // that requires a definition to exist whenever they are referenced.
11411     //
11412     // FIXME: This instantiates constexpr functions too frequently. If this is
11413     // really an unevaluated context (and we're not just in the definition of a
11414     // function template or overload resolution or other cases which we
11415     // incorrectly consider to be unevaluated contexts), and we're not in a
11416     // subexpression which we actually need to evaluate (for instance, a
11417     // template argument, array bound or an expression in a braced-init-list),
11418     // we are not permitted to instantiate this constexpr function definition.
11419     //
11420     // FIXME: This also implicitly defines special members too frequently. They
11421     // are only supposed to be implicitly defined if they are odr-used, but they
11422     // are not odr-used from constant expressions in unevaluated contexts.
11423     // However, they cannot be referenced if they are deleted, and they are
11424     // deleted whenever the implicit definition of the special member would
11425     // fail.
11426     if (!Func->isConstexpr() || Func->getBody())
11427       return;
11428     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11429     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11430       return;
11431   }
11432 
11433   // Note that this declaration has been used.
11434   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11435     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11436     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11437       if (Constructor->isDefaultConstructor()) {
11438         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11439           return;
11440         DefineImplicitDefaultConstructor(Loc, Constructor);
11441       } else if (Constructor->isCopyConstructor()) {
11442         DefineImplicitCopyConstructor(Loc, Constructor);
11443       } else if (Constructor->isMoveConstructor()) {
11444         DefineImplicitMoveConstructor(Loc, Constructor);
11445       }
11446     } else if (Constructor->getInheritedConstructor()) {
11447       DefineInheritingConstructor(Loc, Constructor);
11448     }
11449   } else if (CXXDestructorDecl *Destructor =
11450                  dyn_cast<CXXDestructorDecl>(Func)) {
11451     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11452     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11453       DefineImplicitDestructor(Loc, Destructor);
11454     if (Destructor->isVirtual())
11455       MarkVTableUsed(Loc, Destructor->getParent());
11456   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11457     if (MethodDecl->isOverloadedOperator() &&
11458         MethodDecl->getOverloadedOperator() == OO_Equal) {
11459       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11460       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11461         if (MethodDecl->isCopyAssignmentOperator())
11462           DefineImplicitCopyAssignment(Loc, MethodDecl);
11463         else
11464           DefineImplicitMoveAssignment(Loc, MethodDecl);
11465       }
11466     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11467                MethodDecl->getParent()->isLambda()) {
11468       CXXConversionDecl *Conversion =
11469           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11470       if (Conversion->isLambdaToBlockPointerConversion())
11471         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11472       else
11473         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11474     } else if (MethodDecl->isVirtual())
11475       MarkVTableUsed(Loc, MethodDecl->getParent());
11476   }
11477 
11478   // Recursive functions should be marked when used from another function.
11479   // FIXME: Is this really right?
11480   if (CurContext == Func) return;
11481 
11482   // Resolve the exception specification for any function which is
11483   // used: CodeGen will need it.
11484   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11485   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11486     ResolveExceptionSpec(Loc, FPT);
11487 
11488   if (!OdrUse) return;
11489 
11490   // Implicit instantiation of function templates and member functions of
11491   // class templates.
11492   if (Func->isImplicitlyInstantiable()) {
11493     bool AlreadyInstantiated = false;
11494     SourceLocation PointOfInstantiation = Loc;
11495     if (FunctionTemplateSpecializationInfo *SpecInfo
11496                               = Func->getTemplateSpecializationInfo()) {
11497       if (SpecInfo->getPointOfInstantiation().isInvalid())
11498         SpecInfo->setPointOfInstantiation(Loc);
11499       else if (SpecInfo->getTemplateSpecializationKind()
11500                  == TSK_ImplicitInstantiation) {
11501         AlreadyInstantiated = true;
11502         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11503       }
11504     } else if (MemberSpecializationInfo *MSInfo
11505                                 = Func->getMemberSpecializationInfo()) {
11506       if (MSInfo->getPointOfInstantiation().isInvalid())
11507         MSInfo->setPointOfInstantiation(Loc);
11508       else if (MSInfo->getTemplateSpecializationKind()
11509                  == TSK_ImplicitInstantiation) {
11510         AlreadyInstantiated = true;
11511         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11512       }
11513     }
11514 
11515     if (!AlreadyInstantiated || Func->isConstexpr()) {
11516       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11517           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11518           ActiveTemplateInstantiations.size())
11519         PendingLocalImplicitInstantiations.push_back(
11520             std::make_pair(Func, PointOfInstantiation));
11521       else if (Func->isConstexpr())
11522         // Do not defer instantiations of constexpr functions, to avoid the
11523         // expression evaluator needing to call back into Sema if it sees a
11524         // call to such a function.
11525         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11526       else {
11527         PendingInstantiations.push_back(std::make_pair(Func,
11528                                                        PointOfInstantiation));
11529         // Notify the consumer that a function was implicitly instantiated.
11530         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11531       }
11532     }
11533   } else {
11534     // Walk redefinitions, as some of them may be instantiable.
11535     for (auto i : Func->redecls()) {
11536       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11537         MarkFunctionReferenced(Loc, i);
11538     }
11539   }
11540 
11541   // Keep track of used but undefined functions.
11542   if (!Func->isDefined()) {
11543     if (mightHaveNonExternalLinkage(Func))
11544       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11545     else if (Func->getMostRecentDecl()->isInlined() &&
11546              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11547              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11548       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11549   }
11550 
11551   // Normally the most current decl is marked used while processing the use and
11552   // any subsequent decls are marked used by decl merging. This fails with
11553   // template instantiation since marking can happen at the end of the file
11554   // and, because of the two phase lookup, this function is called with at
11555   // decl in the middle of a decl chain. We loop to maintain the invariant
11556   // that once a decl is used, all decls after it are also used.
11557   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11558     F->markUsed(Context);
11559     if (F == Func)
11560       break;
11561   }
11562 }
11563 
11564 static void
11565 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11566                                    VarDecl *var, DeclContext *DC) {
11567   DeclContext *VarDC = var->getDeclContext();
11568 
11569   //  If the parameter still belongs to the translation unit, then
11570   //  we're actually just using one parameter in the declaration of
11571   //  the next.
11572   if (isa<ParmVarDecl>(var) &&
11573       isa<TranslationUnitDecl>(VarDC))
11574     return;
11575 
11576   // For C code, don't diagnose about capture if we're not actually in code
11577   // right now; it's impossible to write a non-constant expression outside of
11578   // function context, so we'll get other (more useful) diagnostics later.
11579   //
11580   // For C++, things get a bit more nasty... it would be nice to suppress this
11581   // diagnostic for certain cases like using a local variable in an array bound
11582   // for a member of a local class, but the correct predicate is not obvious.
11583   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11584     return;
11585 
11586   if (isa<CXXMethodDecl>(VarDC) &&
11587       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11588     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11589       << var->getIdentifier();
11590   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11591     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11592       << var->getIdentifier() << fn->getDeclName();
11593   } else if (isa<BlockDecl>(VarDC)) {
11594     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11595       << var->getIdentifier();
11596   } else {
11597     // FIXME: Is there any other context where a local variable can be
11598     // declared?
11599     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11600       << var->getIdentifier();
11601   }
11602 
11603   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11604       << var->getIdentifier();
11605 
11606   // FIXME: Add additional diagnostic info about class etc. which prevents
11607   // capture.
11608 }
11609 
11610 
11611 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11612                                       bool &SubCapturesAreNested,
11613                                       QualType &CaptureType,
11614                                       QualType &DeclRefType) {
11615    // Check whether we've already captured it.
11616   if (CSI->CaptureMap.count(Var)) {
11617     // If we found a capture, any subcaptures are nested.
11618     SubCapturesAreNested = true;
11619 
11620     // Retrieve the capture type for this variable.
11621     CaptureType = CSI->getCapture(Var).getCaptureType();
11622 
11623     // Compute the type of an expression that refers to this variable.
11624     DeclRefType = CaptureType.getNonReferenceType();
11625 
11626     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11627     if (Cap.isCopyCapture() &&
11628         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11629       DeclRefType.addConst();
11630     return true;
11631   }
11632   return false;
11633 }
11634 
11635 // Only block literals, captured statements, and lambda expressions can
11636 // capture; other scopes don't work.
11637 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11638                                  SourceLocation Loc,
11639                                  const bool Diagnose, Sema &S) {
11640   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11641     return getLambdaAwareParentOfDeclContext(DC);
11642   else {
11643     if (Diagnose)
11644        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11645   }
11646   return nullptr;
11647 }
11648 
11649 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11650 // certain types of variables (unnamed, variably modified types etc.)
11651 // so check for eligibility.
11652 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11653                                  SourceLocation Loc,
11654                                  const bool Diagnose, Sema &S) {
11655 
11656   bool IsBlock = isa<BlockScopeInfo>(CSI);
11657   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11658 
11659   // Lambdas are not allowed to capture unnamed variables
11660   // (e.g. anonymous unions).
11661   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11662   // assuming that's the intent.
11663   if (IsLambda && !Var->getDeclName()) {
11664     if (Diagnose) {
11665       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11666       S.Diag(Var->getLocation(), diag::note_declared_at);
11667     }
11668     return false;
11669   }
11670 
11671   // Prohibit variably-modified types in blocks; they're difficult to deal with.
11672   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
11673     if (Diagnose) {
11674       S.Diag(Loc, diag::err_ref_vm_type);
11675       S.Diag(Var->getLocation(), diag::note_previous_decl)
11676         << Var->getDeclName();
11677     }
11678     return false;
11679   }
11680   // Prohibit structs with flexible array members too.
11681   // We cannot capture what is in the tail end of the struct.
11682   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11683     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11684       if (Diagnose) {
11685         if (IsBlock)
11686           S.Diag(Loc, diag::err_ref_flexarray_type);
11687         else
11688           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11689             << Var->getDeclName();
11690         S.Diag(Var->getLocation(), diag::note_previous_decl)
11691           << Var->getDeclName();
11692       }
11693       return false;
11694     }
11695   }
11696   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11697   // Lambdas and captured statements are not allowed to capture __block
11698   // variables; they don't support the expected semantics.
11699   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11700     if (Diagnose) {
11701       S.Diag(Loc, diag::err_capture_block_variable)
11702         << Var->getDeclName() << !IsLambda;
11703       S.Diag(Var->getLocation(), diag::note_previous_decl)
11704         << Var->getDeclName();
11705     }
11706     return false;
11707   }
11708 
11709   return true;
11710 }
11711 
11712 // Returns true if the capture by block was successful.
11713 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11714                                  SourceLocation Loc,
11715                                  const bool BuildAndDiagnose,
11716                                  QualType &CaptureType,
11717                                  QualType &DeclRefType,
11718                                  const bool Nested,
11719                                  Sema &S) {
11720   Expr *CopyExpr = nullptr;
11721   bool ByRef = false;
11722 
11723   // Blocks are not allowed to capture arrays.
11724   if (CaptureType->isArrayType()) {
11725     if (BuildAndDiagnose) {
11726       S.Diag(Loc, diag::err_ref_array_type);
11727       S.Diag(Var->getLocation(), diag::note_previous_decl)
11728       << Var->getDeclName();
11729     }
11730     return false;
11731   }
11732 
11733   // Forbid the block-capture of autoreleasing variables.
11734   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11735     if (BuildAndDiagnose) {
11736       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11737         << /*block*/ 0;
11738       S.Diag(Var->getLocation(), diag::note_previous_decl)
11739         << Var->getDeclName();
11740     }
11741     return false;
11742   }
11743   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11744   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11745     // Block capture by reference does not change the capture or
11746     // declaration reference types.
11747     ByRef = true;
11748   } else {
11749     // Block capture by copy introduces 'const'.
11750     CaptureType = CaptureType.getNonReferenceType().withConst();
11751     DeclRefType = CaptureType;
11752 
11753     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11754       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11755         // The capture logic needs the destructor, so make sure we mark it.
11756         // Usually this is unnecessary because most local variables have
11757         // their destructors marked at declaration time, but parameters are
11758         // an exception because it's technically only the call site that
11759         // actually requires the destructor.
11760         if (isa<ParmVarDecl>(Var))
11761           S.FinalizeVarWithDestructor(Var, Record);
11762 
11763         // Enter a new evaluation context to insulate the copy
11764         // full-expression.
11765         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11766 
11767         // According to the blocks spec, the capture of a variable from
11768         // the stack requires a const copy constructor.  This is not true
11769         // of the copy/move done to move a __block variable to the heap.
11770         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11771                                                   DeclRefType.withConst(),
11772                                                   VK_LValue, Loc);
11773 
11774         ExprResult Result
11775           = S.PerformCopyInitialization(
11776               InitializedEntity::InitializeBlock(Var->getLocation(),
11777                                                   CaptureType, false),
11778               Loc, DeclRef);
11779 
11780         // Build a full-expression copy expression if initialization
11781         // succeeded and used a non-trivial constructor.  Recover from
11782         // errors by pretending that the copy isn't necessary.
11783         if (!Result.isInvalid() &&
11784             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11785                 ->isTrivial()) {
11786           Result = S.MaybeCreateExprWithCleanups(Result);
11787           CopyExpr = Result.get();
11788         }
11789       }
11790     }
11791   }
11792 
11793   // Actually capture the variable.
11794   if (BuildAndDiagnose)
11795     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11796                     SourceLocation(), CaptureType, CopyExpr);
11797 
11798   return true;
11799 
11800 }
11801 
11802 
11803 /// \brief Capture the given variable in the captured region.
11804 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11805                                     VarDecl *Var,
11806                                     SourceLocation Loc,
11807                                     const bool BuildAndDiagnose,
11808                                     QualType &CaptureType,
11809                                     QualType &DeclRefType,
11810                                     const bool RefersToEnclosingLocal,
11811                                     Sema &S) {
11812 
11813   // By default, capture variables by reference.
11814   bool ByRef = true;
11815   // Using an LValue reference type is consistent with Lambdas (see below).
11816   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11817   Expr *CopyExpr = nullptr;
11818   if (BuildAndDiagnose) {
11819     // The current implementation assumes that all variables are captured
11820     // by references. Since there is no capture by copy, no expression
11821     // evaluation will be needed.
11822     RecordDecl *RD = RSI->TheRecordDecl;
11823 
11824     FieldDecl *Field
11825       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11826                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11827                           nullptr, false, ICIS_NoInit);
11828     Field->setImplicit(true);
11829     Field->setAccess(AS_private);
11830     RD->addDecl(Field);
11831 
11832     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11833                                             DeclRefType, VK_LValue, Loc);
11834     Var->setReferenced(true);
11835     Var->markUsed(S.Context);
11836   }
11837 
11838   // Actually capture the variable.
11839   if (BuildAndDiagnose)
11840     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11841                     SourceLocation(), CaptureType, CopyExpr);
11842 
11843 
11844   return true;
11845 }
11846 
11847 /// \brief Create a field within the lambda class for the variable
11848 ///  being captured.  Handle Array captures.
11849 static ExprResult addAsFieldToClosureType(Sema &S,
11850                                  LambdaScopeInfo *LSI,
11851                                   VarDecl *Var, QualType FieldType,
11852                                   QualType DeclRefType,
11853                                   SourceLocation Loc,
11854                                   bool RefersToEnclosingLocal) {
11855   CXXRecordDecl *Lambda = LSI->Lambda;
11856 
11857   // Build the non-static data member.
11858   FieldDecl *Field
11859     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11860                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11861                         nullptr, false, ICIS_NoInit);
11862   Field->setImplicit(true);
11863   Field->setAccess(AS_private);
11864   Lambda->addDecl(Field);
11865 
11866   // C++11 [expr.prim.lambda]p21:
11867   //   When the lambda-expression is evaluated, the entities that
11868   //   are captured by copy are used to direct-initialize each
11869   //   corresponding non-static data member of the resulting closure
11870   //   object. (For array members, the array elements are
11871   //   direct-initialized in increasing subscript order.) These
11872   //   initializations are performed in the (unspecified) order in
11873   //   which the non-static data members are declared.
11874 
11875   // Introduce a new evaluation context for the initialization, so
11876   // that temporaries introduced as part of the capture are retained
11877   // to be re-"exported" from the lambda expression itself.
11878   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11879 
11880   // C++ [expr.prim.labda]p12:
11881   //   An entity captured by a lambda-expression is odr-used (3.2) in
11882   //   the scope containing the lambda-expression.
11883   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11884                                           DeclRefType, VK_LValue, Loc);
11885   Var->setReferenced(true);
11886   Var->markUsed(S.Context);
11887 
11888   // When the field has array type, create index variables for each
11889   // dimension of the array. We use these index variables to subscript
11890   // the source array, and other clients (e.g., CodeGen) will perform
11891   // the necessary iteration with these index variables.
11892   SmallVector<VarDecl *, 4> IndexVariables;
11893   QualType BaseType = FieldType;
11894   QualType SizeType = S.Context.getSizeType();
11895   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11896   while (const ConstantArrayType *Array
11897                         = S.Context.getAsConstantArrayType(BaseType)) {
11898     // Create the iteration variable for this array index.
11899     IdentifierInfo *IterationVarName = nullptr;
11900     {
11901       SmallString<8> Str;
11902       llvm::raw_svector_ostream OS(Str);
11903       OS << "__i" << IndexVariables.size();
11904       IterationVarName = &S.Context.Idents.get(OS.str());
11905     }
11906     VarDecl *IterationVar
11907       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11908                         IterationVarName, SizeType,
11909                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11910                         SC_None);
11911     IndexVariables.push_back(IterationVar);
11912     LSI->ArrayIndexVars.push_back(IterationVar);
11913 
11914     // Create a reference to the iteration variable.
11915     ExprResult IterationVarRef
11916       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11917     assert(!IterationVarRef.isInvalid() &&
11918            "Reference to invented variable cannot fail!");
11919     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11920     assert(!IterationVarRef.isInvalid() &&
11921            "Conversion of invented variable cannot fail!");
11922 
11923     // Subscript the array with this iteration variable.
11924     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11925                              Ref, Loc, IterationVarRef.get(), Loc);
11926     if (Subscript.isInvalid()) {
11927       S.CleanupVarDeclMarking();
11928       S.DiscardCleanupsInEvaluationContext();
11929       return ExprError();
11930     }
11931 
11932     Ref = Subscript.get();
11933     BaseType = Array->getElementType();
11934   }
11935 
11936   // Construct the entity that we will be initializing. For an array, this
11937   // will be first element in the array, which may require several levels
11938   // of array-subscript entities.
11939   SmallVector<InitializedEntity, 4> Entities;
11940   Entities.reserve(1 + IndexVariables.size());
11941   Entities.push_back(
11942     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11943         Field->getType(), Loc));
11944   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11945     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11946                                                             0,
11947                                                             Entities.back()));
11948 
11949   InitializationKind InitKind
11950     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11951   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11952   ExprResult Result(true);
11953   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11954     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11955 
11956   // If this initialization requires any cleanups (e.g., due to a
11957   // default argument to a copy constructor), note that for the
11958   // lambda.
11959   if (S.ExprNeedsCleanups)
11960     LSI->ExprNeedsCleanups = true;
11961 
11962   // Exit the expression evaluation context used for the capture.
11963   S.CleanupVarDeclMarking();
11964   S.DiscardCleanupsInEvaluationContext();
11965   return Result;
11966 }
11967 
11968 
11969 
11970 /// \brief Capture the given variable in the lambda.
11971 static bool captureInLambda(LambdaScopeInfo *LSI,
11972                             VarDecl *Var,
11973                             SourceLocation Loc,
11974                             const bool BuildAndDiagnose,
11975                             QualType &CaptureType,
11976                             QualType &DeclRefType,
11977                             const bool RefersToEnclosingLocal,
11978                             const Sema::TryCaptureKind Kind,
11979                             SourceLocation EllipsisLoc,
11980                             const bool IsTopScope,
11981                             Sema &S) {
11982 
11983   // Determine whether we are capturing by reference or by value.
11984   bool ByRef = false;
11985   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11986     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11987   } else {
11988     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11989   }
11990 
11991   // Compute the type of the field that will capture this variable.
11992   if (ByRef) {
11993     // C++11 [expr.prim.lambda]p15:
11994     //   An entity is captured by reference if it is implicitly or
11995     //   explicitly captured but not captured by copy. It is
11996     //   unspecified whether additional unnamed non-static data
11997     //   members are declared in the closure type for entities
11998     //   captured by reference.
11999     //
12000     // FIXME: It is not clear whether we want to build an lvalue reference
12001     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12002     // to do the former, while EDG does the latter. Core issue 1249 will
12003     // clarify, but for now we follow GCC because it's a more permissive and
12004     // easily defensible position.
12005     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12006   } else {
12007     // C++11 [expr.prim.lambda]p14:
12008     //   For each entity captured by copy, an unnamed non-static
12009     //   data member is declared in the closure type. The
12010     //   declaration order of these members is unspecified. The type
12011     //   of such a data member is the type of the corresponding
12012     //   captured entity if the entity is not a reference to an
12013     //   object, or the referenced type otherwise. [Note: If the
12014     //   captured entity is a reference to a function, the
12015     //   corresponding data member is also a reference to a
12016     //   function. - end note ]
12017     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12018       if (!RefType->getPointeeType()->isFunctionType())
12019         CaptureType = RefType->getPointeeType();
12020     }
12021 
12022     // Forbid the lambda copy-capture of autoreleasing variables.
12023     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12024       if (BuildAndDiagnose) {
12025         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12026         S.Diag(Var->getLocation(), diag::note_previous_decl)
12027           << Var->getDeclName();
12028       }
12029       return false;
12030     }
12031 
12032     // Make sure that by-copy captures are of a complete and non-abstract type.
12033     if (BuildAndDiagnose) {
12034       if (!CaptureType->isDependentType() &&
12035           S.RequireCompleteType(Loc, CaptureType,
12036                                 diag::err_capture_of_incomplete_type,
12037                                 Var->getDeclName()))
12038         return false;
12039 
12040       if (S.RequireNonAbstractType(Loc, CaptureType,
12041                                    diag::err_capture_of_abstract_type))
12042         return false;
12043     }
12044   }
12045 
12046   // Capture this variable in the lambda.
12047   Expr *CopyExpr = nullptr;
12048   if (BuildAndDiagnose) {
12049     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
12050                                         CaptureType, DeclRefType, Loc,
12051                                         RefersToEnclosingLocal);
12052     if (!Result.isInvalid())
12053       CopyExpr = Result.get();
12054   }
12055 
12056   // Compute the type of a reference to this captured variable.
12057   if (ByRef)
12058     DeclRefType = CaptureType.getNonReferenceType();
12059   else {
12060     // C++ [expr.prim.lambda]p5:
12061     //   The closure type for a lambda-expression has a public inline
12062     //   function call operator [...]. This function call operator is
12063     //   declared const (9.3.1) if and only if the lambda-expression’s
12064     //   parameter-declaration-clause is not followed by mutable.
12065     DeclRefType = CaptureType.getNonReferenceType();
12066     if (!LSI->Mutable && !CaptureType->isReferenceType())
12067       DeclRefType.addConst();
12068   }
12069 
12070   // Add the capture.
12071   if (BuildAndDiagnose)
12072     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
12073                     Loc, EllipsisLoc, CaptureType, CopyExpr);
12074 
12075   return true;
12076 }
12077 
12078 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
12079                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
12080                               bool BuildAndDiagnose,
12081                               QualType &CaptureType,
12082                               QualType &DeclRefType,
12083 						                const unsigned *const FunctionScopeIndexToStopAt) {
12084   bool Nested = false;
12085 
12086   DeclContext *DC = CurContext;
12087   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12088       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12089   // We need to sync up the Declaration Context with the
12090   // FunctionScopeIndexToStopAt
12091   if (FunctionScopeIndexToStopAt) {
12092     unsigned FSIndex = FunctionScopes.size() - 1;
12093     while (FSIndex != MaxFunctionScopesIndex) {
12094       DC = getLambdaAwareParentOfDeclContext(DC);
12095       --FSIndex;
12096     }
12097   }
12098 
12099 
12100   // If the variable is declared in the current context (and is not an
12101   // init-capture), there is no need to capture it.
12102   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
12103   if (!Var->hasLocalStorage()) return true;
12104 
12105   // Walk up the stack to determine whether we can capture the variable,
12106   // performing the "simple" checks that don't depend on type. We stop when
12107   // we've either hit the declared scope of the variable or find an existing
12108   // capture of that variable.  We start from the innermost capturing-entity
12109   // (the DC) and ensure that all intervening capturing-entities
12110   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12111   // declcontext can either capture the variable or have already captured
12112   // the variable.
12113   CaptureType = Var->getType();
12114   DeclRefType = CaptureType.getNonReferenceType();
12115   bool Explicit = (Kind != TryCapture_Implicit);
12116   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12117   do {
12118     // Only block literals, captured statements, and lambda expressions can
12119     // capture; other scopes don't work.
12120     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12121                                                               ExprLoc,
12122                                                               BuildAndDiagnose,
12123                                                               *this);
12124     if (!ParentDC) return true;
12125 
12126     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12127     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12128 
12129 
12130     // Check whether we've already captured it.
12131     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12132                                              DeclRefType))
12133       break;
12134     // If we are instantiating a generic lambda call operator body,
12135     // we do not want to capture new variables.  What was captured
12136     // during either a lambdas transformation or initial parsing
12137     // should be used.
12138     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12139       if (BuildAndDiagnose) {
12140         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12141         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12142           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12143           Diag(Var->getLocation(), diag::note_previous_decl)
12144              << Var->getDeclName();
12145           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12146         } else
12147           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12148       }
12149       return true;
12150     }
12151     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12152     // certain types of variables (unnamed, variably modified types etc.)
12153     // so check for eligibility.
12154     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12155        return true;
12156 
12157     // Try to capture variable-length arrays types.
12158     if (Var->getType()->isVariablyModifiedType()) {
12159       // We're going to walk down into the type and look for VLA
12160       // expressions.
12161       QualType QTy = Var->getType();
12162       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12163         QTy = PVD->getOriginalType();
12164       do {
12165         const Type *Ty = QTy.getTypePtr();
12166         switch (Ty->getTypeClass()) {
12167 #define TYPE(Class, Base)
12168 #define ABSTRACT_TYPE(Class, Base)
12169 #define NON_CANONICAL_TYPE(Class, Base)
12170 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12171 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12172 #include "clang/AST/TypeNodes.def"
12173           QTy = QualType();
12174           break;
12175         // These types are never variably-modified.
12176         case Type::Builtin:
12177         case Type::Complex:
12178         case Type::Vector:
12179         case Type::ExtVector:
12180         case Type::Record:
12181         case Type::Enum:
12182         case Type::Elaborated:
12183         case Type::TemplateSpecialization:
12184         case Type::ObjCObject:
12185         case Type::ObjCInterface:
12186         case Type::ObjCObjectPointer:
12187           llvm_unreachable("type class is never variably-modified!");
12188         case Type::Adjusted:
12189           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12190           break;
12191         case Type::Decayed:
12192           QTy = cast<DecayedType>(Ty)->getPointeeType();
12193           break;
12194         case Type::Pointer:
12195           QTy = cast<PointerType>(Ty)->getPointeeType();
12196           break;
12197         case Type::BlockPointer:
12198           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12199           break;
12200         case Type::LValueReference:
12201         case Type::RValueReference:
12202           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12203           break;
12204         case Type::MemberPointer:
12205           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12206           break;
12207         case Type::ConstantArray:
12208         case Type::IncompleteArray:
12209           // Losing element qualification here is fine.
12210           QTy = cast<ArrayType>(Ty)->getElementType();
12211           break;
12212         case Type::VariableArray: {
12213           // Losing element qualification here is fine.
12214           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
12215 
12216           // Unknown size indication requires no size computation.
12217           // Otherwise, evaluate and record it.
12218           if (auto Size = VAT->getSizeExpr()) {
12219             if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12220               if (!LSI->isVLATypeCaptured(VAT)) {
12221                 auto ExprLoc = Size->getExprLoc();
12222                 auto SizeType = Context.getSizeType();
12223                 auto Lambda = LSI->Lambda;
12224 
12225                 // Build the non-static data member.
12226                 auto Field = FieldDecl::Create(
12227                     Context, Lambda, ExprLoc, ExprLoc,
12228                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12229                     /*BW*/ nullptr, /*Mutable*/ false,
12230                     /*InitStyle*/ ICIS_NoInit);
12231                 Field->setImplicit(true);
12232                 Field->setAccess(AS_private);
12233                 Field->setCapturedVLAType(VAT);
12234                 Lambda->addDecl(Field);
12235 
12236                 LSI->addVLATypeCapture(ExprLoc, SizeType);
12237               }
12238             } else {
12239               // Immediately mark all referenced vars for CapturedStatements,
12240               // they all are captured by reference.
12241               MarkDeclarationsReferencedInExpr(Size);
12242             }
12243           }
12244           QTy = VAT->getElementType();
12245           break;
12246         }
12247         case Type::FunctionProto:
12248         case Type::FunctionNoProto:
12249           QTy = cast<FunctionType>(Ty)->getReturnType();
12250           break;
12251         case Type::Paren:
12252         case Type::TypeOf:
12253         case Type::UnaryTransform:
12254         case Type::Attributed:
12255         case Type::SubstTemplateTypeParm:
12256         case Type::PackExpansion:
12257           // Keep walking after single level desugaring.
12258           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12259           break;
12260         case Type::Typedef:
12261           QTy = cast<TypedefType>(Ty)->desugar();
12262           break;
12263         case Type::Decltype:
12264           QTy = cast<DecltypeType>(Ty)->desugar();
12265           break;
12266         case Type::Auto:
12267           QTy = cast<AutoType>(Ty)->getDeducedType();
12268           break;
12269         case Type::TypeOfExpr:
12270           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12271           break;
12272         case Type::Atomic:
12273           QTy = cast<AtomicType>(Ty)->getValueType();
12274           break;
12275         }
12276       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12277     }
12278 
12279     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12280       // No capture-default, and this is not an explicit capture
12281       // so cannot capture this variable.
12282       if (BuildAndDiagnose) {
12283         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12284         Diag(Var->getLocation(), diag::note_previous_decl)
12285           << Var->getDeclName();
12286         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12287              diag::note_lambda_decl);
12288         // FIXME: If we error out because an outer lambda can not implicitly
12289         // capture a variable that an inner lambda explicitly captures, we
12290         // should have the inner lambda do the explicit capture - because
12291         // it makes for cleaner diagnostics later.  This would purely be done
12292         // so that the diagnostic does not misleadingly claim that a variable
12293         // can not be captured by a lambda implicitly even though it is captured
12294         // explicitly.  Suggestion:
12295         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12296         //    at the function head
12297         //  - cache the StartingDeclContext - this must be a lambda
12298         //  - captureInLambda in the innermost lambda the variable.
12299       }
12300       return true;
12301     }
12302 
12303     FunctionScopesIndex--;
12304     DC = ParentDC;
12305     Explicit = false;
12306   } while (!Var->getDeclContext()->Equals(DC));
12307 
12308   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12309   // computing the type of the capture at each step, checking type-specific
12310   // requirements, and adding captures if requested.
12311   // If the variable had already been captured previously, we start capturing
12312   // at the lambda nested within that one.
12313   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12314        ++I) {
12315     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12316 
12317     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12318       if (!captureInBlock(BSI, Var, ExprLoc,
12319                           BuildAndDiagnose, CaptureType,
12320                           DeclRefType, Nested, *this))
12321         return true;
12322       Nested = true;
12323     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12324       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12325                                    BuildAndDiagnose, CaptureType,
12326                                    DeclRefType, Nested, *this))
12327         return true;
12328       Nested = true;
12329     } else {
12330       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12331       if (!captureInLambda(LSI, Var, ExprLoc,
12332                            BuildAndDiagnose, CaptureType,
12333                            DeclRefType, Nested, Kind, EllipsisLoc,
12334                             /*IsTopScope*/I == N - 1, *this))
12335         return true;
12336       Nested = true;
12337     }
12338   }
12339   return false;
12340 }
12341 
12342 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12343                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12344   QualType CaptureType;
12345   QualType DeclRefType;
12346   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12347                             /*BuildAndDiagnose=*/true, CaptureType,
12348                             DeclRefType, nullptr);
12349 }
12350 
12351 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12352   QualType CaptureType;
12353   QualType DeclRefType;
12354 
12355   // Determine whether we can capture this variable.
12356   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12357                          /*BuildAndDiagnose=*/false, CaptureType,
12358                          DeclRefType, nullptr))
12359     return QualType();
12360 
12361   return DeclRefType;
12362 }
12363 
12364 
12365 
12366 // If either the type of the variable or the initializer is dependent,
12367 // return false. Otherwise, determine whether the variable is a constant
12368 // expression. Use this if you need to know if a variable that might or
12369 // might not be dependent is truly a constant expression.
12370 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12371     ASTContext &Context) {
12372 
12373   if (Var->getType()->isDependentType())
12374     return false;
12375   const VarDecl *DefVD = nullptr;
12376   Var->getAnyInitializer(DefVD);
12377   if (!DefVD)
12378     return false;
12379   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12380   Expr *Init = cast<Expr>(Eval->Value);
12381   if (Init->isValueDependent())
12382     return false;
12383   return IsVariableAConstantExpression(Var, Context);
12384 }
12385 
12386 
12387 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12388   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12389   // an object that satisfies the requirements for appearing in a
12390   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12391   // is immediately applied."  This function handles the lvalue-to-rvalue
12392   // conversion part.
12393   MaybeODRUseExprs.erase(E->IgnoreParens());
12394 
12395   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12396   // to a variable that is a constant expression, and if so, identify it as
12397   // a reference to a variable that does not involve an odr-use of that
12398   // variable.
12399   if (LambdaScopeInfo *LSI = getCurLambda()) {
12400     Expr *SansParensExpr = E->IgnoreParens();
12401     VarDecl *Var = nullptr;
12402     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12403       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12404     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12405       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12406 
12407     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12408       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12409   }
12410 }
12411 
12412 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12413   if (!Res.isUsable())
12414     return Res;
12415 
12416   // If a constant-expression is a reference to a variable where we delay
12417   // deciding whether it is an odr-use, just assume we will apply the
12418   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12419   // (a non-type template argument), we have special handling anyway.
12420   UpdateMarkingForLValueToRValue(Res.get());
12421   return Res;
12422 }
12423 
12424 void Sema::CleanupVarDeclMarking() {
12425   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12426                                         e = MaybeODRUseExprs.end();
12427        i != e; ++i) {
12428     VarDecl *Var;
12429     SourceLocation Loc;
12430     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12431       Var = cast<VarDecl>(DRE->getDecl());
12432       Loc = DRE->getLocation();
12433     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12434       Var = cast<VarDecl>(ME->getMemberDecl());
12435       Loc = ME->getMemberLoc();
12436     } else {
12437       llvm_unreachable("Unexpected expression");
12438     }
12439 
12440     MarkVarDeclODRUsed(Var, Loc, *this,
12441                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12442   }
12443 
12444   MaybeODRUseExprs.clear();
12445 }
12446 
12447 
12448 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12449                                     VarDecl *Var, Expr *E) {
12450   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12451          "Invalid Expr argument to DoMarkVarDeclReferenced");
12452   Var->setReferenced();
12453 
12454   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12455   bool MarkODRUsed = true;
12456 
12457   // If the context is not potentially evaluated, this is not an odr-use and
12458   // does not trigger instantiation.
12459   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12460     if (SemaRef.isUnevaluatedContext())
12461       return;
12462 
12463     // If we don't yet know whether this context is going to end up being an
12464     // evaluated context, and we're referencing a variable from an enclosing
12465     // scope, add a potential capture.
12466     //
12467     // FIXME: Is this necessary? These contexts are only used for default
12468     // arguments, where local variables can't be used.
12469     const bool RefersToEnclosingScope =
12470         (SemaRef.CurContext != Var->getDeclContext() &&
12471          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
12472     if (RefersToEnclosingScope) {
12473       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12474         // If a variable could potentially be odr-used, defer marking it so
12475         // until we finish analyzing the full expression for any
12476         // lvalue-to-rvalue
12477         // or discarded value conversions that would obviate odr-use.
12478         // Add it to the list of potential captures that will be analyzed
12479         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12480         // unless the variable is a reference that was initialized by a constant
12481         // expression (this will never need to be captured or odr-used).
12482         assert(E && "Capture variable should be used in an expression.");
12483         if (!Var->getType()->isReferenceType() ||
12484             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12485           LSI->addPotentialCapture(E->IgnoreParens());
12486       }
12487     }
12488 
12489     if (!isTemplateInstantiation(TSK))
12490     	return;
12491 
12492     // Instantiate, but do not mark as odr-used, variable templates.
12493     MarkODRUsed = false;
12494   }
12495 
12496   VarTemplateSpecializationDecl *VarSpec =
12497       dyn_cast<VarTemplateSpecializationDecl>(Var);
12498   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12499          "Can't instantiate a partial template specialization.");
12500 
12501   // Perform implicit instantiation of static data members, static data member
12502   // templates of class templates, and variable template specializations. Delay
12503   // instantiations of variable templates, except for those that could be used
12504   // in a constant expression.
12505   if (isTemplateInstantiation(TSK)) {
12506     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12507 
12508     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12509       if (Var->getPointOfInstantiation().isInvalid()) {
12510         // This is a modification of an existing AST node. Notify listeners.
12511         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12512           L->StaticDataMemberInstantiated(Var);
12513       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12514         // Don't bother trying to instantiate it again, unless we might need
12515         // its initializer before we get to the end of the TU.
12516         TryInstantiating = false;
12517     }
12518 
12519     if (Var->getPointOfInstantiation().isInvalid())
12520       Var->setTemplateSpecializationKind(TSK, Loc);
12521 
12522     if (TryInstantiating) {
12523       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12524       bool InstantiationDependent = false;
12525       bool IsNonDependent =
12526           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12527                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12528                   : true;
12529 
12530       // Do not instantiate specializations that are still type-dependent.
12531       if (IsNonDependent) {
12532         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12533           // Do not defer instantiations of variables which could be used in a
12534           // constant expression.
12535           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12536         } else {
12537           SemaRef.PendingInstantiations
12538               .push_back(std::make_pair(Var, PointOfInstantiation));
12539         }
12540       }
12541     }
12542   }
12543 
12544   if(!MarkODRUsed) return;
12545 
12546   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12547   // the requirements for appearing in a constant expression (5.19) and, if
12548   // it is an object, the lvalue-to-rvalue conversion (4.1)
12549   // is immediately applied."  We check the first part here, and
12550   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12551   // Note that we use the C++11 definition everywhere because nothing in
12552   // C++03 depends on whether we get the C++03 version correct. The second
12553   // part does not apply to references, since they are not objects.
12554   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12555     // A reference initialized by a constant expression can never be
12556     // odr-used, so simply ignore it.
12557     if (!Var->getType()->isReferenceType())
12558       SemaRef.MaybeODRUseExprs.insert(E);
12559   } else
12560     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12561                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12562 }
12563 
12564 /// \brief Mark a variable referenced, and check whether it is odr-used
12565 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12566 /// used directly for normal expressions referring to VarDecl.
12567 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12568   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12569 }
12570 
12571 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12572                                Decl *D, Expr *E, bool OdrUse) {
12573   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12574     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12575     return;
12576   }
12577 
12578   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12579 
12580   // If this is a call to a method via a cast, also mark the method in the
12581   // derived class used in case codegen can devirtualize the call.
12582   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12583   if (!ME)
12584     return;
12585   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12586   if (!MD)
12587     return;
12588   // Only attempt to devirtualize if this is truly a virtual call.
12589   bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
12590   if (!IsVirtualCall)
12591     return;
12592   const Expr *Base = ME->getBase();
12593   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12594   if (!MostDerivedClassDecl)
12595     return;
12596   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12597   if (!DM || DM->isPure())
12598     return;
12599   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12600 }
12601 
12602 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12603 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12604   // TODO: update this with DR# once a defect report is filed.
12605   // C++11 defect. The address of a pure member should not be an ODR use, even
12606   // if it's a qualified reference.
12607   bool OdrUse = true;
12608   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12609     if (Method->isVirtual())
12610       OdrUse = false;
12611   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12612 }
12613 
12614 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12615 void Sema::MarkMemberReferenced(MemberExpr *E) {
12616   // C++11 [basic.def.odr]p2:
12617   //   A non-overloaded function whose name appears as a potentially-evaluated
12618   //   expression or a member of a set of candidate functions, if selected by
12619   //   overload resolution when referred to from a potentially-evaluated
12620   //   expression, is odr-used, unless it is a pure virtual function and its
12621   //   name is not explicitly qualified.
12622   bool OdrUse = true;
12623   if (!E->hasQualifier()) {
12624     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12625       if (Method->isPure())
12626         OdrUse = false;
12627   }
12628   SourceLocation Loc = E->getMemberLoc().isValid() ?
12629                             E->getMemberLoc() : E->getLocStart();
12630   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12631 }
12632 
12633 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12634 /// marks the declaration referenced, and performs odr-use checking for
12635 /// functions and variables. This method should not be used when building a
12636 /// normal expression which refers to a variable.
12637 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12638   if (OdrUse) {
12639     if (auto *VD = dyn_cast<VarDecl>(D)) {
12640       MarkVariableReferenced(Loc, VD);
12641       return;
12642     }
12643   }
12644   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
12645     MarkFunctionReferenced(Loc, FD, OdrUse);
12646     return;
12647   }
12648   D->setReferenced();
12649 }
12650 
12651 namespace {
12652   // Mark all of the declarations referenced
12653   // FIXME: Not fully implemented yet! We need to have a better understanding
12654   // of when we're entering
12655   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12656     Sema &S;
12657     SourceLocation Loc;
12658 
12659   public:
12660     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12661 
12662     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12663 
12664     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12665     bool TraverseRecordType(RecordType *T);
12666   };
12667 }
12668 
12669 bool MarkReferencedDecls::TraverseTemplateArgument(
12670     const TemplateArgument &Arg) {
12671   if (Arg.getKind() == TemplateArgument::Declaration) {
12672     if (Decl *D = Arg.getAsDecl())
12673       S.MarkAnyDeclReferenced(Loc, D, true);
12674   }
12675 
12676   return Inherited::TraverseTemplateArgument(Arg);
12677 }
12678 
12679 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12680   if (ClassTemplateSpecializationDecl *Spec
12681                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12682     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12683     return TraverseTemplateArguments(Args.data(), Args.size());
12684   }
12685 
12686   return true;
12687 }
12688 
12689 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12690   MarkReferencedDecls Marker(*this, Loc);
12691   Marker.TraverseType(Context.getCanonicalType(T));
12692 }
12693 
12694 namespace {
12695   /// \brief Helper class that marks all of the declarations referenced by
12696   /// potentially-evaluated subexpressions as "referenced".
12697   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12698     Sema &S;
12699     bool SkipLocalVariables;
12700 
12701   public:
12702     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12703 
12704     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12705       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12706 
12707     void VisitDeclRefExpr(DeclRefExpr *E) {
12708       // If we were asked not to visit local variables, don't.
12709       if (SkipLocalVariables) {
12710         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12711           if (VD->hasLocalStorage())
12712             return;
12713       }
12714 
12715       S.MarkDeclRefReferenced(E);
12716     }
12717 
12718     void VisitMemberExpr(MemberExpr *E) {
12719       S.MarkMemberReferenced(E);
12720       Inherited::VisitMemberExpr(E);
12721     }
12722 
12723     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12724       S.MarkFunctionReferenced(E->getLocStart(),
12725             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12726       Visit(E->getSubExpr());
12727     }
12728 
12729     void VisitCXXNewExpr(CXXNewExpr *E) {
12730       if (E->getOperatorNew())
12731         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12732       if (E->getOperatorDelete())
12733         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12734       Inherited::VisitCXXNewExpr(E);
12735     }
12736 
12737     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12738       if (E->getOperatorDelete())
12739         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12740       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12741       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12742         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12743         S.MarkFunctionReferenced(E->getLocStart(),
12744                                     S.LookupDestructor(Record));
12745       }
12746 
12747       Inherited::VisitCXXDeleteExpr(E);
12748     }
12749 
12750     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12751       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12752       Inherited::VisitCXXConstructExpr(E);
12753     }
12754 
12755     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12756       Visit(E->getExpr());
12757     }
12758 
12759     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12760       Inherited::VisitImplicitCastExpr(E);
12761 
12762       if (E->getCastKind() == CK_LValueToRValue)
12763         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12764     }
12765   };
12766 }
12767 
12768 /// \brief Mark any declarations that appear within this expression or any
12769 /// potentially-evaluated subexpressions as "referenced".
12770 ///
12771 /// \param SkipLocalVariables If true, don't mark local variables as
12772 /// 'referenced'.
12773 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12774                                             bool SkipLocalVariables) {
12775   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12776 }
12777 
12778 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12779 /// of the program being compiled.
12780 ///
12781 /// This routine emits the given diagnostic when the code currently being
12782 /// type-checked is "potentially evaluated", meaning that there is a
12783 /// possibility that the code will actually be executable. Code in sizeof()
12784 /// expressions, code used only during overload resolution, etc., are not
12785 /// potentially evaluated. This routine will suppress such diagnostics or,
12786 /// in the absolutely nutty case of potentially potentially evaluated
12787 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12788 /// later.
12789 ///
12790 /// This routine should be used for all diagnostics that describe the run-time
12791 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12792 /// Failure to do so will likely result in spurious diagnostics or failures
12793 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12794 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12795                                const PartialDiagnostic &PD) {
12796   switch (ExprEvalContexts.back().Context) {
12797   case Unevaluated:
12798   case UnevaluatedAbstract:
12799     // The argument will never be evaluated, so don't complain.
12800     break;
12801 
12802   case ConstantEvaluated:
12803     // Relevant diagnostics should be produced by constant evaluation.
12804     break;
12805 
12806   case PotentiallyEvaluated:
12807   case PotentiallyEvaluatedIfUsed:
12808     if (Statement && getCurFunctionOrMethodDecl()) {
12809       FunctionScopes.back()->PossiblyUnreachableDiags.
12810         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12811     }
12812     else
12813       Diag(Loc, PD);
12814 
12815     return true;
12816   }
12817 
12818   return false;
12819 }
12820 
12821 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12822                                CallExpr *CE, FunctionDecl *FD) {
12823   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12824     return false;
12825 
12826   // If we're inside a decltype's expression, don't check for a valid return
12827   // type or construct temporaries until we know whether this is the last call.
12828   if (ExprEvalContexts.back().IsDecltype) {
12829     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12830     return false;
12831   }
12832 
12833   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12834     FunctionDecl *FD;
12835     CallExpr *CE;
12836 
12837   public:
12838     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12839       : FD(FD), CE(CE) { }
12840 
12841     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12842       if (!FD) {
12843         S.Diag(Loc, diag::err_call_incomplete_return)
12844           << T << CE->getSourceRange();
12845         return;
12846       }
12847 
12848       S.Diag(Loc, diag::err_call_function_incomplete_return)
12849         << CE->getSourceRange() << FD->getDeclName() << T;
12850       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12851           << FD->getDeclName();
12852     }
12853   } Diagnoser(FD, CE);
12854 
12855   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12856     return true;
12857 
12858   return false;
12859 }
12860 
12861 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12862 // will prevent this condition from triggering, which is what we want.
12863 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12864   SourceLocation Loc;
12865 
12866   unsigned diagnostic = diag::warn_condition_is_assignment;
12867   bool IsOrAssign = false;
12868 
12869   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12870     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12871       return;
12872 
12873     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12874 
12875     // Greylist some idioms by putting them into a warning subcategory.
12876     if (ObjCMessageExpr *ME
12877           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12878       Selector Sel = ME->getSelector();
12879 
12880       // self = [<foo> init...]
12881       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12882         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12883 
12884       // <foo> = [<bar> nextObject]
12885       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12886         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12887     }
12888 
12889     Loc = Op->getOperatorLoc();
12890   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12891     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12892       return;
12893 
12894     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12895     Loc = Op->getOperatorLoc();
12896   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12897     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12898   else {
12899     // Not an assignment.
12900     return;
12901   }
12902 
12903   Diag(Loc, diagnostic) << E->getSourceRange();
12904 
12905   SourceLocation Open = E->getLocStart();
12906   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12907   Diag(Loc, diag::note_condition_assign_silence)
12908         << FixItHint::CreateInsertion(Open, "(")
12909         << FixItHint::CreateInsertion(Close, ")");
12910 
12911   if (IsOrAssign)
12912     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12913       << FixItHint::CreateReplacement(Loc, "!=");
12914   else
12915     Diag(Loc, diag::note_condition_assign_to_comparison)
12916       << FixItHint::CreateReplacement(Loc, "==");
12917 }
12918 
12919 /// \brief Redundant parentheses over an equality comparison can indicate
12920 /// that the user intended an assignment used as condition.
12921 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12922   // Don't warn if the parens came from a macro.
12923   SourceLocation parenLoc = ParenE->getLocStart();
12924   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12925     return;
12926   // Don't warn for dependent expressions.
12927   if (ParenE->isTypeDependent())
12928     return;
12929 
12930   Expr *E = ParenE->IgnoreParens();
12931 
12932   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12933     if (opE->getOpcode() == BO_EQ &&
12934         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12935                                                            == Expr::MLV_Valid) {
12936       SourceLocation Loc = opE->getOperatorLoc();
12937 
12938       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12939       SourceRange ParenERange = ParenE->getSourceRange();
12940       Diag(Loc, diag::note_equality_comparison_silence)
12941         << FixItHint::CreateRemoval(ParenERange.getBegin())
12942         << FixItHint::CreateRemoval(ParenERange.getEnd());
12943       Diag(Loc, diag::note_equality_comparison_to_assign)
12944         << FixItHint::CreateReplacement(Loc, "=");
12945     }
12946 }
12947 
12948 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12949   DiagnoseAssignmentAsCondition(E);
12950   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12951     DiagnoseEqualityWithExtraParens(parenE);
12952 
12953   ExprResult result = CheckPlaceholderExpr(E);
12954   if (result.isInvalid()) return ExprError();
12955   E = result.get();
12956 
12957   if (!E->isTypeDependent()) {
12958     if (getLangOpts().CPlusPlus)
12959       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12960 
12961     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12962     if (ERes.isInvalid())
12963       return ExprError();
12964     E = ERes.get();
12965 
12966     QualType T = E->getType();
12967     if (!T->isScalarType()) { // C99 6.8.4.1p1
12968       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12969         << T << E->getSourceRange();
12970       return ExprError();
12971     }
12972   }
12973 
12974   return E;
12975 }
12976 
12977 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12978                                        Expr *SubExpr) {
12979   if (!SubExpr)
12980     return ExprError();
12981 
12982   return CheckBooleanCondition(SubExpr, Loc);
12983 }
12984 
12985 namespace {
12986   /// A visitor for rebuilding a call to an __unknown_any expression
12987   /// to have an appropriate type.
12988   struct RebuildUnknownAnyFunction
12989     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12990 
12991     Sema &S;
12992 
12993     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12994 
12995     ExprResult VisitStmt(Stmt *S) {
12996       llvm_unreachable("unexpected statement!");
12997     }
12998 
12999     ExprResult VisitExpr(Expr *E) {
13000       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13001         << E->getSourceRange();
13002       return ExprError();
13003     }
13004 
13005     /// Rebuild an expression which simply semantically wraps another
13006     /// expression which it shares the type and value kind of.
13007     template <class T> ExprResult rebuildSugarExpr(T *E) {
13008       ExprResult SubResult = Visit(E->getSubExpr());
13009       if (SubResult.isInvalid()) return ExprError();
13010 
13011       Expr *SubExpr = SubResult.get();
13012       E->setSubExpr(SubExpr);
13013       E->setType(SubExpr->getType());
13014       E->setValueKind(SubExpr->getValueKind());
13015       assert(E->getObjectKind() == OK_Ordinary);
13016       return E;
13017     }
13018 
13019     ExprResult VisitParenExpr(ParenExpr *E) {
13020       return rebuildSugarExpr(E);
13021     }
13022 
13023     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13024       return rebuildSugarExpr(E);
13025     }
13026 
13027     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13028       ExprResult SubResult = Visit(E->getSubExpr());
13029       if (SubResult.isInvalid()) return ExprError();
13030 
13031       Expr *SubExpr = SubResult.get();
13032       E->setSubExpr(SubExpr);
13033       E->setType(S.Context.getPointerType(SubExpr->getType()));
13034       assert(E->getValueKind() == VK_RValue);
13035       assert(E->getObjectKind() == OK_Ordinary);
13036       return E;
13037     }
13038 
13039     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13040       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13041 
13042       E->setType(VD->getType());
13043 
13044       assert(E->getValueKind() == VK_RValue);
13045       if (S.getLangOpts().CPlusPlus &&
13046           !(isa<CXXMethodDecl>(VD) &&
13047             cast<CXXMethodDecl>(VD)->isInstance()))
13048         E->setValueKind(VK_LValue);
13049 
13050       return E;
13051     }
13052 
13053     ExprResult VisitMemberExpr(MemberExpr *E) {
13054       return resolveDecl(E, E->getMemberDecl());
13055     }
13056 
13057     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13058       return resolveDecl(E, E->getDecl());
13059     }
13060   };
13061 }
13062 
13063 /// Given a function expression of unknown-any type, try to rebuild it
13064 /// to have a function type.
13065 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13066   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13067   if (Result.isInvalid()) return ExprError();
13068   return S.DefaultFunctionArrayConversion(Result.get());
13069 }
13070 
13071 namespace {
13072   /// A visitor for rebuilding an expression of type __unknown_anytype
13073   /// into one which resolves the type directly on the referring
13074   /// expression.  Strict preservation of the original source
13075   /// structure is not a goal.
13076   struct RebuildUnknownAnyExpr
13077     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13078 
13079     Sema &S;
13080 
13081     /// The current destination type.
13082     QualType DestType;
13083 
13084     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13085       : S(S), DestType(CastType) {}
13086 
13087     ExprResult VisitStmt(Stmt *S) {
13088       llvm_unreachable("unexpected statement!");
13089     }
13090 
13091     ExprResult VisitExpr(Expr *E) {
13092       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13093         << E->getSourceRange();
13094       return ExprError();
13095     }
13096 
13097     ExprResult VisitCallExpr(CallExpr *E);
13098     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13099 
13100     /// Rebuild an expression which simply semantically wraps another
13101     /// expression which it shares the type and value kind of.
13102     template <class T> ExprResult rebuildSugarExpr(T *E) {
13103       ExprResult SubResult = Visit(E->getSubExpr());
13104       if (SubResult.isInvalid()) return ExprError();
13105       Expr *SubExpr = SubResult.get();
13106       E->setSubExpr(SubExpr);
13107       E->setType(SubExpr->getType());
13108       E->setValueKind(SubExpr->getValueKind());
13109       assert(E->getObjectKind() == OK_Ordinary);
13110       return E;
13111     }
13112 
13113     ExprResult VisitParenExpr(ParenExpr *E) {
13114       return rebuildSugarExpr(E);
13115     }
13116 
13117     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13118       return rebuildSugarExpr(E);
13119     }
13120 
13121     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13122       const PointerType *Ptr = DestType->getAs<PointerType>();
13123       if (!Ptr) {
13124         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13125           << E->getSourceRange();
13126         return ExprError();
13127       }
13128       assert(E->getValueKind() == VK_RValue);
13129       assert(E->getObjectKind() == OK_Ordinary);
13130       E->setType(DestType);
13131 
13132       // Build the sub-expression as if it were an object of the pointee type.
13133       DestType = Ptr->getPointeeType();
13134       ExprResult SubResult = Visit(E->getSubExpr());
13135       if (SubResult.isInvalid()) return ExprError();
13136       E->setSubExpr(SubResult.get());
13137       return E;
13138     }
13139 
13140     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13141 
13142     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13143 
13144     ExprResult VisitMemberExpr(MemberExpr *E) {
13145       return resolveDecl(E, E->getMemberDecl());
13146     }
13147 
13148     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13149       return resolveDecl(E, E->getDecl());
13150     }
13151   };
13152 }
13153 
13154 /// Rebuilds a call expression which yielded __unknown_anytype.
13155 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13156   Expr *CalleeExpr = E->getCallee();
13157 
13158   enum FnKind {
13159     FK_MemberFunction,
13160     FK_FunctionPointer,
13161     FK_BlockPointer
13162   };
13163 
13164   FnKind Kind;
13165   QualType CalleeType = CalleeExpr->getType();
13166   if (CalleeType == S.Context.BoundMemberTy) {
13167     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13168     Kind = FK_MemberFunction;
13169     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13170   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13171     CalleeType = Ptr->getPointeeType();
13172     Kind = FK_FunctionPointer;
13173   } else {
13174     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13175     Kind = FK_BlockPointer;
13176   }
13177   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13178 
13179   // Verify that this is a legal result type of a function.
13180   if (DestType->isArrayType() || DestType->isFunctionType()) {
13181     unsigned diagID = diag::err_func_returning_array_function;
13182     if (Kind == FK_BlockPointer)
13183       diagID = diag::err_block_returning_array_function;
13184 
13185     S.Diag(E->getExprLoc(), diagID)
13186       << DestType->isFunctionType() << DestType;
13187     return ExprError();
13188   }
13189 
13190   // Otherwise, go ahead and set DestType as the call's result.
13191   E->setType(DestType.getNonLValueExprType(S.Context));
13192   E->setValueKind(Expr::getValueKindForType(DestType));
13193   assert(E->getObjectKind() == OK_Ordinary);
13194 
13195   // Rebuild the function type, replacing the result type with DestType.
13196   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13197   if (Proto) {
13198     // __unknown_anytype(...) is a special case used by the debugger when
13199     // it has no idea what a function's signature is.
13200     //
13201     // We want to build this call essentially under the K&R
13202     // unprototyped rules, but making a FunctionNoProtoType in C++
13203     // would foul up all sorts of assumptions.  However, we cannot
13204     // simply pass all arguments as variadic arguments, nor can we
13205     // portably just call the function under a non-variadic type; see
13206     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13207     // However, it turns out that in practice it is generally safe to
13208     // call a function declared as "A foo(B,C,D);" under the prototype
13209     // "A foo(B,C,D,...);".  The only known exception is with the
13210     // Windows ABI, where any variadic function is implicitly cdecl
13211     // regardless of its normal CC.  Therefore we change the parameter
13212     // types to match the types of the arguments.
13213     //
13214     // This is a hack, but it is far superior to moving the
13215     // corresponding target-specific code from IR-gen to Sema/AST.
13216 
13217     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13218     SmallVector<QualType, 8> ArgTypes;
13219     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13220       ArgTypes.reserve(E->getNumArgs());
13221       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13222         Expr *Arg = E->getArg(i);
13223         QualType ArgType = Arg->getType();
13224         if (E->isLValue()) {
13225           ArgType = S.Context.getLValueReferenceType(ArgType);
13226         } else if (E->isXValue()) {
13227           ArgType = S.Context.getRValueReferenceType(ArgType);
13228         }
13229         ArgTypes.push_back(ArgType);
13230       }
13231       ParamTypes = ArgTypes;
13232     }
13233     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13234                                          Proto->getExtProtoInfo());
13235   } else {
13236     DestType = S.Context.getFunctionNoProtoType(DestType,
13237                                                 FnType->getExtInfo());
13238   }
13239 
13240   // Rebuild the appropriate pointer-to-function type.
13241   switch (Kind) {
13242   case FK_MemberFunction:
13243     // Nothing to do.
13244     break;
13245 
13246   case FK_FunctionPointer:
13247     DestType = S.Context.getPointerType(DestType);
13248     break;
13249 
13250   case FK_BlockPointer:
13251     DestType = S.Context.getBlockPointerType(DestType);
13252     break;
13253   }
13254 
13255   // Finally, we can recurse.
13256   ExprResult CalleeResult = Visit(CalleeExpr);
13257   if (!CalleeResult.isUsable()) return ExprError();
13258   E->setCallee(CalleeResult.get());
13259 
13260   // Bind a temporary if necessary.
13261   return S.MaybeBindToTemporary(E);
13262 }
13263 
13264 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13265   // Verify that this is a legal result type of a call.
13266   if (DestType->isArrayType() || DestType->isFunctionType()) {
13267     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13268       << DestType->isFunctionType() << DestType;
13269     return ExprError();
13270   }
13271 
13272   // Rewrite the method result type if available.
13273   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13274     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13275     Method->setReturnType(DestType);
13276   }
13277 
13278   // Change the type of the message.
13279   E->setType(DestType.getNonReferenceType());
13280   E->setValueKind(Expr::getValueKindForType(DestType));
13281 
13282   return S.MaybeBindToTemporary(E);
13283 }
13284 
13285 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13286   // The only case we should ever see here is a function-to-pointer decay.
13287   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13288     assert(E->getValueKind() == VK_RValue);
13289     assert(E->getObjectKind() == OK_Ordinary);
13290 
13291     E->setType(DestType);
13292 
13293     // Rebuild the sub-expression as the pointee (function) type.
13294     DestType = DestType->castAs<PointerType>()->getPointeeType();
13295 
13296     ExprResult Result = Visit(E->getSubExpr());
13297     if (!Result.isUsable()) return ExprError();
13298 
13299     E->setSubExpr(Result.get());
13300     return E;
13301   } else if (E->getCastKind() == CK_LValueToRValue) {
13302     assert(E->getValueKind() == VK_RValue);
13303     assert(E->getObjectKind() == OK_Ordinary);
13304 
13305     assert(isa<BlockPointerType>(E->getType()));
13306 
13307     E->setType(DestType);
13308 
13309     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13310     DestType = S.Context.getLValueReferenceType(DestType);
13311 
13312     ExprResult Result = Visit(E->getSubExpr());
13313     if (!Result.isUsable()) return ExprError();
13314 
13315     E->setSubExpr(Result.get());
13316     return E;
13317   } else {
13318     llvm_unreachable("Unhandled cast type!");
13319   }
13320 }
13321 
13322 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13323   ExprValueKind ValueKind = VK_LValue;
13324   QualType Type = DestType;
13325 
13326   // We know how to make this work for certain kinds of decls:
13327 
13328   //  - functions
13329   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13330     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13331       DestType = Ptr->getPointeeType();
13332       ExprResult Result = resolveDecl(E, VD);
13333       if (Result.isInvalid()) return ExprError();
13334       return S.ImpCastExprToType(Result.get(), Type,
13335                                  CK_FunctionToPointerDecay, VK_RValue);
13336     }
13337 
13338     if (!Type->isFunctionType()) {
13339       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13340         << VD << E->getSourceRange();
13341       return ExprError();
13342     }
13343 
13344     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13345       if (MD->isInstance()) {
13346         ValueKind = VK_RValue;
13347         Type = S.Context.BoundMemberTy;
13348       }
13349 
13350     // Function references aren't l-values in C.
13351     if (!S.getLangOpts().CPlusPlus)
13352       ValueKind = VK_RValue;
13353 
13354   //  - variables
13355   } else if (isa<VarDecl>(VD)) {
13356     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13357       Type = RefTy->getPointeeType();
13358     } else if (Type->isFunctionType()) {
13359       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13360         << VD << E->getSourceRange();
13361       return ExprError();
13362     }
13363 
13364   //  - nothing else
13365   } else {
13366     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13367       << VD << E->getSourceRange();
13368     return ExprError();
13369   }
13370 
13371   // Modifying the declaration like this is friendly to IR-gen but
13372   // also really dangerous.
13373   VD->setType(DestType);
13374   E->setType(Type);
13375   E->setValueKind(ValueKind);
13376   return E;
13377 }
13378 
13379 /// Check a cast of an unknown-any type.  We intentionally only
13380 /// trigger this for C-style casts.
13381 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13382                                      Expr *CastExpr, CastKind &CastKind,
13383                                      ExprValueKind &VK, CXXCastPath &Path) {
13384   // Rewrite the casted expression from scratch.
13385   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13386   if (!result.isUsable()) return ExprError();
13387 
13388   CastExpr = result.get();
13389   VK = CastExpr->getValueKind();
13390   CastKind = CK_NoOp;
13391 
13392   return CastExpr;
13393 }
13394 
13395 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13396   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13397 }
13398 
13399 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13400                                     Expr *arg, QualType &paramType) {
13401   // If the syntactic form of the argument is not an explicit cast of
13402   // any sort, just do default argument promotion.
13403   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13404   if (!castArg) {
13405     ExprResult result = DefaultArgumentPromotion(arg);
13406     if (result.isInvalid()) return ExprError();
13407     paramType = result.get()->getType();
13408     return result;
13409   }
13410 
13411   // Otherwise, use the type that was written in the explicit cast.
13412   assert(!arg->hasPlaceholderType());
13413   paramType = castArg->getTypeAsWritten();
13414 
13415   // Copy-initialize a parameter of that type.
13416   InitializedEntity entity =
13417     InitializedEntity::InitializeParameter(Context, paramType,
13418                                            /*consumed*/ false);
13419   return PerformCopyInitialization(entity, callLoc, arg);
13420 }
13421 
13422 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13423   Expr *orig = E;
13424   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13425   while (true) {
13426     E = E->IgnoreParenImpCasts();
13427     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13428       E = call->getCallee();
13429       diagID = diag::err_uncasted_call_of_unknown_any;
13430     } else {
13431       break;
13432     }
13433   }
13434 
13435   SourceLocation loc;
13436   NamedDecl *d;
13437   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13438     loc = ref->getLocation();
13439     d = ref->getDecl();
13440   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13441     loc = mem->getMemberLoc();
13442     d = mem->getMemberDecl();
13443   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13444     diagID = diag::err_uncasted_call_of_unknown_any;
13445     loc = msg->getSelectorStartLoc();
13446     d = msg->getMethodDecl();
13447     if (!d) {
13448       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13449         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13450         << orig->getSourceRange();
13451       return ExprError();
13452     }
13453   } else {
13454     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13455       << E->getSourceRange();
13456     return ExprError();
13457   }
13458 
13459   S.Diag(loc, diagID) << d << orig->getSourceRange();
13460 
13461   // Never recoverable.
13462   return ExprError();
13463 }
13464 
13465 /// Check for operands with placeholder types and complain if found.
13466 /// Returns true if there was an error and no recovery was possible.
13467 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13468   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13469   if (!placeholderType) return E;
13470 
13471   switch (placeholderType->getKind()) {
13472 
13473   // Overloaded expressions.
13474   case BuiltinType::Overload: {
13475     // Try to resolve a single function template specialization.
13476     // This is obligatory.
13477     ExprResult result = E;
13478     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13479       return result;
13480 
13481     // If that failed, try to recover with a call.
13482     } else {
13483       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13484                            /*complain*/ true);
13485       return result;
13486     }
13487   }
13488 
13489   // Bound member functions.
13490   case BuiltinType::BoundMember: {
13491     ExprResult result = E;
13492     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13493                          /*complain*/ true);
13494     return result;
13495   }
13496 
13497   // ARC unbridged casts.
13498   case BuiltinType::ARCUnbridgedCast: {
13499     Expr *realCast = stripARCUnbridgedCast(E);
13500     diagnoseARCUnbridgedCast(realCast);
13501     return realCast;
13502   }
13503 
13504   // Expressions of unknown type.
13505   case BuiltinType::UnknownAny:
13506     return diagnoseUnknownAnyExpr(*this, E);
13507 
13508   // Pseudo-objects.
13509   case BuiltinType::PseudoObject:
13510     return checkPseudoObjectRValue(E);
13511 
13512   case BuiltinType::BuiltinFn: {
13513     // Accept __noop without parens by implicitly converting it to a call expr.
13514     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
13515     if (DRE) {
13516       auto *FD = cast<FunctionDecl>(DRE->getDecl());
13517       if (FD->getBuiltinID() == Builtin::BI__noop) {
13518         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
13519                               CK_BuiltinFnToFnPtr).get();
13520         return new (Context) CallExpr(Context, E, None, Context.IntTy,
13521                                       VK_RValue, SourceLocation());
13522       }
13523     }
13524 
13525     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13526     return ExprError();
13527   }
13528 
13529   // Everything else should be impossible.
13530 #define BUILTIN_TYPE(Id, SingletonId) \
13531   case BuiltinType::Id:
13532 #define PLACEHOLDER_TYPE(Id, SingletonId)
13533 #include "clang/AST/BuiltinTypes.def"
13534     break;
13535   }
13536 
13537   llvm_unreachable("invalid placeholder type!");
13538 }
13539 
13540 bool Sema::CheckCaseExpression(Expr *E) {
13541   if (E->isTypeDependent())
13542     return true;
13543   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13544     return E->getType()->isIntegralOrEnumerationType();
13545   return false;
13546 }
13547 
13548 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13549 ExprResult
13550 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13551   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13552          "Unknown Objective-C Boolean value!");
13553   QualType BoolT = Context.ObjCBuiltinBoolTy;
13554   if (!Context.getBOOLDecl()) {
13555     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13556                         Sema::LookupOrdinaryName);
13557     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13558       NamedDecl *ND = Result.getFoundDecl();
13559       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13560         Context.setBOOLDecl(TD);
13561     }
13562   }
13563   if (Context.getBOOLDecl())
13564     BoolT = Context.getBOOLType();
13565   return new (Context)
13566       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13567 }
13568